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 pathname
.assign(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 termiantor 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 char* slash
= (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 switch (sys::IdentifyFileType(At
, 4)) {
210 case sys::Bitcode_FileType
:
211 flags
|= ArchiveMember::BitcodeFlag
;
214 flags
&= ~ArchiveMember::BitcodeFlag
;
218 // Instantiate the ArchiveMember to be filled
219 ArchiveMember
* member
= new ArchiveMember(this);
221 // Fill in fields of the ArchiveMember
222 member
->parent
= this;
223 member
->path
.set(pathname
);
224 member
->info
.fileSize
= MemberSize
;
225 member
->info
.modTime
.fromEpochTime(atoi(Hdr
->date
));
227 sscanf(Hdr
->mode
, "%o", &mode
);
228 member
->info
.mode
= mode
;
229 member
->info
.user
= atoi(Hdr
->uid
);
230 member
->info
.group
= atoi(Hdr
->gid
);
231 member
->flags
= flags
;
238 Archive::checkSignature(std::string
* error
) {
239 // Check the magic string at file's header
240 if (mapfile
->getBufferSize() < 8 || memcmp(base
, ARFILE_MAGIC
, 8)) {
242 *error
= "invalid signature for an archive file";
248 // This function loads the entire archive and fully populates its ilist with
249 // the members of the archive file. This is typically used in preparation for
250 // editing the contents of the archive.
252 Archive::loadArchive(std::string
* error
) {
257 const char *At
= base
;
258 const char *End
= mapfile
->getBufferEnd();
260 if (!checkSignature(error
))
263 At
+= 8; // Skip the magic string.
265 bool seenSymbolTable
= false;
266 bool foundFirstFile
= false;
268 // parse the member header
269 const char* Save
= At
;
270 ArchiveMember
* mbr
= parseMemberHeader(At
, End
, error
);
274 // check if this is the foreign symbol table
275 if (mbr
->isSVR4SymbolTable() || mbr
->isBSD4SymbolTable()) {
276 // We just save this but don't do anything special
277 // with it. It doesn't count as the "first file".
279 // What? Multiple foreign symbol tables? Just chuck it
280 // and retain the last one found.
284 At
+= mbr
->getSize();
285 if ((intptr_t(At
) & 1) == 1)
287 } else if (mbr
->isStringTable()) {
288 // Simply suck the entire string table into a string
289 // variable. This will be used to get the names of the
290 // members that use the "/ddd" format for their names
291 // (SVR4 style long names).
292 strtab
.assign(At
, mbr
->getSize());
293 At
+= mbr
->getSize();
294 if ((intptr_t(At
) & 1) == 1)
297 } else if (mbr
->isLLVMSymbolTable()) {
298 // This is the LLVM symbol table for the archive. If we've seen it
299 // already, its an error. Otherwise, parse the symbol table and move on.
300 if (seenSymbolTable
) {
302 *error
= "invalid archive: multiple symbol tables";
305 if (!parseSymbolTable(mbr
->getData(), mbr
->getSize(), error
))
307 seenSymbolTable
= true;
308 At
+= mbr
->getSize();
309 if ((intptr_t(At
) & 1) == 1)
311 delete mbr
; // We don't need this member in the list of members.
313 // This is just a regular file. If its the first one, save its offset.
314 // Otherwise just push it on the list and move on to the next file.
315 if (!foundFirstFile
) {
316 firstFileOffset
= Save
- base
;
317 foundFirstFile
= true;
319 members
.push_back(mbr
);
320 At
+= mbr
->getSize();
321 if ((intptr_t(At
) & 1) == 1)
328 // Open and completely load the archive file.
330 Archive::OpenAndLoad(const sys::Path
& file
, std::string
* ErrorMessage
)
332 std::auto_ptr
<Archive
> result ( new Archive(file
));
333 if (result
->mapToMemory(ErrorMessage
))
335 if (!result
->loadArchive(ErrorMessage
))
337 return result
.release();
340 // Get all the bitcode modules from the archive
342 Archive::getAllModules(std::vector
<Module
*>& Modules
, std::string
* ErrMessage
) {
344 for (iterator I
=begin(), E
=end(); I
!= E
; ++I
) {
345 if (I
->isBitcode()) {
346 std::string FullMemberName
= archPath
.toString() +
347 "(" + I
->getPath().toString() + ")";
348 MemoryBuffer
*Buffer
=
349 MemoryBuffer::getNewMemBuffer(I
->getSize(), FullMemberName
.c_str());
350 memcpy((char*)Buffer
->getBufferStart(), I
->getData(), I
->getSize());
352 Module
*M
= ParseBitcodeFile(Buffer
, ErrMessage
);
357 Modules
.push_back(M
);
363 // Load just the symbol table from the archive file
365 Archive::loadSymbolTable(std::string
* ErrorMsg
) {
370 const char *At
= base
;
371 const char *End
= mapfile
->getBufferEnd();
373 // Make sure we're dealing with an archive
374 if (!checkSignature(ErrorMsg
))
377 At
+= 8; // Skip signature
379 // Parse the first file member header
380 const char* FirstFile
= At
;
381 ArchiveMember
* mbr
= parseMemberHeader(At
, End
, ErrorMsg
);
385 if (mbr
->isSVR4SymbolTable() || mbr
->isBSD4SymbolTable()) {
386 // Skip the foreign symbol table, we don't do anything with it
387 At
+= mbr
->getSize();
388 if ((intptr_t(At
) & 1) == 1)
394 mbr
= parseMemberHeader(At
, End
, ErrorMsg
);
401 if (mbr
->isStringTable()) {
402 // Process the string table entry
403 strtab
.assign((const char*)mbr
->getData(), mbr
->getSize());
404 At
+= mbr
->getSize();
405 if ((intptr_t(At
) & 1) == 1)
410 mbr
= parseMemberHeader(At
, End
, ErrorMsg
);
417 // See if its the symbol table
418 if (mbr
->isLLVMSymbolTable()) {
419 if (!parseSymbolTable(mbr
->getData(), mbr
->getSize(), ErrorMsg
)) {
424 At
+= mbr
->getSize();
425 if ((intptr_t(At
) & 1) == 1)
428 // Can't be any more symtab headers so just advance
431 // There's no symbol table in the file. We have to rebuild it from scratch
432 // because the intent of this method is to get the symbol table loaded so
433 // it can be searched efficiently.
434 // Add the member to the members list
435 members
.push_back(mbr
);
438 firstFileOffset
= FirstFile
- base
;
442 // Open the archive and load just the symbol tables
444 Archive::OpenAndLoadSymbols(const sys::Path
& file
, std::string
* ErrorMessage
) {
445 std::auto_ptr
<Archive
> result ( new Archive(file
) );
446 if (result
->mapToMemory(ErrorMessage
))
448 if (!result
->loadSymbolTable(ErrorMessage
))
450 return result
.release();
453 // Look up one symbol in the symbol table and return a ModuleProvider for the
454 // module that defines that symbol.
456 Archive::findModuleDefiningSymbol(const std::string
& symbol
,
457 std::string
* ErrMsg
) {
458 SymTabType::iterator SI
= symTab
.find(symbol
);
459 if (SI
== symTab
.end())
462 // The symbol table was previously constructed assuming that the members were
463 // written without the symbol table header. Because VBR encoding is used, the
464 // values could not be adjusted to account for the offset of the symbol table
465 // because that could affect the size of the symbol table due to VBR encoding.
466 // We now have to account for this by adjusting the offset by the size of the
467 // symbol table and its header.
468 unsigned fileOffset
=
469 SI
->second
+ // offset in symbol-table-less file
470 firstFileOffset
; // add offset to first "real" file in archive
472 // See if the module is already loaded
473 ModuleMap::iterator MI
= modules
.find(fileOffset
);
474 if (MI
!= modules
.end())
475 return MI
->second
.first
;
477 // Module hasn't been loaded yet, we need to load it
478 const char* modptr
= base
+ fileOffset
;
479 ArchiveMember
* mbr
= parseMemberHeader(modptr
, mapfile
->getBufferEnd(),
484 // Now, load the bitcode module to get the ModuleProvider
485 std::string FullMemberName
= archPath
.toString() + "(" +
486 mbr
->getPath().toString() + ")";
487 MemoryBuffer
*Buffer
=MemoryBuffer::getNewMemBuffer(mbr
->getSize(),
488 FullMemberName
.c_str());
489 memcpy((char*)Buffer
->getBufferStart(), mbr
->getData(), mbr
->getSize());
491 ModuleProvider
*mp
= getBitcodeModuleProvider(Buffer
, ErrMsg
);
495 modules
.insert(std::make_pair(fileOffset
, std::make_pair(mp
, mbr
)));
500 // Look up multiple symbols in the symbol table and return a set of
501 // ModuleProviders that define those symbols.
503 Archive::findModulesDefiningSymbols(std::set
<std::string
>& symbols
,
504 std::set
<ModuleProvider
*>& result
,
505 std::string
* error
) {
506 if (!mapfile
|| !base
) {
508 *error
= "Empty archive invalid for finding modules defining symbols";
512 if (symTab
.empty()) {
513 // We don't have a symbol table, so we must build it now but lets also
514 // make sure that we populate the modules table as we do this to ensure
515 // that we don't load them twice when findModuleDefiningSymbol is called
518 // Get a pointer to the first file
519 const char* At
= base
+ firstFileOffset
;
520 const char* End
= mapfile
->getBufferEnd();
523 // Compute the offset to be put in the symbol table
524 unsigned offset
= At
- base
- firstFileOffset
;
526 // Parse the file's header
527 ArchiveMember
* mbr
= parseMemberHeader(At
, End
, error
);
531 // If it contains symbols
532 if (mbr
->isBitcode()) {
534 std::vector
<std::string
> symbols
;
535 std::string FullMemberName
= archPath
.toString() + "(" +
536 mbr
->getPath().toString() + ")";
538 GetBitcodeSymbols((const unsigned char*)At
, mbr
->getSize(),
539 FullMemberName
, symbols
, error
);
542 // Insert the module's symbols into the symbol table
543 for (std::vector
<std::string
>::iterator I
= symbols
.begin(),
544 E
=symbols
.end(); I
!= E
; ++I
) {
545 symTab
.insert(std::make_pair(*I
, offset
));
547 // Insert the ModuleProvider and the ArchiveMember into the table of
549 modules
.insert(std::make_pair(offset
, std::make_pair(MP
, mbr
)));
552 *error
= "Can't parse bitcode member: " +
553 mbr
->getPath().toString() + ": " + *error
;
559 // Go to the next file location
560 At
+= mbr
->getSize();
561 if ((intptr_t(At
) & 1) == 1)
566 // At this point we have a valid symbol table (one way or another) so we
567 // just use it to quickly find the symbols requested.
569 for (std::set
<std::string
>::iterator I
=symbols
.begin(),
570 E
=symbols
.end(); I
!= E
;) {
571 // See if this symbol exists
572 ModuleProvider
* mp
= findModuleDefiningSymbol(*I
,error
);
574 // The symbol exists, insert the ModuleProvider into our result,
575 // duplicates wil be ignored
578 // Remove the symbol now that its been resolved, being careful to
579 // post-increment the iterator.
588 bool Archive::isBitcodeArchive() {
589 // Make sure the symTab has been loaded. In most cases this should have been
590 // done when the archive was constructed, but still, this is just in case.
592 if (!loadSymbolTable(0))
595 // Now that we know it's been loaded, return true
597 if (symTab
.size()) return true;
599 // We still can't be sure it isn't a bitcode archive
603 std::vector
<Module
*> Modules
;
604 std::string ErrorMessage
;
606 // Scan the archive, trying to load a bitcode member. We only load one to
607 // see if this works.
608 for (iterator I
= begin(), E
= end(); I
!= E
; ++I
) {
612 std::string FullMemberName
=
613 archPath
.toString() + "(" + I
->getPath().toString() + ")";
615 MemoryBuffer
*Buffer
=
616 MemoryBuffer::getNewMemBuffer(I
->getSize(), FullMemberName
.c_str());
617 memcpy((char*)Buffer
->getBufferStart(), I
->getData(), I
->getSize());
618 Module
*M
= ParseBitcodeFile(Buffer
);
621 return false; // Couldn't parse bitcode, not a bitcode archive.