1 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Builds up standard unix archive files (.a) containing LLVM bitcode.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/Archive.h"
15 #include "ArchiveInternals.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/MemoryBuffer.h"
25 /// Read a variable-bit-rate encoded unsigned integer
26 static inline unsigned readInteger(const char*&At, const char*End) {
33 Result |= (unsigned)((*At++) & 0x7F) << Shift;
35 } while (At[-1] & 0x80);
39 // Completely parse the Archive's symbol table and populate symTab member var.
41 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
42 const char* At = (const char*) data;
43 const char* End = At + size;
45 unsigned offset = readInteger(At, End);
48 *error = "Ran out of data reading vbr_uint for symtab offset!";
51 unsigned length = readInteger(At, End);
54 *error = "Ran out of data reading vbr_uint for symtab length!";
57 if (At + length > End) {
59 *error = "Malformed symbol table: length not consistent with size";
62 // we don't care if it can't be inserted (duplicate entry)
63 symTab.insert(std::make_pair(std::string(At, length), offset));
70 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
71 // by At. The At pointer is updated to the byte just after the header, which
72 // can be variable in size.
74 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
76 if (At + sizeof(ArchiveMemberHeader) >= End) {
78 *error = "Unexpected end of file";
82 // Cast archive member header
83 const ArchiveMemberHeader* Hdr = (const ArchiveMemberHeader*)At;
84 At += sizeof(ArchiveMemberHeader);
87 int MemberSize = atoi(Hdr->size);
88 assert(MemberSize >= 0);
90 // Check the size of the member for sanity
91 if (At + MemberSize > End) {
93 *error = "invalid member length in archive file";
97 // Check the member signature
98 if (!Hdr->checkSignature()) {
100 *error = "invalid file member signature";
104 // Convert and check the member name
105 // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
106 // table. The special name "//" and 14 blanks is for a string table, used
107 // for long file names. This library doesn't generate either of those but
108 // it will accept them. If the name starts with #1/ and the remainder is
109 // digits, then those digits specify the length of the name that is
110 // stored immediately following the header. The special name
111 // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bitcode.
112 // Anything else is a regular, short filename that is terminated with
115 std::string pathname;
116 switch (Hdr->name[0]) {
118 if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
119 if (isdigit(Hdr->name[3])) {
120 unsigned len = atoi(&Hdr->name[3]);
121 const char *nulp = (const char *)memchr(At, '\0', len);
122 pathname.assign(At, nulp != 0 ? (uintptr_t)(nulp - 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 terminator 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 const char* slash = (const char*) memchr(Hdr->name, '/', 16);
202 slash = Hdr->name + 16;
203 pathname.assign(Hdr->name, slash - Hdr->name);
207 // Determine if this is a bitcode file
208 switch (sys::IdentifyFileType(At, 4)) {
209 case sys::Bitcode_FileType:
210 flags |= ArchiveMember::BitcodeFlag;
213 flags &= ~ArchiveMember::BitcodeFlag;
217 // Instantiate the ArchiveMember to be filled
218 ArchiveMember* member = new ArchiveMember(this);
220 // Fill in fields of the ArchiveMember
221 member->parent = this;
222 member->path.set(pathname);
223 member->info.fileSize = MemberSize;
224 member->info.modTime.fromEpochTime(atoi(Hdr->date));
226 sscanf(Hdr->mode, "%o", &mode);
227 member->info.mode = mode;
228 member->info.user = atoi(Hdr->uid);
229 member->info.group = atoi(Hdr->gid);
230 member->flags = flags;
237 Archive::checkSignature(std::string* error) {
238 // Check the magic string at file's header
239 if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
241 *error = "invalid signature for an archive file";
247 // This function loads the entire archive and fully populates its ilist with
248 // the members of the archive file. This is typically used in preparation for
249 // editing the contents of the archive.
251 Archive::loadArchive(std::string* error) {
256 const char *At = base;
257 const char *End = mapfile->getBufferEnd();
259 if (!checkSignature(error))
262 At += 8; // Skip the magic string.
264 bool seenSymbolTable = false;
265 bool foundFirstFile = false;
267 // parse the member header
268 const char* Save = At;
269 ArchiveMember* mbr = parseMemberHeader(At, End, error);
273 // check if this is the foreign symbol table
274 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
275 // We just save this but don't do anything special
276 // with it. It doesn't count as the "first file".
278 // What? Multiple foreign symbol tables? Just chuck it
279 // and retain the last one found.
283 At += mbr->getSize();
284 if ((intptr_t(At) & 1) == 1)
286 } else if (mbr->isStringTable()) {
287 // Simply suck the entire string table into a string
288 // variable. This will be used to get the names of the
289 // members that use the "/ddd" format for their names
290 // (SVR4 style long names).
291 strtab.assign(At, mbr->getSize());
292 At += mbr->getSize();
293 if ((intptr_t(At) & 1) == 1)
296 } else if (mbr->isLLVMSymbolTable()) {
297 // This is the LLVM symbol table for the archive. If we've seen it
298 // already, its an error. Otherwise, parse the symbol table and move on.
299 if (seenSymbolTable) {
301 *error = "invalid archive: multiple symbol tables";
304 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
306 seenSymbolTable = true;
307 At += mbr->getSize();
308 if ((intptr_t(At) & 1) == 1)
310 delete mbr; // We don't need this member in the list of members.
312 // This is just a regular file. If its the first one, save its offset.
313 // Otherwise just push it on the list and move on to the next file.
314 if (!foundFirstFile) {
315 firstFileOffset = Save - base;
316 foundFirstFile = true;
318 members.push_back(mbr);
319 At += mbr->getSize();
320 if ((intptr_t(At) & 1) == 1)
327 // Open and completely load the archive file.
329 Archive::OpenAndLoad(const sys::Path& File, LLVMContext& C,
330 std::string* ErrorMessage) {
331 OwningPtr<Archive> result ( new Archive(File, C));
332 if (result->mapToMemory(ErrorMessage))
334 if (!result->loadArchive(ErrorMessage))
336 return result.take();
339 // Get all the bitcode modules from the archive
341 Archive::getAllModules(std::vector<Module*>& Modules,
342 std::string* ErrMessage) {
344 for (iterator I=begin(), E=end(); I != E; ++I) {
345 if (I->isBitcode()) {
346 std::string FullMemberName = archPath.str() +
347 "(" + I->getPath().str() + ")";
348 MemoryBuffer *Buffer =
349 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
350 FullMemberName.c_str());
352 Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
357 Modules.push_back(M);
363 // Load just the symbol table from the archive file
365 Archive::loadSymbolTable(std::string* ErrorMsg) {
370 const char *At = base;
371 const char *End = mapfile->getBufferEnd();
373 // Make sure we're dealing with an archive
374 if (!checkSignature(ErrorMsg))
377 At += 8; // Skip signature
379 // Parse the first file member header
380 const char* FirstFile = At;
381 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
385 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
386 // Skip the foreign symbol table, we don't do anything with it
387 At += mbr->getSize();
388 if ((intptr_t(At) & 1) == 1)
394 mbr = parseMemberHeader(At, End, ErrorMsg);
401 if (mbr->isStringTable()) {
402 // Process the string table entry
403 strtab.assign((const char*)mbr->getData(), mbr->getSize());
404 At += mbr->getSize();
405 if ((intptr_t(At) & 1) == 1)
410 mbr = parseMemberHeader(At, End, ErrorMsg);
417 // See if its the symbol table
418 if (mbr->isLLVMSymbolTable()) {
419 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
424 At += mbr->getSize();
425 if ((intptr_t(At) & 1) == 1)
428 // Can't be any more symtab headers so just advance
431 // There's no symbol table in the file. We have to rebuild it from scratch
432 // because the intent of this method is to get the symbol table loaded so
433 // it can be searched efficiently.
434 // Add the member to the members list
435 members.push_back(mbr);
438 firstFileOffset = FirstFile - base;
442 // Open the archive and load just the symbol tables
443 Archive* Archive::OpenAndLoadSymbols(const sys::Path& File,
445 std::string* ErrorMessage) {
446 OwningPtr<Archive> result ( new Archive(File, C) );
447 if (result->mapToMemory(ErrorMessage))
449 if (!result->loadSymbolTable(ErrorMessage))
451 return result.take();
454 // Look up one symbol in the symbol table and return the module that defines
457 Archive::findModuleDefiningSymbol(const std::string& symbol,
458 std::string* ErrMsg) {
459 SymTabType::iterator SI = symTab.find(symbol);
460 if (SI == symTab.end())
463 // The symbol table was previously constructed assuming that the members were
464 // written without the symbol table header. Because VBR encoding is used, the
465 // values could not be adjusted to account for the offset of the symbol table
466 // because that could affect the size of the symbol table due to VBR encoding.
467 // We now have to account for this by adjusting the offset by the size of the
468 // symbol table and its header.
469 unsigned fileOffset =
470 SI->second + // offset in symbol-table-less file
471 firstFileOffset; // add offset to first "real" file in archive
473 // See if the module is already loaded
474 ModuleMap::iterator MI = modules.find(fileOffset);
475 if (MI != modules.end())
476 return MI->second.first;
478 // Module hasn't been loaded yet, we need to load it
479 const char* modptr = base + fileOffset;
480 ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
485 // Now, load the bitcode module to get the Module.
486 std::string FullMemberName = archPath.str() + "(" +
487 mbr->getPath().str() + ")";
488 MemoryBuffer *Buffer =
489 MemoryBuffer::getMemBufferCopy(StringRef(mbr->getData(), mbr->getSize()),
490 FullMemberName.c_str());
492 Module *m = getLazyBitcodeModule(Buffer, Context, ErrMsg);
496 modules.insert(std::make_pair(fileOffset, std::make_pair(m, mbr)));
501 // Look up multiple symbols in the symbol table and return a set of
502 // Modules that define those symbols.
504 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
505 SmallVectorImpl<Module*>& result,
506 std::string* error) {
507 if (!mapfile || !base) {
509 *error = "Empty archive invalid for finding modules defining symbols";
513 if (symTab.empty()) {
514 // We don't have a symbol table, so we must build it now but lets also
515 // make sure that we populate the modules table as we do this to ensure
516 // that we don't load them twice when findModuleDefiningSymbol is called
519 // Get a pointer to the first file
520 const char* At = base + firstFileOffset;
521 const char* End = mapfile->getBufferEnd();
524 // Compute the offset to be put in the symbol table
525 unsigned offset = At - base - firstFileOffset;
527 // Parse the file's header
528 ArchiveMember* mbr = parseMemberHeader(At, End, error);
532 // If it contains symbols
533 if (mbr->isBitcode()) {
535 std::vector<std::string> symbols;
536 std::string FullMemberName = archPath.str() + "(" +
537 mbr->getPath().str() + ")";
539 GetBitcodeSymbols(At, mbr->getSize(), FullMemberName, Context,
543 // Insert the module's symbols into the symbol table
544 for (std::vector<std::string>::iterator I = symbols.begin(),
545 E=symbols.end(); I != E; ++I ) {
546 symTab.insert(std::make_pair(*I, offset));
548 // Insert the Module and the ArchiveMember into the table of
550 modules.insert(std::make_pair(offset, std::make_pair(M, mbr)));
553 *error = "Can't parse bitcode member: " +
554 mbr->getPath().str() + ": " + *error;
560 // Go to the next file location
561 At += mbr->getSize();
562 if ((intptr_t(At) & 1) == 1)
567 // At this point we have a valid symbol table (one way or another) so we
568 // just use it to quickly find the symbols requested.
570 SmallPtrSet<Module*, 16> Added;
571 for (std::set<std::string>::iterator I=symbols.begin(),
573 E=symbols.end(); I != E; I = Next) {
574 // Increment Next before we invalidate it.
577 // See if this symbol exists
578 Module* m = findModuleDefiningSymbol(*I,error);
581 bool NewMember = Added.insert(m);
585 // The symbol exists, insert the Module into our result.
588 // Remove the symbol now that its been resolved.
594 bool Archive::isBitcodeArchive() {
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 bitcode archive
609 std::vector<Module *> Modules;
610 std::string ErrorMessage;
612 // Scan the archive, trying to load a bitcode member. We only load one to
613 // see if this works.
614 for (iterator I = begin(), E = end(); I != E; ++I) {
618 std::string FullMemberName =
619 archPath.str() + "(" + I->getPath().str() + ")";
621 MemoryBuffer *Buffer =
622 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
623 FullMemberName.c_str());
624 Module *M = ParseBitcodeFile(Buffer, Context);
627 return false; // Couldn't parse bitcode, not a bitcode archive.