ArchiveReader.cpp revision dd95e8d71ec04cc91796c008773cd237a4ed107e
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
17using namespace llvm;
18
19/// Read a variable-bit-rate encoded unsigned integer
20inline 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.
34void
35Archive::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.
53ArchiveMember*
54Archive::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_SYMTAB_NAME,16)) {
127          pathname.assign(ARFILE_SYMTAB_NAME);
128          flags |= ArchiveMember::ForeignSymbolTableFlag;
129        } else {
130          throw std::string("invalid foreign 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
156    default:
157      char* slash = (char*) memchr(Hdr->name,'/',16);
158      if (slash == 0)
159        slash = Hdr->name + 16;
160      pathname.assign(Hdr->name,slash-Hdr->name);
161      break;
162  }
163
164  // Determine if this is a bytecode file
165  switch (sys::IdentifyFileType(At,4)) {
166    case sys::BytecodeFileType:
167      flags |= ArchiveMember::BytecodeFlag;
168      break;
169    case sys::CompressedBytecodeFileType:
170      flags |= ArchiveMember::CompressedBytecodeFlag;
171      flags &= ~ArchiveMember::CompressedFlag;
172      break;
173    default:
174      flags &= ~(ArchiveMember::BytecodeFlag|
175                 ArchiveMember::CompressedBytecodeFlag);
176      break;
177  }
178
179  // Fill in fields of the ArchiveMember
180  member->next = 0;
181  member->prev = 0;
182  member->parent = this;
183  member->path.setFile(pathname);
184  member->info.fileSize = MemberSize;
185  member->info.modTime.fromEpochTime(atoi(Hdr->date));
186  sscanf(Hdr->mode,"%o",&(member->info.mode));
187  member->info.user = atoi(Hdr->uid);
188  member->info.group = atoi(Hdr->gid);
189  member->flags = flags;
190  member->data = At;
191
192  return member;
193}
194
195void
196Archive::checkSignature() {
197  // Check the magic string at file's header
198  if (mapfile->size() < 8 || memcmp(base, ARFILE_MAGIC,8))
199    throw std::string("invalid signature for an archive file");
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.
205void
206Archive::loadArchive() {
207
208  // Set up parsing
209  members.clear();
210  symTab.clear();
211  const char *At = base;
212  const char *End = base + mapfile->size();
213
214  checkSignature();
215  At += 8;  // Skip the magic string.
216
217  bool seenSymbolTable = false;
218  bool foundFirstFile = false;
219  while (At < End) {
220    // parse the member header
221    const char* Save = At;
222    ArchiveMember* mbr = parseMemberHeader(At, End);
223
224    // check if this is the foreign symbol table
225    if (mbr->isForeignSymbolTable()) {
226      // We just save this but don't do anything special
227      // with it. It doesn't count as the "first file".
228      foreignST = mbr;
229      At += mbr->getSize();
230      if ((mbr->getSize() & 1) == 1)
231        At++;
232    } else if (mbr->isStringTable()) {
233      // Simply suck the entire string table into a string
234      // variable. This will be used to get the names of the
235      // members that use the "/ddd" format for their names
236      // (SVR4 style long names).
237      strtab.assign(At,mbr->getSize());
238      At += mbr->getSize();
239      if ((mbr->getSize() & 1) == 1)
240        At++;
241      delete mbr;
242    } else if (mbr->isLLVMSymbolTable()) {
243      // This is the LLVM symbol table for the archive. If we've seen it
244      // already, its an error. Otherwise, parse the symbol table and move on.
245      if (seenSymbolTable)
246        throw std::string("invalid archive: multiple symbol tables");
247      parseSymbolTable(mbr->getData(),mbr->getSize());
248      seenSymbolTable = true;
249      At += mbr->getSize();
250      if ((mbr->getSize() & 1) == 1)
251        At++;
252      delete mbr; // We don't need this member in the list of members.
253    } else {
254      // This is just a regular file. If its the first one, save its offset.
255      // Otherwise just push it on the list and move on to the next file.
256      if (!foundFirstFile) {
257        firstFileOffset = Save - base;
258        foundFirstFile = true;
259      }
260      members.push_back(mbr);
261      At += mbr->getSize();
262      if ((mbr->getSize() & 1) == 1)
263        At++;
264    }
265  }
266}
267
268// Open and completely load the archive file.
269Archive*
270Archive::OpenAndLoad(const sys::Path& file) {
271
272  Archive* result = new Archive(file,true);
273
274  result->loadArchive();
275
276  return result;
277}
278
279// Get all the bytecode modules from the archive
280bool
281Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
282
283  for (iterator I=begin(), E=end(); I != E; ++I) {
284    if (I->isBytecode() || I->isCompressedBytecode()) {
285      Module* M = ParseBytecodeBuffer((const unsigned char*)I->getData(),
286          I->getSize(), I->getPath().get(), ErrMessage);
287      if (!M)
288        return true;
289
290      Modules.push_back(M);
291    }
292  }
293  return false;
294}
295
296// Load just the symbol table from the archive file
297void
298Archive::loadSymbolTable() {
299
300  // Set up parsing
301  members.clear();
302  symTab.clear();
303  const char *At = base;
304  const char *End = base + mapfile->size();
305
306  // Make sure we're dealing with an archive
307  checkSignature();
308
309  At += 8; // Skip signature
310
311  // Parse the first file member header
312  const char* FirstFile = At;
313  ArchiveMember* mbr = parseMemberHeader(At, End);
314
315  if (mbr->isForeignSymbolTable()) {
316    // Skip the foreign symbol table, we don't do anything with it
317    At += mbr->getSize();
318    if ((mbr->getSize() & 1) == 1)
319      At++;
320    delete mbr;
321
322    // Read the next one
323    FirstFile = At;
324    mbr = parseMemberHeader(At,End);
325  }
326
327  if (mbr->isStringTable()) {
328    // Process the string table entry
329    strtab.assign((const char*)mbr->getData(),mbr->getSize());
330    At += mbr->getSize();
331    if ((mbr->getSize() & 1) == 1)
332      At++;
333    delete mbr;
334    // Get the next one
335    FirstFile = At;
336    mbr = parseMemberHeader(At,End);
337  }
338
339  // See if its the symbol table
340  if (mbr->isLLVMSymbolTable()) {
341    parseSymbolTable(mbr->getData(),mbr->getSize());
342    FirstFile = At + mbr->getSize();
343    if ((mbr->getSize() & 1) == 1)
344      FirstFile++;
345  } else {
346    // There's no symbol table in the file. We have to rebuild it from scratch
347    // because the intent of this method is to get the symbol table loaded so
348    // it can be searched efficiently.
349    // Add the member to the members list
350    members.push_back(mbr);
351  }
352
353  firstFileOffset = FirstFile - base;
354}
355
356// Open the archive and load just the symbol tables
357Archive*
358Archive::OpenAndLoadSymbols(const sys::Path& file) {
359  Archive* result = new Archive(file,true);
360
361  result->loadSymbolTable();
362
363  return result;
364}
365
366// Look up one symbol in the symbol table and return a ModuleProvider for the
367// module that defines that symbol.
368ModuleProvider*
369Archive::findModuleDefiningSymbol(const std::string& symbol) {
370  SymTabType::iterator SI = symTab.find(symbol);
371  if (SI == symTab.end())
372    return 0;
373
374  // The symbol table was previously constructed assuming that the members were
375  // written without the symbol table header. Because VBR encoding is used, the
376  // values could not be adjusted to account for the offset of the symbol table
377  // because that could affect the size of the symbol table due to VBR encoding.
378  // We now have to account for this by adjusting the offset by the size of the
379  // symbol table and its header.
380  unsigned fileOffset =
381    SI->second +                // offset in symbol-table-less file
382    firstFileOffset;            // add offset to first "real" file in archive
383
384  // See if the module is already loaded
385  ModuleMap::iterator MI = modules.find(fileOffset);
386  if (MI != modules.end())
387    return MI->second.first;
388
389  // Module hasn't been loaded yet, we need to load it
390  const char* modptr = base + fileOffset;
391  ArchiveMember* mbr = parseMemberHeader(modptr, base + mapfile->size());
392
393  // Now, load the bytecode module to get the ModuleProvider
394  ModuleProvider* mp = getBytecodeBufferModuleProvider(
395      (const unsigned char*) mbr->getData(), mbr->getSize(),
396      mbr->getPath().get(), 0);
397
398  modules.insert(std::make_pair(fileOffset,std::make_pair(mp,mbr)));
399
400  return mp;
401}
402
403// Look up multiple symbols in the symbol table and return a set of
404// ModuleProviders that define those symbols.
405void
406Archive::findModulesDefiningSymbols(const std::set<std::string>& symbols,
407                                    std::set<ModuleProvider*>& result)
408{
409  assert(mapfile && base && "Can't findModulesDefiningSymbols on new archive");
410  if (symTab.empty()) {
411    // We don't have a symbol table, so we must build it now but lets also
412    // make sure that we populate the modules table as we do this to ensure
413    // that we don't load them twice when findModuleDefiningSymbol is called
414    // below.
415
416    // Get a pointer to the first file
417    const char* At  = ((const char*)base) + firstFileOffset;
418    const char* End = ((const char*)base) + mapfile->size();
419
420    while ( At < End) {
421      // Compute the offset to be put in the symbol table
422      unsigned offset = At - base - firstFileOffset;
423
424      // Parse the file's header
425      ArchiveMember* mbr = parseMemberHeader(At, End);
426
427      // If it contains symbols
428      if (mbr->isBytecode() || mbr->isCompressedBytecode()) {
429        // Get the symbols
430        std::vector<std::string> symbols;
431        ModuleProvider* MP = GetBytecodeSymbols((const unsigned char*)At,
432            mbr->getSize(), mbr->getPath().get(),symbols);
433
434        if (MP) {
435          // Insert the module's symbols into the symbol table
436          for (std::vector<std::string>::iterator I = symbols.begin(),
437               E=symbols.end(); I != E; ++I ) {
438            symTab.insert(std::make_pair(*I,offset));
439          }
440          // Insert the ModuleProvider and the ArchiveMember into the table of
441          // modules.
442          modules.insert(std::make_pair(offset,std::make_pair(MP,mbr)));
443        } else {
444          throw std::string("Can't parse bytecode member: ") +
445            mbr->getPath().get();
446        }
447      }
448
449      // Go to the next file location
450      At += mbr->getSize();
451      if ((mbr->getSize() & 1) == 1)
452        At++;
453    }
454  }
455
456  // At this point we have a valid symbol table (one way or another) so we
457  // just use it to quickly find the symbols requested.
458
459  for (std::set<std::string>::const_iterator I=symbols.begin(),
460       E=symbols.end(); I != E; ++I) {
461    ModuleProvider* mp = findModuleDefiningSymbol(*I);
462    if (mp) {
463      result.insert(mp);
464    }
465  }
466}
467