Implement error handling in OpenAndLoad* functions so the Linker can handle it.
[oota-llvm.git] / lib / Archive / ArchiveReader.cpp
1 //===-- ArchiveReader.cpp - Read LLVM archive files -------------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up standard unix archive files (.a) containing LLVM bytecode.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ArchiveInternals.h"
15 #include "llvm/Bytecode/Reader.h"
16
17 using namespace llvm;
18
19 /// Read a variable-bit-rate encoded unsigned integer
20 inline unsigned readInteger(const char*&At, const char*End) {
21   unsigned Shift = 0;
22   unsigned Result = 0;
23   
24   do {
25     if (At == End) 
26       throw std::string("Ran out of data reading vbr_uint!");
27     Result |= (unsigned)((*At++) & 0x7F) << Shift;
28     Shift += 7;
29   } while (At[-1] & 0x80);
30   return Result;
31 }
32
33 // Completely parse the Archive's symbol table and populate symTab member var.
34 void
35 Archive::parseSymbolTable(const void* data, unsigned size) {
36   const char* At = (const char*) data;
37   const char* End = At + size;
38   while (At < End) {
39     unsigned offset = readInteger(At, End);
40     unsigned length = readInteger(At, End);
41     if (At + length > End)
42       throw std::string("malformed symbol table");
43     // we don't care if it can't be inserted (duplicate entry)
44     symTab.insert(std::make_pair(std::string(At, length), offset));
45     At += length;
46   }
47   symTabSize = size;
48 }
49
50 // This member parses an ArchiveMemberHeader that is presumed to be pointed to
51 // by At. The At pointer is updated to the byte just after the header, which
52 // can be variable in size. 
53 ArchiveMember*
54 Archive::parseMemberHeader(const char*& At, const char* End) {
55   assert(At + sizeof(ArchiveMemberHeader) < End && "Not enough data");
56
57   // Cast archive member header
58   ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
59   At += sizeof(ArchiveMemberHeader);
60
61   // Instantiate the ArchiveMember to be filled
62   ArchiveMember* member = new ArchiveMember(this);
63
64   // Extract the size and determine if the file is 
65   // compressed or not (negative length).
66   int flags = 0;
67   int MemberSize = atoi(Hdr->size);
68   if (MemberSize < 0) {
69     flags |= ArchiveMember::CompressedFlag;
70     MemberSize = -MemberSize;
71   }
72
73   // Check the size of the member for sanity
74   if (At + MemberSize > End)
75     throw std::string("invalid member length in archive file");
76
77   // Check the member signature
78   if (!Hdr->checkSignature())
79     throw std::string("invalid file member signature");
80
81   // Convert and check the member name
82   // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol 
83   // table. The special name "//" and 14 blanks is for a string table, used 
84   // for long file names. This library doesn't generate either of those but
85   // it will accept them. If the name starts with #1/ and the remainder is 
86   // digits, then those digits specify the length of the name that is 
87   // stored immediately following the header. The special name 
88   // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bytecode. 
89   // Anything else is a regular, short filename that is terminated with 
90   // a '/' and blanks.
91
92   std::string pathname;
93   unsigned index;
94   switch (Hdr->name[0]) {
95     case '#':
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);
100           At += len;
101           MemberSize -= len;
102           flags |= ArchiveMember::HasLongFilenameFlag;
103         } else
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;
115       }
116       break;
117     case '/':
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;
122         } else {
123           throw std::string("invalid string table name");
124         }
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;
129         } else {
130           throw std::string("invalid SVR4 symbol table name");
131         }
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;
139           while (p < endp) {
140             if (*p == '\n' && *last_p == '/') {
141               pathname.assign(namep, last_p - namep);
142               flags |= ArchiveMember::HasLongFilenameFlag;
143               break;
144             }
145             last_p = p;
146             p++;
147           }
148           if (p >= endp)
149             throw std::string("missing name termiantor in string table");
150         } else {
151           throw std::string("name index beyond string table");
152         }
153       }
154       break;
155     case '_':
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;
160         break;
161       }
162       /* FALL THROUGH */
163
164     default:
165       char* slash = (char*) memchr(Hdr->name, '/', 16);
166       if (slash == 0)
167         slash = Hdr->name + 16;
168       pathname.assign(Hdr->name, slash - Hdr->name);
169       break;
170   }
171
172   // Determine if this is a bytecode file
173   switch (sys::IdentifyFileType(At, 4)) {
174     case sys::BytecodeFileType:
175       flags |= ArchiveMember::BytecodeFlag;
176       break;
177     case sys::CompressedBytecodeFileType:
178       flags |= ArchiveMember::CompressedBytecodeFlag;
179       flags &= ~ArchiveMember::CompressedFlag;
180       break;
181     default:
182       flags &= ~(ArchiveMember::BytecodeFlag|
183                  ArchiveMember::CompressedBytecodeFlag);
184       break;
185   }
186
187   // Fill in fields of the ArchiveMember
188   member->next = 0;
189   member->prev = 0;
190   member->parent = this;
191   member->path.setFile(pathname);
192   member->info.fileSize = MemberSize;
193   member->info.modTime.fromEpochTime(atoi(Hdr->date));
194   sscanf(Hdr->mode, "%o", &(member->info.mode));
195   member->info.user = atoi(Hdr->uid);
196   member->info.group = atoi(Hdr->gid);
197   member->flags = flags;
198   member->data = At;
199
200   return member;
201 }
202
203 void
204 Archive::checkSignature() {
205   // Check the magic string at file's header
206   if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC, 8))
207     throw std::string("invalid signature for an archive file");
208 }
209
210 // This function loads the entire archive and fully populates its ilist with 
211 // the members of the archive file. This is typically used in preparation for
212 // editing the contents of the archive.
213 void
214 Archive::loadArchive() {
215
216   // Set up parsing
217   members.clear();
218   symTab.clear();
219   const char *At = base;
220   const char *End = base + mapfile->size();
221
222   checkSignature();
223   At += 8;  // Skip the magic string.
224
225   bool seenSymbolTable = false;
226   bool foundFirstFile = false;
227   while (At < End) {
228     // parse the member header 
229     const char* Save = At;
230     ArchiveMember* mbr = parseMemberHeader(At, End);
231
232     // check if this is the foreign symbol table
233     if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
234       // We just save this but don't do anything special
235       // with it. It doesn't count as the "first file".
236       if (foreignST) {
237         // What? Multiple foreign symbol tables? Just chuck it
238         // and retain the last one found.
239         delete foreignST;
240       }
241       foreignST = mbr;
242       At += mbr->getSize();
243       if ((intptr_t(At) & 1) == 1)
244         At++;
245     } else if (mbr->isStringTable()) {
246       // Simply suck the entire string table into a string
247       // variable. This will be used to get the names of the
248       // members that use the "/ddd" format for their names
249       // (SVR4 style long names).
250       strtab.assign(At, mbr->getSize());
251       At += mbr->getSize();
252       if ((intptr_t(At) & 1) == 1)
253         At++;
254       delete mbr;
255     } else if (mbr->isLLVMSymbolTable()) { 
256       // This is the LLVM symbol table for the archive. If we've seen it
257       // already, its an error. Otherwise, parse the symbol table and move on.
258       if (seenSymbolTable)
259         throw std::string("invalid archive: multiple symbol tables");
260       parseSymbolTable(mbr->getData(), mbr->getSize());
261       seenSymbolTable = true;
262       At += mbr->getSize();
263       if ((intptr_t(At) & 1) == 1)
264         At++;
265       delete mbr; // We don't need this member in the list of members.
266     } else {
267       // This is just a regular file. If its the first one, save its offset.
268       // Otherwise just push it on the list and move on to the next file.
269       if (!foundFirstFile) {
270         firstFileOffset = Save - base;
271         foundFirstFile = true;
272       }
273       members.push_back(mbr);
274       At += mbr->getSize();
275       if ((intptr_t(At) & 1) == 1)
276         At++;
277     }
278   }
279 }
280
281 // Open and completely load the archive file.
282 Archive*
283 Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage) {
284   try {
285     Archive* result = new Archive(file, true);
286     result->loadArchive();
287     return result;
288   } catch (const std::string& msg) {
289     if (ErrorMessage) {
290       *ErrorMessage = msg;
291     }
292     return 0;
293   }
294 }
295
296 // Get all the bytecode modules from the archive
297 bool
298 Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
299
300   for (iterator I=begin(), E=end(); I != E; ++I) {
301     if (I->isBytecode() || I->isCompressedBytecode()) {
302       std::string FullMemberName = archPath.toString() + 
303         "(" + I->getPath().toString() + ")";
304       Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(), 
305           I->getSize(), FullMemberName, ErrMessage);
306       if (!M)
307         return true;
308
309       Modules.push_back(M);
310     }
311   }
312   return false;
313 }
314
315 // Load just the symbol table from the archive file
316 void
317 Archive::loadSymbolTable() {
318
319   // Set up parsing
320   members.clear();
321   symTab.clear();
322   const char *At = base;
323   const char *End = base + mapfile->size();
324
325   // Make sure we're dealing with an archive
326   checkSignature();
327
328   At += 8; // Skip signature
329
330   // Parse the first file member header
331   const char* FirstFile = At;
332   ArchiveMember* mbr = parseMemberHeader(At, End);
333
334   if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
335     // Skip the foreign symbol table, we don't do anything with it
336     At += mbr->getSize();
337     if ((intptr_t(At) & 1) == 1)
338       At++;
339     delete mbr;
340
341     // Read the next one
342     FirstFile = At;
343     mbr = parseMemberHeader(At, End);
344   }
345
346   if (mbr->isStringTable()) {
347     // Process the string table entry
348     strtab.assign((const char*)mbr->getData(), mbr->getSize());
349     At += mbr->getSize();
350     if ((intptr_t(At) & 1) == 1)
351       At++;
352     delete mbr;
353     // Get the next one
354     FirstFile = At;
355     mbr = parseMemberHeader(At, End);
356   }
357
358   // See if its the symbol table
359   if (mbr->isLLVMSymbolTable()) {
360     parseSymbolTable(mbr->getData(), mbr->getSize());
361     At += mbr->getSize();
362     if ((intptr_t(At) & 1) == 1)
363       At++;
364     FirstFile = At;
365   } else {
366     // There's no symbol table in the file. We have to rebuild it from scratch
367     // because the intent of this method is to get the symbol table loaded so 
368     // it can be searched efficiently. 
369     // Add the member to the members list
370     members.push_back(mbr);
371   }
372
373   firstFileOffset = FirstFile - base;
374 }
375
376 // Open the archive and load just the symbol tables
377 Archive*
378 Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
379   try {
380     Archive* result = new Archive(file, true);
381     result->loadSymbolTable();
382     return result;
383   } catch (const std::string& msg) {
384     if (ErrorMessage) {
385       *ErrorMessage = msg;
386     }
387     return 0;
388   }
389 }
390
391 // Look up one symbol in the symbol table and return a ModuleProvider for the
392 // module that defines that symbol.
393 ModuleProvider* 
394 Archive::findModuleDefiningSymbol(const std::string& symbol) {
395   SymTabType::iterator SI = symTab.find(symbol);
396   if (SI == symTab.end())
397     return 0;
398
399   // The symbol table was previously constructed assuming that the members were 
400   // written without the symbol table header. Because VBR encoding is used, the
401   // values could not be adjusted to account for the offset of the symbol table
402   // because that could affect the size of the symbol table due to VBR encoding.
403   // We now have to account for this by adjusting the offset by the size of the 
404   // symbol table and its header.
405   unsigned fileOffset = 
406     SI->second +                // offset in symbol-table-less file
407     firstFileOffset;            // add offset to first "real" file in archive
408
409   // See if the module is already loaded
410   ModuleMap::iterator MI = modules.find(fileOffset);
411   if (MI != modules.end())
412     return MI->second.first;
413
414   // Module hasn't been loaded yet, we need to load it
415   const char* modptr = base + fileOffset;
416   ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size());
417
418   // Now, load the bytecode module to get the ModuleProvider
419   std::string FullMemberName = archPath.toString() + "(" + 
420     mbr->getPath().toString() + ")";
421   ModuleProvider* mp = getBytecodeBufferModuleProvider(
422       (const unsigned char*) mbr->getData(), mbr->getSize(), 
423       FullMemberName, 0);
424
425   modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
426
427   return mp;
428 }
429
430 // Look up multiple symbols in the symbol table and return a set of 
431 // ModuleProviders that define those symbols.
432 void
433 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
434                                     std::set<ModuleProvider*>& result)
435 {
436   assert(mapfile && base && "Can't findModulesDefiningSymbols on new archive");
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  = ((const char*)base) + firstFileOffset;
445     const char* End = ((const char*)base) + mapfile->size();
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);
453
454       // If it contains symbols
455       if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
456         // Get the symbols 
457         std::vector<std::string> symbols;
458         std::string FullMemberName = archPath.toString() + "(" + 
459           mbr->getPath().toString() + ")";
460         ModuleProvider* MP = GetBytecodeSymbols((const unsigned char*)At,
461             mbr->getSize(), FullMemberName, symbols);
462
463         if (MP) {
464           // Insert the module's symbols into the symbol table
465           for (std::vector<std::string>::iterator I = symbols.begin(), 
466                E=symbols.end(); I != E; ++I ) {
467             symTab.insert(std::make_pair(*I, offset));
468           }
469           // Insert the ModuleProvider and the ArchiveMember into the table of
470           // modules.
471           modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
472         } else {
473           throw std::string("Can't parse bytecode member: ") +
474             mbr->getPath().toString();
475         }
476       }
477
478       // Go to the next file location
479       At += mbr->getSize();
480       if ((intptr_t(At) & 1) == 1)
481         At++;
482     }
483   }
484
485   // At this point we have a valid symbol table (one way or another) so we 
486   // just use it to quickly find the symbols requested.
487
488   for (std::set<std::string>::iterator I=symbols.begin(), 
489        E=symbols.end(); I != E;) {
490     // See if this symbol exists
491     ModuleProvider* mp = findModuleDefiningSymbol(*I);
492     if (mp) {
493       // The symbol exists, insert the ModuleProvider into our result,
494       // duplicates wil be ignored
495       result.insert(mp);
496
497       // Remove the symbol now that its been resolved, being careful to 
498       // post-increment the iterator.
499       symbols.erase(I++);
500     } else {
501       ++I;
502     }
503   }
504 }