1271d02028e63bb60dccdd21e4a5b85336e3c9a8
[oota-llvm.git] / tools / llvm-ar / ArchiveReader.cpp
1 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up standard unix archive files (.a) containing LLVM bitcode.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Archive.h"
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"
22 #include <cstdio>
23 #include <cstdlib>
24 using namespace llvm;
25
26 /// Read a variable-bit-rate encoded unsigned integer
27 static inline unsigned readInteger(const char*&At, const char*End) {
28   unsigned Shift = 0;
29   unsigned Result = 0;
30
31   do {
32     if (At == End)
33       return Result;
34     Result |= (unsigned)((*At++) & 0x7F) << Shift;
35     Shift += 7;
36   } while (At[-1] & 0x80);
37   return Result;
38 }
39
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.
43 ArchiveMember*
44 Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
45 {
46   if (At + sizeof(ArchiveMemberHeader) >= End) {
47     if (error)
48       *error = "Unexpected end of file";
49     return 0;
50   }
51
52   // Cast archive member header
53   const ArchiveMemberHeader* Hdr = (const ArchiveMemberHeader*)At;
54   At += sizeof(ArchiveMemberHeader);
55
56   int flags = 0;
57   int MemberSize = atoi(Hdr->size);
58   assert(MemberSize >= 0);
59
60   // Check the size of the member for sanity
61   if (At + MemberSize > End) {
62     if (error)
63       *error = "invalid member length in archive file";
64     return 0;
65   }
66
67   // Check the member signature
68   if (!Hdr->checkSignature()) {
69     if (error)
70       *error = "invalid file member signature";
71     return 0;
72   }
73
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.
82
83   std::string pathname;
84   switch (Hdr->name[0]) {
85     case '#':
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);
91           At += len;
92           MemberSize -= len;
93           flags |= ArchiveMember::HasLongFilenameFlag;
94         } else {
95           if (error)
96             *error = "invalid long filename";
97           return 0;
98         }
99       }
100       break;
101     case '/':
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;
106         } else {
107           if (error)
108             *error = "invalid string table name";
109           return 0;
110         }
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;
115         } else {
116           if (error)
117             *error = "invalid SVR4 symbol table name";
118           return 0;
119         }
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;
127           while (p < endp) {
128             if (*p == '\n' && *last_p == '/') {
129               pathname.assign(namep, last_p - namep);
130               flags |= ArchiveMember::HasLongFilenameFlag;
131               break;
132             }
133             last_p = p;
134             p++;
135           }
136           if (p >= endp) {
137             if (error)
138               *error = "missing name terminator in string table";
139             return 0;
140           }
141         } else {
142           if (error)
143             *error = "name index beyond string table";
144           return 0;
145         }
146       }
147       break;
148     case '_':
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;
153         break;
154       }
155       /* FALL THROUGH */
156
157     default:
158       const char* slash = (const char*) memchr(Hdr->name, '/', 16);
159       if (slash == 0)
160         slash = Hdr->name + 16;
161       pathname.assign(Hdr->name, slash - Hdr->name);
162       break;
163   }
164
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;
169   else
170     flags &= ~ArchiveMember::BitcodeFlag;
171
172   // Instantiate the ArchiveMember to be filled
173   ArchiveMember* member = new ArchiveMember(this);
174
175   // Fill in fields of the ArchiveMember
176   member->parent = this;
177   member->path = pathname;
178   member->info.fileSize = MemberSize;
179   member->info.modTime.fromEpochTime(atoi(Hdr->date));
180   unsigned int mode;
181   sscanf(Hdr->mode, "%o", &mode);
182   member->info.mode = mode;
183   member->info.user = atoi(Hdr->uid);
184   member->info.group = atoi(Hdr->gid);
185   member->flags = flags;
186   member->data = At;
187
188   return member;
189 }
190
191 bool
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)) {
195     if (error)
196       *error = "invalid signature for an archive file";
197     return false;
198   }
199   return true;
200 }
201
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.
205 bool
206 Archive::loadArchive(std::string* error) {
207
208   // Set up parsing
209   members.clear();
210   symTab.clear();
211   const char *At = base;
212   const char *End = mapfile->getBufferEnd();
213
214   if (!checkSignature(error))
215     return false;
216
217   At += 8;  // Skip the magic string.
218
219   bool foundFirstFile = false;
220   while (At < End) {
221     // parse the member header
222     const char* Save = At;
223     ArchiveMember* mbr = parseMemberHeader(At, End, error);
224     if (!mbr)
225       return false;
226
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".
231       if (foreignST) {
232         // What? Multiple foreign symbol tables? Just chuck it
233         // and retain the last one found.
234         delete foreignST;
235       }
236       foreignST = mbr;
237       At += mbr->getSize();
238       if ((intptr_t(At) & 1) == 1)
239         At++;
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)
248         At++;
249       delete mbr;
250     } else {
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;
256       }
257       members.push_back(mbr);
258       At += mbr->getSize();
259       if ((intptr_t(At) & 1) == 1)
260         At++;
261     }
262   }
263   return true;
264 }
265
266 // Open and completely load the archive file.
267 Archive*
268 Archive::OpenAndLoad(const sys::Path& File, LLVMContext& C,
269                      std::string* ErrorMessage) {
270   OwningPtr<Archive> result ( new Archive(File, C));
271   if (result->mapToMemory(ErrorMessage))
272     return NULL;
273   if (!result->loadArchive(ErrorMessage))
274     return NULL;
275   return result.take();
276 }
277
278 // Get all the bitcode modules from the archive
279 bool
280 Archive::getAllModules(std::vector<Module*>& Modules,
281                        std::string* ErrMessage) {
282
283   for (iterator I=begin(), E=end(); I != E; ++I) {
284     if (I->isBitcode()) {
285       std::string FullMemberName = archPath.str() +
286         "(" + I->getPath().str() + ")";
287       MemoryBuffer *Buffer =
288         MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
289                                        FullMemberName.c_str());
290       
291       Module *M = ParseBitcodeFile(Buffer, Context, ErrMessage);
292       delete Buffer;
293       if (!M)
294         return true;
295
296       Modules.push_back(M);
297     }
298   }
299   return false;
300 }
301
302 // Load just the symbol table from the archive file
303 bool
304 Archive::loadSymbolTable(std::string* ErrorMsg) {
305
306   // Set up parsing
307   members.clear();
308   symTab.clear();
309   const char *At = base;
310   const char *End = mapfile->getBufferEnd();
311
312   // Make sure we're dealing with an archive
313   if (!checkSignature(ErrorMsg))
314     return false;
315
316   At += 8; // Skip signature
317
318   // Parse the first file member header
319   const char* FirstFile = At;
320   ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
321   if (!mbr)
322     return false;
323
324   if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
325     // Skip the foreign symbol table, we don't do anything with it
326     At += mbr->getSize();
327     if ((intptr_t(At) & 1) == 1)
328       At++;
329     delete mbr;
330
331     // Read the next one
332     FirstFile = At;
333     mbr = parseMemberHeader(At, End, ErrorMsg);
334     if (!mbr) {
335       delete mbr;
336       return false;
337     }
338   }
339
340   if (mbr->isStringTable()) {
341     // Process the string table entry
342     strtab.assign((const char*)mbr->getData(), mbr->getSize());
343     At += mbr->getSize();
344     if ((intptr_t(At) & 1) == 1)
345       At++;
346     delete mbr;
347     // Get the next one
348     FirstFile = At;
349     mbr = parseMemberHeader(At, End, ErrorMsg);
350     if (!mbr) {
351       delete mbr;
352       return false;
353     }
354   }
355
356   // There's no symbol table in the file. We have to rebuild it from scratch
357   // because the intent of this method is to get the symbol table loaded so
358   // it can be searched efficiently.
359   // Add the member to the members list
360   members.push_back(mbr);
361
362   firstFileOffset = FirstFile - base;
363   return true;
364 }
365
366 // Open the archive and load just the symbol tables
367 Archive* Archive::OpenAndLoadSymbols(const sys::Path& File,
368                                      LLVMContext& C,
369                                      std::string* ErrorMessage) {
370   OwningPtr<Archive> result ( new Archive(File, C) );
371   if (result->mapToMemory(ErrorMessage))
372     return NULL;
373   if (!result->loadSymbolTable(ErrorMessage))
374     return NULL;
375   return result.take();
376 }
377
378 // Look up one symbol in the symbol table and return the module that defines
379 // that symbol.
380 Module*
381 Archive::findModuleDefiningSymbol(const std::string& symbol, 
382                                   std::string* ErrMsg) {
383   SymTabType::iterator SI = symTab.find(symbol);
384   if (SI == symTab.end())
385     return 0;
386
387   // The symbol table was previously constructed assuming that the members were
388   // written without the symbol table header. Because VBR encoding is used, the
389   // values could not be adjusted to account for the offset of the symbol table
390   // because that could affect the size of the symbol table due to VBR encoding.
391   // We now have to account for this by adjusting the offset by the size of the
392   // symbol table and its header.
393   unsigned fileOffset =
394     SI->second +                // offset in symbol-table-less file
395     firstFileOffset;            // add offset to first "real" file in archive
396
397   // See if the module is already loaded
398   ModuleMap::iterator MI = modules.find(fileOffset);
399   if (MI != modules.end())
400     return MI->second.first;
401
402   // Module hasn't been loaded yet, we need to load it
403   const char* modptr = base + fileOffset;
404   ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
405                                          ErrMsg);
406   if (!mbr)
407     return 0;
408
409   // Now, load the bitcode module to get the Module.
410   std::string FullMemberName = archPath.str() + "(" +
411     mbr->getPath().str() + ")";
412   MemoryBuffer *Buffer =
413     MemoryBuffer::getMemBufferCopy(StringRef(mbr->getData(), mbr->getSize()),
414                                    FullMemberName.c_str());
415   
416   Module *m = getLazyBitcodeModule(Buffer, Context, ErrMsg);
417   if (!m)
418     return 0;
419
420   modules.insert(std::make_pair(fileOffset, std::make_pair(m, mbr)));
421
422   return m;
423 }
424
425 // Look up multiple symbols in the symbol table and return a set of
426 // Modules that define those symbols.
427 bool
428 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
429                                     SmallVectorImpl<Module*>& result,
430                                     std::string* error) {
431   if (!mapfile || !base) {
432     if (error)
433       *error = "Empty archive invalid for finding modules defining symbols";
434     return false;
435   }
436
437   if (symTab.empty()) {
438     // We don't have a symbol table, so we must build it now but lets also
439     // make sure that we populate the modules table as we do this to ensure
440     // that we don't load them twice when findModuleDefiningSymbol is called
441     // below.
442
443     // Get a pointer to the first file
444     const char* At  = base + firstFileOffset;
445     const char* End = mapfile->getBufferEnd();
446
447     while ( At < End) {
448       // Compute the offset to be put in the symbol table
449       unsigned offset = At - base - firstFileOffset;
450
451       // Parse the file's header
452       ArchiveMember* mbr = parseMemberHeader(At, End, error);
453       if (!mbr)
454         return false;
455
456       // If it contains symbols
457       if (mbr->isBitcode()) {
458         // Get the symbols
459         std::vector<std::string> symbols;
460         std::string FullMemberName = archPath.str() + "(" +
461           mbr->getPath().str() + ")";
462         Module* M = 
463           GetBitcodeSymbols(At, mbr->getSize(), FullMemberName, Context,
464                             symbols, error);
465
466         if (M) {
467           // Insert the module's symbols into the symbol table
468           for (std::vector<std::string>::iterator I = symbols.begin(),
469                E=symbols.end(); I != E; ++I ) {
470             symTab.insert(std::make_pair(*I, offset));
471           }
472           // Insert the Module and the ArchiveMember into the table of
473           // modules.
474           modules.insert(std::make_pair(offset, std::make_pair(M, mbr)));
475         } else {
476           if (error)
477             *error = "Can't parse bitcode member: " + 
478               mbr->getPath().str() + ": " + *error;
479           delete mbr;
480           return false;
481         }
482       }
483
484       // Go to the next file location
485       At += mbr->getSize();
486       if ((intptr_t(At) & 1) == 1)
487         At++;
488     }
489   }
490
491   // At this point we have a valid symbol table (one way or another) so we
492   // just use it to quickly find the symbols requested.
493
494   SmallPtrSet<Module*, 16> Added;
495   for (std::set<std::string>::iterator I=symbols.begin(),
496          Next = I,
497          E=symbols.end(); I != E; I = Next) {
498     // Increment Next before we invalidate it.
499     ++Next;
500
501     // See if this symbol exists
502     Module* m = findModuleDefiningSymbol(*I,error);
503     if (!m)
504       continue;
505     bool NewMember = Added.insert(m);
506     if (!NewMember)
507       continue;
508
509     // The symbol exists, insert the Module into our result.
510     result.push_back(m);
511
512     // Remove the symbol now that its been resolved.
513     symbols.erase(I);
514   }
515   return true;
516 }
517
518 bool Archive::isBitcodeArchive() {
519   // Make sure the symTab has been loaded. In most cases this should have been
520   // done when the archive was constructed, but still,  this is just in case.
521   if (symTab.empty())
522     if (!loadSymbolTable(0))
523       return false;
524
525   // Now that we know it's been loaded, return true
526   // if it has a size
527   if (symTab.size()) return true;
528
529   // We still can't be sure it isn't a bitcode archive
530   if (!loadArchive(0))
531     return false;
532
533   std::vector<Module *> Modules;
534   std::string ErrorMessage;
535
536   // Scan the archive, trying to load a bitcode member.  We only load one to
537   // see if this works.
538   for (iterator I = begin(), E = end(); I != E; ++I) {
539     if (!I->isBitcode())
540       continue;
541     
542     std::string FullMemberName = 
543       archPath.str() + "(" + I->getPath().str() + ")";
544
545     MemoryBuffer *Buffer =
546       MemoryBuffer::getMemBufferCopy(StringRef(I->getData(), I->getSize()),
547                                      FullMemberName.c_str());
548     Module *M = ParseBitcodeFile(Buffer, Context);
549     delete Buffer;
550     if (!M)
551       return false;  // Couldn't parse bitcode, not a bitcode archive.
552     delete M;
553     return true;
554   }
555   
556   return false;
557 }