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/Bytecode/Reader.h"
20 /// Read a variable-bit-rate encoded unsigned integer
21 inline unsigned readInteger(const char*&At, const char*End){
28 Result |= (unsigned)((*At++) & 0x7F) << Shift;
30 } while (At[-1] & 0x80);
34 // Completely parse the Archive's symbol table and populate symTab member var.
36 Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
37 const char* At = (const char*) data;
38 const char* End = At + size;
40 unsigned offset = readInteger(At, End);
43 *error = "Ran out of data reading vbr_uint for symtab offset!";
46 unsigned length = readInteger(At, End);
49 *error = "Ran out of data reading vbr_uint for symtab length!";
52 if (At + length > End) {
54 *error = "Malformed symbol table: length not consistent with size";
57 // we don't care if it can't be inserted (duplicate entry)
58 symTab.insert(std::make_pair(std::string(At, length), offset));
65 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
66 // by At. The At pointer is updated to the byte just after the header, which
67 // can be variable in size.
69 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
71 assert(At + sizeof(ArchiveMemberHeader) < End && "Not enough data");
73 // Cast archive member header
74 ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
75 At += sizeof(ArchiveMemberHeader);
77 // Extract the size and determine if the file is
78 // compressed or not (negative length).
80 int MemberSize = atoi(Hdr->size);
82 flags |= ArchiveMember::CompressedFlag;
83 MemberSize = -MemberSize;
86 // Check the size of the member for sanity
87 if (At + MemberSize > End) {
89 *error = "invalid member length in archive file";
93 // Check the member signature
94 if (!Hdr->checkSignature()) {
96 *error = "invalid file member signature";
100 // Convert and check the member name
101 // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
102 // table. The special name "//" and 14 blanks is for a string table, used
103 // for long file names. This library doesn't generate either of those but
104 // it will accept them. If the name starts with #1/ and the remainder is
105 // digits, then those digits specify the length of the name that is
106 // stored immediately following the header. The special name
107 // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bytecode.
108 // Anything else is a regular, short filename that is terminated with
111 std::string pathname;
112 switch (Hdr->name[0]) {
114 if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
115 if (isdigit(Hdr->name[3])) {
116 unsigned len = atoi(&Hdr->name[3]);
117 pathname.assign(At, len);
120 flags |= ArchiveMember::HasLongFilenameFlag;
123 *error = "invalid long filename";
126 } else if (Hdr->name[1] == '_' &&
127 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
128 // The member is using a long file name (>15 chars) format.
129 // This format is standard for 4.4BSD and Mac OSX operating
130 // systems. LLVM uses it similarly. In this format, the
131 // remainder of the name field (after #1/) specifies the
132 // length of the file name which occupy the first bytes of
133 // the member's data. The pathname already has the #1/ stripped.
134 pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
135 flags |= ArchiveMember::LLVMSymbolTableFlag;
139 if (Hdr->name[1]== '/') {
140 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
141 pathname.assign(ARFILE_STRTAB_NAME);
142 flags |= ArchiveMember::StringTableFlag;
145 *error = "invalid string table name";
148 } else if (Hdr->name[1] == ' ') {
149 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
150 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
151 flags |= ArchiveMember::SVR4SymbolTableFlag;
154 *error = "invalid SVR4 symbol table name";
157 } else if (isdigit(Hdr->name[1])) {
158 unsigned index = atoi(&Hdr->name[1]);
159 if (index < strtab.length()) {
160 const char* namep = strtab.c_str() + index;
161 const char* endp = strtab.c_str() + strtab.length();
162 const char* p = namep;
163 const char* last_p = p;
165 if (*p == '\n' && *last_p == '/') {
166 pathname.assign(namep, last_p - namep);
167 flags |= ArchiveMember::HasLongFilenameFlag;
175 *error = "missing name termiantor in string table";
180 *error = "name index beyond string table";
186 if (Hdr->name[1] == '_' &&
187 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
188 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
189 flags |= ArchiveMember::BSD4SymbolTableFlag;
195 char* slash = (char*) memchr(Hdr->name, '/', 16);
197 slash = Hdr->name + 16;
198 pathname.assign(Hdr->name, slash - Hdr->name);
202 // Determine if this is a bytecode file
203 switch (sys::IdentifyFileType(At, 4)) {
204 case sys::BytecodeFileType:
205 flags |= ArchiveMember::BytecodeFlag;
207 case sys::CompressedBytecodeFileType:
208 flags |= ArchiveMember::CompressedBytecodeFlag;
209 flags &= ~ArchiveMember::CompressedFlag;
212 flags &= ~(ArchiveMember::BytecodeFlag|
213 ArchiveMember::CompressedBytecodeFlag);
217 // Instantiate the ArchiveMember to be filled
218 ArchiveMember* member = new ArchiveMember(this);
220 // 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->size() < 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 = base + mapfile->size();
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, std::string* ErrorMessage)
333 std::auto_ptr<Archive> result ( new Archive(file));
334 if (result->mapToMemory(ErrorMessage))
336 if (!result->loadArchive(ErrorMessage))
338 return result.release();
341 // Get all the bytecode modules from the archive
343 Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
345 for (iterator I=begin(), E=end(); I != E; ++I) {
346 if (I->isBytecode() || I->isCompressedBytecode()) {
347 std::string FullMemberName = archPath.toString() +
348 "(" + I->getPath().toString() + ")";
349 Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
350 I->getSize(), FullMemberName, ErrMessage);
354 Modules.push_back(M);
360 // Load just the symbol table from the archive file
362 Archive::loadSymbolTable(std::string* ErrorMsg) {
367 const char *At = base;
368 const char *End = base + mapfile->size();
370 // Make sure we're dealing with an archive
371 if (!checkSignature(ErrorMsg))
374 At += 8; // Skip signature
376 // Parse the first file member header
377 const char* FirstFile = At;
378 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
382 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
383 // Skip the foreign symbol table, we don't do anything with it
384 At += mbr->getSize();
385 if ((intptr_t(At) & 1) == 1)
391 mbr = parseMemberHeader(At, End, ErrorMsg);
398 if (mbr->isStringTable()) {
399 // Process the string table entry
400 strtab.assign((const char*)mbr->getData(), mbr->getSize());
401 At += mbr->getSize();
402 if ((intptr_t(At) & 1) == 1)
407 mbr = parseMemberHeader(At, End, ErrorMsg);
414 // See if its the symbol table
415 if (mbr->isLLVMSymbolTable()) {
416 if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
421 At += mbr->getSize();
422 if ((intptr_t(At) & 1) == 1)
425 // Can't be any more symtab headers so just advance
428 // There's no symbol table in the file. We have to rebuild it from scratch
429 // because the intent of this method is to get the symbol table loaded so
430 // it can be searched efficiently.
431 // Add the member to the members list
432 members.push_back(mbr);
435 firstFileOffset = FirstFile - base;
439 // Open the archive and load just the symbol tables
441 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
442 std::auto_ptr<Archive> result ( new Archive(file) );
443 if (result->mapToMemory(ErrorMessage))
445 if (!result->loadSymbolTable(ErrorMessage))
447 return result.release();
450 // Look up one symbol in the symbol table and return a ModuleProvider for the
451 // module that defines that symbol.
453 Archive::findModuleDefiningSymbol(const std::string& symbol,
454 std::string* ErrMsg) {
455 SymTabType::iterator SI = symTab.find(symbol);
456 if (SI == symTab.end())
459 // The symbol table was previously constructed assuming that the members were
460 // written without the symbol table header. Because VBR encoding is used, the
461 // values could not be adjusted to account for the offset of the symbol table
462 // because that could affect the size of the symbol table due to VBR encoding.
463 // We now have to account for this by adjusting the offset by the size of the
464 // symbol table and its header.
465 unsigned fileOffset =
466 SI->second + // offset in symbol-table-less file
467 firstFileOffset; // add offset to first "real" file in archive
469 // See if the module is already loaded
470 ModuleMap::iterator MI = modules.find(fileOffset);
471 if (MI != modules.end())
472 return MI->second.first;
474 // Module hasn't been loaded yet, we need to load it
475 const char* modptr = base + fileOffset;
476 ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size(),ErrMsg);
480 // Now, load the bytecode module to get the ModuleProvider
481 std::string FullMemberName = archPath.toString() + "(" +
482 mbr->getPath().toString() + ")";
483 ModuleProvider* mp = getBytecodeBufferModuleProvider(
484 (const unsigned char*) mbr->getData(), mbr->getSize(),
485 FullMemberName, ErrMsg, 0);
489 modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
494 // Look up multiple symbols in the symbol table and return a set of
495 // ModuleProviders that define those symbols.
497 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
498 std::set<ModuleProvider*>& result,
501 assert(mapfile && base && "Can't findModulesDefiningSymbols on new archive");
502 if (symTab.empty()) {
503 // We don't have a symbol table, so we must build it now but lets also
504 // make sure that we populate the modules table as we do this to ensure
505 // that we don't load them twice when findModuleDefiningSymbol is called
508 // Get a pointer to the first file
509 const char* At = ((const char*)base) + firstFileOffset;
510 const char* End = ((const char*)base) + mapfile->size();
513 // Compute the offset to be put in the symbol table
514 unsigned offset = At - base - firstFileOffset;
516 // Parse the file's header
517 ArchiveMember* mbr = parseMemberHeader(At, End, error);
521 // If it contains symbols
522 if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
524 std::vector<std::string> symbols;
525 std::string FullMemberName = archPath.toString() + "(" +
526 mbr->getPath().toString() + ")";
527 ModuleProvider* MP = GetBytecodeSymbols((const unsigned char*)At,
528 mbr->getSize(), FullMemberName, symbols, error);
531 // Insert the module's symbols into the symbol table
532 for (std::vector<std::string>::iterator I = symbols.begin(),
533 E=symbols.end(); I != E; ++I ) {
534 symTab.insert(std::make_pair(*I, offset));
536 // Insert the ModuleProvider and the ArchiveMember into the table of
538 modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
541 *error = "Can't parse bytecode member: " +
542 mbr->getPath().toString() + ": " + *error;
548 // Go to the next file location
549 At += mbr->getSize();
550 if ((intptr_t(At) & 1) == 1)
555 // At this point we have a valid symbol table (one way or another) so we
556 // just use it to quickly find the symbols requested.
558 for (std::set<std::string>::iterator I=symbols.begin(),
559 E=symbols.end(); I != E;) {
560 // See if this symbol exists
561 ModuleProvider* mp = findModuleDefiningSymbol(*I,error);
563 // The symbol exists, insert the ModuleProvider into our result,
564 // duplicates wil be ignored
567 // Remove the symbol now that its been resolved, being careful to
568 // post-increment the iterator.
577 bool Archive::isBytecodeArchive() {
578 // Make sure the symTab has been loaded. In most cases this should have been
579 // done when the archive was constructed, but still, this is just in case.
581 if (!loadSymbolTable(0))
584 // Now that we know it's been loaded, return true
586 if (symTab.size()) return true;
588 //We still can't be sure it isn't a bytecode archive
592 std::vector<Module *> Modules;
593 std::string ErrorMessage;
595 // Scan the archive, trying to load a bytecode member. We only load one to
596 // see if this works.
597 for (iterator I = begin(), E = end(); I != E; ++I) {
598 if (!I->isBytecode() && !I->isCompressedBytecode())
601 std::string FullMemberName =
602 archPath.toString() + "(" + I->getPath().toString() + ")";
603 Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
604 I->getSize(), FullMemberName);
606 return false; // Couldn't parse bytecode, not a bytecode archive.