ArchiveReader.cpp 17 KB

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