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 "ArchiveInternals.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/Bitcode/ReaderWriter.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Module.h"
24 /// Read a variable-bit-rate encoded unsigned integer
25 static 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 bitcode.
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 const char *nulp = (const char *)memchr(At, '\0', len);
126 pathname.assign(At, nulp != 0 ? (uintptr_t)(nulp - At) : len);
129 flags |= ArchiveMember::HasLongFilenameFlag;
132 *error = "invalid long filename";
135 } else if (Hdr->name[1] == '_' &&
136 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
137 // The member is using a long file name (>15 chars) format.
138 // This format is standard for 4.4BSD and Mac OSX operating
139 // systems. LLVM uses it similarly. In this format, the
140 // remainder of the name field (after #1/) specifies the
141 // length of the file name which occupy the first bytes of
142 // the member's data. The pathname already has the #1/ stripped.
143 pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
144 flags |= ArchiveMember::LLVMSymbolTableFlag;
148 if (Hdr->name[1]== '/') {
149 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
150 pathname.assign(ARFILE_STRTAB_NAME);
151 flags |= ArchiveMember::StringTableFlag;
154 *error = "invalid string table name";
157 } else if (Hdr->name[1] == ' ') {
158 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
159 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
160 flags |= ArchiveMember::SVR4SymbolTableFlag;
163 *error = "invalid SVR4 symbol table name";
166 } else if (isdigit(Hdr->name[1])) {
167 unsigned index = atoi(&Hdr->name[1]);
168 if (index < strtab.length()) {
169 const char* namep = strtab.c_str() + index;
170 const char* endp = strtab.c_str() + strtab.length();
171 const char* p = namep;
172 const char* last_p = p;
174 if (*p == '\n' && *last_p == '/') {
175 pathname.assign(namep, last_p - namep);
176 flags |= ArchiveMember::HasLongFilenameFlag;
184 *error = "missing name termiantor in string table";
189 *error = "name index beyond string table";
195 if (Hdr->name[1] == '_' &&
196 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
197 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
198 flags |= ArchiveMember::BSD4SymbolTableFlag;
204 char* slash = (char*) memchr(Hdr->name, '/', 16);
206 slash = Hdr->name + 16;
207 pathname.assign(Hdr->name, slash - Hdr->name);
211 // Determine if this is a bitcode file
212 switch (sys::IdentifyFileType(At, 4)) {
213 case sys::Bitcode_FileType:
214 flags |= ArchiveMember::BitcodeFlag;
217 flags &= ~ArchiveMember::BitcodeFlag;
221 // Instantiate the ArchiveMember to be filled
222 ArchiveMember* member = new ArchiveMember(this);
224 // Fill in fields of the ArchiveMember
225 member->parent = this;
226 member->path.set(pathname);
227 member->info.fileSize = MemberSize;
228 member->info.modTime.fromEpochTime(atoi(Hdr->date));
230 sscanf(Hdr->mode, "%o", &mode);
231 member->info.mode = mode;
232 member->info.user = atoi(Hdr->uid);
233 member->info.group = atoi(Hdr->gid);
234 member->flags = flags;
241 Archive::checkSignature(std::string* error) {
242 // Check the magic string at file's header
243 if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
245 *error = "invalid signature for an archive file";
251 // This function loads the entire archive and fully populates its ilist with
252 // the members of the archive file. This is typically used in preparation for
253 // editing the contents of the archive.
255 Archive::loadArchive(std::string* error) {
260 const char *At = base;
261 const char *End = mapfile->getBufferEnd();
263 if (!checkSignature(error))
266 At += 8; // Skip the magic string.
268 bool seenSymbolTable = false;
269 bool foundFirstFile = false;
271 // parse the member header
272 const char* Save = At;
273 ArchiveMember* mbr = parseMemberHeader(At, End, error);
277 // check if this is the foreign symbol table
278 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
279 // We just save this but don't do anything special
280 // with it. It doesn't count as the "first file".
282 // What? Multiple foreign symbol tables? Just chuck it
283 // and retain the last one found.
287 At += mbr->getSize();
288 if ((intptr_t(At) & 1) == 1)
290 } else if (mbr->isStringTable()) {
291 // Simply suck the entire string table into a string
292 // variable. This will be used to get the names of the
293 // members that use the "/ddd" format for their names
294 // (SVR4 style long names).
295 strtab.assign(At, mbr->getSize());
296 At += mbr->getSize();
297 if ((intptr_t(At) & 1) == 1)
300 } else if (mbr->isLLVMSymbolTable()) {
301 // This is the LLVM symbol table for the archive. If we've seen it
302 // already, its an error. Otherwise, parse the symbol table and move on.
303 if (seenSymbolTable) {
305 *error = "invalid archive: multiple symbol tables";
308 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
310 seenSymbolTable = true;
311 At += mbr->getSize();
312 if ((intptr_t(At) & 1) == 1)
314 delete mbr; // We don't need this member in the list of members.
316 // This is just a regular file. If its the first one, save its offset.
317 // Otherwise just push it on the list and move on to the next file.
318 if (!foundFirstFile) {
319 firstFileOffset = Save - base;
320 foundFirstFile = true;
322 members.push_back(mbr);
323 At += mbr->getSize();
324 if ((intptr_t(At) & 1) == 1)
331 // Open and completely load the archive file.
333 Archive::OpenAndLoad(const sys::Path& file, LLVMContext& C,
334 std::string* ErrorMessage) {
335 std::auto_ptr<Archive> result ( new Archive(file, C));
336 if (result->mapToMemory(ErrorMessage))
338 if (!result->loadArchive(ErrorMessage))
340 return result.release();
343 // Get all the bitcode modules from the archive
345 Archive::getAllModules(std::vector<Module*>& Modules,
346 std::string* ErrMessage) {
348 for (iterator I=begin(), E=end(); I != E; ++I) {
349 if (I->isBitcode()) {
350 std::string FullMemberName = archPath.str() +
351 "(" + I->getPath().str() + ")";
352 MemoryBuffer *Buffer =
353 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
354 FullMemberName.c_str());
356 Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
361 Modules.push_back(M);
367 // Load just the symbol table from the archive file
369 Archive::loadSymbolTable(std::string* ErrorMsg) {
374 const char *At = base;
375 const char *End = mapfile->getBufferEnd();
377 // Make sure we're dealing with an archive
378 if (!checkSignature(ErrorMsg))
381 At += 8; // Skip signature
383 // Parse the first file member header
384 const char* FirstFile = At;
385 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
389 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
390 // Skip the foreign symbol table, we don't do anything with it
391 At += mbr->getSize();
392 if ((intptr_t(At) & 1) == 1)
398 mbr = parseMemberHeader(At, End, ErrorMsg);
405 if (mbr->isStringTable()) {
406 // Process the string table entry
407 strtab.assign((const char*)mbr->getData(), mbr->getSize());
408 At += mbr->getSize();
409 if ((intptr_t(At) & 1) == 1)
414 mbr = parseMemberHeader(At, End, ErrorMsg);
421 // See if its the symbol table
422 if (mbr->isLLVMSymbolTable()) {
423 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
428 At += mbr->getSize();
429 if ((intptr_t(At) & 1) == 1)
432 // Can't be any more symtab headers so just advance
435 // There's no symbol table in the file. We have to rebuild it from scratch
436 // because the intent of this method is to get the symbol table loaded so
437 // it can be searched efficiently.
438 // Add the member to the members list
439 members.push_back(mbr);
442 firstFileOffset = FirstFile - base;
446 // Open the archive and load just the symbol tables
447 Archive* Archive::OpenAndLoadSymbols(const sys::Path& file,
449 std::string* ErrorMessage) {
450 std::auto_ptr<Archive> result ( new Archive(file, C) );
451 if (result->mapToMemory(ErrorMessage))
453 if (!result->loadSymbolTable(ErrorMessage))
455 return result.release();
458 // Look up one symbol in the symbol table and return the module that defines
461 Archive::findModuleDefiningSymbol(const std::string& symbol,
462 std::string* ErrMsg) {
463 SymTabType::iterator SI = symTab.find(symbol);
464 if (SI == symTab.end())
467 // The symbol table was previously constructed assuming that the members were
468 // written without the symbol table header. Because VBR encoding is used, the
469 // values could not be adjusted to account for the offset of the symbol table
470 // because that could affect the size of the symbol table due to VBR encoding.
471 // We now have to account for this by adjusting the offset by the size of the
472 // symbol table and its header.
473 unsigned fileOffset =
474 SI->second + // offset in symbol-table-less file
475 firstFileOffset; // add offset to first "real" file in archive
477 // See if the module is already loaded
478 ModuleMap::iterator MI = modules.find(fileOffset);
479 if (MI != modules.end())
480 return MI->second.first;
482 // Module hasn't been loaded yet, we need to load it
483 const char* modptr = base + fileOffset;
484 ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
489 // Now, load the bitcode module to get the Module.
490 std::string FullMemberName = archPath.str() + "(" +
491 mbr->getPath().str() + ")";
492 MemoryBuffer *Buffer =
493 MemoryBuffer::getMemBufferCopy(StringRef(mbr->getData(), mbr->getSize()),
494 FullMemberName.c_str());
496 Module *m = getLazyBitcodeModule(Buffer, Context, ErrMsg);
500 modules.insert(std::make_pair(fileOffset, std::make_pair(m, mbr)));
505 // Look up multiple symbols in the symbol table and return a set of
506 // Modules that define those symbols.
508 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
509 SmallVectorImpl<Module*>& result,
510 std::string* error) {
511 if (!mapfile || !base) {
513 *error = "Empty archive invalid for finding modules defining symbols";
517 if (symTab.empty()) {
518 // We don't have a symbol table, so we must build it now but lets also
519 // make sure that we populate the modules table as we do this to ensure
520 // that we don't load them twice when findModuleDefiningSymbol is called
523 // Get a pointer to the first file
524 const char* At = base + firstFileOffset;
525 const char* End = mapfile->getBufferEnd();
528 // Compute the offset to be put in the symbol table
529 unsigned offset = At - base - firstFileOffset;
531 // Parse the file's header
532 ArchiveMember* mbr = parseMemberHeader(At, End, error);
536 // If it contains symbols
537 if (mbr->isBitcode()) {
539 std::vector<std::string> symbols;
540 std::string FullMemberName = archPath.str() + "(" +
541 mbr->getPath().str() + ")";
543 GetBitcodeSymbols(At, mbr->getSize(), FullMemberName, Context,
547 // Insert the module's symbols into the symbol table
548 for (std::vector<std::string>::iterator I = symbols.begin(),
549 E=symbols.end(); I != E; ++I ) {
550 symTab.insert(std::make_pair(*I, offset));
552 // Insert the Module and the ArchiveMember into the table of
554 modules.insert(std::make_pair(offset, std::make_pair(M, mbr)));
557 *error = "Can't parse bitcode member: " +
558 mbr->getPath().str() + ": " + *error;
564 // Go to the next file location
565 At += mbr->getSize();
566 if ((intptr_t(At) & 1) == 1)
571 // At this point we have a valid symbol table (one way or another) so we
572 // just use it to quickly find the symbols requested.
574 SmallPtrSet<Module*, 16> Added;
575 for (std::set<std::string>::iterator I=symbols.begin(),
577 E=symbols.end(); I != E; I = Next) {
578 // Increment Next before we invalidate it.
581 // See if this symbol exists
582 Module* m = findModuleDefiningSymbol(*I,error);
585 bool NewMember = Added.insert(m);
589 // The symbol exists, insert the Module into our result.
592 // Remove the symbol now that its been resolved.
598 bool Archive::isBitcodeArchive() {
599 // Make sure the symTab has been loaded. In most cases this should have been
600 // done when the archive was constructed, but still, this is just in case.
602 if (!loadSymbolTable(0))
605 // Now that we know it's been loaded, return true
607 if (symTab.size()) return true;
609 // We still can't be sure it isn't a bitcode archive
613 std::vector<Module *> Modules;
614 std::string ErrorMessage;
616 // Scan the archive, trying to load a bitcode member. We only load one to
617 // see if this works.
618 for (iterator I = begin(), E = end(); I != E; ++I) {
622 std::string FullMemberName =
623 archPath.str() + "(" + I->getPath().str() + ")";
625 MemoryBuffer *Buffer =
626 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
627 FullMemberName.c_str());
628 Module *M = ParseBitcodeFile(Buffer, Context);
631 return false; // Couldn't parse bitcode, not a bitcode archive.