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/Bitcode/ReaderWriter.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Module.h"
21 /// Read a variable-bit-rate encoded unsigned integer
22 inline unsigned readInteger(const char*&At, const char*End){
29 Result |= (unsigned)((*At++) & 0x7F) << Shift;
31 } while (At[-1] & 0x80);
35 // Completely parse the Archive's symbol table and populate symTab member var.
37 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
38 const char* At = (const char*) data;
39 const char* End = At + size;
41 unsigned offset = readInteger(At, End);
44 *error = "Ran out of data reading vbr_uint for symtab offset!";
47 unsigned length = readInteger(At, End);
50 *error = "Ran out of data reading vbr_uint for symtab length!";
53 if (At + length > End) {
55 *error = "Malformed symbol table: length not consistent with size";
58 // we don't care if it can't be inserted (duplicate entry)
59 symTab.insert(std::make_pair(std::string(At, length), offset));
66 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
67 // by At. The At pointer is updated to the byte just after the header, which
68 // can be variable in size.
70 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
72 if (At + sizeof(ArchiveMemberHeader) >= End) {
74 *error = "Unexpected end of file";
78 // Cast archive member header
79 ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
80 At += sizeof(ArchiveMemberHeader);
82 // Extract the size and determine if the file is
83 // compressed or not (negative length).
85 int MemberSize = atoi(Hdr->size);
87 flags |= ArchiveMember::CompressedFlag;
88 MemberSize = -MemberSize;
91 // Check the size of the member for sanity
92 if (At + MemberSize > End) {
94 *error = "invalid member length in archive file";
98 // Check the member signature
99 if (!Hdr->checkSignature()) {
101 *error = "invalid file member signature";
105 // Convert and check the member name
106 // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
107 // table. The special name "//" and 14 blanks is for a string table, used
108 // for long file names. This library doesn't generate either of those but
109 // it will accept them. If the name starts with #1/ and the remainder is
110 // digits, then those digits specify the length of the name that is
111 // stored immediately following the header. The special name
112 // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bytecode.
113 // Anything else is a regular, short filename that is terminated with
116 std::string pathname;
117 switch (Hdr->name[0]) {
119 if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
120 if (isdigit(Hdr->name[3])) {
121 unsigned len = atoi(&Hdr->name[3]);
122 pathname.assign(At, len);
125 flags |= ArchiveMember::HasLongFilenameFlag;
128 *error = "invalid long filename";
131 } else if (Hdr->name[1] == '_' &&
132 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
133 // The member is using a long file name (>15 chars) format.
134 // This format is standard for 4.4BSD and Mac OSX operating
135 // systems. LLVM uses it similarly. In this format, the
136 // remainder of the name field (after #1/) specifies the
137 // length of the file name which occupy the first bytes of
138 // the member's data. The pathname already has the #1/ stripped.
139 pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
140 flags |= ArchiveMember::LLVMSymbolTableFlag;
144 if (Hdr->name[1]== '/') {
145 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
146 pathname.assign(ARFILE_STRTAB_NAME);
147 flags |= ArchiveMember::StringTableFlag;
150 *error = "invalid string table name";
153 } else if (Hdr->name[1] == ' ') {
154 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
155 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
156 flags |= ArchiveMember::SVR4SymbolTableFlag;
159 *error = "invalid SVR4 symbol table name";
162 } else if (isdigit(Hdr->name[1])) {
163 unsigned index = atoi(&Hdr->name[1]);
164 if (index < strtab.length()) {
165 const char* namep = strtab.c_str() + index;
166 const char* endp = strtab.c_str() + strtab.length();
167 const char* p = namep;
168 const char* last_p = p;
170 if (*p == '\n' && *last_p == '/') {
171 pathname.assign(namep, last_p - namep);
172 flags |= ArchiveMember::HasLongFilenameFlag;
180 *error = "missing name termiantor in string table";
185 *error = "name index beyond string table";
191 if (Hdr->name[1] == '_' &&
192 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
193 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
194 flags |= ArchiveMember::BSD4SymbolTableFlag;
200 char* slash = (char*) memchr(Hdr->name, '/', 16);
202 slash = Hdr->name + 16;
203 pathname.assign(Hdr->name, slash - Hdr->name);
207 // Determine if this is a bytecode file
208 switch (sys::IdentifyFileType(At, 4)) {
209 case sys::Bitcode_FileType:
210 case sys::Bytecode_FileType:
211 flags |= ArchiveMember::BytecodeFlag;
213 case sys::CompressedBytecode_FileType:
214 flags |= ArchiveMember::CompressedBytecodeFlag;
215 flags &= ~ArchiveMember::CompressedFlag;
218 flags &= ~(ArchiveMember::BytecodeFlag|
219 ArchiveMember::CompressedBytecodeFlag);
223 // Instantiate the ArchiveMember to be filled
224 ArchiveMember* member = new ArchiveMember(this);
226 // Fill in fields of the ArchiveMember
229 member->parent = this;
230 member->path.set(pathname);
231 member->info.fileSize = MemberSize;
232 member->info.modTime.fromEpochTime(atoi(Hdr->date));
234 sscanf(Hdr->mode, "%o", &mode);
235 member->info.mode = mode;
236 member->info.user = atoi(Hdr->uid);
237 member->info.group = atoi(Hdr->gid);
238 member->flags = flags;
245 Archive::checkSignature(std::string* error) {
246 // Check the magic string at file's header
247 if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
249 *error = "invalid signature for an archive file";
255 // This function loads the entire archive and fully populates its ilist with
256 // the members of the archive file. This is typically used in preparation for
257 // editing the contents of the archive.
259 Archive::loadArchive(std::string* error) {
264 const char *At = base;
265 const char *End = base + mapfile->size();
267 if (!checkSignature(error))
270 At += 8; // Skip the magic string.
272 bool seenSymbolTable = false;
273 bool foundFirstFile = false;
275 // parse the member header
276 const char* Save = At;
277 ArchiveMember* mbr = parseMemberHeader(At, End, error);
281 // check if this is the foreign symbol table
282 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
283 // We just save this but don't do anything special
284 // with it. It doesn't count as the "first file".
286 // What? Multiple foreign symbol tables? Just chuck it
287 // and retain the last one found.
291 At += mbr->getSize();
292 if ((intptr_t(At) & 1) == 1)
294 } else if (mbr->isStringTable()) {
295 // Simply suck the entire string table into a string
296 // variable. This will be used to get the names of the
297 // members that use the "/ddd" format for their names
298 // (SVR4 style long names).
299 strtab.assign(At, mbr->getSize());
300 At += mbr->getSize();
301 if ((intptr_t(At) & 1) == 1)
304 } else if (mbr->isLLVMSymbolTable()) {
305 // This is the LLVM symbol table for the archive. If we've seen it
306 // already, its an error. Otherwise, parse the symbol table and move on.
307 if (seenSymbolTable) {
309 *error = "invalid archive: multiple symbol tables";
312 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
314 seenSymbolTable = true;
315 At += mbr->getSize();
316 if ((intptr_t(At) & 1) == 1)
318 delete mbr; // We don't need this member in the list of members.
320 // This is just a regular file. If its the first one, save its offset.
321 // Otherwise just push it on the list and move on to the next file.
322 if (!foundFirstFile) {
323 firstFileOffset = Save - base;
324 foundFirstFile = true;
326 members.push_back(mbr);
327 At += mbr->getSize();
328 if ((intptr_t(At) & 1) == 1)
335 // Open and completely load the archive file.
337 Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage)
339 std::auto_ptr<Archive> result ( new Archive(file));
340 if (result->mapToMemory(ErrorMessage))
342 if (!result->loadArchive(ErrorMessage))
344 return result.release();
347 // Get all the bytecode modules from the archive
349 Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
351 for (iterator I=begin(), E=end(); I != E; ++I) {
352 if (I->isBytecode() || I->isCompressedBytecode()) {
353 std::string FullMemberName = archPath.toString() +
354 "(" + I->getPath().toString() + ")";
355 MemoryBuffer *Buffer =
356 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
357 memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
359 Module *M = ParseBitcodeFile(Buffer, ErrMessage);
364 Modules.push_back(M);
370 // Load just the symbol table from the archive file
372 Archive::loadSymbolTable(std::string* ErrorMsg) {
377 const char *At = base;
378 const char *End = base + mapfile->size();
380 // Make sure we're dealing with an archive
381 if (!checkSignature(ErrorMsg))
384 At += 8; // Skip signature
386 // Parse the first file member header
387 const char* FirstFile = At;
388 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
392 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
393 // Skip the foreign symbol table, we don't do anything with it
394 At += mbr->getSize();
395 if ((intptr_t(At) & 1) == 1)
401 mbr = parseMemberHeader(At, End, ErrorMsg);
408 if (mbr->isStringTable()) {
409 // Process the string table entry
410 strtab.assign((const char*)mbr->getData(), mbr->getSize());
411 At += mbr->getSize();
412 if ((intptr_t(At) & 1) == 1)
417 mbr = parseMemberHeader(At, End, ErrorMsg);
424 // See if its the symbol table
425 if (mbr->isLLVMSymbolTable()) {
426 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
431 At += mbr->getSize();
432 if ((intptr_t(At) & 1) == 1)
435 // Can't be any more symtab headers so just advance
438 // There's no symbol table in the file. We have to rebuild it from scratch
439 // because the intent of this method is to get the symbol table loaded so
440 // it can be searched efficiently.
441 // Add the member to the members list
442 members.push_back(mbr);
445 firstFileOffset = FirstFile - base;
449 // Open the archive and load just the symbol tables
451 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
452 std::auto_ptr<Archive> result ( new Archive(file) );
453 if (result->mapToMemory(ErrorMessage))
455 if (!result->loadSymbolTable(ErrorMessage))
457 return result.release();
460 // Look up one symbol in the symbol table and return a ModuleProvider for the
461 // module that defines that symbol.
463 Archive::findModuleDefiningSymbol(const std::string& symbol,
464 std::string* ErrMsg) {
465 SymTabType::iterator SI = symTab.find(symbol);
466 if (SI == symTab.end())
469 // The symbol table was previously constructed assuming that the members were
470 // written without the symbol table header. Because VBR encoding is used, the
471 // values could not be adjusted to account for the offset of the symbol table
472 // because that could affect the size of the symbol table due to VBR encoding.
473 // We now have to account for this by adjusting the offset by the size of the
474 // symbol table and its header.
475 unsigned fileOffset =
476 SI->second + // offset in symbol-table-less file
477 firstFileOffset; // add offset to first "real" file in archive
479 // See if the module is already loaded
480 ModuleMap::iterator MI = modules.find(fileOffset);
481 if (MI != modules.end())
482 return MI->second.first;
484 // Module hasn't been loaded yet, we need to load it
485 const char* modptr = base + fileOffset;
486 ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size(),ErrMsg);
490 // Now, load the bytecode module to get the ModuleProvider
491 std::string FullMemberName = archPath.toString() + "(" +
492 mbr->getPath().toString() + ")";
493 MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(),
494 FullMemberName.c_str());
495 memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
497 ModuleProvider *mp = getBitcodeModuleProvider(Buffer, ErrMsg);
501 modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
506 // Look up multiple symbols in the symbol table and return a set of
507 // ModuleProviders that define those symbols.
509 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
510 std::set<ModuleProvider*>& result,
511 std::string* error) {
512 if (!mapfile || !base) {
514 *error = "Empty archive invalid for finding modules defining symbols";
518 if (symTab.empty()) {
519 // We don't have a symbol table, so we must build it now but lets also
520 // make sure that we populate the modules table as we do this to ensure
521 // that we don't load them twice when findModuleDefiningSymbol is called
524 // Get a pointer to the first file
525 const char* At = ((const char*)base) + firstFileOffset;
526 const char* End = ((const char*)base) + mapfile->size();
529 // Compute the offset to be put in the symbol table
530 unsigned offset = At - base - firstFileOffset;
532 // Parse the file's header
533 ArchiveMember* mbr = parseMemberHeader(At, End, error);
537 // If it contains symbols
538 if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
540 std::vector<std::string> symbols;
541 std::string FullMemberName = archPath.toString() + "(" +
542 mbr->getPath().toString() + ")";
544 GetBytecodeSymbols((const unsigned char*)At, mbr->getSize(),
545 FullMemberName, symbols, error);
548 // Insert the module's symbols into the symbol table
549 for (std::vector<std::string>::iterator I = symbols.begin(),
550 E=symbols.end(); I != E; ++I ) {
551 symTab.insert(std::make_pair(*I, offset));
553 // Insert the ModuleProvider and the ArchiveMember into the table of
555 modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
558 *error = "Can't parse bytecode member: " +
559 mbr->getPath().toString() + ": " + *error;
565 // Go to the next file location
566 At += mbr->getSize();
567 if ((intptr_t(At) & 1) == 1)
572 // At this point we have a valid symbol table (one way or another) so we
573 // just use it to quickly find the symbols requested.
575 for (std::set<std::string>::iterator I=symbols.begin(),
576 E=symbols.end(); I != E;) {
577 // See if this symbol exists
578 ModuleProvider* mp = findModuleDefiningSymbol(*I,error);
580 // The symbol exists, insert the ModuleProvider into our result,
581 // duplicates wil be ignored
584 // Remove the symbol now that its been resolved, being careful to
585 // post-increment the iterator.
594 bool Archive::isBytecodeArchive() {
595 // Make sure the symTab has been loaded. In most cases this should have been
596 // done when the archive was constructed, but still, this is just in case.
598 if (!loadSymbolTable(0))
601 // Now that we know it's been loaded, return true
603 if (symTab.size()) return true;
605 //We still can't be sure it isn't a bytecode archive
609 std::vector<Module *> Modules;
610 std::string ErrorMessage;
612 // Scan the archive, trying to load a bytecode member. We only load one to
613 // see if this works.
614 for (iterator I = begin(), E = end(); I != E; ++I) {
615 if (!I->isBytecode() && !I->isCompressedBytecode())
618 std::string FullMemberName =
619 archPath.toString() + "(" + I->getPath().toString() + ")";
621 MemoryBuffer *Buffer =
622 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
623 memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
624 Module *M = ParseBitcodeFile(Buffer);
627 return false; // Couldn't parse bytecode, not a bytecode archive.