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/Bitcode/ReaderWriter.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Module.h"
22 /// Read a variable-bit-rate encoded unsigned integer
23 static inline unsigned readInteger(const char*&At, const char*End) {
30 Result |= (unsigned)((*At++) & 0x7F) << Shift;
32 } while (At[-1] & 0x80);
36 // Completely parse the Archive's symbol table and populate symTab member var.
38 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
39 const char* At = (const char*) data;
40 const char* End = At + size;
42 unsigned offset = readInteger(At, End);
45 *error = "Ran out of data reading vbr_uint for symtab offset!";
48 unsigned length = readInteger(At, End);
51 *error = "Ran out of data reading vbr_uint for symtab length!";
54 if (At + length > End) {
56 *error = "Malformed symbol table: length not consistent with size";
59 // we don't care if it can't be inserted (duplicate entry)
60 symTab.insert(std::make_pair(std::string(At, length), offset));
67 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
68 // by At. The At pointer is updated to the byte just after the header, which
69 // can be variable in size.
71 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
73 if (At + sizeof(ArchiveMemberHeader) >= End) {
75 *error = "Unexpected end of file";
79 // Cast archive member header
80 ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
81 At += sizeof(ArchiveMemberHeader);
83 // Extract the size and determine if the file is
84 // compressed or not (negative length).
86 int MemberSize = atoi(Hdr->size);
88 flags |= ArchiveMember::CompressedFlag;
89 MemberSize = -MemberSize;
92 // Check the size of the member for sanity
93 if (At + MemberSize > End) {
95 *error = "invalid member length in archive file";
99 // Check the member signature
100 if (!Hdr->checkSignature()) {
102 *error = "invalid file member signature";
106 // Convert and check the member name
107 // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
108 // table. The special name "//" and 14 blanks is for a string table, used
109 // for long file names. This library doesn't generate either of those but
110 // it will accept them. If the name starts with #1/ and the remainder is
111 // digits, then those digits specify the length of the name that is
112 // stored immediately following the header. The special name
113 // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bitcode.
114 // Anything else is a regular, short filename that is terminated with
117 std::string pathname;
118 switch (Hdr->name[0]) {
120 if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
121 if (isdigit(Hdr->name[3])) {
122 unsigned len = atoi(&Hdr->name[3]);
123 const char *nulp = (const char *)memchr(At, '\0', len);
124 pathname.assign(At, nulp != 0 ? nulp - At : len);
127 flags |= ArchiveMember::HasLongFilenameFlag;
130 *error = "invalid long filename";
133 } else if (Hdr->name[1] == '_' &&
134 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
135 // The member is using a long file name (>15 chars) format.
136 // This format is standard for 4.4BSD and Mac OSX operating
137 // systems. LLVM uses it similarly. In this format, the
138 // remainder of the name field (after #1/) specifies the
139 // length of the file name which occupy the first bytes of
140 // the member's data. The pathname already has the #1/ stripped.
141 pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
142 flags |= ArchiveMember::LLVMSymbolTableFlag;
146 if (Hdr->name[1]== '/') {
147 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
148 pathname.assign(ARFILE_STRTAB_NAME);
149 flags |= ArchiveMember::StringTableFlag;
152 *error = "invalid string table name";
155 } else if (Hdr->name[1] == ' ') {
156 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
157 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
158 flags |= ArchiveMember::SVR4SymbolTableFlag;
161 *error = "invalid SVR4 symbol table name";
164 } else if (isdigit(Hdr->name[1])) {
165 unsigned index = atoi(&Hdr->name[1]);
166 if (index < strtab.length()) {
167 const char* namep = strtab.c_str() + index;
168 const char* endp = strtab.c_str() + strtab.length();
169 const char* p = namep;
170 const char* last_p = p;
172 if (*p == '\n' && *last_p == '/') {
173 pathname.assign(namep, last_p - namep);
174 flags |= ArchiveMember::HasLongFilenameFlag;
182 *error = "missing name termiantor in string table";
187 *error = "name index beyond string table";
193 if (Hdr->name[1] == '_' &&
194 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
195 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
196 flags |= ArchiveMember::BSD4SymbolTableFlag;
202 char* slash = (char*) memchr(Hdr->name, '/', 16);
204 slash = Hdr->name + 16;
205 pathname.assign(Hdr->name, slash - Hdr->name);
209 // Determine if this is a bitcode file
210 switch (sys::IdentifyFileType(At, 4)) {
211 case sys::Bitcode_FileType:
212 flags |= ArchiveMember::BitcodeFlag;
215 flags &= ~ArchiveMember::BitcodeFlag;
219 // Instantiate the ArchiveMember to be filled
220 ArchiveMember* member = new ArchiveMember(this);
222 // Fill in fields of the ArchiveMember
223 member->parent = this;
224 member->path.set(pathname);
225 member->info.fileSize = MemberSize;
226 member->info.modTime.fromEpochTime(atoi(Hdr->date));
228 sscanf(Hdr->mode, "%o", &mode);
229 member->info.mode = mode;
230 member->info.user = atoi(Hdr->uid);
231 member->info.group = atoi(Hdr->gid);
232 member->flags = flags;
239 Archive::checkSignature(std::string* error) {
240 // Check the magic string at file's header
241 if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
243 *error = "invalid signature for an archive file";
249 // This function loads the entire archive and fully populates its ilist with
250 // the members of the archive file. This is typically used in preparation for
251 // editing the contents of the archive.
253 Archive::loadArchive(std::string* error) {
258 const char *At = base;
259 const char *End = mapfile->getBufferEnd();
261 if (!checkSignature(error))
264 At += 8; // Skip the magic string.
266 bool seenSymbolTable = false;
267 bool foundFirstFile = false;
269 // parse the member header
270 const char* Save = At;
271 ArchiveMember* mbr = parseMemberHeader(At, End, error);
275 // check if this is the foreign symbol table
276 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
277 // We just save this but don't do anything special
278 // with it. It doesn't count as the "first file".
280 // What? Multiple foreign symbol tables? Just chuck it
281 // and retain the last one found.
285 At += mbr->getSize();
286 if ((intptr_t(At) & 1) == 1)
288 } else if (mbr->isStringTable()) {
289 // Simply suck the entire string table into a string
290 // variable. This will be used to get the names of the
291 // members that use the "/ddd" format for their names
292 // (SVR4 style long names).
293 strtab.assign(At, mbr->getSize());
294 At += mbr->getSize();
295 if ((intptr_t(At) & 1) == 1)
298 } else if (mbr->isLLVMSymbolTable()) {
299 // This is the LLVM symbol table for the archive. If we've seen it
300 // already, its an error. Otherwise, parse the symbol table and move on.
301 if (seenSymbolTable) {
303 *error = "invalid archive: multiple symbol tables";
306 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
308 seenSymbolTable = true;
309 At += mbr->getSize();
310 if ((intptr_t(At) & 1) == 1)
312 delete mbr; // We don't need this member in the list of members.
314 // This is just a regular file. If its the first one, save its offset.
315 // Otherwise just push it on the list and move on to the next file.
316 if (!foundFirstFile) {
317 firstFileOffset = Save - base;
318 foundFirstFile = true;
320 members.push_back(mbr);
321 At += mbr->getSize();
322 if ((intptr_t(At) & 1) == 1)
329 // Open and completely load the archive file.
331 Archive::OpenAndLoad(const sys::Path& file, LLVMContext& C,
332 std::string* ErrorMessage) {
333 std::auto_ptr<Archive> result ( new Archive(file, C));
334 if (result->mapToMemory(ErrorMessage))
336 if (!result->loadArchive(ErrorMessage))
338 return result.release();
341 // Get all the bitcode modules from the archive
343 Archive::getAllModules(std::vector<Module*>& Modules,
344 std::string* ErrMessage) {
346 for (iterator I=begin(), E=end(); I != E; ++I) {
347 if (I->isBitcode()) {
348 std::string FullMemberName = archPath.str() +
349 "(" + I->getPath().str() + ")";
350 MemoryBuffer *Buffer =
351 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
352 memcpy(const_cast<char *>(Buffer->getBufferStart()),
353 I->getData(), I->getSize());
355 Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
360 Modules.push_back(M);
366 // Load just the symbol table from the archive file
368 Archive::loadSymbolTable(std::string* ErrorMsg) {
373 const char *At = base;
374 const char *End = mapfile->getBufferEnd();
376 // Make sure we're dealing with an archive
377 if (!checkSignature(ErrorMsg))
380 At += 8; // Skip signature
382 // Parse the first file member header
383 const char* FirstFile = At;
384 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
388 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
389 // Skip the foreign symbol table, we don't do anything with it
390 At += mbr->getSize();
391 if ((intptr_t(At) & 1) == 1)
397 mbr = parseMemberHeader(At, End, ErrorMsg);
404 if (mbr->isStringTable()) {
405 // Process the string table entry
406 strtab.assign((const char*)mbr->getData(), mbr->getSize());
407 At += mbr->getSize();
408 if ((intptr_t(At) & 1) == 1)
413 mbr = parseMemberHeader(At, End, ErrorMsg);
420 // See if its the symbol table
421 if (mbr->isLLVMSymbolTable()) {
422 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
427 At += mbr->getSize();
428 if ((intptr_t(At) & 1) == 1)
431 // Can't be any more symtab headers so just advance
434 // There's no symbol table in the file. We have to rebuild it from scratch
435 // because the intent of this method is to get the symbol table loaded so
436 // it can be searched efficiently.
437 // Add the member to the members list
438 members.push_back(mbr);
441 firstFileOffset = FirstFile - base;
445 // Open the archive and load just the symbol tables
446 Archive* Archive::OpenAndLoadSymbols(const sys::Path& file,
448 std::string* ErrorMessage) {
449 std::auto_ptr<Archive> result ( new Archive(file, C) );
450 if (result->mapToMemory(ErrorMessage))
452 if (!result->loadSymbolTable(ErrorMessage))
454 return result.release();
457 // Look up one symbol in the symbol table and return the module that defines
460 Archive::findModuleDefiningSymbol(const std::string& symbol,
461 std::string* ErrMsg) {
462 SymTabType::iterator SI = symTab.find(symbol);
463 if (SI == symTab.end())
466 // The symbol table was previously constructed assuming that the members were
467 // written without the symbol table header. Because VBR encoding is used, the
468 // values could not be adjusted to account for the offset of the symbol table
469 // because that could affect the size of the symbol table due to VBR encoding.
470 // We now have to account for this by adjusting the offset by the size of the
471 // symbol table and its header.
472 unsigned fileOffset =
473 SI->second + // offset in symbol-table-less file
474 firstFileOffset; // add offset to first "real" file in archive
476 // See if the module is already loaded
477 ModuleMap::iterator MI = modules.find(fileOffset);
478 if (MI != modules.end())
479 return MI->second.first;
481 // Module hasn't been loaded yet, we need to load it
482 const char* modptr = base + fileOffset;
483 ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
488 // Now, load the bitcode module to get the Module.
489 std::string FullMemberName = archPath.str() + "(" +
490 mbr->getPath().str() + ")";
491 MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(),
492 FullMemberName.c_str());
493 memcpy(const_cast<char *>(Buffer->getBufferStart()),
494 mbr->getData(), mbr->getSize());
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 std::set<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((const unsigned char*)At, mbr->getSize(),
544 FullMemberName, Context, symbols, error);
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 for (std::set<std::string>::iterator I=symbols.begin(),
575 E=symbols.end(); I != E;) {
576 // See if this symbol exists
577 Module* m = findModuleDefiningSymbol(*I,error);
579 // The symbol exists, insert the Module into our result, duplicates will
583 // Remove the symbol now that its been resolved, being careful to
584 // post-increment the iterator.
593 bool Archive::isBitcodeArchive() {
594 // Make sure the symTab has been loaded. In most cases this should have been
595 // done when the archive was constructed, but still, this is just in case.
597 if (!loadSymbolTable(0))
600 // Now that we know it's been loaded, return true
602 if (symTab.size()) return true;
604 // We still can't be sure it isn't a bitcode archive
608 std::vector<Module *> Modules;
609 std::string ErrorMessage;
611 // Scan the archive, trying to load a bitcode member. We only load one to
612 // see if this works.
613 for (iterator I = begin(), E = end(); I != E; ++I) {
617 std::string FullMemberName =
618 archPath.str() + "(" + I->getPath().str() + ")";
620 MemoryBuffer *Buffer =
621 MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
622 memcpy(const_cast<char *>(Buffer->getBufferStart()),
623 I->getData(), I->getSize());
624 Module *M = ParseBitcodeFile(Buffer, Context);
627 return false; // Couldn't parse bitcode, not a bitcode archive.