add missing #includes
[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/Bitcode/ReaderWriter.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/System/MappedFile.h"
18 #include "llvm/Module.h"
19 #include <memory>
20 using namespace llvm;
21
22 /// Read a variable-bit-rate encoded unsigned integer
23 inline unsigned readInteger(const char*&At, const char*End){
24   unsigned Shift = 0;
25   unsigned Result = 0;
26
27   do {
28     if (At == End)
29       return Result;
30     Result |= (unsigned)((*At++) & 0x7F) << Shift;
31     Shift += 7;
32   } while (At[-1] & 0x80);
33   return Result;
34 }
35
36 // Completely parse the Archive's symbol table and populate symTab member var.
37 bool
38 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
39   const char* At = (const char*) data;
40   const char* End = At + size;
41   while (At < End) {
42     unsigned offset = readInteger(At, End);
43     if (At == End) {
44       if (error)
45         *error = "Ran out of data reading vbr_uint for symtab offset!";
46       return false;
47     }
48     unsigned length = readInteger(At, End);
49     if (At == End) {
50       if (error)
51         *error = "Ran out of data reading vbr_uint for symtab length!";
52       return false;
53     }
54     if (At + length > End) {
55       if (error)
56         *error = "Malformed symbol table: length not consistent with size";
57       return false;
58     }
59     // we don't care if it can't be inserted (duplicate entry)
60     symTab.insert(std::make_pair(std::string(At, length), offset));
61     At += length;
62   }
63   symTabSize = size;
64   return true;
65 }
66
67 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
68 // by At. The At pointer is updated to the byte just after the header, which
69 // can be variable in size.
70 ArchiveMember*
71 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
72 {
73   if (At + sizeof(ArchiveMemberHeader) >= End) {
74     if (error)
75       *error = "Unexpected end of file";
76     return 0;
77   }
78
79   // Cast archive member header
80   ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
81   At += sizeof(ArchiveMemberHeader);
82
83   // Extract the size and determine if the file is
84   // compressed or not (negative length).
85   int flags = 0;
86   int MemberSize = atoi(Hdr->size);
87   if (MemberSize < 0) {
88     flags |= ArchiveMember::CompressedFlag;
89     MemberSize = -MemberSize;
90   }
91
92   // Check the size of the member for sanity
93   if (At + MemberSize > End) {
94     if (error)
95       *error = "invalid member length in archive file";
96     return 0;
97   }
98
99   // Check the member signature
100   if (!Hdr->checkSignature()) {
101     if (error)
102       *error = "invalid file member signature";
103     return 0;
104   }
105
106   // Convert and check the member name
107   // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
108   // table. The special name "//" and 14 blanks is for a string table, used
109   // for long file names. This library doesn't generate either of those but
110   // it will accept them. If the name starts with #1/ and the remainder is
111   // digits, then those digits specify the length of the name that is
112   // stored immediately following the header. The special name
113   // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bitcode.
114   // Anything else is a regular, short filename that is terminated with
115   // a '/' and blanks.
116
117   std::string pathname;
118   switch (Hdr->name[0]) {
119     case '#':
120       if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
121         if (isdigit(Hdr->name[3])) {
122           unsigned len = atoi(&Hdr->name[3]);
123           pathname.assign(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 termiantor 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       char* slash = (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   switch (sys::IdentifyFileType(At, 4)) {
210     case sys::Bitcode_FileType:
211       flags |= ArchiveMember::BitcodeFlag;
212       break;
213     default:
214       flags &= ~ArchiveMember::BitcodeFlag;
215       break;
216   }
217
218   // Instantiate the ArchiveMember to be filled
219   ArchiveMember* member = new ArchiveMember(this);
220
221   // Fill in fields of the ArchiveMember
222   member->next = 0;
223   member->prev = 0;
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->size() < 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 = base + mapfile->size();
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, std::string* ErrorMessage) 
333 {
334   std::auto_ptr<Archive> result ( new Archive(file));
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, std::string* ErrMessage) {
345
346   for (iterator I=begin(), E=end(); I != E; ++I) {
347     if (I->isBitcode()) {
348       std::string FullMemberName = archPath.toString() +
349         "(" + I->getPath().toString() + ")";
350       MemoryBuffer *Buffer =
351         MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
352       memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
353       
354       Module *M = ParseBitcodeFile(Buffer, ErrMessage);
355       delete Buffer;
356       if (!M)
357         return true;
358
359       Modules.push_back(M);
360     }
361   }
362   return false;
363 }
364
365 // Load just the symbol table from the archive file
366 bool
367 Archive::loadSymbolTable(std::string* ErrorMsg) {
368
369   // Set up parsing
370   members.clear();
371   symTab.clear();
372   const char *At = base;
373   const char *End = base + mapfile->size();
374
375   // Make sure we're dealing with an archive
376   if (!checkSignature(ErrorMsg))
377     return false;
378
379   At += 8; // Skip signature
380
381   // Parse the first file member header
382   const char* FirstFile = At;
383   ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
384   if (!mbr)
385     return false;
386
387   if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
388     // Skip the foreign symbol table, we don't do anything with it
389     At += mbr->getSize();
390     if ((intptr_t(At) & 1) == 1)
391       At++;
392     delete mbr;
393
394     // Read the next one
395     FirstFile = At;
396     mbr = parseMemberHeader(At, End, ErrorMsg);
397     if (!mbr) {
398       delete mbr;
399       return false;
400     }
401   }
402
403   if (mbr->isStringTable()) {
404     // Process the string table entry
405     strtab.assign((const char*)mbr->getData(), mbr->getSize());
406     At += mbr->getSize();
407     if ((intptr_t(At) & 1) == 1)
408       At++;
409     delete mbr;
410     // Get the next one
411     FirstFile = At;
412     mbr = parseMemberHeader(At, End, ErrorMsg);
413     if (!mbr) {
414       delete mbr;
415       return false;
416     }
417   }
418
419   // See if its the symbol table
420   if (mbr->isLLVMSymbolTable()) {
421     if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
422       delete mbr;
423       return false;
424     }
425
426     At += mbr->getSize();
427     if ((intptr_t(At) & 1) == 1)
428       At++;
429     delete mbr;
430     // Can't be any more symtab headers so just advance
431     FirstFile = At;
432   } else {
433     // There's no symbol table in the file. We have to rebuild it from scratch
434     // because the intent of this method is to get the symbol table loaded so
435     // it can be searched efficiently.
436     // Add the member to the members list
437     members.push_back(mbr);
438   }
439
440   firstFileOffset = FirstFile - base;
441   return true;
442 }
443
444 // Open the archive and load just the symbol tables
445 Archive*
446 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
447   std::auto_ptr<Archive> result ( new Archive(file) );
448   if (result->mapToMemory(ErrorMessage))
449     return 0;
450   if (!result->loadSymbolTable(ErrorMessage))
451     return 0;
452   return result.release();
453 }
454
455 // Look up one symbol in the symbol table and return a ModuleProvider for the
456 // module that defines that symbol.
457 ModuleProvider*
458 Archive::findModuleDefiningSymbol(const std::string& symbol, 
459                                   std::string* ErrMsg) {
460   SymTabType::iterator SI = symTab.find(symbol);
461   if (SI == symTab.end())
462     return 0;
463
464   // The symbol table was previously constructed assuming that the members were
465   // written without the symbol table header. Because VBR encoding is used, the
466   // values could not be adjusted to account for the offset of the symbol table
467   // because that could affect the size of the symbol table due to VBR encoding.
468   // We now have to account for this by adjusting the offset by the size of the
469   // symbol table and its header.
470   unsigned fileOffset =
471     SI->second +                // offset in symbol-table-less file
472     firstFileOffset;            // add offset to first "real" file in archive
473
474   // See if the module is already loaded
475   ModuleMap::iterator MI = modules.find(fileOffset);
476   if (MI != modules.end())
477     return MI->second.first;
478
479   // Module hasn't been loaded yet, we need to load it
480   const char* modptr = base + fileOffset;
481   ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size(),ErrMsg);
482   if (!mbr)
483     return 0;
484
485   // Now, load the bitcode module to get the ModuleProvider
486   std::string FullMemberName = archPath.toString() + "(" +
487     mbr->getPath().toString() + ")";
488   MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(),
489                                                       FullMemberName.c_str());
490   memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
491   
492   ModuleProvider *mp = getBitcodeModuleProvider(Buffer, ErrMsg);
493   if (!mp)
494     return 0;
495
496   modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
497
498   return mp;
499 }
500
501 // Look up multiple symbols in the symbol table and return a set of
502 // ModuleProviders that define those symbols.
503 bool
504 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
505                                     std::set<ModuleProvider*>& result,
506                                     std::string* error) {
507   if (!mapfile || !base) {
508     if (error)
509       *error = "Empty archive invalid for finding modules defining symbols";
510     return false;
511   }
512
513   if (symTab.empty()) {
514     // We don't have a symbol table, so we must build it now but lets also
515     // make sure that we populate the modules table as we do this to ensure
516     // that we don't load them twice when findModuleDefiningSymbol is called
517     // below.
518
519     // Get a pointer to the first file
520     const char* At  = ((const char*)base) + firstFileOffset;
521     const char* End = ((const char*)base) + mapfile->size();
522
523     while ( At < End) {
524       // Compute the offset to be put in the symbol table
525       unsigned offset = At - base - firstFileOffset;
526
527       // Parse the file's header
528       ArchiveMember* mbr = parseMemberHeader(At, End, error);
529       if (!mbr)
530         return false;
531
532       // If it contains symbols
533       if (mbr->isBitcode()) {
534         // Get the symbols
535         std::vector<std::string> symbols;
536         std::string FullMemberName = archPath.toString() + "(" +
537           mbr->getPath().toString() + ")";
538         ModuleProvider* MP = 
539           GetBitcodeSymbols((const unsigned char*)At, mbr->getSize(),
540                             FullMemberName, symbols, error);
541
542         if (MP) {
543           // Insert the module's symbols into the symbol table
544           for (std::vector<std::string>::iterator I = symbols.begin(),
545                E=symbols.end(); I != E; ++I ) {
546             symTab.insert(std::make_pair(*I, offset));
547           }
548           // Insert the ModuleProvider and the ArchiveMember into the table of
549           // modules.
550           modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
551         } else {
552           if (error)
553             *error = "Can't parse bitcode member: " + 
554               mbr->getPath().toString() + ": " + *error;
555           delete mbr;
556           return false;
557         }
558       }
559
560       // Go to the next file location
561       At += mbr->getSize();
562       if ((intptr_t(At) & 1) == 1)
563         At++;
564     }
565   }
566
567   // At this point we have a valid symbol table (one way or another) so we
568   // just use it to quickly find the symbols requested.
569
570   for (std::set<std::string>::iterator I=symbols.begin(),
571        E=symbols.end(); I != E;) {
572     // See if this symbol exists
573     ModuleProvider* mp = findModuleDefiningSymbol(*I,error);
574     if (mp) {
575       // The symbol exists, insert the ModuleProvider into our result,
576       // duplicates wil be ignored
577       result.insert(mp);
578
579       // Remove the symbol now that its been resolved, being careful to
580       // post-increment the iterator.
581       symbols.erase(I++);
582     } else {
583       ++I;
584     }
585   }
586   return true;
587 }
588
589 bool Archive::isBitcodeArchive() {
590   // Make sure the symTab has been loaded. In most cases this should have been
591   // done when the archive was constructed, but still,  this is just in case.
592   if (symTab.empty())
593     if (!loadSymbolTable(0))
594       return false;
595
596   // Now that we know it's been loaded, return true
597   // if it has a size
598   if (symTab.size()) return true;
599
600   // We still can't be sure it isn't a bitcode archive
601   if (!loadArchive(0))
602     return false;
603
604   std::vector<Module *> Modules;
605   std::string ErrorMessage;
606
607   // Scan the archive, trying to load a bitcode member.  We only load one to
608   // see if this works.
609   for (iterator I = begin(), E = end(); I != E; ++I) {
610     if (!I->isBitcode())
611       continue;
612     
613     std::string FullMemberName = 
614       archPath.toString() + "(" + I->getPath().toString() + ")";
615
616     MemoryBuffer *Buffer =
617       MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
618     memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
619     Module *M = ParseBitcodeFile(Buffer);
620     delete Buffer;
621     if (!M)
622       return false;  // Couldn't parse bitcode, not a bitcode archive.
623     delete M;
624     return true;
625   }
626   
627   return false;
628 }