Convert another use of sys::identifyFileType.
[oota-llvm.git] / lib / Archive / ArchiveReader.cpp
1 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up standard unix archive files (.a) containing LLVM bitcode.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/Archive.h"
15 #include "ArchiveInternals.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include <cstdio>
23 #include <cstdlib>
24 using namespace llvm;
25
26 /// Read a variable-bit-rate encoded unsigned integer
27 static inline unsigned readInteger(const char*&At, const char*End) {
28   unsigned Shift = 0;
29   unsigned Result = 0;
30
31   do {
32     if (At == End)
33       return Result;
34     Result |= (unsigned)((*At++) & 0x7F) << Shift;
35     Shift += 7;
36   } while (At[-1] & 0x80);
37   return Result;
38 }
39
40 // Completely parse the Archive's symbol table and populate symTab member var.
41 bool
42 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
43   const char* At = (const char*) data;
44   const char* End = At + size;
45   while (At < End) {
46     unsigned offset = readInteger(At, End);
47     if (At == End) {
48       if (error)
49         *error = "Ran out of data reading vbr_uint for symtab offset!";
50       return false;
51     }
52     unsigned length = readInteger(At, End);
53     if (At == End) {
54       if (error)
55         *error = "Ran out of data reading vbr_uint for symtab length!";
56       return false;
57     }
58     if (At + length > End) {
59       if (error)
60         *error = "Malformed symbol table: length not consistent with size";
61       return false;
62     }
63     // we don't care if it can't be inserted (duplicate entry)
64     symTab.insert(std::make_pair(std::string(At, length), offset));
65     At += length;
66   }
67   symTabSize = size;
68   return true;
69 }
70
71 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
72 // by At. The At pointer is updated to the byte just after the header, which
73 // can be variable in size.
74 ArchiveMember*
75 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
76 {
77   if (At + sizeof(ArchiveMemberHeader) >= End) {
78     if (error)
79       *error = "Unexpected end of file";
80     return 0;
81   }
82
83   // Cast archive member header
84   const ArchiveMemberHeader* Hdr = (const ArchiveMemberHeader*)At;
85   At += sizeof(ArchiveMemberHeader);
86
87   int flags = 0;
88   int MemberSize = atoi(Hdr->size);
89   assert(MemberSize >= 0);
90
91   // Check the size of the member for sanity
92   if (At + MemberSize > End) {
93     if (error)
94       *error = "invalid member length in archive file";
95     return 0;
96   }
97
98   // Check the member signature
99   if (!Hdr->checkSignature()) {
100     if (error)
101       *error = "invalid file member signature";
102     return 0;
103   }
104
105   // Convert and check the member name
106   // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
107   // table. The special name "//" and 14 blanks is for a string table, used
108   // for long file names. This library doesn't generate either of those but
109   // it will accept them. If the name starts with #1/ and the remainder is
110   // digits, then those digits specify the length of the name that is
111   // stored immediately following the header. The special name
112   // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bitcode.
113   // Anything else is a regular, short filename that is terminated with
114   // a '/' and blanks.
115
116   std::string pathname;
117   switch (Hdr->name[0]) {
118     case '#':
119       if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
120         if (isdigit(Hdr->name[3])) {
121           unsigned len = atoi(&Hdr->name[3]);
122           const char *nulp = (const char *)memchr(At, '\0', len);
123           pathname.assign(At, nulp != 0 ? (uintptr_t)(nulp - At) : len);
124           At += len;
125           MemberSize -= len;
126           flags |= ArchiveMember::HasLongFilenameFlag;
127         } else {
128           if (error)
129             *error = "invalid long filename";
130           return 0;
131         }
132       } else if (Hdr->name[1] == '_' &&
133                  (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
134         // The member is using a long file name (>15 chars) format.
135         // This format is standard for 4.4BSD and Mac OSX operating
136         // systems. LLVM uses it similarly. In this format, the
137         // remainder of the name field (after #1/) specifies the
138         // length of the file name which occupy the first bytes of
139         // the member's data. The pathname already has the #1/ stripped.
140         pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
141         flags |= ArchiveMember::LLVMSymbolTableFlag;
142       }
143       break;
144     case '/':
145       if (Hdr->name[1]== '/') {
146         if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
147           pathname.assign(ARFILE_STRTAB_NAME);
148           flags |= ArchiveMember::StringTableFlag;
149         } else {
150           if (error)
151             *error = "invalid string table name";
152           return 0;
153         }
154       } else if (Hdr->name[1] == ' ') {
155         if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
156           pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
157           flags |= ArchiveMember::SVR4SymbolTableFlag;
158         } else {
159           if (error)
160             *error = "invalid SVR4 symbol table name";
161           return 0;
162         }
163       } else if (isdigit(Hdr->name[1])) {
164         unsigned index = atoi(&Hdr->name[1]);
165         if (index < strtab.length()) {
166           const char* namep = strtab.c_str() + index;
167           const char* endp = strtab.c_str() + strtab.length();
168           const char* p = namep;
169           const char* last_p = p;
170           while (p < endp) {
171             if (*p == '\n' && *last_p == '/') {
172               pathname.assign(namep, last_p - namep);
173               flags |= ArchiveMember::HasLongFilenameFlag;
174               break;
175             }
176             last_p = p;
177             p++;
178           }
179           if (p >= endp) {
180             if (error)
181               *error = "missing name terminator in string table";
182             return 0;
183           }
184         } else {
185           if (error)
186             *error = "name index beyond string table";
187           return 0;
188         }
189       }
190       break;
191     case '_':
192       if (Hdr->name[1] == '_' &&
193           (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
194         pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
195         flags |= ArchiveMember::BSD4SymbolTableFlag;
196         break;
197       }
198       /* FALL THROUGH */
199
200     default:
201       const char* slash = (const char*) memchr(Hdr->name, '/', 16);
202       if (slash == 0)
203         slash = Hdr->name + 16;
204       pathname.assign(Hdr->name, slash - Hdr->name);
205       break;
206   }
207
208   // Determine if this is a bitcode file
209   if (sys::fs::identify_magic(StringRef(At, 4)) ==
210       sys::fs::file_magic::bitcode)
211     flags |= ArchiveMember::BitcodeFlag;
212   else
213     flags &= ~ArchiveMember::BitcodeFlag;
214
215   // Instantiate the ArchiveMember to be filled
216   ArchiveMember* member = new ArchiveMember(this);
217
218   // Fill in fields of the ArchiveMember
219   member->parent = this;
220   member->path.set(pathname);
221   member->info.fileSize = MemberSize;
222   member->info.modTime.fromEpochTime(atoi(Hdr->date));
223   unsigned int mode;
224   sscanf(Hdr->mode, "%o", &mode);
225   member->info.mode = mode;
226   member->info.user = atoi(Hdr->uid);
227   member->info.group = atoi(Hdr->gid);
228   member->flags = flags;
229   member->data = At;
230
231   return member;
232 }
233
234 bool
235 Archive::checkSignature(std::string* error) {
236   // Check the magic string at file's header
237   if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
238     if (error)
239       *error = "invalid signature for an archive file";
240     return false;
241   }
242   return true;
243 }
244
245 // This function loads the entire archive and fully populates its ilist with
246 // the members of the archive file. This is typically used in preparation for
247 // editing the contents of the archive.
248 bool
249 Archive::loadArchive(std::string* error) {
250
251   // Set up parsing
252   members.clear();
253   symTab.clear();
254   const char *At = base;
255   const char *End = mapfile->getBufferEnd();
256
257   if (!checkSignature(error))
258     return false;
259
260   At += 8;  // Skip the magic string.
261
262   bool seenSymbolTable = false;
263   bool foundFirstFile = false;
264   while (At < End) {
265     // parse the member header
266     const char* Save = At;
267     ArchiveMember* mbr = parseMemberHeader(At, End, error);
268     if (!mbr)
269       return false;
270
271     // check if this is the foreign symbol table
272     if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
273       // We just save this but don't do anything special
274       // with it. It doesn't count as the "first file".
275       if (foreignST) {
276         // What? Multiple foreign symbol tables? Just chuck it
277         // and retain the last one found.
278         delete foreignST;
279       }
280       foreignST = mbr;
281       At += mbr->getSize();
282       if ((intptr_t(At) & 1) == 1)
283         At++;
284     } else if (mbr->isStringTable()) {
285       // Simply suck the entire string table into a string
286       // variable. This will be used to get the names of the
287       // members that use the "/ddd" format for their names
288       // (SVR4 style long names).
289       strtab.assign(At, mbr->getSize());
290       At += mbr->getSize();
291       if ((intptr_t(At) & 1) == 1)
292         At++;
293       delete mbr;
294     } else if (mbr->isLLVMSymbolTable()) {
295       // This is the LLVM symbol table for the archive. If we've seen it
296       // already, its an error. Otherwise, parse the symbol table and move on.
297       if (seenSymbolTable) {
298         if (error)
299           *error = "invalid archive: multiple symbol tables";
300         return false;
301       }
302       if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
303         return false;
304       seenSymbolTable = true;
305       At += mbr->getSize();
306       if ((intptr_t(At) & 1) == 1)
307         At++;
308       delete mbr; // We don't need this member in the list of members.
309     } else {
310       // This is just a regular file. If its the first one, save its offset.
311       // Otherwise just push it on the list and move on to the next file.
312       if (!foundFirstFile) {
313         firstFileOffset = Save - base;
314         foundFirstFile = true;
315       }
316       members.push_back(mbr);
317       At += mbr->getSize();
318       if ((intptr_t(At) & 1) == 1)
319         At++;
320     }
321   }
322   return true;
323 }
324
325 // Open and completely load the archive file.
326 Archive*
327 Archive::OpenAndLoad(const sys::Path& File, LLVMContext& C,
328                      std::string* ErrorMessage) {
329   OwningPtr<Archive> result ( new Archive(File, C));
330   if (result->mapToMemory(ErrorMessage))
331     return NULL;
332   if (!result->loadArchive(ErrorMessage))
333     return NULL;
334   return result.take();
335 }
336
337 // Get all the bitcode modules from the archive
338 bool
339 Archive::getAllModules(std::vector<Module*>& Modules,
340                        std::string* ErrMessage) {
341
342   for (iterator I=begin(), E=end(); I != E; ++I) {
343     if (I->isBitcode()) {
344       std::string FullMemberName = archPath.str() +
345         "(" + I->getPath().str() + ")";
346       MemoryBuffer *Buffer =
347         MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
348                                        FullMemberName.c_str());
349       
350       Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
351       delete Buffer;
352       if (!M)
353         return true;
354
355       Modules.push_back(M);
356     }
357   }
358   return false;
359 }
360
361 // Load just the symbol table from the archive file
362 bool
363 Archive::loadSymbolTable(std::string* ErrorMsg) {
364
365   // Set up parsing
366   members.clear();
367   symTab.clear();
368   const char *At = base;
369   const char *End = mapfile->getBufferEnd();
370
371   // Make sure we're dealing with an archive
372   if (!checkSignature(ErrorMsg))
373     return false;
374
375   At += 8; // Skip signature
376
377   // Parse the first file member header
378   const char* FirstFile = At;
379   ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
380   if (!mbr)
381     return false;
382
383   if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
384     // Skip the foreign symbol table, we don't do anything with it
385     At += mbr->getSize();
386     if ((intptr_t(At) & 1) == 1)
387       At++;
388     delete mbr;
389
390     // Read the next one
391     FirstFile = At;
392     mbr = parseMemberHeader(At, End, ErrorMsg);
393     if (!mbr) {
394       delete mbr;
395       return false;
396     }
397   }
398
399   if (mbr->isStringTable()) {
400     // Process the string table entry
401     strtab.assign((const char*)mbr->getData(), mbr->getSize());
402     At += mbr->getSize();
403     if ((intptr_t(At) & 1) == 1)
404       At++;
405     delete mbr;
406     // Get the next one
407     FirstFile = At;
408     mbr = parseMemberHeader(At, End, ErrorMsg);
409     if (!mbr) {
410       delete mbr;
411       return false;
412     }
413   }
414
415   // See if its the symbol table
416   if (mbr->isLLVMSymbolTable()) {
417     if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
418       delete mbr;
419       return false;
420     }
421
422     At += mbr->getSize();
423     if ((intptr_t(At) & 1) == 1)
424       At++;
425     delete mbr;
426     // Can't be any more symtab headers so just advance
427     FirstFile = At;
428   } else {
429     // There's no symbol table in the file. We have to rebuild it from scratch
430     // because the intent of this method is to get the symbol table loaded so
431     // it can be searched efficiently.
432     // Add the member to the members list
433     members.push_back(mbr);
434   }
435
436   firstFileOffset = FirstFile - base;
437   return true;
438 }
439
440 // Open the archive and load just the symbol tables
441 Archive* Archive::OpenAndLoadSymbols(const sys::Path& File,
442                                      LLVMContext& C,
443                                      std::string* ErrorMessage) {
444   OwningPtr<Archive> result ( new Archive(File, C) );
445   if (result->mapToMemory(ErrorMessage))
446     return NULL;
447   if (!result->loadSymbolTable(ErrorMessage))
448     return NULL;
449   return result.take();
450 }
451
452 // Look up one symbol in the symbol table and return the module that defines
453 // that symbol.
454 Module*
455 Archive::findModuleDefiningSymbol(const std::string& symbol, 
456                                   std::string* ErrMsg) {
457   SymTabType::iterator SI = symTab.find(symbol);
458   if (SI == symTab.end())
459     return 0;
460
461   // The symbol table was previously constructed assuming that the members were
462   // written without the symbol table header. Because VBR encoding is used, the
463   // values could not be adjusted to account for the offset of the symbol table
464   // because that could affect the size of the symbol table due to VBR encoding.
465   // We now have to account for this by adjusting the offset by the size of the
466   // symbol table and its header.
467   unsigned fileOffset =
468     SI->second +                // offset in symbol-table-less file
469     firstFileOffset;            // add offset to first "real" file in archive
470
471   // See if the module is already loaded
472   ModuleMap::iterator MI = modules.find(fileOffset);
473   if (MI != modules.end())
474     return MI->second.first;
475
476   // Module hasn't been loaded yet, we need to load it
477   const char* modptr = base + fileOffset;
478   ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
479                                          ErrMsg);
480   if (!mbr)
481     return 0;
482
483   // Now, load the bitcode module to get the Module.
484   std::string FullMemberName = archPath.str() + "(" +
485     mbr->getPath().str() + ")";
486   MemoryBuffer *Buffer =
487     MemoryBuffer::getMemBufferCopy(StringRef(mbr->getData(), mbr->getSize()),
488                                    FullMemberName.c_str());
489   
490   Module *m = getLazyBitcodeModule(Buffer, Context, ErrMsg);
491   if (!m)
492     return 0;
493
494   modules.insert(std::make_pair(fileOffset, std::make_pair(m, mbr)));
495
496   return m;
497 }
498
499 // Look up multiple symbols in the symbol table and return a set of
500 // Modules that define those symbols.
501 bool
502 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
503                                     SmallVectorImpl<Module*>& result,
504                                     std::string* error) {
505   if (!mapfile || !base) {
506     if (error)
507       *error = "Empty archive invalid for finding modules defining symbols";
508     return false;
509   }
510
511   if (symTab.empty()) {
512     // We don't have a symbol table, so we must build it now but lets also
513     // make sure that we populate the modules table as we do this to ensure
514     // that we don't load them twice when findModuleDefiningSymbol is called
515     // below.
516
517     // Get a pointer to the first file
518     const char* At  = base + firstFileOffset;
519     const char* End = mapfile->getBufferEnd();
520
521     while ( At < End) {
522       // Compute the offset to be put in the symbol table
523       unsigned offset = At - base - firstFileOffset;
524
525       // Parse the file's header
526       ArchiveMember* mbr = parseMemberHeader(At, End, error);
527       if (!mbr)
528         return false;
529
530       // If it contains symbols
531       if (mbr->isBitcode()) {
532         // Get the symbols
533         std::vector<std::string> symbols;
534         std::string FullMemberName = archPath.str() + "(" +
535           mbr->getPath().str() + ")";
536         Module* M = 
537           GetBitcodeSymbols(At, mbr->getSize(), FullMemberName, Context,
538                             symbols, error);
539
540         if (M) {
541           // Insert the module's symbols into the symbol table
542           for (std::vector<std::string>::iterator I = symbols.begin(),
543                E=symbols.end(); I != E; ++I ) {
544             symTab.insert(std::make_pair(*I, offset));
545           }
546           // Insert the Module and the ArchiveMember into the table of
547           // modules.
548           modules.insert(std::make_pair(offset, std::make_pair(M, mbr)));
549         } else {
550           if (error)
551             *error = "Can't parse bitcode member: " + 
552               mbr->getPath().str() + ": " + *error;
553           delete mbr;
554           return false;
555         }
556       }
557
558       // Go to the next file location
559       At += mbr->getSize();
560       if ((intptr_t(At) & 1) == 1)
561         At++;
562     }
563   }
564
565   // At this point we have a valid symbol table (one way or another) so we
566   // just use it to quickly find the symbols requested.
567
568   SmallPtrSet<Module*, 16> Added;
569   for (std::set<std::string>::iterator I=symbols.begin(),
570          Next = I,
571          E=symbols.end(); I != E; I = Next) {
572     // Increment Next before we invalidate it.
573     ++Next;
574
575     // See if this symbol exists
576     Module* m = findModuleDefiningSymbol(*I,error);
577     if (!m)
578       continue;
579     bool NewMember = Added.insert(m);
580     if (!NewMember)
581       continue;
582
583     // The symbol exists, insert the Module into our result.
584     result.push_back(m);
585
586     // Remove the symbol now that its been resolved.
587     symbols.erase(I);
588   }
589   return true;
590 }
591
592 bool Archive::isBitcodeArchive() {
593   // Make sure the symTab has been loaded. In most cases this should have been
594   // done when the archive was constructed, but still,  this is just in case.
595   if (symTab.empty())
596     if (!loadSymbolTable(0))
597       return false;
598
599   // Now that we know it's been loaded, return true
600   // if it has a size
601   if (symTab.size()) return true;
602
603   // We still can't be sure it isn't a bitcode archive
604   if (!loadArchive(0))
605     return false;
606
607   std::vector<Module *> Modules;
608   std::string ErrorMessage;
609
610   // Scan the archive, trying to load a bitcode member.  We only load one to
611   // see if this works.
612   for (iterator I = begin(), E = end(); I != E; ++I) {
613     if (!I->isBitcode())
614       continue;
615     
616     std::string FullMemberName = 
617       archPath.str() + "(" + I->getPath().str() + ")";
618
619     MemoryBuffer *Buffer =
620       MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
621                                      FullMemberName.c_str());
622     Module *M = ParseBitcodeFile(Buffer, Context);
623     delete Buffer;
624     if (!M)
625       return false;  // Couldn't parse bitcode, not a bitcode archive.
626     delete M;
627     return true;
628   }
629   
630   return false;
631 }