ArchiveReader.cpp 20 KB

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