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