1 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Builds up standard unix archive files (.a) containing LLVM bytecode.
12 //===----------------------------------------------------------------------===//
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"
22 static bool Bitcode = false;
24 /// Read a variable-bit-rate encoded unsigned integer
25 inline unsigned readInteger(const char*&At, const char*End){
32 Result |= (unsigned)((*At++) & 0x7F) << Shift;
34 } while (At[-1] & 0x80);
38 // Completely parse the Archive's symbol table and populate symTab member var.
40 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
41 const char* At = (const char*) data;
42 const char* End = At + size;
44 unsigned offset = readInteger(At, End);
47 *error = "Ran out of data reading vbr_uint for symtab offset!";
50 unsigned length = readInteger(At, End);
53 *error = "Ran out of data reading vbr_uint for symtab length!";
56 if (At + length > End) {
58 *error = "Malformed symbol table: length not consistent with size";
61 // we don't care if it can't be inserted (duplicate entry)
62 symTab.insert(std::make_pair(std::string(At, length), offset));
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.
73 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
75 if (At + sizeof(ArchiveMemberHeader) >= End) {
77 *error = "Unexpected end of file";
81 // Cast archive member header
82 ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
83 At += sizeof(ArchiveMemberHeader);
85 // Extract the size and determine if the file is
86 // compressed or not (negative length).
88 int MemberSize = atoi(Hdr->size);
90 flags |= ArchiveMember::CompressedFlag;
91 MemberSize = -MemberSize;
94 // Check the size of the member for sanity
95 if (At + MemberSize > End) {
97 *error = "invalid member length in archive file";
101 // Check the member signature
102 if (!Hdr->checkSignature()) {
104 *error = "invalid file member signature";
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
119 std::string pathname;
120 switch (Hdr->name[0]) {
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);
128 flags |= ArchiveMember::HasLongFilenameFlag;
131 *error = "invalid long filename";
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;
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;
153 *error = "invalid string table name";
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;
162 *error = "invalid SVR4 symbol table name";
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;
173 if (*p == '\n' && *last_p == '/') {
174 pathname.assign(namep, last_p - namep);
175 flags |= ArchiveMember::HasLongFilenameFlag;
183 *error = "missing name termiantor in string table";
188 *error = "name index beyond string table";
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;
203 char* slash = (char*) memchr(Hdr->name, '/', 16);
205 slash = Hdr->name + 16;
206 pathname.assign(Hdr->name, slash - Hdr->name);
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;
216 case sys::CompressedBytecode_FileType:
217 flags |= ArchiveMember::CompressedBytecodeFlag;
218 flags &= ~ArchiveMember::CompressedFlag;
221 flags &= ~(ArchiveMember::BytecodeFlag|
222 ArchiveMember::CompressedBytecodeFlag);
226 // Instantiate the ArchiveMember to be filled
227 ArchiveMember* member = new ArchiveMember(this);
229 // Fill in fields of the ArchiveMember
232 member->parent = this;
233 member->path.set(pathname);
234 member->info.fileSize = MemberSize;
235 member->info.modTime.fromEpochTime(atoi(Hdr->date));
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;
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)) {
252 *error = "invalid signature for an archive file";
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.
262 Archive::loadArchive(std::string* error) {
267 const char *At = base;
268 const char *End = base + mapfile->size();
270 if (!checkSignature(error))
273 At += 8; // Skip the magic string.
275 bool seenSymbolTable = false;
276 bool foundFirstFile = false;
278 // parse the member header
279 const char* Save = At;
280 ArchiveMember* mbr = parseMemberHeader(At, End, error);
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".
289 // What? Multiple foreign symbol tables? Just chuck it
290 // and retain the last one found.
294 At += mbr->getSize();
295 if ((intptr_t(At) & 1) == 1)
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)
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) {
312 *error = "invalid archive: multiple symbol tables";
315 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
317 seenSymbolTable = true;
318 At += mbr->getSize();
319 if ((intptr_t(At) & 1) == 1)
321 delete mbr; // We don't need this member in the list of members.
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;
329 members.push_back(mbr);
330 At += mbr->getSize();
331 if ((intptr_t(At) & 1) == 1)
338 // Open and completely load the archive file.
340 Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage)
342 std::auto_ptr<Archive> result ( new Archive(file));
343 if (result->mapToMemory(ErrorMessage))
345 if (!result->loadArchive(ErrorMessage))
347 return result.release();
350 // Get all the bytecode modules from the archive
352 Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
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() + ")";
361 MemoryBuffer *Buffer =
362 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
363 memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
365 M = ParseBitcodeFile(Buffer, ErrMessage);
368 M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
369 I->getSize(), FullMemberName,
370 Compressor::decompressToNewBuffer,
376 Modules.push_back(M);
382 // Load just the symbol table from the archive file
384 Archive::loadSymbolTable(std::string* ErrorMsg) {
389 const char *At = base;
390 const char *End = base + mapfile->size();
392 // Make sure we're dealing with an archive
393 if (!checkSignature(ErrorMsg))
396 At += 8; // Skip signature
398 // Parse the first file member header
399 const char* FirstFile = At;
400 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
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)
413 mbr = parseMemberHeader(At, End, ErrorMsg);
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)
429 mbr = parseMemberHeader(At, End, ErrorMsg);
436 // See if its the symbol table
437 if (mbr->isLLVMSymbolTable()) {
438 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
443 At += mbr->getSize();
444 if ((intptr_t(At) & 1) == 1)
447 // Can't be any more symtab headers so just advance
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);
457 firstFileOffset = FirstFile - base;
461 // Open the archive and load just the symbol tables
463 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
464 std::auto_ptr<Archive> result ( new Archive(file) );
465 if (result->mapToMemory(ErrorMessage))
467 if (!result->loadSymbolTable(ErrorMessage))
469 return result.release();
472 // Look up one symbol in the symbol table and return a ModuleProvider for the
473 // module that defines that symbol.
475 Archive::findModuleDefiningSymbol(const std::string& symbol,
476 std::string* ErrMsg) {
477 SymTabType::iterator SI = symTab.find(symbol);
478 if (SI == symTab.end())
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
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;
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);
502 // Now, load the bytecode module to get the ModuleProvider
503 std::string FullMemberName = archPath.toString() + "(" +
504 mbr->getPath().toString() + ")";
507 MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(),
508 FullMemberName.c_str());
509 memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
511 mp = getBitcodeModuleProvider(Buffer, ErrMsg);
513 mp = getBytecodeBufferModuleProvider(
514 (const unsigned char*) mbr->getData(), mbr->getSize(),
515 FullMemberName, Decompressor, ErrMsg, 0);
519 modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
524 // Look up multiple symbols in the symbol table and return a set of
525 // ModuleProviders that define those symbols.
527 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
528 std::set<ModuleProvider*>& result,
529 std::string* error) {
530 if (!mapfile || !base) {
532 *error = "Empty archive invalid for finding modules defining symbols";
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
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();
547 // Compute the offset to be put in the symbol table
548 unsigned offset = At - base - firstFileOffset;
550 // Parse the file's header
551 ArchiveMember* mbr = parseMemberHeader(At, End, error);
555 // If it contains symbols
556 if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
558 std::vector<std::string> symbols;
559 std::string FullMemberName = archPath.toString() + "(" +
560 mbr->getPath().toString() + ")";
562 GetBytecodeSymbols((const unsigned char*)At, mbr->getSize(),
563 FullMemberName, symbols,
564 Compressor::decompressToNewBuffer, error);
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));
572 // Insert the ModuleProvider and the ArchiveMember into the table of
574 modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
577 *error = "Can't parse bytecode member: " +
578 mbr->getPath().toString() + ": " + *error;
584 // Go to the next file location
585 At += mbr->getSize();
586 if ((intptr_t(At) & 1) == 1)
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.
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);
599 // The symbol exists, insert the ModuleProvider into our result,
600 // duplicates wil be ignored
603 // Remove the symbol now that its been resolved, being careful to
604 // post-increment the iterator.
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.
617 if (!loadSymbolTable(0))
620 // Now that we know it's been loaded, return true
622 if (symTab.size()) return true;
624 //We still can't be sure it isn't a bytecode archive
628 std::vector<Module *> Modules;
629 std::string ErrorMessage;
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())
637 std::string FullMemberName =
638 archPath.toString() + "(" + I->getPath().toString() + ")";
642 MemoryBuffer *Buffer =
643 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
644 memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
645 M = ParseBitcodeFile(Buffer);
648 M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
649 I->getSize(), FullMemberName);
652 return false; // Couldn't parse bytecode, not a bytecode archive.