Archive.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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/SmallString.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/Support/Endian.h"
  17. #include "llvm/Support/MemoryBuffer.h"
  18. #include "llvm/Support/Path.h"
  19. using namespace llvm;
  20. using namespace object;
  21. using namespace llvm::support::endian;
  22. static const char *const Magic = "!<arch>\n";
  23. static const char *const ThinMagic = "!<thin>\n";
  24. void Archive::anchor() { }
  25. static Error
  26. malformedError(Twine Msg) {
  27. std::string StringMsg = "truncated or malformed archive (" + Msg.str() + ")";
  28. return make_error<GenericBinaryError>(std::move(StringMsg),
  29. object_error::parse_failed);
  30. }
  31. ArchiveMemberHeader::ArchiveMemberHeader(const Archive *Parent,
  32. const char *RawHeaderPtr,
  33. uint64_t Size, Error *Err)
  34. : Parent(Parent),
  35. ArMemHdr(reinterpret_cast<const ArMemHdrType *>(RawHeaderPtr)) {
  36. if (RawHeaderPtr == nullptr)
  37. return;
  38. ErrorAsOutParameter ErrAsOutParam(Err);
  39. if (Size < sizeof(ArMemHdrType)) {
  40. if (Err) {
  41. std::string Msg("remaining size of archive too small for next archive "
  42. "member header ");
  43. Expected<StringRef> NameOrErr = getName(Size);
  44. if (!NameOrErr) {
  45. consumeError(NameOrErr.takeError());
  46. uint64_t Offset = RawHeaderPtr - Parent->getData().data();
  47. *Err = malformedError(Msg + "at offset " + Twine(Offset));
  48. } else
  49. *Err = malformedError(Msg + "for " + NameOrErr.get());
  50. }
  51. return;
  52. }
  53. if (ArMemHdr->Terminator[0] != '`' || ArMemHdr->Terminator[1] != '\n') {
  54. if (Err) {
  55. std::string Buf;
  56. raw_string_ostream OS(Buf);
  57. OS.write_escaped(llvm::StringRef(ArMemHdr->Terminator,
  58. sizeof(ArMemHdr->Terminator)));
  59. OS.flush();
  60. std::string Msg("terminator characters in archive member \"" + Buf +
  61. "\" not the correct \"`\\n\" values for the archive "
  62. "member header ");
  63. Expected<StringRef> NameOrErr = getName(Size);
  64. if (!NameOrErr) {
  65. consumeError(NameOrErr.takeError());
  66. uint64_t Offset = RawHeaderPtr - Parent->getData().data();
  67. *Err = malformedError(Msg + "at offset " + Twine(Offset));
  68. } else
  69. *Err = malformedError(Msg + "for " + NameOrErr.get());
  70. }
  71. return;
  72. }
  73. }
  74. // This gets the raw name from the ArMemHdr->Name field and checks that it is
  75. // valid for the kind of archive. If it is not valid it returns an Error.
  76. Expected<StringRef> ArchiveMemberHeader::getRawName() const {
  77. char EndCond;
  78. auto Kind = Parent->kind();
  79. if (Kind == Archive::K_BSD || Kind == Archive::K_DARWIN64) {
  80. if (ArMemHdr->Name[0] == ' ') {
  81. uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
  82. Parent->getData().data();
  83. return malformedError("name contains a leading space for archive member "
  84. "header at offset " + Twine(Offset));
  85. }
  86. EndCond = ' ';
  87. }
  88. else if (ArMemHdr->Name[0] == '/' || ArMemHdr->Name[0] == '#')
  89. EndCond = ' ';
  90. else
  91. EndCond = '/';
  92. llvm::StringRef::size_type end =
  93. llvm::StringRef(ArMemHdr->Name, sizeof(ArMemHdr->Name)).find(EndCond);
  94. if (end == llvm::StringRef::npos)
  95. end = sizeof(ArMemHdr->Name);
  96. assert(end <= sizeof(ArMemHdr->Name) && end > 0);
  97. // Don't include the EndCond if there is one.
  98. return llvm::StringRef(ArMemHdr->Name, end);
  99. }
  100. // This gets the name looking up long names. Size is the size of the archive
  101. // member including the header, so the size of any name following the header
  102. // is checked to make sure it does not overflow.
  103. Expected<StringRef> ArchiveMemberHeader::getName(uint64_t Size) const {
  104. // This can be called from the ArchiveMemberHeader constructor when the
  105. // archive header is truncated to produce an error message with the name.
  106. // Make sure the name field is not truncated.
  107. if (Size < offsetof(ArMemHdrType, Name) + sizeof(ArMemHdr->Name)) {
  108. uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
  109. Parent->getData().data();
  110. return malformedError("archive header truncated before the name field "
  111. "for archive member header at offset " +
  112. Twine(ArchiveOffset));
  113. }
  114. // The raw name itself can be invalid.
  115. Expected<StringRef> NameOrErr = getRawName();
  116. if (!NameOrErr)
  117. return NameOrErr.takeError();
  118. StringRef Name = NameOrErr.get();
  119. // Check if it's a special name.
  120. if (Name[0] == '/') {
  121. if (Name.size() == 1) // Linker member.
  122. return Name;
  123. if (Name.size() == 2 && Name[1] == '/') // String table.
  124. return Name;
  125. // It's a long name.
  126. // Get the string table offset.
  127. std::size_t StringOffset;
  128. if (Name.substr(1).rtrim(' ').getAsInteger(10, StringOffset)) {
  129. std::string Buf;
  130. raw_string_ostream OS(Buf);
  131. OS.write_escaped(Name.substr(1).rtrim(' '));
  132. OS.flush();
  133. uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
  134. Parent->getData().data();
  135. return malformedError("long name offset characters after the '/' are "
  136. "not all decimal numbers: '" + Buf + "' for "
  137. "archive member header at offset " +
  138. Twine(ArchiveOffset));
  139. }
  140. // Verify it.
  141. if (StringOffset >= Parent->getStringTable().size()) {
  142. uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
  143. Parent->getData().data();
  144. return malformedError("long name offset " + Twine(StringOffset) + " past "
  145. "the end of the string table for archive member "
  146. "header at offset " + Twine(ArchiveOffset));
  147. }
  148. const char *addr = Parent->getStringTable().begin() + StringOffset;
  149. // GNU long file names end with a "/\n".
  150. if (Parent->kind() == Archive::K_GNU ||
  151. Parent->kind() == Archive::K_MIPS64) {
  152. StringRef::size_type End = StringRef(addr).find('\n');
  153. return StringRef(addr, End - 1);
  154. }
  155. return addr;
  156. }
  157. if (Name.startswith("#1/")) {
  158. uint64_t NameLength;
  159. if (Name.substr(3).rtrim(' ').getAsInteger(10, NameLength)) {
  160. std::string Buf;
  161. raw_string_ostream OS(Buf);
  162. OS.write_escaped(Name.substr(3).rtrim(' '));
  163. OS.flush();
  164. uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
  165. Parent->getData().data();
  166. return malformedError("long name length characters after the #1/ are "
  167. "not all decimal numbers: '" + Buf + "' for "
  168. "archive member header at offset " +
  169. Twine(ArchiveOffset));
  170. }
  171. if (getSizeOf() + NameLength > Size) {
  172. uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
  173. Parent->getData().data();
  174. return malformedError("long name length: " + Twine(NameLength) +
  175. " extends past the end of the member or archive "
  176. "for archive member header at offset " +
  177. Twine(ArchiveOffset));
  178. }
  179. return StringRef(reinterpret_cast<const char *>(ArMemHdr) + getSizeOf(),
  180. NameLength).rtrim('\0');
  181. }
  182. // It is not a long name so trim the blanks at the end of the name.
  183. if (Name[Name.size() - 1] != '/')
  184. return Name.rtrim(' ');
  185. // It's a simple name.
  186. return Name.drop_back(1);
  187. }
  188. Expected<uint32_t> ArchiveMemberHeader::getSize() const {
  189. uint32_t Ret;
  190. if (llvm::StringRef(ArMemHdr->Size,
  191. sizeof(ArMemHdr->Size)).rtrim(" ").getAsInteger(10, Ret)) {
  192. std::string Buf;
  193. raw_string_ostream OS(Buf);
  194. OS.write_escaped(llvm::StringRef(ArMemHdr->Size,
  195. sizeof(ArMemHdr->Size)).rtrim(" "));
  196. OS.flush();
  197. uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
  198. Parent->getData().data();
  199. return malformedError("characters in size field in archive header are not "
  200. "all decimal numbers: '" + Buf + "' for archive "
  201. "member header at offset " + Twine(Offset));
  202. }
  203. return Ret;
  204. }
  205. sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
  206. unsigned Ret;
  207. if (StringRef(ArMemHdr->AccessMode,
  208. sizeof(ArMemHdr->AccessMode)).rtrim(' ').getAsInteger(8, Ret))
  209. llvm_unreachable("Access mode is not an octal number.");
  210. return static_cast<sys::fs::perms>(Ret);
  211. }
  212. sys::TimeValue ArchiveMemberHeader::getLastModified() const {
  213. unsigned Seconds;
  214. if (StringRef(ArMemHdr->LastModified,
  215. sizeof(ArMemHdr->LastModified)).rtrim(' ')
  216. .getAsInteger(10, Seconds))
  217. llvm_unreachable("Last modified time not a decimal number.");
  218. sys::TimeValue Ret;
  219. Ret.fromEpochTime(Seconds);
  220. return Ret;
  221. }
  222. unsigned ArchiveMemberHeader::getUID() const {
  223. unsigned Ret;
  224. StringRef User = StringRef(ArMemHdr->UID, sizeof(ArMemHdr->UID)).rtrim(' ');
  225. if (User.empty())
  226. return 0;
  227. if (User.getAsInteger(10, Ret))
  228. llvm_unreachable("UID time not a decimal number.");
  229. return Ret;
  230. }
  231. unsigned ArchiveMemberHeader::getGID() const {
  232. unsigned Ret;
  233. StringRef Group = StringRef(ArMemHdr->GID, sizeof(ArMemHdr->GID)).rtrim(' ');
  234. if (Group.empty())
  235. return 0;
  236. if (Group.getAsInteger(10, Ret))
  237. llvm_unreachable("GID time not a decimal number.");
  238. return Ret;
  239. }
  240. Archive::Child::Child(const Archive *Parent, StringRef Data,
  241. uint16_t StartOfFile)
  242. : Parent(Parent), Header(Parent, Data.data(), Data.size(), nullptr),
  243. Data(Data), StartOfFile(StartOfFile) {
  244. }
  245. Archive::Child::Child(const Archive *Parent, const char *Start, Error *Err)
  246. : Parent(Parent), Header(Parent, Start, Parent->getData().size() -
  247. (Start - Parent->getData().data()), Err) {
  248. if (!Start)
  249. return;
  250. ErrorAsOutParameter ErrAsOutParam(Err);
  251. // If there was an error in the construction of the Header and we were passed
  252. // Err that is not nullptr then just return with the error now set.
  253. if (Err && *Err)
  254. return;
  255. uint64_t Size = Header.getSizeOf();
  256. Data = StringRef(Start, Size);
  257. Expected<bool> isThinOrErr = isThinMember();
  258. if (!isThinOrErr) {
  259. if (Err)
  260. *Err = isThinOrErr.takeError();
  261. return;
  262. }
  263. bool isThin = isThinOrErr.get();
  264. if (!isThin) {
  265. Expected<uint64_t> MemberSize = getRawSize();
  266. if (!MemberSize) {
  267. if (Err)
  268. *Err = MemberSize.takeError();
  269. return;
  270. }
  271. Size += MemberSize.get();
  272. Data = StringRef(Start, Size);
  273. }
  274. // Setup StartOfFile and PaddingBytes.
  275. StartOfFile = Header.getSizeOf();
  276. // Don't include attached name.
  277. Expected<StringRef> NameOrErr = getRawName();
  278. if (!NameOrErr){
  279. if (Err)
  280. *Err = NameOrErr.takeError();
  281. return;
  282. }
  283. StringRef Name = NameOrErr.get();
  284. if (Name.startswith("#1/")) {
  285. uint64_t NameSize;
  286. if (Name.substr(3).rtrim(' ').getAsInteger(10, NameSize)) {
  287. if (Err) {
  288. std::string Buf;
  289. raw_string_ostream OS(Buf);
  290. OS.write_escaped(Name.substr(3).rtrim(' '));
  291. OS.flush();
  292. uint64_t Offset = Start - Parent->getData().data();
  293. *Err = malformedError("long name length characters after the #1/ are "
  294. "not all decimal numbers: '" + Buf + "' for "
  295. "archive member header at offset " +
  296. Twine(Offset));
  297. return;
  298. }
  299. }
  300. StartOfFile += NameSize;
  301. }
  302. }
  303. Expected<uint64_t> Archive::Child::getSize() const {
  304. if (Parent->IsThin) {
  305. Expected<uint32_t> Size = Header.getSize();
  306. if (!Size)
  307. return Size.takeError();
  308. return Size.get();
  309. }
  310. return Data.size() - StartOfFile;
  311. }
  312. Expected<uint64_t> Archive::Child::getRawSize() const {
  313. return Header.getSize();
  314. }
  315. Expected<bool> Archive::Child::isThinMember() const {
  316. Expected<StringRef> NameOrErr = Header.getRawName();
  317. if (!NameOrErr)
  318. return NameOrErr.takeError();
  319. StringRef Name = NameOrErr.get();
  320. return Parent->IsThin && Name != "/" && Name != "//";
  321. }
  322. ErrorOr<std::string> Archive::Child::getFullName() const {
  323. Expected<bool> isThin = isThinMember();
  324. if (!isThin)
  325. return errorToErrorCode(isThin.takeError());
  326. assert(isThin.get());
  327. Expected<StringRef> NameOrErr = getName();
  328. if (!NameOrErr)
  329. return errorToErrorCode(NameOrErr.takeError());
  330. StringRef Name = *NameOrErr;
  331. if (sys::path::is_absolute(Name))
  332. return Name;
  333. SmallString<128> FullName = sys::path::parent_path(
  334. Parent->getMemoryBufferRef().getBufferIdentifier());
  335. sys::path::append(FullName, Name);
  336. return StringRef(FullName);
  337. }
  338. ErrorOr<StringRef> Archive::Child::getBuffer() const {
  339. Expected<bool> isThinOrErr = isThinMember();
  340. if (!isThinOrErr)
  341. return errorToErrorCode(isThinOrErr.takeError());
  342. bool isThin = isThinOrErr.get();
  343. if (!isThin) {
  344. Expected<uint32_t> Size = getSize();
  345. if (!Size)
  346. return errorToErrorCode(Size.takeError());
  347. return StringRef(Data.data() + StartOfFile, Size.get());
  348. }
  349. ErrorOr<std::string> FullNameOrEr = getFullName();
  350. if (std::error_code EC = FullNameOrEr.getError())
  351. return EC;
  352. const std::string &FullName = *FullNameOrEr;
  353. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
  354. if (std::error_code EC = Buf.getError())
  355. return EC;
  356. Parent->ThinBuffers.push_back(std::move(*Buf));
  357. return Parent->ThinBuffers.back()->getBuffer();
  358. }
  359. Expected<Archive::Child> Archive::Child::getNext() const {
  360. size_t SpaceToSkip = Data.size();
  361. // If it's odd, add 1 to make it even.
  362. if (SpaceToSkip & 1)
  363. ++SpaceToSkip;
  364. const char *NextLoc = Data.data() + SpaceToSkip;
  365. // Check to see if this is at the end of the archive.
  366. if (NextLoc == Parent->Data.getBufferEnd())
  367. return Child(Parent, nullptr, nullptr);
  368. // Check to see if this is past the end of the archive.
  369. if (NextLoc > Parent->Data.getBufferEnd()) {
  370. std::string Msg("offset to next archive member past the end of the archive "
  371. "after member ");
  372. Expected<StringRef> NameOrErr = getName();
  373. if (!NameOrErr) {
  374. consumeError(NameOrErr.takeError());
  375. uint64_t Offset = Data.data() - Parent->getData().data();
  376. return malformedError(Msg + "at offset " + Twine(Offset));
  377. } else
  378. return malformedError(Msg + NameOrErr.get());
  379. }
  380. Error Err;
  381. Child Ret(Parent, NextLoc, &Err);
  382. if (Err)
  383. return std::move(Err);
  384. return Ret;
  385. }
  386. uint64_t Archive::Child::getChildOffset() const {
  387. const char *a = Parent->Data.getBuffer().data();
  388. const char *c = Data.data();
  389. uint64_t offset = c - a;
  390. return offset;
  391. }
  392. Expected<StringRef> Archive::Child::getName() const {
  393. Expected<uint64_t> RawSizeOrErr = getRawSize();
  394. if (!RawSizeOrErr)
  395. return RawSizeOrErr.takeError();
  396. uint64_t RawSize = RawSizeOrErr.get();
  397. Expected<StringRef> NameOrErr = Header.getName(Header.getSizeOf() + RawSize);
  398. if (!NameOrErr)
  399. return NameOrErr.takeError();
  400. StringRef Name = NameOrErr.get();
  401. return Name;
  402. }
  403. Expected<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
  404. Expected<StringRef> NameOrErr = getName();
  405. if (!NameOrErr)
  406. return NameOrErr.takeError();
  407. StringRef Name = NameOrErr.get();
  408. ErrorOr<StringRef> Buf = getBuffer();
  409. if (std::error_code EC = Buf.getError())
  410. return errorCodeToError(EC);
  411. return MemoryBufferRef(*Buf, Name);
  412. }
  413. Expected<std::unique_ptr<Binary>>
  414. Archive::Child::getAsBinary(LLVMContext *Context) const {
  415. Expected<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
  416. if (!BuffOrErr)
  417. return BuffOrErr.takeError();
  418. auto BinaryOrErr = createBinary(BuffOrErr.get(), Context);
  419. if (BinaryOrErr)
  420. return std::move(*BinaryOrErr);
  421. return BinaryOrErr.takeError();
  422. }
  423. Expected<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
  424. Error Err;
  425. std::unique_ptr<Archive> Ret(new Archive(Source, Err));
  426. if (Err)
  427. return std::move(Err);
  428. return std::move(Ret);
  429. }
  430. void Archive::setFirstRegular(const Child &C) {
  431. FirstRegularData = C.Data;
  432. FirstRegularStartOfFile = C.StartOfFile;
  433. }
  434. Archive::Archive(MemoryBufferRef Source, Error &Err)
  435. : Binary(Binary::ID_Archive, Source) {
  436. ErrorAsOutParameter ErrAsOutParam(&Err);
  437. StringRef Buffer = Data.getBuffer();
  438. // Check for sufficient magic.
  439. if (Buffer.startswith(ThinMagic)) {
  440. IsThin = true;
  441. } else if (Buffer.startswith(Magic)) {
  442. IsThin = false;
  443. } else {
  444. Err = make_error<GenericBinaryError>("File too small to be an archive",
  445. object_error::invalid_file_type);
  446. return;
  447. }
  448. // Make sure Format is initialized before any call to
  449. // ArchiveMemberHeader::getName() is made. This could be a valid empty
  450. // archive which is the same in all formats. So claiming it to be gnu to is
  451. // fine if not totally correct before we look for a string table or table of
  452. // contents.
  453. Format = K_GNU;
  454. // Get the special members.
  455. child_iterator I = child_begin(Err, false);
  456. if (Err)
  457. return;
  458. child_iterator E = child_end();
  459. // See if this is a valid empty archive and if so return.
  460. if (I == E) {
  461. Err = Error::success();
  462. return;
  463. }
  464. const Child *C = &*I;
  465. auto Increment = [&]() {
  466. ++I;
  467. if (Err)
  468. return true;
  469. C = &*I;
  470. return false;
  471. };
  472. Expected<StringRef> NameOrErr = C->getRawName();
  473. if (!NameOrErr) {
  474. Err = NameOrErr.takeError();
  475. return;
  476. }
  477. StringRef Name = NameOrErr.get();
  478. // Below is the pattern that is used to figure out the archive format
  479. // GNU archive format
  480. // First member : / (may exist, if it exists, points to the symbol table )
  481. // Second member : // (may exist, if it exists, points to the string table)
  482. // Note : The string table is used if the filename exceeds 15 characters
  483. // BSD archive format
  484. // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
  485. // There is no string table, if the filename exceeds 15 characters or has a
  486. // embedded space, the filename has #1/<size>, The size represents the size
  487. // of the filename that needs to be read after the archive header
  488. // COFF archive format
  489. // First member : /
  490. // Second member : / (provides a directory of symbols)
  491. // Third member : // (may exist, if it exists, contains the string table)
  492. // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
  493. // even if the string table is empty. However, lib.exe does not in fact
  494. // seem to create the third member if there's no member whose filename
  495. // exceeds 15 characters. So the third member is optional.
  496. if (Name == "__.SYMDEF" || Name == "__.SYMDEF_64") {
  497. if (Name == "__.SYMDEF")
  498. Format = K_BSD;
  499. else // Name == "__.SYMDEF_64"
  500. Format = K_DARWIN64;
  501. // We know that the symbol table is not an external file, so we just assert
  502. // there is no error.
  503. SymbolTable = *C->getBuffer();
  504. if (Increment())
  505. return;
  506. setFirstRegular(*C);
  507. Err = Error::success();
  508. return;
  509. }
  510. if (Name.startswith("#1/")) {
  511. Format = K_BSD;
  512. // We know this is BSD, so getName will work since there is no string table.
  513. Expected<StringRef> NameOrErr = C->getName();
  514. if (!NameOrErr) {
  515. Err = NameOrErr.takeError();
  516. return;
  517. }
  518. Name = NameOrErr.get();
  519. if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
  520. // We know that the symbol table is not an external file, so we just
  521. // assert there is no error.
  522. SymbolTable = *C->getBuffer();
  523. if (Increment())
  524. return;
  525. }
  526. else if (Name == "__.SYMDEF_64 SORTED" || Name == "__.SYMDEF_64") {
  527. Format = K_DARWIN64;
  528. // We know that the symbol table is not an external file, so we just
  529. // assert there is no error.
  530. SymbolTable = *C->getBuffer();
  531. if (Increment())
  532. return;
  533. }
  534. setFirstRegular(*C);
  535. return;
  536. }
  537. // MIPS 64-bit ELF archives use a special format of a symbol table.
  538. // This format is marked by `ar_name` field equals to "/SYM64/".
  539. // For detailed description see page 96 in the following document:
  540. // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
  541. bool has64SymTable = false;
  542. if (Name == "/" || Name == "/SYM64/") {
  543. // We know that the symbol table is not an external file, so we just assert
  544. // there is no error.
  545. SymbolTable = *C->getBuffer();
  546. if (Name == "/SYM64/")
  547. has64SymTable = true;
  548. if (Increment())
  549. return;
  550. if (I == E) {
  551. Err = Error::success();
  552. return;
  553. }
  554. Expected<StringRef> NameOrErr = C->getRawName();
  555. if (!NameOrErr) {
  556. Err = NameOrErr.takeError();
  557. return;
  558. }
  559. Name = NameOrErr.get();
  560. }
  561. if (Name == "//") {
  562. Format = has64SymTable ? K_MIPS64 : K_GNU;
  563. // The string table is never an external member, so we just assert on the
  564. // ErrorOr.
  565. StringTable = *C->getBuffer();
  566. if (Increment())
  567. return;
  568. setFirstRegular(*C);
  569. Err = Error::success();
  570. return;
  571. }
  572. if (Name[0] != '/') {
  573. Format = has64SymTable ? K_MIPS64 : K_GNU;
  574. setFirstRegular(*C);
  575. Err = Error::success();
  576. return;
  577. }
  578. if (Name != "/") {
  579. Err = errorCodeToError(object_error::parse_failed);
  580. return;
  581. }
  582. Format = K_COFF;
  583. // We know that the symbol table is not an external file, so we just assert
  584. // there is no error.
  585. SymbolTable = *C->getBuffer();
  586. if (Increment())
  587. return;
  588. if (I == E) {
  589. setFirstRegular(*C);
  590. Err = Error::success();
  591. return;
  592. }
  593. NameOrErr = C->getRawName();
  594. if (!NameOrErr) {
  595. Err = NameOrErr.takeError();
  596. return;
  597. }
  598. Name = NameOrErr.get();
  599. if (Name == "//") {
  600. // The string table is never an external member, so we just assert on the
  601. // ErrorOr.
  602. StringTable = *C->getBuffer();
  603. if (Increment())
  604. return;
  605. }
  606. setFirstRegular(*C);
  607. Err = Error::success();
  608. }
  609. Archive::child_iterator Archive::child_begin(Error &Err,
  610. bool SkipInternal) const {
  611. if (Data.getBufferSize() == 8) // empty archive.
  612. return child_end();
  613. if (SkipInternal)
  614. return child_iterator(Child(this, FirstRegularData,
  615. FirstRegularStartOfFile),
  616. &Err);
  617. const char *Loc = Data.getBufferStart() + strlen(Magic);
  618. Child C(this, Loc, &Err);
  619. if (Err)
  620. return child_end();
  621. return child_iterator(C, &Err);
  622. }
  623. Archive::child_iterator Archive::child_end() const {
  624. return child_iterator(Child(this, nullptr, nullptr), nullptr);
  625. }
  626. StringRef Archive::Symbol::getName() const {
  627. return Parent->getSymbolTable().begin() + StringIndex;
  628. }
  629. ErrorOr<Archive::Child> Archive::Symbol::getMember() const {
  630. const char *Buf = Parent->getSymbolTable().begin();
  631. const char *Offsets = Buf;
  632. if (Parent->kind() == K_MIPS64 || Parent->kind() == K_DARWIN64)
  633. Offsets += sizeof(uint64_t);
  634. else
  635. Offsets += sizeof(uint32_t);
  636. uint32_t Offset = 0;
  637. if (Parent->kind() == K_GNU) {
  638. Offset = read32be(Offsets + SymbolIndex * 4);
  639. } else if (Parent->kind() == K_MIPS64) {
  640. Offset = read64be(Offsets + SymbolIndex * 8);
  641. } else if (Parent->kind() == K_BSD) {
  642. // The SymbolIndex is an index into the ranlib structs that start at
  643. // Offsets (the first uint32_t is the number of bytes of the ranlib
  644. // structs). The ranlib structs are a pair of uint32_t's the first
  645. // being a string table offset and the second being the offset into
  646. // the archive of the member that defines the symbol. Which is what
  647. // is needed here.
  648. Offset = read32le(Offsets + SymbolIndex * 8 + 4);
  649. } else if (Parent->kind() == K_DARWIN64) {
  650. // The SymbolIndex is an index into the ranlib_64 structs that start at
  651. // Offsets (the first uint64_t is the number of bytes of the ranlib_64
  652. // structs). The ranlib_64 structs are a pair of uint64_t's the first
  653. // being a string table offset and the second being the offset into
  654. // the archive of the member that defines the symbol. Which is what
  655. // is needed here.
  656. Offset = read64le(Offsets + SymbolIndex * 16 + 8);
  657. } else {
  658. // Skip offsets.
  659. uint32_t MemberCount = read32le(Buf);
  660. Buf += MemberCount * 4 + 4;
  661. uint32_t SymbolCount = read32le(Buf);
  662. if (SymbolIndex >= SymbolCount)
  663. return object_error::parse_failed;
  664. // Skip SymbolCount to get to the indices table.
  665. const char *Indices = Buf + 4;
  666. // Get the index of the offset in the file member offset table for this
  667. // symbol.
  668. uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
  669. // Subtract 1 since OffsetIndex is 1 based.
  670. --OffsetIndex;
  671. if (OffsetIndex >= MemberCount)
  672. return object_error::parse_failed;
  673. Offset = read32le(Offsets + OffsetIndex * 4);
  674. }
  675. const char *Loc = Parent->getData().begin() + Offset;
  676. Error Err;
  677. Child C(Parent, Loc, &Err);
  678. if (Err)
  679. return errorToErrorCode(std::move(Err));
  680. return C;
  681. }
  682. Archive::Symbol Archive::Symbol::getNext() const {
  683. Symbol t(*this);
  684. if (Parent->kind() == K_BSD) {
  685. // t.StringIndex is an offset from the start of the __.SYMDEF or
  686. // "__.SYMDEF SORTED" member into the string table for the ranlib
  687. // struct indexed by t.SymbolIndex . To change t.StringIndex to the
  688. // offset in the string table for t.SymbolIndex+1 we subtract the
  689. // its offset from the start of the string table for t.SymbolIndex
  690. // and add the offset of the string table for t.SymbolIndex+1.
  691. // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
  692. // which is the number of bytes of ranlib structs that follow. The ranlib
  693. // structs are a pair of uint32_t's the first being a string table offset
  694. // and the second being the offset into the archive of the member that
  695. // define the symbol. After that the next uint32_t is the byte count of
  696. // the string table followed by the string table.
  697. const char *Buf = Parent->getSymbolTable().begin();
  698. uint32_t RanlibCount = 0;
  699. RanlibCount = read32le(Buf) / 8;
  700. // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
  701. // don't change the t.StringIndex as we don't want to reference a ranlib
  702. // past RanlibCount.
  703. if (t.SymbolIndex + 1 < RanlibCount) {
  704. const char *Ranlibs = Buf + 4;
  705. uint32_t CurRanStrx = 0;
  706. uint32_t NextRanStrx = 0;
  707. CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
  708. NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
  709. t.StringIndex -= CurRanStrx;
  710. t.StringIndex += NextRanStrx;
  711. }
  712. } else {
  713. // Go to one past next null.
  714. t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
  715. }
  716. ++t.SymbolIndex;
  717. return t;
  718. }
  719. Archive::symbol_iterator Archive::symbol_begin() const {
  720. if (!hasSymbolTable())
  721. return symbol_iterator(Symbol(this, 0, 0));
  722. const char *buf = getSymbolTable().begin();
  723. if (kind() == K_GNU) {
  724. uint32_t symbol_count = 0;
  725. symbol_count = read32be(buf);
  726. buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
  727. } else if (kind() == K_MIPS64) {
  728. uint64_t symbol_count = read64be(buf);
  729. buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
  730. } else if (kind() == K_BSD) {
  731. // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
  732. // which is the number of bytes of ranlib structs that follow. The ranlib
  733. // structs are a pair of uint32_t's the first being a string table offset
  734. // and the second being the offset into the archive of the member that
  735. // define the symbol. After that the next uint32_t is the byte count of
  736. // the string table followed by the string table.
  737. uint32_t ranlib_count = 0;
  738. ranlib_count = read32le(buf) / 8;
  739. const char *ranlibs = buf + 4;
  740. uint32_t ran_strx = 0;
  741. ran_strx = read32le(ranlibs);
  742. buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
  743. // Skip the byte count of the string table.
  744. buf += sizeof(uint32_t);
  745. buf += ran_strx;
  746. } else if (kind() == K_DARWIN64) {
  747. // The __.SYMDEF_64 or "__.SYMDEF_64 SORTED" member starts with a uint64_t
  748. // which is the number of bytes of ranlib_64 structs that follow. The
  749. // ranlib_64 structs are a pair of uint64_t's the first being a string
  750. // table offset and the second being the offset into the archive of the
  751. // member that define the symbol. After that the next uint64_t is the byte
  752. // count of the string table followed by the string table.
  753. uint64_t ranlib_count = 0;
  754. ranlib_count = read64le(buf) / 16;
  755. const char *ranlibs = buf + 8;
  756. uint64_t ran_strx = 0;
  757. ran_strx = read64le(ranlibs);
  758. buf += sizeof(uint64_t) + (ranlib_count * (2 * (sizeof(uint64_t))));
  759. // Skip the byte count of the string table.
  760. buf += sizeof(uint64_t);
  761. buf += ran_strx;
  762. } else {
  763. uint32_t member_count = 0;
  764. uint32_t symbol_count = 0;
  765. member_count = read32le(buf);
  766. buf += 4 + (member_count * 4); // Skip offsets.
  767. symbol_count = read32le(buf);
  768. buf += 4 + (symbol_count * 2); // Skip indices.
  769. }
  770. uint32_t string_start_offset = buf - getSymbolTable().begin();
  771. return symbol_iterator(Symbol(this, 0, string_start_offset));
  772. }
  773. Archive::symbol_iterator Archive::symbol_end() const {
  774. return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
  775. }
  776. uint32_t Archive::getNumberOfSymbols() const {
  777. if (!hasSymbolTable())
  778. return 0;
  779. const char *buf = getSymbolTable().begin();
  780. if (kind() == K_GNU)
  781. return read32be(buf);
  782. if (kind() == K_MIPS64)
  783. return read64be(buf);
  784. if (kind() == K_BSD)
  785. return read32le(buf) / 8;
  786. if (kind() == K_DARWIN64)
  787. return read64le(buf) / 16;
  788. uint32_t member_count = 0;
  789. member_count = read32le(buf);
  790. buf += 4 + (member_count * 4); // Skip offsets.
  791. return read32le(buf);
  792. }
  793. Expected<Optional<Archive::Child>> Archive::findSym(StringRef name) const {
  794. Archive::symbol_iterator bs = symbol_begin();
  795. Archive::symbol_iterator es = symbol_end();
  796. for (; bs != es; ++bs) {
  797. StringRef SymName = bs->getName();
  798. if (SymName == name) {
  799. if (auto MemberOrErr = bs->getMember())
  800. return Child(*MemberOrErr);
  801. else
  802. return errorCodeToError(MemberOrErr.getError());
  803. }
  804. }
  805. return Optional<Child>();
  806. }
  807. bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }