X-Git-Url: http://demsky.eecs.uci.edu/git/?a=blobdiff_plain;f=lib%2FArchive%2FArchiveReader.cpp;h=718d44608b1d262db4363bffc357ea111b3c2db5;hb=401e10c4fbfcdcfade5065093e2ca97f69a1d144;hp=56b42ffdb2e521815391c0069d63b7bdfc400cd4;hpb=56127624e7b31c1c2477b10fae207f2991eeb72c;p=oota-llvm.git diff --git a/lib/Archive/ArchiveReader.cpp b/lib/Archive/ArchiveReader.cpp index 56b42ffdb2e..718d44608b1 100644 --- a/lib/Archive/ArchiveReader.cpp +++ b/lib/Archive/ArchiveReader.cpp @@ -1,29 +1,32 @@ //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===// -// +// // The LLVM Compiler Infrastructure // -// This file was developed by Reid Spencer and is distributed under the -// University of Illinois Open Source License. See LICENSE.TXT for details. -// +// This file 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. +// Builds up standard unix archive files (.a) containing LLVM bitcode. // //===----------------------------------------------------------------------===// #include "ArchiveInternals.h" -#include "llvm/Bytecode/Reader.h" - +#include "llvm/Bitcode/ReaderWriter.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Module.h" +#include +#include using namespace llvm; /// Read a variable-bit-rate encoded unsigned integer -inline unsigned readInteger(const char*&At, const char*End) { +static inline unsigned readInteger(const char*&At, const char*End) { unsigned Shift = 0; unsigned Result = 0; - + do { - if (At == End) - throw std::string("Ran out of data reading vbr_uint!"); + if (At == End) + return Result; Result |= (unsigned)((*At++) & 0x7F) << Shift; Shift += 7; } while (At[-1] & 0x80); @@ -31,37 +34,53 @@ inline unsigned readInteger(const char*&At, const char*End) { } // Completely parse the Archive's symbol table and populate symTab member var. -void -Archive::parseSymbolTable(const void* data, unsigned size) { +bool +Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) { const char* At = (const char*) data; const char* End = At + size; while (At < End) { unsigned offset = readInteger(At, End); + if (At == End) { + if (error) + *error = "Ran out of data reading vbr_uint for symtab offset!"; + return false; + } unsigned length = readInteger(At, End); - if (At + length > End) - throw std::string("malformed symbol table"); + if (At == End) { + if (error) + *error = "Ran out of data reading vbr_uint for symtab length!"; + return false; + } + if (At + length > End) { + if (error) + *error = "Malformed symbol table: length not consistent with size"; + return false; + } // we don't care if it can't be inserted (duplicate entry) symTab.insert(std::make_pair(std::string(At, length), offset)); At += length; } symTabSize = size; + return true; } // 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"); +Archive::parseMemberHeader(const char*& At, const char* End, std::string* error) +{ + if (At + sizeof(ArchiveMemberHeader) >= End) { + if (error) + *error = "Unexpected end of file"; + return 0; + } // Cast archive member header ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At; At += sizeof(ArchiveMemberHeader); - // 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); @@ -71,22 +90,28 @@ Archive::parseMemberHeader(const char*& At, const char* End) { } // Check the size of the member for sanity - if (At + MemberSize > End) - throw std::string("invalid member length in archive file"); + if (At + MemberSize > End) { + if (error) + *error = "invalid member length in archive file"; + return 0; + } // Check the member signature - if (!Hdr->checkSignature()) - throw std::string("invalid file member signature"); + if (!Hdr->checkSignature()) { + if (error) + *error = "invalid file member signature"; + return 0; + } // 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 bitcode. + // Anything else is a regular, short filename that is terminated with // a '/' and blanks. std::string pathname; @@ -99,9 +124,12 @@ Archive::parseMemberHeader(const char*& At, const char* End) { At += len; MemberSize -= len; flags |= ArchiveMember::HasLongFilenameFlag; - } else - throw std::string("invalid long filename"); - } else if (Hdr->name[1] == '_' && + } else { + if (error) + *error = "invalid long filename"; + return 0; + } + } 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 @@ -119,14 +147,18 @@ Archive::parseMemberHeader(const char*& At, const char* End) { pathname.assign(ARFILE_STRTAB_NAME); flags |= ArchiveMember::StringTableFlag; } else { - throw std::string("invalid string table name"); + if (error) + *error = "invalid string table name"; + return 0; } } else if (Hdr->name[1] == ' ') { if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) { pathname.assign(ARFILE_SVR4_SYMTAB_NAME); flags |= ArchiveMember::SVR4SymbolTableFlag; } else { - throw std::string("invalid SVR4 symbol table name"); + if (error) + *error = "invalid SVR4 symbol table name"; + return 0; } } else if (isdigit(Hdr->name[1])) { unsigned index = atoi(&Hdr->name[1]); @@ -144,15 +176,20 @@ Archive::parseMemberHeader(const char*& At, const char* End) { last_p = p; p++; } - if (p >= endp) - throw std::string("missing name termiantor in string table"); + if (p >= endp) { + if (error) + *error = "missing name termiantor in string table"; + return 0; + } } else { - throw std::string("name index beyond string table"); + if (error) + *error = "name index beyond string table"; + return 0; } } break; case '_': - if (Hdr->name[1] == '_' && + if (Hdr->name[1] == '_' && (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) { pathname.assign(ARFILE_BSD4_SYMTAB_NAME); flags |= ArchiveMember::BSD4SymbolTableFlag; @@ -168,26 +205,22 @@ Archive::parseMemberHeader(const char*& At, const char* End) { break; } - // Determine if this is a bytecode file + // Determine if this is a bitcode file switch (sys::IdentifyFileType(At, 4)) { - case sys::BytecodeFileType: - flags |= ArchiveMember::BytecodeFlag; - break; - case sys::CompressedBytecodeFileType: - flags |= ArchiveMember::CompressedBytecodeFlag; - flags &= ~ArchiveMember::CompressedFlag; + case sys::Bitcode_FileType: + flags |= ArchiveMember::BitcodeFlag; break; default: - flags &= ~(ArchiveMember::BytecodeFlag| - ArchiveMember::CompressedBytecodeFlag); + flags &= ~ArchiveMember::BitcodeFlag; break; } + // Instantiate the ArchiveMember to be filled + ArchiveMember* member = new ArchiveMember(this); + // Fill in fields of the ArchiveMember - 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)); unsigned int mode; @@ -201,34 +234,42 @@ Archive::parseMemberHeader(const char*& At, const char* End) { return member; } -void -Archive::checkSignature() { +bool +Archive::checkSignature(std::string* error) { // Check the magic string at file's header - if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC, 8)) - throw std::string("invalid signature for an archive file"); + if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) { + if (error) + *error = "invalid signature for an archive file"; + return false; + } + return true; } -// 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 -Archive::loadArchive() { +bool +Archive::loadArchive(std::string* error) { // Set up parsing members.clear(); symTab.clear(); const char *At = base; - const char *End = base + mapfile->size(); + const char *End = mapfile->getBufferEnd(); + + if (!checkSignature(error)) + return false; - checkSignature(); At += 8; // Skip the magic string. 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); + ArchiveMember* mbr = parseMemberHeader(At, End, error); + if (!mbr) + return false; // check if this is the foreign symbol table if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) { @@ -253,12 +294,16 @@ Archive::loadArchive() { 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()); + if (seenSymbolTable) { + if (error) + *error = "invalid archive: multiple symbol tables"; + return false; + } + if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error)) + return false; seenSymbolTable = true; At += mbr->getSize(); if ((intptr_t(At) & 1) == 1) @@ -277,33 +322,36 @@ Archive::loadArchive() { At++; } } + return true; } // Open and completely load the archive file. Archive* -Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage) { - try { - std::auto_ptr result ( new Archive(file, true)); - result->loadArchive(); - return result.release(); - } catch (const std::string& msg) { - if (ErrorMessage) { - *ErrorMessage = msg; - } +Archive::OpenAndLoad(const sys::Path& file, LLVMContext& C, + std::string* ErrorMessage) { + std::auto_ptr result ( new Archive(file, C)); + if (result->mapToMemory(ErrorMessage)) return 0; - } + if (!result->loadArchive(ErrorMessage)) + return 0; + return result.release(); } -// Get all the bytecode modules from the archive +// Get all the bitcode modules from the archive bool -Archive::getAllModules(std::vector& Modules, std::string* ErrMessage) { +Archive::getAllModules(std::vector& Modules, + std::string* ErrMessage) { for (iterator I=begin(), E=end(); I != E; ++I) { - if (I->isBytecode() || I->isCompressedBytecode()) { - std::string FullMemberName = archPath.toString() + + if (I->isBitcode()) { + std::string FullMemberName = archPath.toString() + "(" + I->getPath().toString() + ")"; - Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(), - I->getSize(), FullMemberName, ErrMessage); + MemoryBuffer *Buffer = + MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str()); + memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize()); + + Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage); + delete Buffer; if (!M) return true; @@ -314,23 +362,26 @@ Archive::getAllModules(std::vector& Modules, std::string* ErrMessage) { } // Load just the symbol table from the archive file -void -Archive::loadSymbolTable() { +bool +Archive::loadSymbolTable(std::string* ErrorMsg) { // Set up parsing members.clear(); symTab.clear(); const char *At = base; - const char *End = base + mapfile->size(); + const char *End = mapfile->getBufferEnd(); // Make sure we're dealing with an archive - checkSignature(); + if (!checkSignature(ErrorMsg)) + return false; At += 8; // Skip signature // Parse the first file member header const char* FirstFile = At; - ArchiveMember* mbr = parseMemberHeader(At, End); + ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg); + if (!mbr) + return false; if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) { // Skip the foreign symbol table, we don't do anything with it @@ -341,7 +392,11 @@ Archive::loadSymbolTable() { // Read the next one FirstFile = At; - mbr = parseMemberHeader(At, End); + mbr = parseMemberHeader(At, End, ErrorMsg); + if (!mbr) { + delete mbr; + return false; + } } if (mbr->isStringTable()) { @@ -353,57 +408,66 @@ Archive::loadSymbolTable() { delete mbr; // Get the next one FirstFile = At; - mbr = parseMemberHeader(At, End); + mbr = parseMemberHeader(At, End, ErrorMsg); + if (!mbr) { + delete mbr; + return false; + } } // See if its the symbol table if (mbr->isLLVMSymbolTable()) { - parseSymbolTable(mbr->getData(), mbr->getSize()); + if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) { + delete mbr; + return false; + } + At += mbr->getSize(); if ((intptr_t(At) & 1) == 1) At++; + delete mbr; + // Can't be any more symtab headers so just advance 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); } firstFileOffset = FirstFile - base; + return true; } // Open the archive and load just the symbol tables -Archive* -Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) { - try { - std::auto_ptr result ( new Archive(file, true) ); - result->loadSymbolTable(); - return result.release(); - } catch (const std::string& msg) { - if (ErrorMessage) { - *ErrorMessage = msg; - } +Archive* Archive::OpenAndLoadSymbols(const sys::Path& file, + LLVMContext& C, + std::string* ErrorMessage) { + std::auto_ptr result ( new Archive(file, C) ); + if (result->mapToMemory(ErrorMessage)) return 0; - } + if (!result->loadSymbolTable(ErrorMessage)) + return 0; + return result.release(); } // Look up one symbol in the symbol table and return a ModuleProvider for the // module that defines that symbol. -ModuleProvider* -Archive::findModuleDefiningSymbol(const std::string& symbol) { +ModuleProvider* +Archive::findModuleDefiningSymbol(const std::string& symbol, + std::string* ErrMsg) { 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 @@ -414,27 +478,39 @@ Archive::findModuleDefiningSymbol(const std::string& symbol) { // Module hasn't been loaded yet, we need to load it const char* modptr = base + fileOffset; - ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size()); + ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(), + ErrMsg); + if (!mbr) + return 0; - // Now, load the bytecode module to get the ModuleProvider - std::string FullMemberName = archPath.toString() + "(" + + // Now, load the bitcode module to get the ModuleProvider + std::string FullMemberName = archPath.toString() + "(" + mbr->getPath().toString() + ")"; - ModuleProvider* mp = getBytecodeBufferModuleProvider( - (const unsigned char*) mbr->getData(), mbr->getSize(), - FullMemberName, 0); + MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(), + FullMemberName.c_str()); + memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize()); + + ModuleProvider *mp = getBitcodeModuleProvider(Buffer, Context, ErrMsg); + if (!mp) + return 0; 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 +bool Archive::findModulesDefiningSymbols(std::set& symbols, - std::set& result) -{ - assert(mapfile && base && "Can't findModulesDefiningSymbols on new archive"); + std::set& result, + std::string* error) { + if (!mapfile || !base) { + if (error) + *error = "Empty archive invalid for finding modules defining symbols"; + return false; + } + if (symTab.empty()) { // We don't have a symbol table, so we must build it now but lets also // make sure that we populate the modules table as we do this to ensure @@ -442,28 +518,31 @@ Archive::findModulesDefiningSymbols(std::set& symbols, // below. // Get a pointer to the first file - const char* At = ((const char*)base) + firstFileOffset; - const char* End = ((const char*)base) + mapfile->size(); + const char* At = base + firstFileOffset; + const char* End = mapfile->getBufferEnd(); while ( At < End) { // Compute the offset to be put in the symbol table unsigned offset = At - base - firstFileOffset; // Parse the file's header - ArchiveMember* mbr = parseMemberHeader(At, End); + ArchiveMember* mbr = parseMemberHeader(At, End, error); + if (!mbr) + return false; // If it contains symbols - if (mbr->isBytecode() || mbr->isCompressedBytecode()) { - // Get the symbols + if (mbr->isBitcode()) { + // Get the symbols std::vector symbols; - std::string FullMemberName = archPath.toString() + "(" + + std::string FullMemberName = archPath.toString() + "(" + mbr->getPath().toString() + ")"; - ModuleProvider* MP = GetBytecodeSymbols((const unsigned char*)At, - mbr->getSize(), FullMemberName, symbols); + ModuleProvider* MP = + GetBitcodeSymbols((const unsigned char*)At, mbr->getSize(), + FullMemberName, Context, symbols, error); if (MP) { // Insert the module's symbols into the symbol table - for (std::vector::iterator I = symbols.begin(), + for (std::vector::iterator I = symbols.begin(), E=symbols.end(); I != E; ++I ) { symTab.insert(std::make_pair(*I, offset)); } @@ -471,8 +550,11 @@ Archive::findModulesDefiningSymbols(std::set& symbols, // modules. modules.insert(std::make_pair(offset, std::make_pair(MP, mbr))); } else { - throw std::string("Can't parse bytecode member: ") + - mbr->getPath().toString(); + if (error) + *error = "Can't parse bitcode member: " + + mbr->getPath().toString() + ": " + *error; + delete mbr; + return false; } } @@ -483,23 +565,65 @@ Archive::findModulesDefiningSymbols(std::set& symbols, } } - // 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::iterator I=symbols.begin(), + for (std::set::iterator I=symbols.begin(), E=symbols.end(); I != E;) { // See if this symbol exists - ModuleProvider* mp = findModuleDefiningSymbol(*I); + ModuleProvider* mp = findModuleDefiningSymbol(*I,error); 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 + // Remove the symbol now that its been resolved, being careful to // post-increment the iterator. symbols.erase(I++); } else { ++I; } } + return true; +} + +bool Archive::isBitcodeArchive() { + // 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.empty()) + if (!loadSymbolTable(0)) + return false; + + // 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 bitcode archive + if (!loadArchive(0)) + return false; + + std::vector Modules; + std::string ErrorMessage; + + // Scan the archive, trying to load a bitcode member. We only load one to + // see if this works. + for (iterator I = begin(), E = end(); I != E; ++I) { + if (!I->isBitcode()) + continue; + + std::string FullMemberName = + archPath.toString() + "(" + I->getPath().toString() + ")"; + + MemoryBuffer *Buffer = + MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str()); + memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize()); + Module *M = ParseBitcodeFile(Buffer, Context); + delete Buffer; + if (!M) + return false; // Couldn't parse bitcode, not a bitcode archive. + delete M; + return true; + } + + return false; }