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/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
26 /// Read a variable-bit-rate encoded unsigned integer
27 static inline unsigned readInteger(const char*&At, const char*End) {
34 Result |= (unsigned)((*At++) & 0x7F) << Shift;
36 } while (At[-1] & 0x80);
40 // Completely parse the Archive's symbol table and populate symTab member var.
42 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
43 const char* At = (const char*) data;
44 const char* End = At + size;
46 unsigned offset = readInteger(At, End);
49 *error = "Ran out of data reading vbr_uint for symtab offset!";
52 unsigned length = readInteger(At, End);
55 *error = "Ran out of data reading vbr_uint for symtab length!";
58 if (At + length > End) {
60 *error = "Malformed symbol table: length not consistent with size";
63 // we don't care if it can't be inserted (duplicate entry)
64 symTab.insert(std::make_pair(std::string(At, length), offset));
71 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
72 // by At. The At pointer is updated to the byte just after the header, which
73 // can be variable in size.
75 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
77 if (At + sizeof(ArchiveMemberHeader) >= End) {
79 *error = "Unexpected end of file";
83 // Cast archive member header
84 const ArchiveMemberHeader* Hdr = (const ArchiveMemberHeader*)At;
85 At += sizeof(ArchiveMemberHeader);
88 int MemberSize = atoi(Hdr->size);
89 assert(MemberSize >= 0);
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 bitcode.
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 const char *nulp = (const char *)memchr(At, '\0', len);
123 pathname.assign(At, nulp != 0 ? (uintptr_t)(nulp - At) : len);
126 flags |= ArchiveMember::HasLongFilenameFlag;
129 *error = "invalid long filename";
132 } else if (Hdr->name[1] == '_' &&
133 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
134 // The member is using a long file name (>15 chars) format.
135 // This format is standard for 4.4BSD and Mac OSX operating
136 // systems. LLVM uses it similarly. In this format, the
137 // remainder of the name field (after #1/) specifies the
138 // length of the file name which occupy the first bytes of
139 // the member's data. The pathname already has the #1/ stripped.
140 pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
141 flags |= ArchiveMember::LLVMSymbolTableFlag;
145 if (Hdr->name[1]== '/') {
146 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
147 pathname.assign(ARFILE_STRTAB_NAME);
148 flags |= ArchiveMember::StringTableFlag;
151 *error = "invalid string table name";
154 } else if (Hdr->name[1] == ' ') {
155 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
156 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
157 flags |= ArchiveMember::SVR4SymbolTableFlag;
160 *error = "invalid SVR4 symbol table name";
163 } else if (isdigit(Hdr->name[1])) {
164 unsigned index = atoi(&Hdr->name[1]);
165 if (index < strtab.length()) {
166 const char* namep = strtab.c_str() + index;
167 const char* endp = strtab.c_str() + strtab.length();
168 const char* p = namep;
169 const char* last_p = p;
171 if (*p == '\n' && *last_p == '/') {
172 pathname.assign(namep, last_p - namep);
173 flags |= ArchiveMember::HasLongFilenameFlag;
181 *error = "missing name terminator in string table";
186 *error = "name index beyond string table";
192 if (Hdr->name[1] == '_' &&
193 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
194 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
195 flags |= ArchiveMember::BSD4SymbolTableFlag;
201 const char* slash = (const char*) memchr(Hdr->name, '/', 16);
203 slash = Hdr->name + 16;
204 pathname.assign(Hdr->name, slash - Hdr->name);
208 // Determine if this is a bitcode file
209 if (sys::fs::identify_magic(StringRef(At, 4)) ==
210 sys::fs::file_magic::bitcode)
211 flags |= ArchiveMember::BitcodeFlag;
213 flags &= ~ArchiveMember::BitcodeFlag;
215 // Instantiate the ArchiveMember to be filled
216 ArchiveMember* member = new ArchiveMember(this);
218 // Fill in fields of the ArchiveMember
219 member->parent = this;
220 member->path.set(pathname);
221 member->info.fileSize = MemberSize;
222 member->info.modTime.fromEpochTime(atoi(Hdr->date));
224 sscanf(Hdr->mode, "%o", &mode);
225 member->info.mode = mode;
226 member->info.user = atoi(Hdr->uid);
227 member->info.group = atoi(Hdr->gid);
228 member->flags = flags;
235 Archive::checkSignature(std::string* error) {
236 // Check the magic string at file's header
237 if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
239 *error = "invalid signature for an archive file";
245 // This function loads the entire archive and fully populates its ilist with
246 // the members of the archive file. This is typically used in preparation for
247 // editing the contents of the archive.
249 Archive::loadArchive(std::string* error) {
254 const char *At = base;
255 const char *End = mapfile->getBufferEnd();
257 if (!checkSignature(error))
260 At += 8; // Skip the magic string.
262 bool seenSymbolTable = false;
263 bool foundFirstFile = false;
265 // parse the member header
266 const char* Save = At;
267 ArchiveMember* mbr = parseMemberHeader(At, End, error);
271 // check if this is the foreign symbol table
272 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
273 // We just save this but don't do anything special
274 // with it. It doesn't count as the "first file".
276 // What? Multiple foreign symbol tables? Just chuck it
277 // and retain the last one found.
281 At += mbr->getSize();
282 if ((intptr_t(At) & 1) == 1)
284 } else if (mbr->isStringTable()) {
285 // Simply suck the entire string table into a string
286 // variable. This will be used to get the names of the
287 // members that use the "/ddd" format for their names
288 // (SVR4 style long names).
289 strtab.assign(At, mbr->getSize());
290 At += mbr->getSize();
291 if ((intptr_t(At) & 1) == 1)
294 } else if (mbr->isLLVMSymbolTable()) {
295 // This is the LLVM symbol table for the archive. If we've seen it
296 // already, its an error. Otherwise, parse the symbol table and move on.
297 if (seenSymbolTable) {
299 *error = "invalid archive: multiple symbol tables";
302 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
304 seenSymbolTable = true;
305 At += mbr->getSize();
306 if ((intptr_t(At) & 1) == 1)
308 delete mbr; // We don't need this member in the list of members.
310 // This is just a regular file. If its the first one, save its offset.
311 // Otherwise just push it on the list and move on to the next file.
312 if (!foundFirstFile) {
313 firstFileOffset = Save - base;
314 foundFirstFile = true;
316 members.push_back(mbr);
317 At += mbr->getSize();
318 if ((intptr_t(At) & 1) == 1)
325 // Open and completely load the archive file.
327 Archive::OpenAndLoad(const sys::Path& File, LLVMContext& C,
328 std::string* ErrorMessage) {
329 OwningPtr<Archive> result ( new Archive(File, C));
330 if (result->mapToMemory(ErrorMessage))
332 if (!result->loadArchive(ErrorMessage))
334 return result.take();
337 // Get all the bitcode modules from the archive
339 Archive::getAllModules(std::vector<Module*>& Modules,
340 std::string* ErrMessage) {
342 for (iterator I=begin(), E=end(); I != E; ++I) {
343 if (I->isBitcode()) {
344 std::string FullMemberName = archPath.str() +
345 "(" + I->getPath().str() + ")";
346 MemoryBuffer *Buffer =
347 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
348 FullMemberName.c_str());
350 Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
355 Modules.push_back(M);
361 // Load just the symbol table from the archive file
363 Archive::loadSymbolTable(std::string* ErrorMsg) {
368 const char *At = base;
369 const char *End = mapfile->getBufferEnd();
371 // Make sure we're dealing with an archive
372 if (!checkSignature(ErrorMsg))
375 At += 8; // Skip signature
377 // Parse the first file member header
378 const char* FirstFile = At;
379 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
383 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
384 // Skip the foreign symbol table, we don't do anything with it
385 At += mbr->getSize();
386 if ((intptr_t(At) & 1) == 1)
392 mbr = parseMemberHeader(At, End, ErrorMsg);
399 if (mbr->isStringTable()) {
400 // Process the string table entry
401 strtab.assign((const char*)mbr->getData(), mbr->getSize());
402 At += mbr->getSize();
403 if ((intptr_t(At) & 1) == 1)
408 mbr = parseMemberHeader(At, End, ErrorMsg);
415 // See if its the symbol table
416 if (mbr->isLLVMSymbolTable()) {
417 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
422 At += mbr->getSize();
423 if ((intptr_t(At) & 1) == 1)
426 // Can't be any more symtab headers so just advance
429 // There's no symbol table in the file. We have to rebuild it from scratch
430 // because the intent of this method is to get the symbol table loaded so
431 // it can be searched efficiently.
432 // Add the member to the members list
433 members.push_back(mbr);
436 firstFileOffset = FirstFile - base;
440 // Open the archive and load just the symbol tables
441 Archive* Archive::OpenAndLoadSymbols(const sys::Path& File,
443 std::string* ErrorMessage) {
444 OwningPtr<Archive> result ( new Archive(File, C) );
445 if (result->mapToMemory(ErrorMessage))
447 if (!result->loadSymbolTable(ErrorMessage))
449 return result.take();
452 // Look up one symbol in the symbol table and return the module that defines
455 Archive::findModuleDefiningSymbol(const std::string& symbol,
456 std::string* ErrMsg) {
457 SymTabType::iterator SI = symTab.find(symbol);
458 if (SI == symTab.end())
461 // The symbol table was previously constructed assuming that the members were
462 // written without the symbol table header. Because VBR encoding is used, the
463 // values could not be adjusted to account for the offset of the symbol table
464 // because that could affect the size of the symbol table due to VBR encoding.
465 // We now have to account for this by adjusting the offset by the size of the
466 // symbol table and its header.
467 unsigned fileOffset =
468 SI->second + // offset in symbol-table-less file
469 firstFileOffset; // add offset to first "real" file in archive
471 // See if the module is already loaded
472 ModuleMap::iterator MI = modules.find(fileOffset);
473 if (MI != modules.end())
474 return MI->second.first;
476 // Module hasn't been loaded yet, we need to load it
477 const char* modptr = base + fileOffset;
478 ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
483 // Now, load the bitcode module to get the Module.
484 std::string FullMemberName = archPath.str() + "(" +
485 mbr->getPath().str() + ")";
486 MemoryBuffer *Buffer =
487 MemoryBuffer::getMemBufferCopy(StringRef(mbr->getData(), mbr->getSize()),
488 FullMemberName.c_str());
490 Module *m = getLazyBitcodeModule(Buffer, Context, ErrMsg);
494 modules.insert(std::make_pair(fileOffset, std::make_pair(m, mbr)));
499 // Look up multiple symbols in the symbol table and return a set of
500 // Modules that define those symbols.
502 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
503 SmallVectorImpl<Module*>& result,
504 std::string* error) {
505 if (!mapfile || !base) {
507 *error = "Empty archive invalid for finding modules defining symbols";
511 if (symTab.empty()) {
512 // We don't have a symbol table, so we must build it now but lets also
513 // make sure that we populate the modules table as we do this to ensure
514 // that we don't load them twice when findModuleDefiningSymbol is called
517 // Get a pointer to the first file
518 const char* At = base + firstFileOffset;
519 const char* End = mapfile->getBufferEnd();
522 // Compute the offset to be put in the symbol table
523 unsigned offset = At - base - firstFileOffset;
525 // Parse the file's header
526 ArchiveMember* mbr = parseMemberHeader(At, End, error);
530 // If it contains symbols
531 if (mbr->isBitcode()) {
533 std::vector<std::string> symbols;
534 std::string FullMemberName = archPath.str() + "(" +
535 mbr->getPath().str() + ")";
537 GetBitcodeSymbols(At, mbr->getSize(), FullMemberName, Context,
541 // Insert the module's symbols into the symbol table
542 for (std::vector<std::string>::iterator I = symbols.begin(),
543 E=symbols.end(); I != E; ++I ) {
544 symTab.insert(std::make_pair(*I, offset));
546 // Insert the Module and the ArchiveMember into the table of
548 modules.insert(std::make_pair(offset, std::make_pair(M, mbr)));
551 *error = "Can't parse bitcode member: " +
552 mbr->getPath().str() + ": " + *error;
558 // Go to the next file location
559 At += mbr->getSize();
560 if ((intptr_t(At) & 1) == 1)
565 // At this point we have a valid symbol table (one way or another) so we
566 // just use it to quickly find the symbols requested.
568 SmallPtrSet<Module*, 16> Added;
569 for (std::set<std::string>::iterator I=symbols.begin(),
571 E=symbols.end(); I != E; I = Next) {
572 // Increment Next before we invalidate it.
575 // See if this symbol exists
576 Module* m = findModuleDefiningSymbol(*I,error);
579 bool NewMember = Added.insert(m);
583 // The symbol exists, insert the Module into our result.
586 // Remove the symbol now that its been resolved.
592 bool Archive::isBitcodeArchive() {
593 // Make sure the symTab has been loaded. In most cases this should have been
594 // done when the archive was constructed, but still, this is just in case.
596 if (!loadSymbolTable(0))
599 // Now that we know it's been loaded, return true
601 if (symTab.size()) return true;
603 // We still can't be sure it isn't a bitcode archive
607 std::vector<Module *> Modules;
608 std::string ErrorMessage;
610 // Scan the archive, trying to load a bitcode member. We only load one to
611 // see if this works.
612 for (iterator I = begin(), E = end(); I != E; ++I) {
616 std::string FullMemberName =
617 archPath.str() + "(" + I->getPath().str() + ")";
619 MemoryBuffer *Buffer =
620 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
621 FullMemberName.c_str());
622 Module *M = ParseBitcodeFile(Buffer, Context);
625 return false; // Couldn't parse bitcode, not a bitcode archive.