ArchiveReader.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. #include "ArchiveInternals.h"
  14. #include "llvm/Bitcode/ReaderWriter.h"
  15. #include "llvm/Support/MemoryBuffer.h"
  16. #include "llvm/Module.h"
  17. #include <cstdlib>
  18. #include <memory>
  19. using namespace llvm;
  20. /// Read a variable-bit-rate encoded unsigned integer
  21. static inline unsigned readInteger(const char*&At, const char*End) {
  22. unsigned Shift = 0;
  23. unsigned Result = 0;
  24. do {
  25. if (At == End)
  26. return Result;
  27. Result |= (unsigned)((*At++) & 0x7F) << Shift;
  28. Shift += 7;
  29. } while (At[-1] & 0x80);
  30. return Result;
  31. }
  32. // Completely parse the Archive's symbol table and populate symTab member var.
  33. bool
  34. Archive::parseSymbolTable(const void* data, unsigned size, std::string* error) {
  35. const char* At = (const char*) data;
  36. const char* End = At + size;
  37. while (At < End) {
  38. unsigned offset = readInteger(At, End);
  39. if (At == End) {
  40. if (error)
  41. *error = "Ran out of data reading vbr_uint for symtab offset!";
  42. return false;
  43. }
  44. unsigned length = readInteger(At, End);
  45. if (At == End) {
  46. if (error)
  47. *error = "Ran out of data reading vbr_uint for symtab length!";
  48. return false;
  49. }
  50. if (At + length > End) {
  51. if (error)
  52. *error = "Malformed symbol table: length not consistent with size";
  53. return false;
  54. }
  55. // we don't care if it can't be inserted (duplicate entry)
  56. symTab.insert(std::make_pair(std::string(At, length), offset));
  57. At += length;
  58. }
  59. symTabSize = size;
  60. return true;
  61. }
  62. // This member parses an ArchiveMemberHeader that is presumed to be pointed to
  63. // by At. The At pointer is updated to the byte just after the header, which
  64. // can be variable in size.
  65. ArchiveMember*
  66. Archive::parseMemberHeader(const char*& At, const char* End, std::string* error)
  67. {
  68. if (At + sizeof(ArchiveMemberHeader) >= End) {
  69. if (error)
  70. *error = "Unexpected end of file";
  71. return 0;
  72. }
  73. // Cast archive member header
  74. ArchiveMemberHeader* Hdr = (ArchiveMemberHeader*)At;
  75. At += sizeof(ArchiveMemberHeader);
  76. // Extract the size and determine if the file is
  77. // compressed or not (negative length).
  78. int flags = 0;
  79. int MemberSize = atoi(Hdr->size);
  80. if (MemberSize < 0) {
  81. flags |= ArchiveMember::CompressedFlag;
  82. MemberSize = -MemberSize;
  83. }
  84. // Check the size of the member for sanity
  85. if (At + MemberSize > End) {
  86. if (error)
  87. *error = "invalid member length in archive file";
  88. return 0;
  89. }
  90. // Check the member signature
  91. if (!Hdr->checkSignature()) {
  92. if (error)
  93. *error = "invalid file member signature";
  94. return 0;
  95. }
  96. // Convert and check the member name
  97. // The empty name ( '/' and 15 blanks) is for a foreign (non-LLVM) symbol
  98. // table. The special name "//" and 14 blanks is for a string table, used
  99. // for long file names. This library doesn't generate either of those but
  100. // it will accept them. If the name starts with #1/ and the remainder is
  101. // digits, then those digits specify the length of the name that is
  102. // stored immediately following the header. The special name
  103. // __LLVM_SYM_TAB__ identifies the symbol table for LLVM bitcode.
  104. // Anything else is a regular, short filename that is terminated with
  105. // a '/' and blanks.
  106. std::string pathname;
  107. switch (Hdr->name[0]) {
  108. case '#':
  109. if (Hdr->name[1] == '1' && Hdr->name[2] == '/') {
  110. if (isdigit(Hdr->name[3])) {
  111. unsigned len = atoi(&Hdr->name[3]);
  112. pathname.assign(At, len);
  113. At += len;
  114. MemberSize -= len;
  115. flags |= ArchiveMember::HasLongFilenameFlag;
  116. } else {
  117. if (error)
  118. *error = "invalid long filename";
  119. return 0;
  120. }
  121. } else if (Hdr->name[1] == '_' &&
  122. (0 == memcmp(Hdr->name, ARFILE_LLVM_SYMTAB_NAME, 16))) {
  123. // The member is using a long file name (>15 chars) format.
  124. // This format is standard for 4.4BSD and Mac OSX operating
  125. // systems. LLVM uses it similarly. In this format, the
  126. // remainder of the name field (after #1/) specifies the
  127. // length of the file name which occupy the first bytes of
  128. // the member's data. The pathname already has the #1/ stripped.
  129. pathname.assign(ARFILE_LLVM_SYMTAB_NAME);
  130. flags |= ArchiveMember::LLVMSymbolTableFlag;
  131. }
  132. break;
  133. case '/':
  134. if (Hdr->name[1]== '/') {
  135. if (0 == memcmp(Hdr->name, ARFILE_STRTAB_NAME, 16)) {
  136. pathname.assign(ARFILE_STRTAB_NAME);
  137. flags |= ArchiveMember::StringTableFlag;
  138. } else {
  139. if (error)
  140. *error = "invalid string table name";
  141. return 0;
  142. }
  143. } else if (Hdr->name[1] == ' ') {
  144. if (0 == memcmp(Hdr->name, ARFILE_SVR4_SYMTAB_NAME, 16)) {
  145. pathname.assign(ARFILE_SVR4_SYMTAB_NAME);
  146. flags |= ArchiveMember::SVR4SymbolTableFlag;
  147. } else {
  148. if (error)
  149. *error = "invalid SVR4 symbol table name";
  150. return 0;
  151. }
  152. } else if (isdigit(Hdr->name[1])) {
  153. unsigned index = atoi(&Hdr->name[1]);
  154. if (index < strtab.length()) {
  155. const char* namep = strtab.c_str() + index;
  156. const char* endp = strtab.c_str() + strtab.length();
  157. const char* p = namep;
  158. const char* last_p = p;
  159. while (p < endp) {
  160. if (*p == '\n' && *last_p == '/') {
  161. pathname.assign(namep, last_p - namep);
  162. flags |= ArchiveMember::HasLongFilenameFlag;
  163. break;
  164. }
  165. last_p = p;
  166. p++;
  167. }
  168. if (p >= endp) {
  169. if (error)
  170. *error = "missing name termiantor in string table";
  171. return 0;
  172. }
  173. } else {
  174. if (error)
  175. *error = "name index beyond string table";
  176. return 0;
  177. }
  178. }
  179. break;
  180. case '_':
  181. if (Hdr->name[1] == '_' &&
  182. (0 == memcmp(Hdr->name, ARFILE_BSD4_SYMTAB_NAME, 16))) {
  183. pathname.assign(ARFILE_BSD4_SYMTAB_NAME);
  184. flags |= ArchiveMember::BSD4SymbolTableFlag;
  185. break;
  186. }
  187. /* FALL THROUGH */
  188. default:
  189. char* slash = (char*) memchr(Hdr->name, '/', 16);
  190. if (slash == 0)
  191. slash = Hdr->name + 16;
  192. pathname.assign(Hdr->name, slash - Hdr->name);
  193. break;
  194. }
  195. // Determine if this is a bitcode file
  196. switch (sys::IdentifyFileType(At, 4)) {
  197. case sys::Bitcode_FileType:
  198. flags |= ArchiveMember::BitcodeFlag;
  199. break;
  200. default:
  201. flags &= ~ArchiveMember::BitcodeFlag;
  202. break;
  203. }
  204. // Instantiate the ArchiveMember to be filled
  205. ArchiveMember* member = new ArchiveMember(this);
  206. // Fill in fields of the ArchiveMember
  207. member->parent = this;
  208. member->path.set(pathname);
  209. member->info.fileSize = MemberSize;
  210. member->info.modTime.fromEpochTime(atoi(Hdr->date));
  211. unsigned int mode;
  212. sscanf(Hdr->mode, "%o", &mode);
  213. member->info.mode = mode;
  214. member->info.user = atoi(Hdr->uid);
  215. member->info.group = atoi(Hdr->gid);
  216. member->flags = flags;
  217. member->data = At;
  218. return member;
  219. }
  220. bool
  221. Archive::checkSignature(std::string* error) {
  222. // Check the magic string at file's header
  223. if (mapfile->getBufferSize() < 8 || memcmp(base, ARFILE_MAGIC, 8)) {
  224. if (error)
  225. *error = "invalid signature for an archive file";
  226. return false;
  227. }
  228. return true;
  229. }
  230. // This function loads the entire archive and fully populates its ilist with
  231. // the members of the archive file. This is typically used in preparation for
  232. // editing the contents of the archive.
  233. bool
  234. Archive::loadArchive(std::string* error) {
  235. // Set up parsing
  236. members.clear();
  237. symTab.clear();
  238. const char *At = base;
  239. const char *End = mapfile->getBufferEnd();
  240. if (!checkSignature(error))
  241. return false;
  242. At += 8; // Skip the magic string.
  243. bool seenSymbolTable = false;
  244. bool foundFirstFile = false;
  245. while (At < End) {
  246. // parse the member header
  247. const char* Save = At;
  248. ArchiveMember* mbr = parseMemberHeader(At, End, error);
  249. if (!mbr)
  250. return false;
  251. // check if this is the foreign symbol table
  252. if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
  253. // We just save this but don't do anything special
  254. // with it. It doesn't count as the "first file".
  255. if (foreignST) {
  256. // What? Multiple foreign symbol tables? Just chuck it
  257. // and retain the last one found.
  258. delete foreignST;
  259. }
  260. foreignST = mbr;
  261. At += mbr->getSize();
  262. if ((intptr_t(At) & 1) == 1)
  263. At++;
  264. } else if (mbr->isStringTable()) {
  265. // Simply suck the entire string table into a string
  266. // variable. This will be used to get the names of the
  267. // members that use the "/ddd" format for their names
  268. // (SVR4 style long names).
  269. strtab.assign(At, mbr->getSize());
  270. At += mbr->getSize();
  271. if ((intptr_t(At) & 1) == 1)
  272. At++;
  273. delete mbr;
  274. } else if (mbr->isLLVMSymbolTable()) {
  275. // This is the LLVM symbol table for the archive. If we've seen it
  276. // already, its an error. Otherwise, parse the symbol table and move on.
  277. if (seenSymbolTable) {
  278. if (error)
  279. *error = "invalid archive: multiple symbol tables";
  280. return false;
  281. }
  282. if (!parseSymbolTable(mbr->getData(), mbr->getSize(), error))
  283. return false;
  284. seenSymbolTable = true;
  285. At += mbr->getSize();
  286. if ((intptr_t(At) & 1) == 1)
  287. At++;
  288. delete mbr; // We don't need this member in the list of members.
  289. } else {
  290. // This is just a regular file. If its the first one, save its offset.
  291. // Otherwise just push it on the list and move on to the next file.
  292. if (!foundFirstFile) {
  293. firstFileOffset = Save - base;
  294. foundFirstFile = true;
  295. }
  296. members.push_back(mbr);
  297. At += mbr->getSize();
  298. if ((intptr_t(At) & 1) == 1)
  299. At++;
  300. }
  301. }
  302. return true;
  303. }
  304. // Open and completely load the archive file.
  305. Archive*
  306. Archive::OpenAndLoad(const sys::Path& file, std::string* ErrorMessage)
  307. {
  308. std::auto_ptr<Archive> result ( new Archive(file));
  309. if (result->mapToMemory(ErrorMessage))
  310. return 0;
  311. if (!result->loadArchive(ErrorMessage))
  312. return 0;
  313. return result.release();
  314. }
  315. // Get all the bitcode modules from the archive
  316. bool
  317. Archive::getAllModules(std::vector<Module*>& Modules, std::string* ErrMessage) {
  318. for (iterator I=begin(), E=end(); I != E; ++I) {
  319. if (I->isBitcode()) {
  320. std::string FullMemberName = archPath.toString() +
  321. "(" + I->getPath().toString() + ")";
  322. MemoryBuffer *Buffer =
  323. MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
  324. memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
  325. Module *M = ParseBitcodeFile(Buffer, ErrMessage);
  326. delete Buffer;
  327. if (!M)
  328. return true;
  329. Modules.push_back(M);
  330. }
  331. }
  332. return false;
  333. }
  334. // Load just the symbol table from the archive file
  335. bool
  336. Archive::loadSymbolTable(std::string* ErrorMsg) {
  337. // Set up parsing
  338. members.clear();
  339. symTab.clear();
  340. const char *At = base;
  341. const char *End = mapfile->getBufferEnd();
  342. // Make sure we're dealing with an archive
  343. if (!checkSignature(ErrorMsg))
  344. return false;
  345. At += 8; // Skip signature
  346. // Parse the first file member header
  347. const char* FirstFile = At;
  348. ArchiveMember* mbr = parseMemberHeader(At, End, ErrorMsg);
  349. if (!mbr)
  350. return false;
  351. if (mbr->isSVR4SymbolTable() || mbr->isBSD4SymbolTable()) {
  352. // Skip the foreign symbol table, we don't do anything with it
  353. At += mbr->getSize();
  354. if ((intptr_t(At) & 1) == 1)
  355. At++;
  356. delete mbr;
  357. // Read the next one
  358. FirstFile = At;
  359. mbr = parseMemberHeader(At, End, ErrorMsg);
  360. if (!mbr) {
  361. delete mbr;
  362. return false;
  363. }
  364. }
  365. if (mbr->isStringTable()) {
  366. // Process the string table entry
  367. strtab.assign((const char*)mbr->getData(), mbr->getSize());
  368. At += mbr->getSize();
  369. if ((intptr_t(At) & 1) == 1)
  370. At++;
  371. delete mbr;
  372. // Get the next one
  373. FirstFile = At;
  374. mbr = parseMemberHeader(At, End, ErrorMsg);
  375. if (!mbr) {
  376. delete mbr;
  377. return false;
  378. }
  379. }
  380. // See if its the symbol table
  381. if (mbr->isLLVMSymbolTable()) {
  382. if (!parseSymbolTable(mbr->getData(), mbr->getSize(), ErrorMsg)) {
  383. delete mbr;
  384. return false;
  385. }
  386. At += mbr->getSize();
  387. if ((intptr_t(At) & 1) == 1)
  388. At++;
  389. delete mbr;
  390. // Can't be any more symtab headers so just advance
  391. FirstFile = At;
  392. } else {
  393. // There's no symbol table in the file. We have to rebuild it from scratch
  394. // because the intent of this method is to get the symbol table loaded so
  395. // it can be searched efficiently.
  396. // Add the member to the members list
  397. members.push_back(mbr);
  398. }
  399. firstFileOffset = FirstFile - base;
  400. return true;
  401. }
  402. // Open the archive and load just the symbol tables
  403. Archive*
  404. Archive::OpenAndLoadSymbols(const sys::Path& file, std::string* ErrorMessage) {
  405. std::auto_ptr<Archive> result ( new Archive(file) );
  406. if (result->mapToMemory(ErrorMessage))
  407. return 0;
  408. if (!result->loadSymbolTable(ErrorMessage))
  409. return 0;
  410. return result.release();
  411. }
  412. // Look up one symbol in the symbol table and return a ModuleProvider for the
  413. // module that defines that symbol.
  414. ModuleProvider*
  415. Archive::findModuleDefiningSymbol(const std::string& symbol,
  416. std::string* ErrMsg) {
  417. SymTabType::iterator SI = symTab.find(symbol);
  418. if (SI == symTab.end())
  419. return 0;
  420. // The symbol table was previously constructed assuming that the members were
  421. // written without the symbol table header. Because VBR encoding is used, the
  422. // values could not be adjusted to account for the offset of the symbol table
  423. // because that could affect the size of the symbol table due to VBR encoding.
  424. // We now have to account for this by adjusting the offset by the size of the
  425. // symbol table and its header.
  426. unsigned fileOffset =
  427. SI->second + // offset in symbol-table-less file
  428. firstFileOffset; // add offset to first "real" file in archive
  429. // See if the module is already loaded
  430. ModuleMap::iterator MI = modules.find(fileOffset);
  431. if (MI != modules.end())
  432. return MI->second.first;
  433. // Module hasn't been loaded yet, we need to load it
  434. const char* modptr = base + fileOffset;
  435. ArchiveMember* mbr = parseMemberHeader(modptr, mapfile->getBufferEnd(),
  436. ErrMsg);
  437. if (!mbr)
  438. return 0;
  439. // Now, load the bitcode module to get the ModuleProvider
  440. std::string FullMemberName = archPath.toString() + "(" +
  441. mbr->getPath().toString() + ")";
  442. MemoryBuffer *Buffer =MemoryBuffer::getNewMemBuffer(mbr->getSize(),
  443. FullMemberName.c_str());
  444. memcpy((char*)Buffer->getBufferStart(), mbr->getData(), mbr->getSize());
  445. ModuleProvider *mp = getBitcodeModuleProvider(Buffer, ErrMsg);
  446. if (!mp)
  447. return 0;
  448. modules.insert(std::make_pair(fileOffset, std::make_pair(mp, mbr)));
  449. return mp;
  450. }
  451. // Look up multiple symbols in the symbol table and return a set of
  452. // ModuleProviders that define those symbols.
  453. bool
  454. Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
  455. std::set<ModuleProvider*>& result,
  456. std::string* error) {
  457. if (!mapfile || !base) {
  458. if (error)
  459. *error = "Empty archive invalid for finding modules defining symbols";
  460. return false;
  461. }
  462. if (symTab.empty()) {
  463. // We don't have a symbol table, so we must build it now but lets also
  464. // make sure that we populate the modules table as we do this to ensure
  465. // that we don't load them twice when findModuleDefiningSymbol is called
  466. // below.
  467. // Get a pointer to the first file
  468. const char* At = base + firstFileOffset;
  469. const char* End = mapfile->getBufferEnd();
  470. while ( At < End) {
  471. // Compute the offset to be put in the symbol table
  472. unsigned offset = At - base - firstFileOffset;
  473. // Parse the file's header
  474. ArchiveMember* mbr = parseMemberHeader(At, End, error);
  475. if (!mbr)
  476. return false;
  477. // If it contains symbols
  478. if (mbr->isBitcode()) {
  479. // Get the symbols
  480. std::vector<std::string> symbols;
  481. std::string FullMemberName = archPath.toString() + "(" +
  482. mbr->getPath().toString() + ")";
  483. ModuleProvider* MP =
  484. GetBitcodeSymbols((const unsigned char*)At, mbr->getSize(),
  485. FullMemberName, symbols, error);
  486. if (MP) {
  487. // Insert the module's symbols into the symbol table
  488. for (std::vector<std::string>::iterator I = symbols.begin(),
  489. E=symbols.end(); I != E; ++I ) {
  490. symTab.insert(std::make_pair(*I, offset));
  491. }
  492. // Insert the ModuleProvider and the ArchiveMember into the table of
  493. // modules.
  494. modules.insert(std::make_pair(offset, std::make_pair(MP, mbr)));
  495. } else {
  496. if (error)
  497. *error = "Can't parse bitcode member: " +
  498. mbr->getPath().toString() + ": " + *error;
  499. delete mbr;
  500. return false;
  501. }
  502. }
  503. // Go to the next file location
  504. At += mbr->getSize();
  505. if ((intptr_t(At) & 1) == 1)
  506. At++;
  507. }
  508. }
  509. // At this point we have a valid symbol table (one way or another) so we
  510. // just use it to quickly find the symbols requested.
  511. for (std::set<std::string>::iterator I=symbols.begin(),
  512. E=symbols.end(); I != E;) {
  513. // See if this symbol exists
  514. ModuleProvider* mp = findModuleDefiningSymbol(*I,error);
  515. if (mp) {
  516. // The symbol exists, insert the ModuleProvider into our result,
  517. // duplicates wil be ignored
  518. result.insert(mp);
  519. // Remove the symbol now that its been resolved, being careful to
  520. // post-increment the iterator.
  521. symbols.erase(I++);
  522. } else {
  523. ++I;
  524. }
  525. }
  526. return true;
  527. }
  528. bool Archive::isBitcodeArchive() {
  529. // Make sure the symTab has been loaded. In most cases this should have been
  530. // done when the archive was constructed, but still, this is just in case.
  531. if (symTab.empty())
  532. if (!loadSymbolTable(0))
  533. return false;
  534. // Now that we know it's been loaded, return true
  535. // if it has a size
  536. if (symTab.size()) return true;
  537. // We still can't be sure it isn't a bitcode archive
  538. if (!loadArchive(0))
  539. return false;
  540. std::vector<Module *> Modules;
  541. std::string ErrorMessage;
  542. // Scan the archive, trying to load a bitcode member. We only load one to
  543. // see if this works.
  544. for (iterator I = begin(), E = end(); I != E; ++I) {
  545. if (!I->isBitcode())
  546. continue;
  547. std::string FullMemberName =
  548. archPath.toString() + "(" + I->getPath().toString() + ")";
  549. MemoryBuffer *Buffer =
  550. MemoryBuffer::getNewMemBuffer(I->getSize(), FullMemberName.c_str());
  551. memcpy((char*)Buffer->getBufferStart(), I->getData(), I->getSize());
  552. Module *M = ParseBitcodeFile(Buffer);
  553. delete Buffer;
  554. if (!M)
  555. return false; // Couldn't parse bitcode, not a bitcode archive.
  556. delete M;
  557. return true;
  558. }
  559. return false;
  560. }