DwarfWriter reading basic type information from llvm-gcc4 code.
[oota-llvm.git] / lib / Archive / ArchiveReader.cpp
index 8cec1383e67d620a24e8703e73999e136eac256e..ac8fb11f4c03324709583d501a716cd699293db4 100644 (file)
@@ -1,10 +1,10 @@
 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===//
-// 
+//
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Reid Spencer and is distributed under the 
+// This file was developed by Reid Spencer and is distributed under the
 // University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+//
 //===----------------------------------------------------------------------===//
 //
 // Builds up standard unix archive files (.a) containing LLVM bytecode.
@@ -13,6 +13,7 @@
 
 #include "ArchiveInternals.h"
 #include "llvm/Bytecode/Reader.h"
+#include <memory>
 
 using namespace llvm;
 
@@ -20,9 +21,9 @@ using namespace llvm;
 inline unsigned readInteger(const char*&At, const char*End) {
   unsigned Shift = 0;
   unsigned Result = 0;
-  
+
   do {
-    if (At == End) 
+    if (At == End)
       throw std::string("Ran out of data reading vbr_uint!");
     Result |= (unsigned)((*At++) & 0x7F) << Shift;
     Shift += 7;
@@ -41,7 +42,7 @@ Archive::parseSymbolTable(const void* data, unsigned size) {
     if (At + length > End)
       throw std::string("malformed symbol table");
     // we don't care if it can't be inserted (duplicate entry)
-    symTab.insert(std::make_pair(std::string(At,length),offset));
+    symTab.insert(std::make_pair(std::string(At, length), offset));
     At += length;
   }
   symTabSize = size;
@@ -49,7 +50,7 @@ Archive::parseSymbolTable(const void* data, unsigned size) {
 
 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
 // by At. The At pointer is updated to the byte just after the header, which
-// can be variable in size. 
+// can be variable in size.
 ArchiveMember*
 Archive::parseMemberHeader(const char*& At, const char* End) {
   assert(At + sizeof(ArchiveMemberHeader) < End && "Not enough data");
@@ -61,7 +62,7 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
   // Instantiate the ArchiveMember to be filled
   ArchiveMember* member = new ArchiveMember(this);
 
-  // Extract the size and determine if the file is 
+  // Extract the size and determine if the file is
   // compressed or not (negative length).
   int flags = 0;
   int MemberSize = atoi(Hdr->size);
@@ -79,30 +80,30 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
     throw std::string("invalid file member signature");
 
   // Convert and check the member name
-  // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol 
-  // table. The special name "//" and 14 blanks is for a string table, used 
+  // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
+  // table. The special name "//" and 14 blanks is for a string table, used
   // for long file names. This library doesn't generate either of those but
-  // it will accept them. If the name starts with #1/ and the remainder is 
-  // digits, then those digits specify the length of the name that is 
-  // stored immediately following the header. The special name 
-  // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bytecode. 
-  // Anything else is a regular, short filename that is terminated with 
+  // it will accept them. If the name starts with #1/ and the remainder is
+  // digits, then those digits specify the length of the name that is
+  // stored immediately following the header. The special name
+  // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bytecode.
+  // Anything else is a regular, short filename that is terminated with
   // a '/' and blanks.
 
   std::string pathname;
-  unsigned index;
   switch (Hdr->name[0]) {
     case '#':
       if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
         if (isdigit(Hdr->name[3])) {
           unsigned len = atoi(&Hdr->name[3]);
-          pathname.assign(At,len);
-          At += len + 1; // terminated by \n
+          pathname.assign(At, len);
+          At += len;
+          MemberSize -= len;
           flags |= ArchiveMember::HasLongFilenameFlag;
         } else
           throw std::string("invalid long filename");
-      } else if (Hdr->name[1] == '_' && 
-                 (0==memcmp(Hdr->name,ARFILE_LLVM_SYMTAB_NAME,16))) {
+      } else if (Hdr->name[1] == '_' &&
+                 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
         // The member is using a long file name (>15 chars) format.
         // This format is standard for 4.4BSD and Mac OSX operating
         // systems. LLVM uses it similarly. In this format, the
@@ -115,18 +116,18 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
       break;
     case '/':
       if (Hdr->name[1]== '/') {
-        if (0==memcmp(Hdr->name,ARFILE_STRTAB_NAME,16)) {
+        if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
           pathname.assign(ARFILE_STRTAB_NAME);
           flags |= ArchiveMember::StringTableFlag;
         } else {
           throw std::string("invalid string table name");
         }
       } else if (Hdr->name[1] == ' ') {
-        if (0==memcmp(Hdr->name,ARFILE_SYMTAB_NAME,16)) {
-          pathname.assign(ARFILE_SYMTAB_NAME);
-          flags |= ArchiveMember::ForeignSymbolTableFlag;
+        if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
+          pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
+          flags |= ArchiveMember::SVR4SymbolTableFlag;
         } else {
-          throw std::string("invalid foreign symbol table name");
+          throw std::string("invalid SVR4 symbol table name");
         }
       } else if (isdigit(Hdr->name[1])) {
         unsigned index = atoi(&Hdr->name[1]);
@@ -137,7 +138,7 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
           const char* last_p = p;
           while (p < endp) {
             if (*p == '\n' && *last_p == '/') {
-              pathname.assign(namep,last_p-namep);
+              pathname.assign(namep, last_p - namep);
               flags |= ArchiveMember::HasLongFilenameFlag;
               break;
             }
@@ -151,17 +152,25 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
         }
       }
       break;
+    case '_':
+      if (Hdr->name[1] == '_' &&
+          (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
+        pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
+        flags |= ArchiveMember::BSD4SymbolTableFlag;
+        break;
+      }
+      /* FALL THROUGH */
 
     default:
-      char* slash = (char*) memchr(Hdr->name,'/',16);
+      char* slash = (char*) memchr(Hdr->name, '/', 16);
       if (slash == 0)
-        throw std::string("missing name terminator");
-      pathname.assign(Hdr->name,slash-Hdr->name);
+        slash = Hdr->name + 16;
+      pathname.assign(Hdr->name, slash - Hdr->name);
       break;
   }
 
   // Determine if this is a bytecode file
-  switch (sys::IdentifyFileType(At,4)) {
+  switch (sys::IdentifyFileType(At, 4)) {
     case sys::BytecodeFileType:
       flags |= ArchiveMember::BytecodeFlag;
       break;
@@ -179,10 +188,12 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
   member->next = 0;
   member->prev = 0;
   member->parent = this;
-  member->path.setFile(pathname);
+  member->path.set(pathname);
   member->info.fileSize = MemberSize;
   member->info.modTime.fromEpochTime(atoi(Hdr->date));
-  sscanf(Hdr->mode,"%o",&(member->info.mode));
+  unsigned int mode;
+  sscanf(Hdr->mode, "%o", &mode);
+  member->info.mode = mode;
   member->info.user = atoi(Hdr->uid);
   member->info.group = atoi(Hdr->gid);
   member->flags = flags;
@@ -194,11 +205,11 @@ Archive::parseMemberHeader(const char*& At, const char* End) {
 void
 Archive::checkSignature() {
   // Check the magic string at file's header
-  if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC,8))
+  if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC, 8))
     throw std::string("invalid signature for an archive file");
 }
 
-// This function loads the entire archive and fully populates its ilist with 
+// This function loads the entire archive and fully populates its ilist with
 // the members of the archive file. This is typically used in preparation for
 // editing the contents of the archive.
 void
@@ -216,37 +227,42 @@ Archive::loadArchive() {
   bool seenSymbolTable = false;
   bool foundFirstFile = false;
   while (At < End) {
-    // parse the member header 
+    // parse the member header
     const char* Save = At;
     ArchiveMember* mbr = parseMemberHeader(At, End);
 
     // check if this is the foreign symbol table
-    if (mbr->isForeignSymbolTable()) {
+    if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
       // We just save this but don't do anything special
       // with it. It doesn't count as the "first file".
+      if (foreignST) {
+        // What? Multiple foreign symbol tables? Just chuck it
+        // and retain the last one found.
+        delete foreignST;
+      }
       foreignST = mbr;
       At += mbr->getSize();
-      if ((mbr->getSize() & 1) == 1)
+      if ((intptr_t(At) & 1) == 1)
         At++;
     } else if (mbr->isStringTable()) {
       // Simply suck the entire string table into a string
       // variable. This will be used to get the names of the
       // members that use the "/ddd" format for their names
       // (SVR4 style long names).
-      strtab.assign(At,mbr->getSize());
+      strtab.assign(At, mbr->getSize());
       At += mbr->getSize();
-      if ((mbr->getSize() & 1) == 1)
+      if ((intptr_t(At) & 1) == 1)
         At++;
       delete mbr;
-    } else if (mbr->isLLVMSymbolTable()) { 
+    } else if (mbr->isLLVMSymbolTable()) {
       // This is the LLVM symbol table for the archive. If we've seen it
       // already, its an error. Otherwise, parse the symbol table and move on.
       if (seenSymbolTable)
         throw std::string("invalid archive: multiple symbol tables");
-      parseSymbolTable(mbr->getData(),mbr->getSize());
+      parseSymbolTable(mbr->getData(), mbr->getSize());
       seenSymbolTable = true;
       At += mbr->getSize();
-      if ((mbr->getSize() & 1) == 1)
+      if ((intptr_t(At) & 1) == 1)
         At++;
       delete mbr; // We don't need this member in the list of members.
     } else {
@@ -258,7 +274,7 @@ Archive::loadArchive() {
       }
       members.push_back(mbr);
       At += mbr->getSize();
-      if ((mbr->getSize() & 1) == 1)
+      if ((intptr_t(At) & 1) == 1)
         At++;
     }
   }
@@ -266,13 +282,17 @@ Archive::loadArchive() {
 
 // Open and completely load the archive file.
 Archive*
-Archive::OpenAndLoad(const sys::Path& file) {
-
-  Archive* result = new Archive(file,true);
-
-  result->loadArchive();
-  
-  return result;
+Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage) {
+  try {
+    std::auto_ptr<Archive> result ( new Archive(file, true));
+    result->loadArchive();
+    return result.release();
+  } catch (const std::string& msg) {
+    if (ErrorMessage) {
+      *ErrorMessage = msg;
+    }
+    return 0;
+  }
 }
 
 // Get all the bytecode modules from the archive
@@ -281,8 +301,10 @@ Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
 
   for (iterator I=begin(), E=end(); I != E; ++I) {
     if (I->isBytecode() || I->isCompressedBytecode()) {
-      Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(), 
-          I->getSize(), I->getPath().get(), ErrMessage);
+      std::string FullMemberName = archPath.toString() +
+        "(" + I->getPath().toString() + ")";
+      Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
+          I->getSize(), FullMemberName, ErrMessage);
       if (!M)
         return true;
 
@@ -311,40 +333,41 @@ Archive::loadSymbolTable() {
   const char* FirstFile = At;
   ArchiveMember* mbr = parseMemberHeader(At, End);
 
-  if (mbr->isForeignSymbolTable()) {
+  if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
     // Skip the foreign symbol table, we don't do anything with it
     At += mbr->getSize();
-    if ((mbr->getSize() & 1) == 1)
+    if ((intptr_t(At) & 1) == 1)
       At++;
     delete mbr;
 
     // Read the next one
     FirstFile = At;
-    mbr = parseMemberHeader(At,End);
+    mbr = parseMemberHeader(At, End);
   }
 
   if (mbr->isStringTable()) {
     // Process the string table entry
-    strtab.assign((const char*)mbr->getData(),mbr->getSize());
+    strtab.assign((const char*)mbr->getData(), mbr->getSize());
     At += mbr->getSize();
-    if ((mbr->getSize() & 1) == 1)
+    if ((intptr_t(At) & 1) == 1)
       At++;
     delete mbr;
     // Get the next one
     FirstFile = At;
-    mbr = parseMemberHeader(At,End);
+    mbr = parseMemberHeader(At, End);
   }
 
   // See if its the symbol table
   if (mbr->isLLVMSymbolTable()) {
-    parseSymbolTable(mbr->getData(),mbr->getSize());
-    FirstFile = At + mbr->getSize();
-    if ((mbr->getSize() & 1) == 1)
-      FirstFile++;
+    parseSymbolTable(mbr->getData(), mbr->getSize());
+    At += mbr->getSize();
+    if ((intptr_t(At) & 1) == 1)
+      At++;
+    FirstFile = At;
   } else {
     // There's no symbol table in the file. We have to rebuild it from scratch
-    // because the intent of this method is to get the symbol table loaded so 
-    // it can be searched efficiently. 
+    // because the intent of this method is to get the symbol table loaded so
+    // it can be searched efficiently.
     // Add the member to the members list
     members.push_back(mbr);
   }
@@ -354,29 +377,34 @@ Archive::loadSymbolTable() {
 
 // Open the archive and load just the symbol tables
 Archive*
-Archive::OpenAndLoadSymbols(const sys::Path& file) {
-  Archive* result = new Archive(file,true);
-
-  result->loadSymbolTable();
-
-  return result;
+Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
+  try {
+    std::auto_ptr<Archive> result ( new Archive(file, true) );
+    result->loadSymbolTable();
+    return result.release();
+  } catch (const std::string& msg) {
+    if (ErrorMessage) {
+      *ErrorMessage = msg;
+    }
+    return 0;
+  }
 }
 
 // Look up one symbol in the symbol table and return a ModuleProvider for the
 // module that defines that symbol.
-ModuleProvider* 
+ModuleProvider*
 Archive::findModuleDefiningSymbol(const std::string& symbol) {
   SymTabType::iterator SI = symTab.find(symbol);
   if (SI == symTab.end())
     return 0;
 
-  // The symbol table was previously constructed assuming that the members were 
+  // The symbol table was previously constructed assuming that the members were
   // written without the symbol table header. Because VBR encoding is used, the
   // values could not be adjusted to account for the offset of the symbol table
   // because that could affect the size of the symbol table due to VBR encoding.
-  // We now have to account for this by adjusting the offset by the size of the 
+  // We now have to account for this by adjusting the offset by the size of the
   // symbol table and its header.
-  unsigned fileOffset = 
+  unsigned fileOffset =
     SI->second +                // offset in symbol-table-less file
     firstFileOffset;            // add offset to first "real" file in archive
 
@@ -390,19 +418,21 @@ Archive::findModuleDefiningSymbol(const std::string& symbol) {
   ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size());
 
   // Now, load the bytecode module to get the ModuleProvider
+  std::string FullMemberName = archPath.toString() + "(" +
+    mbr->getPath().toString() + ")";
   ModuleProvider* mp = getBytecodeBufferModuleProvider(
-      (const unsigned char*) mbr->getData(), mbr->getSize(), 
-      mbr->getPath().get(), 0);
+      (const unsigned char*) mbr->getData(), mbr->getSize(),
+      FullMemberName, 0);
 
-  modules.insert(std::make_pair(fileOffset,std::make_pair(mp,mbr)));
+  modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
 
   return mp;
 }
 
-// Look up multiple symbols in the symbol table and return a set of 
+// Look up multiple symbols in the symbol table and return a set of
 // ModuleProviders that define those symbols.
 void
-Archive::findModulesDefiningSymbols(const std::set<std::string>& symbols,
+Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
                                     std::set<ModuleProvider*>& result)
 {
   assert(mapfile && base && "Can't findModulesDefiningSymbols on new archive");
@@ -425,41 +455,87 @@ Archive::findModulesDefiningSymbols(const std::set<std::string>& symbols,
 
       // If it contains symbols
       if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
-        // Get the symbols 
+        // Get the symbols
         std::vector<std::string> symbols;
+        std::string FullMemberName = archPath.toString() + "(" +
+          mbr->getPath().toString() + ")";
         ModuleProvider* MP = GetBytecodeSymbols((const unsigned char*)At,
-            mbr->getSize(), mbr->getPath().get(),symbols);
+            mbr->getSize(), FullMemberName, symbols);
 
         if (MP) {
           // Insert the module's symbols into the symbol table
-          for (std::vector<std::string>::iterator I = symbols.begin(), 
+          for (std::vector<std::string>::iterator I = symbols.begin(),
                E=symbols.end(); I != E; ++I ) {
-            symTab.insert(std::make_pair(*I,offset));
+            symTab.insert(std::make_pair(*I, offset));
           }
           // Insert the ModuleProvider and the ArchiveMember into the table of
           // modules.
-          modules.insert(std::make_pair(offset,std::make_pair(MP,mbr)));
+          modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
         } else {
           throw std::string("Can't parse bytecode member: ") +
-            mbr->getPath().get();
+            mbr->getPath().toString();
         }
       }
 
       // Go to the next file location
       At += mbr->getSize();
-      if ((mbr->getSize() & 1) == 1)
+      if ((intptr_t(At) & 1) == 1)
         At++;
     }
   }
 
-  // At this point we have a valid symbol table (one way or another) so we 
+  // At this point we have a valid symbol table (one way or another) so we
   // just use it to quickly find the symbols requested.
 
-  for (std::set<std::string>::const_iterator I=symbols.begin(), 
-       E=symbols.end(); I != E; ++I) {
+  for (std::set<std::string>::iterator I=symbols.begin(),
+       E=symbols.end(); I != E;) {
+    // See if this symbol exists
     ModuleProvider* mp = findModuleDefiningSymbol(*I);
     if (mp) {
+      // The symbol exists, insert the ModuleProvider into our result,
+      // duplicates wil be ignored
       result.insert(mp);
+
+      // Remove the symbol now that its been resolved, being careful to
+      // post-increment the iterator.
+      symbols.erase(I++);
+    } else {
+      ++I;
     }
   }
 }
+
+bool Archive::isBytecodeArchive() {
+  // Make sure the symTab has been loaded. In most cases this should have been
+  // done when the archive was constructed, but still,  this is just in case.
+  if (!symTab.size())
+    loadSymbolTable();
+
+  // Now that we know it's been loaded, return true
+  // if it has a size
+  if (symTab.size()) return true;
+
+  //We still can't be sure it isn't a bytecode archive
+  loadArchive();
+
+  std::vector<Module *> Modules;
+  std::string ErrorMessage;
+
+  // Scan the archive, trying to load a bytecode member.  We only load one to
+  // see if this works.
+  for (iterator I = begin(), E = end(); I != E; ++I) {
+    if (!I->isBytecode() && !I->isCompressedBytecode())
+      continue;
+    
+    std::string FullMemberName = 
+      archPath.toString() + "(" + I->getPath().toString() + ")";
+    Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
+                                    I->getSize(), FullMemberName);
+    if (!M)
+      return false;  // Couldn't parse bytecode, not a bytecode archive.
+    delete M;
+    return true;
+  }
+  
+  return false;
+}