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