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