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