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 //===----------------------------------------------------------------------===//
15 #include "ArchiveInternals.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
26 /// Read a variable-bit-rate encoded unsigned integer
27 static inline unsigned readInteger(const char*&At, const char*End) {
34 Result |= (unsigned)((*At++) & 0x7F) << Shift;
36 } while (At[-1] & 0x80);
40 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
41 // by At. The At pointer is updated to the byte just after the header, which
42 // can be variable in size.
44 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
46 if (At + sizeof(ArchiveMemberHeader) >= End) {
48 *error = "Unexpected end of file";
52 // Cast archive member header
53 const ArchiveMemberHeader* Hdr = (const ArchiveMemberHeader*)At;
54 At += sizeof(ArchiveMemberHeader);
57 int MemberSize = atoi(Hdr->size);
58 assert(MemberSize >= 0);
60 // Check the size of the member for sanity
61 if (At + MemberSize > End) {
63 *error = "invalid member length in archive file";
67 // Check the member signature
68 if (!Hdr->checkSignature()) {
70 *error = "invalid file member signature";
74 // Convert and check the member name
75 // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
76 // table. The special name "//" and 14 blanks is for a string table, used
77 // for long file names. This library doesn't generate either of those but
78 // it will accept them. If the name starts with #1/ and the remainder is
79 // digits, then those digits specify the length of the name that is
80 // stored immediately following the header. Anything else is a regular, short
81 // filename that is terminated with a '/' and blanks.
84 switch (Hdr->name[0]) {
86 if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
87 if (isdigit(Hdr->name[3])) {
88 unsigned len = atoi(&Hdr->name[3]);
89 const char *nulp = (const char *)memchr(At, '\0', len);
90 pathname.assign(At, nulp != 0 ? (uintptr_t)(nulp - At) : len);
93 flags |= ArchiveMember::HasLongFilenameFlag;
96 *error = "invalid long filename";
102 if (Hdr->name[1]== '/') {
103 if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
104 pathname.assign(ARFILE_STRTAB_NAME);
105 flags |= ArchiveMember::StringTableFlag;
108 *error = "invalid string table name";
111 } else if (Hdr->name[1] == ' ') {
112 if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
113 pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
114 flags |= ArchiveMember::SVR4SymbolTableFlag;
117 *error = "invalid SVR4 symbol table name";
120 } else if (isdigit(Hdr->name[1])) {
121 unsigned index = atoi(&Hdr->name[1]);
122 if (index < strtab.length()) {
123 const char* namep = strtab.c_str() + index;
124 const char* endp = strtab.c_str() + strtab.length();
125 const char* p = namep;
126 const char* last_p = p;
128 if (*p == '\n' && *last_p == '/') {
129 pathname.assign(namep, last_p - namep);
130 flags |= ArchiveMember::HasLongFilenameFlag;
138 *error = "missing name terminator in string table";
143 *error = "name index beyond string table";
149 if (Hdr->name[1] == '_' &&
150 (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
151 pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
152 flags |= ArchiveMember::BSD4SymbolTableFlag;
158 const char* slash = (const char*) memchr(Hdr->name, '/', 16);
160 slash = Hdr->name + 16;
161 pathname.assign(Hdr->name, slash - Hdr->name);
165 // Determine if this is a bitcode file
166 if (sys::fs::identify_magic(StringRef(At, 4)) ==
167 sys::fs::file_magic::bitcode)
168 flags |= ArchiveMember::BitcodeFlag;
170 flags &= ~ArchiveMember::BitcodeFlag;
172 // Instantiate the ArchiveMember to be filled
173 ArchiveMember* member = new ArchiveMember(this);
175 // Fill in fields of the ArchiveMember
176 member->parent = this;
177 member->path = pathname;
178 member->Size = MemberSize;
179 member->ModTime.fromEpochTime(atoi(Hdr->date));
181 sscanf(Hdr->mode, "%o", &mode);
183 member->User = atoi(Hdr->uid);
184 member->Group = atoi(Hdr->gid);
185 member->flags = flags;
192 Archive::checkSignature(std::string* error) {
193 // Check the magic string at file's header
194 if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
196 *error = "invalid signature for an archive file";
202 // This function loads the entire archive and fully populates its ilist with
203 // the members of the archive file. This is typically used in preparation for
204 // editing the contents of the archive.
206 Archive::loadArchive(std::string* error) {
211 const char *At = base;
212 const char *End = mapfile->getBufferEnd();
214 if (!checkSignature(error))
217 At += 8; // Skip the magic string.
219 bool foundFirstFile = false;
221 // parse the member header
222 const char* Save = At;
223 ArchiveMember* mbr = parseMemberHeader(At, End, error);
227 // check if this is the foreign symbol table
228 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
229 // We just save this but don't do anything special
230 // with it. It doesn't count as the "first file".
232 // What? Multiple foreign symbol tables? Just chuck it
233 // and retain the last one found.
237 At += mbr->getSize();
238 if ((intptr_t(At) & 1) == 1)
240 } else if (mbr->isStringTable()) {
241 // Simply suck the entire string table into a string
242 // variable. This will be used to get the names of the
243 // members that use the "/ddd" format for their names
244 // (SVR4 style long names).
245 strtab.assign(At, mbr->getSize());
246 At += mbr->getSize();
247 if ((intptr_t(At) & 1) == 1)
251 // This is just a regular file. If its the first one, save its offset.
252 // Otherwise just push it on the list and move on to the next file.
253 if (!foundFirstFile) {
254 firstFileOffset = Save - base;
255 foundFirstFile = true;
257 members.push_back(mbr);
258 At += mbr->getSize();
259 if ((intptr_t(At) & 1) == 1)
266 // Open and completely load the archive file.
268 Archive::OpenAndLoad(StringRef File, LLVMContext& C,
269 std::string* ErrorMessage) {
270 OwningPtr<Archive> result(new Archive(File, C));
271 if (result->mapToMemory(ErrorMessage))
273 if (!result->loadArchive(ErrorMessage))
275 return result.take();
278 // Get all the bitcode modules from the archive
280 Archive::getAllModules(std::vector<Module*>& Modules,
281 std::string* ErrMessage) {
283 for (iterator I=begin(), E=end(); I != E; ++I) {
284 if (I->isBitcode()) {
285 std::string FullMemberName = archPath + "(" + I->getPath().str() + ")";
286 MemoryBuffer *Buffer =
287 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
288 FullMemberName.c_str());
290 Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
295 Modules.push_back(M);
301 // Load just the symbol table from the archive file
303 Archive::loadSymbolTable(std::string* ErrorMsg) {
308 const char *At = base;
309 const char *End = mapfile->getBufferEnd();
311 // Make sure we're dealing with an archive
312 if (!checkSignature(ErrorMsg))
315 At += 8; // Skip signature
317 // Parse the first file member header
318 const char* FirstFile = At;
319 ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
323 if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
324 // Skip the foreign symbol table, we don't do anything with it
325 At += mbr->getSize();
326 if ((intptr_t(At) & 1) == 1)
332 mbr = parseMemberHeader(At, End, ErrorMsg);
339 if (mbr->isStringTable()) {
340 // Process the string table entry
341 strtab.assign((const char*)mbr->getData(), mbr->getSize());
342 At += mbr->getSize();
343 if ((intptr_t(At) & 1) == 1)
348 mbr = parseMemberHeader(At, End, ErrorMsg);
355 // There's no symbol table in the file. We have to rebuild it from scratch
356 // because the intent of this method is to get the symbol table loaded so
357 // it can be searched efficiently.
358 // Add the member to the members list
359 members.push_back(mbr);
361 firstFileOffset = FirstFile - base;
365 bool Archive::isBitcodeArchive() {
366 // Make sure the symTab has been loaded. In most cases this should have been
367 // done when the archive was constructed, but still, this is just in case.
369 if (!loadSymbolTable(0))
372 // Now that we know it's been loaded, return true
374 if (symTab.size()) return true;
376 // We still can't be sure it isn't a bitcode archive
380 std::vector<Module *> Modules;
381 std::string ErrorMessage;
383 // Scan the archive, trying to load a bitcode member. We only load one to
384 // see if this works.
385 for (iterator I = begin(), E = end(); I != E; ++I) {
389 std::string FullMemberName = archPath + "(" + I->getPath().str() + ")";
391 MemoryBuffer *Buffer =
392 MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
393 FullMemberName.c_str());
394 Module *M = ParseBitcodeFile(Buffer, Context);
397 return false; // Couldn't parse bitcode, not a bitcode archive.