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) {
27 throw std::string("Ran out of data reading vbr_uint!");
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) {
37 const char* At = (const char*) data;
38 const char* End = At + size;
40 unsigned offset = readInteger(At, End);
41 unsigned length = readInteger(At, End);
42 if (At + length > End)
43 throw std::string("malformed symbol table");
44 // we don't care if it can't be inserted (duplicate entry)
45 symTab.insert(std::make_pair(std::string(At, length), offset));
51 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
52 // by At. The At pointer is updated to the byte just after the header, which
53 // can be variable in size.
55 Archive::parseMemberHeader(const char*& At, const char* End) {
56 assert(At + sizeof(ArchiveMemberHeader) < End && "Not enough data");
58 // Cast archive member header
59 ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
60 At += sizeof(ArchiveMemberHeader);
62 // Instantiate the ArchiveMember to be filled
63 ArchiveMember* member = new ArchiveMember(this);
65 // Extract the size and determine if the file is
66 // compressed or not (negative length).
68 int MemberSize = atoi(Hdr->size);
70 flags |= ArchiveMember::CompressedFlag;
71 MemberSize = -MemberSize;
74 // Check the size of the member for sanity
75 if (At + MemberSize > End)
76 throw std::string("invalid member length in archive file");
78 // Check the member signature
79 if (!Hdr->checkSignature())
80 throw std::string("invalid file member signature");
82 // Convert and check the member name
83 // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
84 // table. The special name "//" and 14 blanks is for a string table, used
85 // for long file names. This library doesn't generate either of those but
86 // it will accept them. If the name starts with #1/ and the remainder is
87 // digits, then those digits specify the length of the name that is
88 // stored immediately following the header. The special name
89 // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bytecode.
90 // Anything else is a regular, short filename that is terminated with
94 switch (Hdr->name[0]) {
96 if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
97 if (isdigit(Hdr->name[3])) {
98 unsigned len = atoi(&Hdr->name[3]);
99 pathname.assign(At, len);
102 flags |= ArchiveMember::HasLongFilenameFlag;
104 throw std::string("invalid long filename");
105 } else if (Hdr->name[1] == '_' &&
106 (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
107 // The member is using a long file name (>15 chars) format.
108 // This format is standard for 4.4BSD and Mac OSX operating
109 // systems. LLVM uses it similarly. In this format, the
110 // remainder of the name field (after #1/) specifies the
111 // length of the file name which occupy the first bytes of
112 // the member's data. The pathname already has the #1/ stripped.
113 pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
114 flags |= ArchiveMember::LLVMSymbolTableFlag;
118 if (Hdr->name[1]== '/') {
119 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
120 pathname.assign(ARFILE_STRTAB_NAME);
121 flags |= ArchiveMember::StringTableFlag;
123 throw std::string("invalid string table name");
125 } else if (Hdr->name[1] == ' ') {
126 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
127 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
128 flags |= ArchiveMember::SVR4SymbolTableFlag;
130 throw std::string("invalid SVR4 symbol table name");
132 } else if (isdigit(Hdr->name[1])) {
133 unsigned index = atoi(&Hdr->name[1]);
134 if (index < strtab.length()) {
135 const char* namep = strtab.c_str() + index;
136 const char* endp = strtab.c_str() + strtab.length();
137 const char* p = namep;
138 const char* last_p = p;
140 if (*p == '\n' && *last_p == '/') {
141 pathname.assign(namep, last_p - namep);
142 flags |= ArchiveMember::HasLongFilenameFlag;
149 throw std::string("missing name termiantor in string table");
151 throw std::string("name index beyond string table");
156 if (Hdr->name[1] == '_' &&
157 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
158 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
159 flags |= ArchiveMember::BSD4SymbolTableFlag;
165 char* slash = (char*) memchr(Hdr->name, '/', 16);
167 slash = Hdr->name + 16;
168 pathname.assign(Hdr->name, slash - Hdr->name);
172 // Determine if this is a bytecode file
173 switch (sys::IdentifyFileType(At, 4)) {
174 case sys::BytecodeFileType:
175 flags |= ArchiveMember::BytecodeFlag;
177 case sys::CompressedBytecodeFileType:
178 flags |= ArchiveMember::CompressedBytecodeFlag;
179 flags &= ~ArchiveMember::CompressedFlag;
182 flags &= ~(ArchiveMember::BytecodeFlag|
183 ArchiveMember::CompressedBytecodeFlag);
187 // Fill in fields of the ArchiveMember
190 member->parent = this;
191 member->path.set(pathname);
192 member->info.fileSize = MemberSize;
193 member->info.modTime.fromEpochTime(atoi(Hdr->date));
195 sscanf(Hdr->mode, "%o", &mode);
196 member->info.mode = mode;
197 member->info.user = atoi(Hdr->uid);
198 member->info.group = atoi(Hdr->gid);
199 member->flags = flags;
206 Archive::checkSignature() {
207 // Check the magic string at file's header
208 if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC, 8))
209 throw std::string("invalid signature for an archive file");
212 // This function loads the entire archive and fully populates its ilist with
213 // the members of the archive file. This is typically used in preparation for
214 // editing the contents of the archive.
216 Archive::loadArchive() {
221 const char *At = base;
222 const char *End = base + mapfile->size();
225 At += 8; // Skip the magic string.
227 bool seenSymbolTable = false;
228 bool foundFirstFile = false;
230 // parse the member header
231 const char* Save = At;
232 ArchiveMember* mbr = parseMemberHeader(At, End);
234 // check if this is the foreign symbol table
235 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
236 // We just save this but don't do anything special
237 // with it. It doesn't count as the "first file".
239 // What? Multiple foreign symbol tables? Just chuck it
240 // and retain the last one found.
244 At += mbr->getSize();
245 if ((intptr_t(At) & 1) == 1)
247 } else if (mbr->isStringTable()) {
248 // Simply suck the entire string table into a string
249 // variable. This will be used to get the names of the
250 // members that use the "/ddd" format for their names
251 // (SVR4 style long names).
252 strtab.assign(At, mbr->getSize());
253 At += mbr->getSize();
254 if ((intptr_t(At) & 1) == 1)
257 } else if (mbr->isLLVMSymbolTable()) {
258 // This is the LLVM symbol table for the archive. If we've seen it
259 // already, its an error. Otherwise, parse the symbol table and move on.
261 throw std::string("invalid archive: multiple symbol tables");
262 parseSymbolTable(mbr->getData(), mbr->getSize());
263 seenSymbolTable = true;
264 At += mbr->getSize();
265 if ((intptr_t(At) & 1) == 1)
267 delete mbr; // We don't need this member in the list of members.
269 // This is just a regular file. If its the first one, save its offset.
270 // Otherwise just push it on the list and move on to the next file.
271 if (!foundFirstFile) {
272 firstFileOffset = Save - base;
273 foundFirstFile = true;
275 members.push_back(mbr);
276 At += mbr->getSize();
277 if ((intptr_t(At) & 1) == 1)
283 // Open and completely load the archive file.
285 Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage) {
287 std::auto_ptr<Archive> result ( new Archive(file, true));
288 result->loadArchive();
289 return result.release();
290 } catch (const std::string& msg) {
298 // Get all the bytecode modules from the archive
300 Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
302 for (iterator I=begin(), E=end(); I != E; ++I) {
303 if (I->isBytecode() || I->isCompressedBytecode()) {
304 std::string FullMemberName = archPath.toString() +
305 "(" + I->getPath().toString() + ")";
306 Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
307 I->getSize(), FullMemberName, ErrMessage);
311 Modules.push_back(M);
317 // Load just the symbol table from the archive file
319 Archive::loadSymbolTable() {
324 const char *At = base;
325 const char *End = base + mapfile->size();
327 // Make sure we're dealing with an archive
330 At += 8; // Skip signature
332 // Parse the first file member header
333 const char* FirstFile = At;
334 ArchiveMember* mbr = parseMemberHeader(At, End);
336 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
337 // Skip the foreign symbol table, we don't do anything with it
338 At += mbr->getSize();
339 if ((intptr_t(At) & 1) == 1)
345 mbr = parseMemberHeader(At, End);
348 if (mbr->isStringTable()) {
349 // Process the string table entry
350 strtab.assign((const char*)mbr->getData(), mbr->getSize());
351 At += mbr->getSize();
352 if ((intptr_t(At) & 1) == 1)
357 mbr = parseMemberHeader(At, End);
360 // See if its the symbol table
361 if (mbr->isLLVMSymbolTable()) {
362 parseSymbolTable(mbr->getData(), mbr->getSize());
363 At += mbr->getSize();
364 if ((intptr_t(At) & 1) == 1)
368 // There's no symbol table in the file. We have to rebuild it from scratch
369 // because the intent of this method is to get the symbol table loaded so
370 // it can be searched efficiently.
371 // Add the member to the members list
372 members.push_back(mbr);
375 firstFileOffset = FirstFile - base;
378 // Open the archive and load just the symbol tables
380 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
382 std::auto_ptr<Archive> result ( new Archive(file, true) );
383 result->loadSymbolTable();
384 return result.release();
385 } catch (const std::string& msg) {
393 // Look up one symbol in the symbol table and return a ModuleProvider for the
394 // module that defines that symbol.
396 Archive::findModuleDefiningSymbol(const std::string& symbol) {
397 SymTabType::iterator SI = symTab.find(symbol);
398 if (SI == symTab.end())
401 // The symbol table was previously constructed assuming that the members were
402 // written without the symbol table header. Because VBR encoding is used, the
403 // values could not be adjusted to account for the offset of the symbol table
404 // because that could affect the size of the symbol table due to VBR encoding.
405 // We now have to account for this by adjusting the offset by the size of the
406 // symbol table and its header.
407 unsigned fileOffset =
408 SI->second + // offset in symbol-table-less file
409 firstFileOffset; // add offset to first "real" file in archive
411 // See if the module is already loaded
412 ModuleMap::iterator MI = modules.find(fileOffset);
413 if (MI != modules.end())
414 return MI->second.first;
416 // Module hasn't been loaded yet, we need to load it
417 const char* modptr = base + fileOffset;
418 ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size());
420 // Now, load the bytecode module to get the ModuleProvider
421 std::string FullMemberName = archPath.toString() + "(" +
422 mbr->getPath().toString() + ")";
423 ModuleProvider* mp = getBytecodeBufferModuleProvider(
424 (const unsigned char*) mbr->getData(), mbr->getSize(),
427 modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
432 // Look up multiple symbols in the symbol table and return a set of
433 // ModuleProviders that define those symbols.
435 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
436 std::set<ModuleProvider*>& result)
438 assert(mapfile && base && "Can't findModulesDefiningSymbols on new archive");
439 if (symTab.empty()) {
440 // We don't have a symbol table, so we must build it now but lets also
441 // make sure that we populate the modules table as we do this to ensure
442 // that we don't load them twice when findModuleDefiningSymbol is called
445 // Get a pointer to the first file
446 const char* At = ((const char*)base) + firstFileOffset;
447 const char* End = ((const char*)base) + mapfile->size();
450 // Compute the offset to be put in the symbol table
451 unsigned offset = At - base - firstFileOffset;
453 // Parse the file's header
454 ArchiveMember* mbr = parseMemberHeader(At, End);
456 // If it contains symbols
457 if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
459 std::vector<std::string> symbols;
460 std::string FullMemberName = archPath.toString() + "(" +
461 mbr->getPath().toString() + ")";
462 ModuleProvider* MP = GetBytecodeSymbols((const unsigned char*)At,
463 mbr->getSize(), FullMemberName, symbols);
466 // Insert the module's symbols into the symbol table
467 for (std::vector<std::string>::iterator I = symbols.begin(),
468 E=symbols.end(); I != E; ++I ) {
469 symTab.insert(std::make_pair(*I, offset));
471 // Insert the ModuleProvider and the ArchiveMember into the table of
473 modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
475 throw std::string("Can't parse bytecode member: ") +
476 mbr->getPath().toString();
480 // Go to the next file location
481 At += mbr->getSize();
482 if ((intptr_t(At) & 1) == 1)
487 // At this point we have a valid symbol table (one way or another) so we
488 // just use it to quickly find the symbols requested.
490 for (std::set<std::string>::iterator I=symbols.begin(),
491 E=symbols.end(); I != E;) {
492 // See if this symbol exists
493 ModuleProvider* mp = findModuleDefiningSymbol(*I);
495 // The symbol exists, insert the ModuleProvider into our result,
496 // duplicates wil be ignored
499 // Remove the symbol now that its been resolved, being careful to
500 // post-increment the iterator.
508 bool Archive::isBytecodeArchive() {
509 // Make sure the symTab has been loaded. In most cases this should have been
510 // done when the archive was constructed, but still, this is just in case.
514 // Now that we know it's been loaded, return true
516 if (symTab.size()) return true;
518 //We still can't be sure it isn't a bytecode archive
521 std::vector<Module *> Modules;
522 std::string ErrorMessage;
524 // Scan the archive, trying to load a bytecode member. We only load one to
525 // see if this works.
526 for (iterator I = begin(), E = end(); I != E; ++I) {
527 if (!I->isBytecode() && !I->isCompressedBytecode())
530 std::string FullMemberName =
531 archPath.toString() + "(" + I->getPath().toString() + ")";
532 Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
533 I->getSize(), FullMemberName);
535 return false; // Couldn't parse bytecode, not a bytecode archive.