2
0

Archive.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. //===- Archive.cpp - ar File Format implementation --------------*- 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. // This file defines the ArchiveObjectFile class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Object/Archive.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/Twine.h"
  17. #include "llvm/Support/Endian.h"
  18. #include "llvm/Support/MemoryBuffer.h"
  19. #include "llvm/Support/Path.h"
  20. using namespace llvm;
  21. using namespace object;
  22. using namespace llvm::support::endian;
  23. static const char *const Magic = "!<arch>\n";
  24. static const char *const ThinMagic = "!<thin>\n";
  25. void Archive::anchor() { }
  26. StringRef ArchiveMemberHeader::getName() const {
  27. char EndCond;
  28. if (Name[0] == '/' || Name[0] == '#')
  29. EndCond = ' ';
  30. else
  31. EndCond = '/';
  32. llvm::StringRef::size_type end =
  33. llvm::StringRef(Name, sizeof(Name)).find(EndCond);
  34. if (end == llvm::StringRef::npos)
  35. end = sizeof(Name);
  36. assert(end <= sizeof(Name) && end > 0);
  37. // Don't include the EndCond if there is one.
  38. return llvm::StringRef(Name, end);
  39. }
  40. uint32_t ArchiveMemberHeader::getSize() const {
  41. uint32_t Ret;
  42. if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
  43. llvm_unreachable("Size is not a decimal number.");
  44. return Ret;
  45. }
  46. sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
  47. unsigned Ret;
  48. if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
  49. llvm_unreachable("Access mode is not an octal number.");
  50. return static_cast<sys::fs::perms>(Ret);
  51. }
  52. sys::TimeValue ArchiveMemberHeader::getLastModified() const {
  53. unsigned Seconds;
  54. if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
  55. .getAsInteger(10, Seconds))
  56. llvm_unreachable("Last modified time not a decimal number.");
  57. sys::TimeValue Ret;
  58. Ret.fromEpochTime(Seconds);
  59. return Ret;
  60. }
  61. unsigned ArchiveMemberHeader::getUID() const {
  62. unsigned Ret;
  63. if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
  64. llvm_unreachable("UID time not a decimal number.");
  65. return Ret;
  66. }
  67. unsigned ArchiveMemberHeader::getGID() const {
  68. unsigned Ret;
  69. if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
  70. llvm_unreachable("GID time not a decimal number.");
  71. return Ret;
  72. }
  73. Archive::Child::Child(const Archive *Parent, const char *Start)
  74. : Parent(Parent) {
  75. if (!Start)
  76. return;
  77. const ArchiveMemberHeader *Header =
  78. reinterpret_cast<const ArchiveMemberHeader *>(Start);
  79. uint64_t Size = sizeof(ArchiveMemberHeader);
  80. if (!Parent->IsThin || Header->getName() == "/" || Header->getName() == "//")
  81. Size += Header->getSize();
  82. Data = StringRef(Start, Size);
  83. // Setup StartOfFile and PaddingBytes.
  84. StartOfFile = sizeof(ArchiveMemberHeader);
  85. // Don't include attached name.
  86. StringRef Name = Header->getName();
  87. if (Name.startswith("#1/")) {
  88. uint64_t NameSize;
  89. if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
  90. llvm_unreachable("Long name length is not an integer");
  91. StartOfFile += NameSize;
  92. }
  93. }
  94. uint64_t Archive::Child::getSize() const {
  95. if (Parent->IsThin)
  96. return getHeader()->getSize();
  97. return Data.size() - StartOfFile;
  98. }
  99. uint64_t Archive::Child::getRawSize() const {
  100. return getHeader()->getSize();
  101. }
  102. ErrorOr<StringRef> Archive::Child::getBuffer() const {
  103. if (!Parent->IsThin)
  104. return StringRef(Data.data() + StartOfFile, getSize());
  105. ErrorOr<StringRef> Name = getName();
  106. if (std::error_code EC = Name.getError())
  107. return EC;
  108. SmallString<128> FullName =
  109. Parent->getMemoryBufferRef().getBufferIdentifier();
  110. sys::path::remove_filename(FullName);
  111. sys::path::append(FullName, *Name);
  112. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
  113. if (std::error_code EC = Buf.getError())
  114. return EC;
  115. Parent->ThinBuffers.push_back(std::move(*Buf));
  116. return Parent->ThinBuffers.back()->getBuffer();
  117. }
  118. Archive::Child Archive::Child::getNext() const {
  119. size_t SpaceToSkip = Data.size();
  120. // If it's odd, add 1 to make it even.
  121. if (SpaceToSkip & 1)
  122. ++SpaceToSkip;
  123. const char *NextLoc = Data.data() + SpaceToSkip;
  124. // Check to see if this is past the end of the archive.
  125. if (NextLoc >= Parent->Data.getBufferEnd())
  126. return Child(Parent, nullptr);
  127. return Child(Parent, NextLoc);
  128. }
  129. uint64_t Archive::Child::getChildOffset() const {
  130. const char *a = Parent->Data.getBuffer().data();
  131. const char *c = Data.data();
  132. uint64_t offset = c - a;
  133. return offset;
  134. }
  135. ErrorOr<StringRef> Archive::Child::getName() const {
  136. StringRef name = getRawName();
  137. // Check if it's a special name.
  138. if (name[0] == '/') {
  139. if (name.size() == 1) // Linker member.
  140. return name;
  141. if (name.size() == 2 && name[1] == '/') // String table.
  142. return name;
  143. // It's a long name.
  144. // Get the offset.
  145. std::size_t offset;
  146. if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
  147. llvm_unreachable("Long name offset is not an integer");
  148. const char *addr = Parent->StringTable->Data.begin()
  149. + sizeof(ArchiveMemberHeader)
  150. + offset;
  151. // Verify it.
  152. if (Parent->StringTable == Parent->child_end()
  153. || addr < (Parent->StringTable->Data.begin()
  154. + sizeof(ArchiveMemberHeader))
  155. || addr > (Parent->StringTable->Data.begin()
  156. + sizeof(ArchiveMemberHeader)
  157. + Parent->StringTable->getSize()))
  158. return object_error::parse_failed;
  159. // GNU long file names end with a "/\n".
  160. if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
  161. StringRef::size_type End = StringRef(addr).find('\n');
  162. return StringRef(addr, End - 1);
  163. }
  164. return StringRef(addr);
  165. } else if (name.startswith("#1/")) {
  166. uint64_t name_size;
  167. if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
  168. llvm_unreachable("Long name length is not an ingeter");
  169. return Data.substr(sizeof(ArchiveMemberHeader), name_size)
  170. .rtrim(StringRef("\0", 1));
  171. }
  172. // It's a simple name.
  173. if (name[name.size() - 1] == '/')
  174. return name.substr(0, name.size() - 1);
  175. return name;
  176. }
  177. ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
  178. ErrorOr<StringRef> NameOrErr = getName();
  179. if (std::error_code EC = NameOrErr.getError())
  180. return EC;
  181. StringRef Name = NameOrErr.get();
  182. ErrorOr<StringRef> Buf = getBuffer();
  183. if (std::error_code EC = Buf.getError())
  184. return EC;
  185. return MemoryBufferRef(*Buf, Name);
  186. }
  187. ErrorOr<std::unique_ptr<Binary>>
  188. Archive::Child::getAsBinary(LLVMContext *Context) const {
  189. ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
  190. if (std::error_code EC = BuffOrErr.getError())
  191. return EC;
  192. return createBinary(BuffOrErr.get(), Context);
  193. }
  194. ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
  195. std::error_code EC;
  196. std::unique_ptr<Archive> Ret(new Archive(Source, EC));
  197. if (EC)
  198. return EC;
  199. return std::move(Ret);
  200. }
  201. Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
  202. : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()),
  203. StringTable(child_end()), FirstRegular(child_end()) {
  204. StringRef Buffer = Data.getBuffer();
  205. // Check for sufficient magic.
  206. if (Buffer.startswith(ThinMagic)) {
  207. IsThin = true;
  208. } else if (Buffer.startswith(Magic)) {
  209. IsThin = false;
  210. } else {
  211. ec = object_error::invalid_file_type;
  212. return;
  213. }
  214. // Get the special members.
  215. child_iterator i = child_begin(false);
  216. child_iterator e = child_end();
  217. if (i == e) {
  218. ec = std::error_code();
  219. return;
  220. }
  221. StringRef Name = i->getRawName();
  222. // Below is the pattern that is used to figure out the archive format
  223. // GNU archive format
  224. // First member : / (may exist, if it exists, points to the symbol table )
  225. // Second member : // (may exist, if it exists, points to the string table)
  226. // Note : The string table is used if the filename exceeds 15 characters
  227. // BSD archive format
  228. // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
  229. // There is no string table, if the filename exceeds 15 characters or has a
  230. // embedded space, the filename has #1/<size>, The size represents the size
  231. // of the filename that needs to be read after the archive header
  232. // COFF archive format
  233. // First member : /
  234. // Second member : / (provides a directory of symbols)
  235. // Third member : // (may exist, if it exists, contains the string table)
  236. // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
  237. // even if the string table is empty. However, lib.exe does not in fact
  238. // seem to create the third member if there's no member whose filename
  239. // exceeds 15 characters. So the third member is optional.
  240. if (Name == "__.SYMDEF") {
  241. Format = K_BSD;
  242. SymbolTable = i;
  243. ++i;
  244. FirstRegular = i;
  245. ec = std::error_code();
  246. return;
  247. }
  248. if (Name.startswith("#1/")) {
  249. Format = K_BSD;
  250. // We know this is BSD, so getName will work since there is no string table.
  251. ErrorOr<StringRef> NameOrErr = i->getName();
  252. ec = NameOrErr.getError();
  253. if (ec)
  254. return;
  255. Name = NameOrErr.get();
  256. if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
  257. SymbolTable = i;
  258. ++i;
  259. }
  260. FirstRegular = i;
  261. return;
  262. }
  263. // MIPS 64-bit ELF archives use a special format of a symbol table.
  264. // This format is marked by `ar_name` field equals to "/SYM64/".
  265. // For detailed description see page 96 in the following document:
  266. // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
  267. bool has64SymTable = false;
  268. if (Name == "/" || Name == "/SYM64/") {
  269. SymbolTable = i;
  270. if (Name == "/SYM64/")
  271. has64SymTable = true;
  272. ++i;
  273. if (i == e) {
  274. ec = std::error_code();
  275. return;
  276. }
  277. Name = i->getRawName();
  278. }
  279. if (Name == "//") {
  280. Format = has64SymTable ? K_MIPS64 : K_GNU;
  281. StringTable = i;
  282. ++i;
  283. FirstRegular = i;
  284. ec = std::error_code();
  285. return;
  286. }
  287. if (Name[0] != '/') {
  288. Format = has64SymTable ? K_MIPS64 : K_GNU;
  289. FirstRegular = i;
  290. ec = std::error_code();
  291. return;
  292. }
  293. if (Name != "/") {
  294. ec = object_error::parse_failed;
  295. return;
  296. }
  297. Format = K_COFF;
  298. SymbolTable = i;
  299. ++i;
  300. if (i == e) {
  301. FirstRegular = i;
  302. ec = std::error_code();
  303. return;
  304. }
  305. Name = i->getRawName();
  306. if (Name == "//") {
  307. StringTable = i;
  308. ++i;
  309. }
  310. FirstRegular = i;
  311. ec = std::error_code();
  312. }
  313. Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
  314. if (Data.getBufferSize() == 8) // empty archive.
  315. return child_end();
  316. if (SkipInternal)
  317. return FirstRegular;
  318. const char *Loc = Data.getBufferStart() + strlen(Magic);
  319. Child c(this, Loc);
  320. return c;
  321. }
  322. Archive::child_iterator Archive::child_end() const {
  323. return Child(this, nullptr);
  324. }
  325. StringRef Archive::Symbol::getName() const {
  326. return Parent->getSymbolTable().begin() + StringIndex;
  327. }
  328. ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
  329. const char *Buf = Parent->getSymbolTable().begin();
  330. const char *Offsets = Buf;
  331. if (Parent->kind() == K_MIPS64)
  332. Offsets += sizeof(uint64_t);
  333. else
  334. Offsets += sizeof(uint32_t);
  335. uint32_t Offset = 0;
  336. if (Parent->kind() == K_GNU) {
  337. Offset = read32be(Offsets + SymbolIndex * 4);
  338. } else if (Parent->kind() == K_MIPS64) {
  339. Offset = read64be(Offsets + SymbolIndex * 8);
  340. } else if (Parent->kind() == K_BSD) {
  341. // The SymbolIndex is an index into the ranlib structs that start at
  342. // Offsets (the first uint32_t is the number of bytes of the ranlib
  343. // structs). The ranlib structs are a pair of uint32_t's the first
  344. // being a string table offset and the second being the offset into
  345. // the archive of the member that defines the symbol. Which is what
  346. // is needed here.
  347. Offset = read32le(Offsets + SymbolIndex * 8 + 4);
  348. } else {
  349. // Skip offsets.
  350. uint32_t MemberCount = read32le(Buf);
  351. Buf += MemberCount * 4 + 4;
  352. uint32_t SymbolCount = read32le(Buf);
  353. if (SymbolIndex >= SymbolCount)
  354. return object_error::parse_failed;
  355. // Skip SymbolCount to get to the indices table.
  356. const char *Indices = Buf + 4;
  357. // Get the index of the offset in the file member offset table for this
  358. // symbol.
  359. uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
  360. // Subtract 1 since OffsetIndex is 1 based.
  361. --OffsetIndex;
  362. if (OffsetIndex >= MemberCount)
  363. return object_error::parse_failed;
  364. Offset = read32le(Offsets + OffsetIndex * 4);
  365. }
  366. const char *Loc = Parent->getData().begin() + Offset;
  367. child_iterator Iter(Child(Parent, Loc));
  368. return Iter;
  369. }
  370. Archive::Symbol Archive::Symbol::getNext() const {
  371. Symbol t(*this);
  372. if (Parent->kind() == K_BSD) {
  373. // t.StringIndex is an offset from the start of the __.SYMDEF or
  374. // "__.SYMDEF SORTED" member into the string table for the ranlib
  375. // struct indexed by t.SymbolIndex . To change t.StringIndex to the
  376. // offset in the string table for t.SymbolIndex+1 we subtract the
  377. // its offset from the start of the string table for t.SymbolIndex
  378. // and add the offset of the string table for t.SymbolIndex+1.
  379. // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
  380. // which is the number of bytes of ranlib structs that follow. The ranlib
  381. // structs are a pair of uint32_t's the first being a string table offset
  382. // and the second being the offset into the archive of the member that
  383. // define the symbol. After that the next uint32_t is the byte count of
  384. // the string table followed by the string table.
  385. const char *Buf = Parent->getSymbolTable().begin();
  386. uint32_t RanlibCount = 0;
  387. RanlibCount = read32le(Buf) / 8;
  388. // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
  389. // don't change the t.StringIndex as we don't want to reference a ranlib
  390. // past RanlibCount.
  391. if (t.SymbolIndex + 1 < RanlibCount) {
  392. const char *Ranlibs = Buf + 4;
  393. uint32_t CurRanStrx = 0;
  394. uint32_t NextRanStrx = 0;
  395. CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
  396. NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
  397. t.StringIndex -= CurRanStrx;
  398. t.StringIndex += NextRanStrx;
  399. }
  400. } else {
  401. // Go to one past next null.
  402. t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
  403. }
  404. ++t.SymbolIndex;
  405. return t;
  406. }
  407. Archive::symbol_iterator Archive::symbol_begin() const {
  408. if (!hasSymbolTable())
  409. return symbol_iterator(Symbol(this, 0, 0));
  410. const char *buf = getSymbolTable().begin();
  411. if (kind() == K_GNU) {
  412. uint32_t symbol_count = 0;
  413. symbol_count = read32be(buf);
  414. buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
  415. } else if (kind() == K_MIPS64) {
  416. uint64_t symbol_count = read64be(buf);
  417. buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
  418. } else if (kind() == K_BSD) {
  419. // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
  420. // which is the number of bytes of ranlib structs that follow. The ranlib
  421. // structs are a pair of uint32_t's the first being a string table offset
  422. // and the second being the offset into the archive of the member that
  423. // define the symbol. After that the next uint32_t is the byte count of
  424. // the string table followed by the string table.
  425. uint32_t ranlib_count = 0;
  426. ranlib_count = read32le(buf) / 8;
  427. const char *ranlibs = buf + 4;
  428. uint32_t ran_strx = 0;
  429. ran_strx = read32le(ranlibs);
  430. buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
  431. // Skip the byte count of the string table.
  432. buf += sizeof(uint32_t);
  433. buf += ran_strx;
  434. } else {
  435. uint32_t member_count = 0;
  436. uint32_t symbol_count = 0;
  437. member_count = read32le(buf);
  438. buf += 4 + (member_count * 4); // Skip offsets.
  439. symbol_count = read32le(buf);
  440. buf += 4 + (symbol_count * 2); // Skip indices.
  441. }
  442. uint32_t string_start_offset = buf - getSymbolTable().begin();
  443. return symbol_iterator(Symbol(this, 0, string_start_offset));
  444. }
  445. Archive::symbol_iterator Archive::symbol_end() const {
  446. if (!hasSymbolTable())
  447. return symbol_iterator(Symbol(this, 0, 0));
  448. return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
  449. }
  450. uint32_t Archive::getNumberOfSymbols() const {
  451. const char *buf = getSymbolTable().begin();
  452. if (kind() == K_GNU)
  453. return read32be(buf);
  454. if (kind() == K_MIPS64)
  455. return read64be(buf);
  456. if (kind() == K_BSD)
  457. return read32le(buf) / 8;
  458. uint32_t member_count = 0;
  459. member_count = read32le(buf);
  460. buf += 4 + (member_count * 4); // Skip offsets.
  461. return read32le(buf);
  462. }
  463. Archive::child_iterator Archive::findSym(StringRef name) const {
  464. Archive::symbol_iterator bs = symbol_begin();
  465. Archive::symbol_iterator es = symbol_end();
  466. for (; bs != es; ++bs) {
  467. StringRef SymName = bs->getName();
  468. if (SymName == name) {
  469. ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
  470. // FIXME: Should we really eat the error?
  471. if (ResultOrErr.getError())
  472. return child_end();
  473. return ResultOrErr.get();
  474. }
  475. }
  476. return child_end();
  477. }
  478. bool Archive::hasSymbolTable() const {
  479. return SymbolTable != child_end();
  480. }