Archive.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. //===- Archive.cpp - ar File Format implementation ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ArchiveObjectFile class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Object/Archive.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/ADT/Twine.h"
  16. #include "llvm/Object/Binary.h"
  17. #include "llvm/Object/Error.h"
  18. #include "llvm/Support/Chrono.h"
  19. #include "llvm/Support/Endian.h"
  20. #include "llvm/Support/Error.h"
  21. #include "llvm/Support/ErrorOr.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/Host.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/Support/Path.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cstddef>
  31. #include <cstdint>
  32. #include <memory>
  33. #include <string>
  34. #include <system_error>
  35. using namespace llvm;
  36. using namespace object;
  37. using namespace llvm::support::endian;
  38. void Archive::anchor() {}
  39. static Error malformedError(Twine Msg) {
  40. std::string StringMsg = "truncated or malformed archive (" + Msg.str() + ")";
  41. return make_error<GenericBinaryError>(std::move(StringMsg),
  42. object_error::parse_failed);
  43. }
  44. static Error
  45. createMemberHeaderParseError(const AbstractArchiveMemberHeader *ArMemHeader,
  46. const char *RawHeaderPtr, uint64_t Size) {
  47. StringRef Msg("remaining size of archive too small for next archive "
  48. "member header ");
  49. Expected<StringRef> NameOrErr = ArMemHeader->getName(Size);
  50. if (NameOrErr)
  51. return malformedError(Msg + "for " + *NameOrErr);
  52. consumeError(NameOrErr.takeError());
  53. uint64_t Offset = RawHeaderPtr - ArMemHeader->Parent->getData().data();
  54. return malformedError(Msg + "at offset " + Twine(Offset));
  55. }
  56. template <class T, std::size_t N>
  57. StringRef getFieldRawString(const T (&Field)[N]) {
  58. return StringRef(Field, N).rtrim(" ");
  59. }
  60. template <class T>
  61. StringRef CommonArchiveMemberHeader<T>::getRawAccessMode() const {
  62. return getFieldRawString(ArMemHdr->AccessMode);
  63. }
  64. template <class T>
  65. StringRef CommonArchiveMemberHeader<T>::getRawLastModified() const {
  66. return getFieldRawString(ArMemHdr->LastModified);
  67. }
  68. template <class T> StringRef CommonArchiveMemberHeader<T>::getRawUID() const {
  69. return getFieldRawString(ArMemHdr->UID);
  70. }
  71. template <class T> StringRef CommonArchiveMemberHeader<T>::getRawGID() const {
  72. return getFieldRawString(ArMemHdr->GID);
  73. }
  74. template <class T> uint64_t CommonArchiveMemberHeader<T>::getOffset() const {
  75. return reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  76. }
  77. template class object::CommonArchiveMemberHeader<UnixArMemHdrType>;
  78. template class object::CommonArchiveMemberHeader<BigArMemHdrType>;
  79. ArchiveMemberHeader::ArchiveMemberHeader(const Archive *Parent,
  80. const char *RawHeaderPtr,
  81. uint64_t Size, Error *Err)
  82. : CommonArchiveMemberHeader<UnixArMemHdrType>(
  83. Parent, reinterpret_cast<const UnixArMemHdrType *>(RawHeaderPtr)) {
  84. if (RawHeaderPtr == nullptr)
  85. return;
  86. ErrorAsOutParameter ErrAsOutParam(Err);
  87. if (Size < getSizeOf()) {
  88. *Err = createMemberHeaderParseError(this, RawHeaderPtr, Size);
  89. return;
  90. }
  91. if (ArMemHdr->Terminator[0] != '`' || ArMemHdr->Terminator[1] != '\n') {
  92. if (Err) {
  93. std::string Buf;
  94. raw_string_ostream OS(Buf);
  95. OS.write_escaped(
  96. StringRef(ArMemHdr->Terminator, sizeof(ArMemHdr->Terminator)));
  97. OS.flush();
  98. std::string Msg("terminator characters in archive member \"" + Buf +
  99. "\" not the correct \"`\\n\" values for the archive "
  100. "member header ");
  101. Expected<StringRef> NameOrErr = getName(Size);
  102. if (!NameOrErr) {
  103. consumeError(NameOrErr.takeError());
  104. uint64_t Offset = RawHeaderPtr - Parent->getData().data();
  105. *Err = malformedError(Msg + "at offset " + Twine(Offset));
  106. } else
  107. *Err = malformedError(Msg + "for " + NameOrErr.get());
  108. }
  109. return;
  110. }
  111. }
  112. BigArchiveMemberHeader::BigArchiveMemberHeader(const Archive *Parent,
  113. const char *RawHeaderPtr,
  114. uint64_t Size, Error *Err)
  115. : CommonArchiveMemberHeader<BigArMemHdrType>(
  116. Parent, reinterpret_cast<const BigArMemHdrType *>(RawHeaderPtr)) {
  117. if (RawHeaderPtr == nullptr)
  118. return;
  119. ErrorAsOutParameter ErrAsOutParam(Err);
  120. if (Size < getSizeOf()) {
  121. Error SubErr = createMemberHeaderParseError(this, RawHeaderPtr, Size);
  122. if (Err)
  123. *Err = std::move(SubErr);
  124. }
  125. }
  126. // This gets the raw name from the ArMemHdr->Name field and checks that it is
  127. // valid for the kind of archive. If it is not valid it returns an Error.
  128. Expected<StringRef> ArchiveMemberHeader::getRawName() const {
  129. char EndCond;
  130. auto Kind = Parent->kind();
  131. if (Kind == Archive::K_BSD || Kind == Archive::K_DARWIN64) {
  132. if (ArMemHdr->Name[0] == ' ') {
  133. uint64_t Offset =
  134. reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  135. return malformedError("name contains a leading space for archive member "
  136. "header at offset " +
  137. Twine(Offset));
  138. }
  139. EndCond = ' ';
  140. } else if (ArMemHdr->Name[0] == '/' || ArMemHdr->Name[0] == '#')
  141. EndCond = ' ';
  142. else
  143. EndCond = '/';
  144. StringRef::size_type end =
  145. StringRef(ArMemHdr->Name, sizeof(ArMemHdr->Name)).find(EndCond);
  146. if (end == StringRef::npos)
  147. end = sizeof(ArMemHdr->Name);
  148. assert(end <= sizeof(ArMemHdr->Name) && end > 0);
  149. // Don't include the EndCond if there is one.
  150. return StringRef(ArMemHdr->Name, end);
  151. }
  152. Expected<uint64_t>
  153. getArchiveMemberDecField(Twine FieldName, const StringRef RawField,
  154. const Archive *Parent,
  155. const AbstractArchiveMemberHeader *MemHeader) {
  156. uint64_t Value;
  157. if (RawField.getAsInteger(10, Value)) {
  158. uint64_t Offset = MemHeader->getOffset();
  159. return malformedError("characters in " + FieldName +
  160. " field in archive member header are not "
  161. "all decimal numbers: '" +
  162. RawField +
  163. "' for the archive "
  164. "member header at offset " +
  165. Twine(Offset));
  166. }
  167. return Value;
  168. }
  169. Expected<uint64_t>
  170. getArchiveMemberOctField(Twine FieldName, const StringRef RawField,
  171. const Archive *Parent,
  172. const AbstractArchiveMemberHeader *MemHeader) {
  173. uint64_t Value;
  174. if (RawField.getAsInteger(8, Value)) {
  175. uint64_t Offset = MemHeader->getOffset();
  176. return malformedError("characters in " + FieldName +
  177. " field in archive member header are not "
  178. "all octal numbers: '" +
  179. RawField +
  180. "' for the archive "
  181. "member header at offset " +
  182. Twine(Offset));
  183. }
  184. return Value;
  185. }
  186. Expected<StringRef> BigArchiveMemberHeader::getRawName() const {
  187. Expected<uint64_t> NameLenOrErr = getArchiveMemberDecField(
  188. "NameLen", getFieldRawString(ArMemHdr->NameLen), Parent, this);
  189. if (!NameLenOrErr)
  190. // TODO: Out-of-line.
  191. return NameLenOrErr.takeError();
  192. uint64_t NameLen = NameLenOrErr.get();
  193. // If the name length is odd, pad with '\0' to get an even length. After
  194. // padding, there is the name terminator "`\n".
  195. uint64_t NameLenWithPadding = alignTo(NameLen, 2);
  196. StringRef NameTerminator = "`\n";
  197. StringRef NameStringWithNameTerminator =
  198. StringRef(ArMemHdr->Name, NameLenWithPadding + NameTerminator.size());
  199. if (!NameStringWithNameTerminator.endswith(NameTerminator)) {
  200. uint64_t Offset =
  201. reinterpret_cast<const char *>(ArMemHdr->Name + NameLenWithPadding) -
  202. Parent->getData().data();
  203. // TODO: Out-of-line.
  204. return malformedError(
  205. "name does not have name terminator \"`\\n\" for archive member"
  206. "header at offset " +
  207. Twine(Offset));
  208. }
  209. return StringRef(ArMemHdr->Name, NameLen);
  210. }
  211. // member including the header, so the size of any name following the header
  212. // is checked to make sure it does not overflow.
  213. Expected<StringRef> ArchiveMemberHeader::getName(uint64_t Size) const {
  214. // This can be called from the ArchiveMemberHeader constructor when the
  215. // archive header is truncated to produce an error message with the name.
  216. // Make sure the name field is not truncated.
  217. if (Size < offsetof(UnixArMemHdrType, Name) + sizeof(ArMemHdr->Name)) {
  218. uint64_t ArchiveOffset =
  219. reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  220. return malformedError("archive header truncated before the name field "
  221. "for archive member header at offset " +
  222. Twine(ArchiveOffset));
  223. }
  224. // The raw name itself can be invalid.
  225. Expected<StringRef> NameOrErr = getRawName();
  226. if (!NameOrErr)
  227. return NameOrErr.takeError();
  228. StringRef Name = NameOrErr.get();
  229. // Check if it's a special name.
  230. if (Name[0] == '/') {
  231. if (Name.size() == 1) // Linker member.
  232. return Name;
  233. if (Name.size() == 2 && Name[1] == '/') // String table.
  234. return Name;
  235. // System libraries from the Windows SDK for Windows 11 contain this symbol.
  236. // It looks like a CFG guard: we just skip it for now.
  237. if (Name.equals("/<XFGHASHMAP>/"))
  238. return Name;
  239. // Some libraries (e.g., arm64rt.lib) from the Windows WDK
  240. // (version 10.0.22000.0) contain this undocumented special member.
  241. if (Name.equals("/<ECSYMBOLS>/"))
  242. return Name;
  243. // It's a long name.
  244. // Get the string table offset.
  245. std::size_t StringOffset;
  246. if (Name.substr(1).rtrim(' ').getAsInteger(10, StringOffset)) {
  247. std::string Buf;
  248. raw_string_ostream OS(Buf);
  249. OS.write_escaped(Name.substr(1).rtrim(' '));
  250. OS.flush();
  251. uint64_t ArchiveOffset =
  252. reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  253. return malformedError("long name offset characters after the '/' are "
  254. "not all decimal numbers: '" +
  255. Buf + "' for archive member header at offset " +
  256. Twine(ArchiveOffset));
  257. }
  258. // Verify it.
  259. if (StringOffset >= Parent->getStringTable().size()) {
  260. uint64_t ArchiveOffset =
  261. reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  262. return malformedError("long name offset " + Twine(StringOffset) +
  263. " past the end of the string table for archive "
  264. "member header at offset " +
  265. Twine(ArchiveOffset));
  266. }
  267. // GNU long file names end with a "/\n".
  268. if (Parent->kind() == Archive::K_GNU ||
  269. Parent->kind() == Archive::K_GNU64) {
  270. size_t End = Parent->getStringTable().find('\n', /*From=*/StringOffset);
  271. if (End == StringRef::npos || End < 1 ||
  272. Parent->getStringTable()[End - 1] != '/') {
  273. return malformedError("string table at long name offset " +
  274. Twine(StringOffset) + "not terminated");
  275. }
  276. return Parent->getStringTable().slice(StringOffset, End - 1);
  277. }
  278. return Parent->getStringTable().begin() + StringOffset;
  279. }
  280. if (Name.startswith("#1/")) {
  281. uint64_t NameLength;
  282. if (Name.substr(3).rtrim(' ').getAsInteger(10, NameLength)) {
  283. std::string Buf;
  284. raw_string_ostream OS(Buf);
  285. OS.write_escaped(Name.substr(3).rtrim(' '));
  286. OS.flush();
  287. uint64_t ArchiveOffset =
  288. reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  289. return malformedError("long name length characters after the #1/ are "
  290. "not all decimal numbers: '" +
  291. Buf + "' for archive member header at offset " +
  292. Twine(ArchiveOffset));
  293. }
  294. if (getSizeOf() + NameLength > Size) {
  295. uint64_t ArchiveOffset =
  296. reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
  297. return malformedError("long name length: " + Twine(NameLength) +
  298. " extends past the end of the member or archive "
  299. "for archive member header at offset " +
  300. Twine(ArchiveOffset));
  301. }
  302. return StringRef(reinterpret_cast<const char *>(ArMemHdr) + getSizeOf(),
  303. NameLength)
  304. .rtrim('\0');
  305. }
  306. // It is not a long name so trim the blanks at the end of the name.
  307. if (Name[Name.size() - 1] != '/')
  308. return Name.rtrim(' ');
  309. // It's a simple name.
  310. return Name.drop_back(1);
  311. }
  312. Expected<StringRef> BigArchiveMemberHeader::getName(uint64_t Size) const {
  313. return getRawName();
  314. }
  315. Expected<uint64_t> ArchiveMemberHeader::getSize() const {
  316. return getArchiveMemberDecField("size", getFieldRawString(ArMemHdr->Size),
  317. Parent, this);
  318. }
  319. Expected<uint64_t> BigArchiveMemberHeader::getSize() const {
  320. Expected<uint64_t> SizeOrErr = getArchiveMemberDecField(
  321. "size", getFieldRawString(ArMemHdr->Size), Parent, this);
  322. if (!SizeOrErr)
  323. return SizeOrErr.takeError();
  324. Expected<uint64_t> NameLenOrErr = getRawNameSize();
  325. if (!NameLenOrErr)
  326. return NameLenOrErr.takeError();
  327. return *SizeOrErr + alignTo(*NameLenOrErr, 2);
  328. }
  329. Expected<uint64_t> BigArchiveMemberHeader::getRawNameSize() const {
  330. return getArchiveMemberDecField(
  331. "NameLen", getFieldRawString(ArMemHdr->NameLen), Parent, this);
  332. }
  333. Expected<uint64_t> BigArchiveMemberHeader::getNextOffset() const {
  334. return getArchiveMemberDecField(
  335. "NextOffset", getFieldRawString(ArMemHdr->NextOffset), Parent, this);
  336. }
  337. Expected<sys::fs::perms> AbstractArchiveMemberHeader::getAccessMode() const {
  338. Expected<uint64_t> AccessModeOrErr =
  339. getArchiveMemberOctField("AccessMode", getRawAccessMode(), Parent, this);
  340. if (!AccessModeOrErr)
  341. return AccessModeOrErr.takeError();
  342. return static_cast<sys::fs::perms>(*AccessModeOrErr);
  343. }
  344. Expected<sys::TimePoint<std::chrono::seconds>>
  345. AbstractArchiveMemberHeader::getLastModified() const {
  346. Expected<uint64_t> SecondsOrErr = getArchiveMemberDecField(
  347. "LastModified", getRawLastModified(), Parent, this);
  348. if (!SecondsOrErr)
  349. return SecondsOrErr.takeError();
  350. return sys::toTimePoint(*SecondsOrErr);
  351. }
  352. Expected<unsigned> AbstractArchiveMemberHeader::getUID() const {
  353. StringRef User = getRawUID();
  354. if (User.empty())
  355. return 0;
  356. return getArchiveMemberDecField("UID", User, Parent, this);
  357. }
  358. Expected<unsigned> AbstractArchiveMemberHeader::getGID() const {
  359. StringRef Group = getRawGID();
  360. if (Group.empty())
  361. return 0;
  362. return getArchiveMemberDecField("GID", Group, Parent, this);
  363. }
  364. Expected<bool> ArchiveMemberHeader::isThin() const {
  365. Expected<StringRef> NameOrErr = getRawName();
  366. if (!NameOrErr)
  367. return NameOrErr.takeError();
  368. StringRef Name = NameOrErr.get();
  369. return Parent->isThin() && Name != "/" && Name != "//" && Name != "/SYM64/";
  370. }
  371. Expected<const char *> ArchiveMemberHeader::getNextChildLoc() const {
  372. uint64_t Size = getSizeOf();
  373. Expected<bool> isThinOrErr = isThin();
  374. if (!isThinOrErr)
  375. return isThinOrErr.takeError();
  376. bool isThin = isThinOrErr.get();
  377. if (!isThin) {
  378. Expected<uint64_t> MemberSize = getSize();
  379. if (!MemberSize)
  380. return MemberSize.takeError();
  381. Size += MemberSize.get();
  382. }
  383. // If Size is odd, add 1 to make it even.
  384. const char *NextLoc =
  385. reinterpret_cast<const char *>(ArMemHdr) + alignTo(Size, 2);
  386. if (NextLoc == Parent->getMemoryBufferRef().getBufferEnd())
  387. return nullptr;
  388. return NextLoc;
  389. }
  390. Expected<const char *> BigArchiveMemberHeader::getNextChildLoc() const {
  391. if (getOffset() ==
  392. static_cast<const BigArchive *>(Parent)->getLastChildOffset())
  393. return nullptr;
  394. Expected<uint64_t> NextOffsetOrErr = getNextOffset();
  395. if (!NextOffsetOrErr)
  396. return NextOffsetOrErr.takeError();
  397. return Parent->getData().data() + NextOffsetOrErr.get();
  398. }
  399. Archive::Child::Child(const Archive *Parent, StringRef Data,
  400. uint16_t StartOfFile)
  401. : Parent(Parent), Data(Data), StartOfFile(StartOfFile) {
  402. Header = Parent->createArchiveMemberHeader(Data.data(), Data.size(), nullptr);
  403. }
  404. Archive::Child::Child(const Archive *Parent, const char *Start, Error *Err)
  405. : Parent(Parent) {
  406. if (!Start) {
  407. Header = nullptr;
  408. return;
  409. }
  410. Header = Parent->createArchiveMemberHeader(
  411. Start,
  412. Parent ? Parent->getData().size() - (Start - Parent->getData().data())
  413. : 0,
  414. Err);
  415. // If we are pointed to real data, Start is not a nullptr, then there must be
  416. // a non-null Err pointer available to report malformed data on. Only in
  417. // the case sentinel value is being constructed is Err is permitted to be a
  418. // nullptr.
  419. assert(Err && "Err can't be nullptr if Start is not a nullptr");
  420. ErrorAsOutParameter ErrAsOutParam(Err);
  421. // If there was an error in the construction of the Header
  422. // then just return with the error now set.
  423. if (*Err)
  424. return;
  425. uint64_t Size = Header->getSizeOf();
  426. Data = StringRef(Start, Size);
  427. Expected<bool> isThinOrErr = isThinMember();
  428. if (!isThinOrErr) {
  429. *Err = isThinOrErr.takeError();
  430. return;
  431. }
  432. bool isThin = isThinOrErr.get();
  433. if (!isThin) {
  434. Expected<uint64_t> MemberSize = getRawSize();
  435. if (!MemberSize) {
  436. *Err = MemberSize.takeError();
  437. return;
  438. }
  439. Size += MemberSize.get();
  440. Data = StringRef(Start, Size);
  441. }
  442. // Setup StartOfFile and PaddingBytes.
  443. StartOfFile = Header->getSizeOf();
  444. // Don't include attached name.
  445. Expected<StringRef> NameOrErr = getRawName();
  446. if (!NameOrErr) {
  447. *Err = NameOrErr.takeError();
  448. return;
  449. }
  450. StringRef Name = NameOrErr.get();
  451. if (Parent->kind() == Archive::K_AIXBIG) {
  452. // The actual start of the file is after the name and any necessary
  453. // even-alignment padding.
  454. StartOfFile += ((Name.size() + 1) >> 1) << 1;
  455. } else if (Name.startswith("#1/")) {
  456. uint64_t NameSize;
  457. StringRef RawNameSize = Name.substr(3).rtrim(' ');
  458. if (RawNameSize.getAsInteger(10, NameSize)) {
  459. uint64_t Offset = Start - Parent->getData().data();
  460. *Err = malformedError("long name length characters after the #1/ are "
  461. "not all decimal numbers: '" +
  462. RawNameSize +
  463. "' for archive member header at offset " +
  464. Twine(Offset));
  465. return;
  466. }
  467. StartOfFile += NameSize;
  468. }
  469. }
  470. Expected<uint64_t> Archive::Child::getSize() const {
  471. if (Parent->IsThin)
  472. return Header->getSize();
  473. return Data.size() - StartOfFile;
  474. }
  475. Expected<uint64_t> Archive::Child::getRawSize() const {
  476. return Header->getSize();
  477. }
  478. Expected<bool> Archive::Child::isThinMember() const { return Header->isThin(); }
  479. Expected<std::string> Archive::Child::getFullName() const {
  480. Expected<bool> isThin = isThinMember();
  481. if (!isThin)
  482. return isThin.takeError();
  483. assert(isThin.get());
  484. Expected<StringRef> NameOrErr = getName();
  485. if (!NameOrErr)
  486. return NameOrErr.takeError();
  487. StringRef Name = *NameOrErr;
  488. if (sys::path::is_absolute(Name))
  489. return std::string(Name);
  490. SmallString<128> FullName = sys::path::parent_path(
  491. Parent->getMemoryBufferRef().getBufferIdentifier());
  492. sys::path::append(FullName, Name);
  493. return std::string(FullName.str());
  494. }
  495. Expected<StringRef> Archive::Child::getBuffer() const {
  496. Expected<bool> isThinOrErr = isThinMember();
  497. if (!isThinOrErr)
  498. return isThinOrErr.takeError();
  499. bool isThin = isThinOrErr.get();
  500. if (!isThin) {
  501. Expected<uint64_t> Size = getSize();
  502. if (!Size)
  503. return Size.takeError();
  504. return StringRef(Data.data() + StartOfFile, Size.get());
  505. }
  506. Expected<std::string> FullNameOrErr = getFullName();
  507. if (!FullNameOrErr)
  508. return FullNameOrErr.takeError();
  509. const std::string &FullName = *FullNameOrErr;
  510. ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
  511. if (std::error_code EC = Buf.getError())
  512. return errorCodeToError(EC);
  513. Parent->ThinBuffers.push_back(std::move(*Buf));
  514. return Parent->ThinBuffers.back()->getBuffer();
  515. }
  516. Expected<Archive::Child> Archive::Child::getNext() const {
  517. Expected<const char *> NextLocOrErr = Header->getNextChildLoc();
  518. if (!NextLocOrErr)
  519. return NextLocOrErr.takeError();
  520. const char *NextLoc = *NextLocOrErr;
  521. // Check to see if this is at the end of the archive.
  522. if (NextLoc == nullptr)
  523. return Child(nullptr, nullptr, nullptr);
  524. // Check to see if this is past the end of the archive.
  525. if (NextLoc > Parent->Data.getBufferEnd()) {
  526. std::string Msg("offset to next archive member past the end of the archive "
  527. "after member ");
  528. Expected<StringRef> NameOrErr = getName();
  529. if (!NameOrErr) {
  530. consumeError(NameOrErr.takeError());
  531. uint64_t Offset = Data.data() - Parent->getData().data();
  532. return malformedError(Msg + "at offset " + Twine(Offset));
  533. } else
  534. return malformedError(Msg + NameOrErr.get());
  535. }
  536. Error Err = Error::success();
  537. Child Ret(Parent, NextLoc, &Err);
  538. if (Err)
  539. return std::move(Err);
  540. return Ret;
  541. }
  542. uint64_t Archive::Child::getChildOffset() const {
  543. const char *a = Parent->Data.getBuffer().data();
  544. const char *c = Data.data();
  545. uint64_t offset = c - a;
  546. return offset;
  547. }
  548. Expected<StringRef> Archive::Child::getName() const {
  549. Expected<uint64_t> RawSizeOrErr = getRawSize();
  550. if (!RawSizeOrErr)
  551. return RawSizeOrErr.takeError();
  552. uint64_t RawSize = RawSizeOrErr.get();
  553. Expected<StringRef> NameOrErr =
  554. Header->getName(Header->getSizeOf() + RawSize);
  555. if (!NameOrErr)
  556. return NameOrErr.takeError();
  557. StringRef Name = NameOrErr.get();
  558. return Name;
  559. }
  560. Expected<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
  561. Expected<StringRef> NameOrErr = getName();
  562. if (!NameOrErr)
  563. return NameOrErr.takeError();
  564. StringRef Name = NameOrErr.get();
  565. Expected<StringRef> Buf = getBuffer();
  566. if (!Buf)
  567. return createFileError(Name, Buf.takeError());
  568. return MemoryBufferRef(*Buf, Name);
  569. }
  570. Expected<std::unique_ptr<Binary>>
  571. Archive::Child::getAsBinary(LLVMContext *Context) const {
  572. Expected<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
  573. if (!BuffOrErr)
  574. return BuffOrErr.takeError();
  575. auto BinaryOrErr = createBinary(BuffOrErr.get(), Context);
  576. if (BinaryOrErr)
  577. return std::move(*BinaryOrErr);
  578. return BinaryOrErr.takeError();
  579. }
  580. Expected<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
  581. Error Err = Error::success();
  582. std::unique_ptr<Archive> Ret;
  583. StringRef Buffer = Source.getBuffer();
  584. if (Buffer.startswith(BigArchiveMagic))
  585. Ret = std::make_unique<BigArchive>(Source, Err);
  586. else
  587. Ret = std::make_unique<Archive>(Source, Err);
  588. if (Err)
  589. return std::move(Err);
  590. return std::move(Ret);
  591. }
  592. std::unique_ptr<AbstractArchiveMemberHeader>
  593. Archive::createArchiveMemberHeader(const char *RawHeaderPtr, uint64_t Size,
  594. Error *Err) const {
  595. ErrorAsOutParameter ErrAsOutParam(Err);
  596. if (kind() != K_AIXBIG)
  597. return std::make_unique<ArchiveMemberHeader>(this, RawHeaderPtr, Size, Err);
  598. return std::make_unique<BigArchiveMemberHeader>(this, RawHeaderPtr, Size,
  599. Err);
  600. }
  601. uint64_t Archive::getArchiveMagicLen() const {
  602. if (isThin())
  603. return sizeof(ThinArchiveMagic) - 1;
  604. if (Kind() == K_AIXBIG)
  605. return sizeof(BigArchiveMagic) - 1;
  606. return sizeof(ArchiveMagic) - 1;
  607. }
  608. void Archive::setFirstRegular(const Child &C) {
  609. FirstRegularData = C.Data;
  610. FirstRegularStartOfFile = C.StartOfFile;
  611. }
  612. Archive::Archive(MemoryBufferRef Source, Error &Err)
  613. : Binary(Binary::ID_Archive, Source) {
  614. ErrorAsOutParameter ErrAsOutParam(&Err);
  615. StringRef Buffer = Data.getBuffer();
  616. // Check for sufficient magic.
  617. if (Buffer.startswith(ThinArchiveMagic)) {
  618. IsThin = true;
  619. } else if (Buffer.startswith(ArchiveMagic)) {
  620. IsThin = false;
  621. } else if (Buffer.startswith(BigArchiveMagic)) {
  622. Format = K_AIXBIG;
  623. IsThin = false;
  624. return;
  625. } else {
  626. Err = make_error<GenericBinaryError>("file too small to be an archive",
  627. object_error::invalid_file_type);
  628. return;
  629. }
  630. // Make sure Format is initialized before any call to
  631. // ArchiveMemberHeader::getName() is made. This could be a valid empty
  632. // archive which is the same in all formats. So claiming it to be gnu to is
  633. // fine if not totally correct before we look for a string table or table of
  634. // contents.
  635. Format = K_GNU;
  636. // Get the special members.
  637. child_iterator I = child_begin(Err, false);
  638. if (Err)
  639. return;
  640. child_iterator E = child_end();
  641. // See if this is a valid empty archive and if so return.
  642. if (I == E) {
  643. Err = Error::success();
  644. return;
  645. }
  646. const Child *C = &*I;
  647. auto Increment = [&]() {
  648. ++I;
  649. if (Err)
  650. return true;
  651. C = &*I;
  652. return false;
  653. };
  654. Expected<StringRef> NameOrErr = C->getRawName();
  655. if (!NameOrErr) {
  656. Err = NameOrErr.takeError();
  657. return;
  658. }
  659. StringRef Name = NameOrErr.get();
  660. // Below is the pattern that is used to figure out the archive format
  661. // GNU archive format
  662. // First member : / (may exist, if it exists, points to the symbol table )
  663. // Second member : // (may exist, if it exists, points to the string table)
  664. // Note : The string table is used if the filename exceeds 15 characters
  665. // BSD archive format
  666. // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
  667. // There is no string table, if the filename exceeds 15 characters or has a
  668. // embedded space, the filename has #1/<size>, The size represents the size
  669. // of the filename that needs to be read after the archive header
  670. // COFF archive format
  671. // First member : /
  672. // Second member : / (provides a directory of symbols)
  673. // Third member : // (may exist, if it exists, contains the string table)
  674. // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
  675. // even if the string table is empty. However, lib.exe does not in fact
  676. // seem to create the third member if there's no member whose filename
  677. // exceeds 15 characters. So the third member is optional.
  678. if (Name == "__.SYMDEF" || Name == "__.SYMDEF_64") {
  679. if (Name == "__.SYMDEF")
  680. Format = K_BSD;
  681. else // Name == "__.SYMDEF_64"
  682. Format = K_DARWIN64;
  683. // We know that the symbol table is not an external file, but we still must
  684. // check any Expected<> return value.
  685. Expected<StringRef> BufOrErr = C->getBuffer();
  686. if (!BufOrErr) {
  687. Err = BufOrErr.takeError();
  688. return;
  689. }
  690. SymbolTable = BufOrErr.get();
  691. if (Increment())
  692. return;
  693. setFirstRegular(*C);
  694. Err = Error::success();
  695. return;
  696. }
  697. if (Name.startswith("#1/")) {
  698. Format = K_BSD;
  699. // We know this is BSD, so getName will work since there is no string table.
  700. Expected<StringRef> NameOrErr = C->getName();
  701. if (!NameOrErr) {
  702. Err = NameOrErr.takeError();
  703. return;
  704. }
  705. Name = NameOrErr.get();
  706. if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
  707. // We know that the symbol table is not an external file, but we still
  708. // must check any Expected<> return value.
  709. Expected<StringRef> BufOrErr = C->getBuffer();
  710. if (!BufOrErr) {
  711. Err = BufOrErr.takeError();
  712. return;
  713. }
  714. SymbolTable = BufOrErr.get();
  715. if (Increment())
  716. return;
  717. } else if (Name == "__.SYMDEF_64 SORTED" || Name == "__.SYMDEF_64") {
  718. Format = K_DARWIN64;
  719. // We know that the symbol table is not an external file, but we still
  720. // must check any Expected<> return value.
  721. Expected<StringRef> BufOrErr = C->getBuffer();
  722. if (!BufOrErr) {
  723. Err = BufOrErr.takeError();
  724. return;
  725. }
  726. SymbolTable = BufOrErr.get();
  727. if (Increment())
  728. return;
  729. }
  730. setFirstRegular(*C);
  731. return;
  732. }
  733. // MIPS 64-bit ELF archives use a special format of a symbol table.
  734. // This format is marked by `ar_name` field equals to "/SYM64/".
  735. // For detailed description see page 96 in the following document:
  736. // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
  737. bool has64SymTable = false;
  738. if (Name == "/" || Name == "/SYM64/") {
  739. // We know that the symbol table is not an external file, but we still
  740. // must check any Expected<> return value.
  741. Expected<StringRef> BufOrErr = C->getBuffer();
  742. if (!BufOrErr) {
  743. Err = BufOrErr.takeError();
  744. return;
  745. }
  746. SymbolTable = BufOrErr.get();
  747. if (Name == "/SYM64/")
  748. has64SymTable = true;
  749. if (Increment())
  750. return;
  751. if (I == E) {
  752. Err = Error::success();
  753. return;
  754. }
  755. Expected<StringRef> NameOrErr = C->getRawName();
  756. if (!NameOrErr) {
  757. Err = NameOrErr.takeError();
  758. return;
  759. }
  760. Name = NameOrErr.get();
  761. }
  762. if (Name == "//") {
  763. Format = has64SymTable ? K_GNU64 : K_GNU;
  764. // The string table is never an external member, but we still
  765. // must check any Expected<> return value.
  766. Expected<StringRef> BufOrErr = C->getBuffer();
  767. if (!BufOrErr) {
  768. Err = BufOrErr.takeError();
  769. return;
  770. }
  771. StringTable = BufOrErr.get();
  772. if (Increment())
  773. return;
  774. setFirstRegular(*C);
  775. Err = Error::success();
  776. return;
  777. }
  778. if (Name[0] != '/') {
  779. Format = has64SymTable ? K_GNU64 : K_GNU;
  780. setFirstRegular(*C);
  781. Err = Error::success();
  782. return;
  783. }
  784. if (Name != "/") {
  785. Err = errorCodeToError(object_error::parse_failed);
  786. return;
  787. }
  788. Format = K_COFF;
  789. // We know that the symbol table is not an external file, but we still
  790. // must check any Expected<> return value.
  791. Expected<StringRef> BufOrErr = C->getBuffer();
  792. if (!BufOrErr) {
  793. Err = BufOrErr.takeError();
  794. return;
  795. }
  796. SymbolTable = BufOrErr.get();
  797. if (Increment())
  798. return;
  799. if (I == E) {
  800. setFirstRegular(*C);
  801. Err = Error::success();
  802. return;
  803. }
  804. NameOrErr = C->getRawName();
  805. if (!NameOrErr) {
  806. Err = NameOrErr.takeError();
  807. return;
  808. }
  809. Name = NameOrErr.get();
  810. if (Name == "//") {
  811. // The string table is never an external member, but we still
  812. // must check any Expected<> return value.
  813. Expected<StringRef> BufOrErr = C->getBuffer();
  814. if (!BufOrErr) {
  815. Err = BufOrErr.takeError();
  816. return;
  817. }
  818. StringTable = BufOrErr.get();
  819. if (Increment())
  820. return;
  821. }
  822. setFirstRegular(*C);
  823. Err = Error::success();
  824. }
  825. object::Archive::Kind Archive::getDefaultKindForHost() {
  826. Triple HostTriple(sys::getProcessTriple());
  827. return HostTriple.isOSDarwin()
  828. ? object::Archive::K_DARWIN
  829. : (HostTriple.isOSAIX() ? object::Archive::K_AIXBIG
  830. : object::Archive::K_GNU);
  831. }
  832. Archive::child_iterator Archive::child_begin(Error &Err,
  833. bool SkipInternal) const {
  834. if (isEmpty())
  835. return child_end();
  836. if (SkipInternal)
  837. return child_iterator::itr(
  838. Child(this, FirstRegularData, FirstRegularStartOfFile), Err);
  839. const char *Loc = Data.getBufferStart() + getFirstChildOffset();
  840. Child C(this, Loc, &Err);
  841. if (Err)
  842. return child_end();
  843. return child_iterator::itr(C, Err);
  844. }
  845. Archive::child_iterator Archive::child_end() const {
  846. return child_iterator::end(Child(nullptr, nullptr, nullptr));
  847. }
  848. StringRef Archive::Symbol::getName() const {
  849. return Parent->getSymbolTable().begin() + StringIndex;
  850. }
  851. Expected<Archive::Child> Archive::Symbol::getMember() const {
  852. const char *Buf = Parent->getSymbolTable().begin();
  853. const char *Offsets = Buf;
  854. if (Parent->kind() == K_GNU64 || Parent->kind() == K_DARWIN64 ||
  855. Parent->kind() == K_AIXBIG)
  856. Offsets += sizeof(uint64_t);
  857. else
  858. Offsets += sizeof(uint32_t);
  859. uint64_t Offset = 0;
  860. if (Parent->kind() == K_GNU) {
  861. Offset = read32be(Offsets + SymbolIndex * 4);
  862. } else if (Parent->kind() == K_GNU64 || Parent->kind() == K_AIXBIG) {
  863. Offset = read64be(Offsets + SymbolIndex * 8);
  864. } else if (Parent->kind() == K_BSD) {
  865. // The SymbolIndex is an index into the ranlib structs that start at
  866. // Offsets (the first uint32_t is the number of bytes of the ranlib
  867. // structs). The ranlib structs are a pair of uint32_t's the first
  868. // being a string table offset and the second being the offset into
  869. // the archive of the member that defines the symbol. Which is what
  870. // is needed here.
  871. Offset = read32le(Offsets + SymbolIndex * 8 + 4);
  872. } else if (Parent->kind() == K_DARWIN64) {
  873. // The SymbolIndex is an index into the ranlib_64 structs that start at
  874. // Offsets (the first uint64_t is the number of bytes of the ranlib_64
  875. // structs). The ranlib_64 structs are a pair of uint64_t's the first
  876. // being a string table offset and the second being the offset into
  877. // the archive of the member that defines the symbol. Which is what
  878. // is needed here.
  879. Offset = read64le(Offsets + SymbolIndex * 16 + 8);
  880. } else {
  881. // Skip offsets.
  882. uint32_t MemberCount = read32le(Buf);
  883. Buf += MemberCount * 4 + 4;
  884. uint32_t SymbolCount = read32le(Buf);
  885. if (SymbolIndex >= SymbolCount)
  886. return errorCodeToError(object_error::parse_failed);
  887. // Skip SymbolCount to get to the indices table.
  888. const char *Indices = Buf + 4;
  889. // Get the index of the offset in the file member offset table for this
  890. // symbol.
  891. uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
  892. // Subtract 1 since OffsetIndex is 1 based.
  893. --OffsetIndex;
  894. if (OffsetIndex >= MemberCount)
  895. return errorCodeToError(object_error::parse_failed);
  896. Offset = read32le(Offsets + OffsetIndex * 4);
  897. }
  898. const char *Loc = Parent->getData().begin() + Offset;
  899. Error Err = Error::success();
  900. Child C(Parent, Loc, &Err);
  901. if (Err)
  902. return std::move(Err);
  903. return C;
  904. }
  905. Archive::Symbol Archive::Symbol::getNext() const {
  906. Symbol t(*this);
  907. if (Parent->kind() == K_BSD) {
  908. // t.StringIndex is an offset from the start of the __.SYMDEF or
  909. // "__.SYMDEF SORTED" member into the string table for the ranlib
  910. // struct indexed by t.SymbolIndex . To change t.StringIndex to the
  911. // offset in the string table for t.SymbolIndex+1 we subtract the
  912. // its offset from the start of the string table for t.SymbolIndex
  913. // and add the offset of the string table for t.SymbolIndex+1.
  914. // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
  915. // which is the number of bytes of ranlib structs that follow. The ranlib
  916. // structs are a pair of uint32_t's the first being a string table offset
  917. // and the second being the offset into the archive of the member that
  918. // define the symbol. After that the next uint32_t is the byte count of
  919. // the string table followed by the string table.
  920. const char *Buf = Parent->getSymbolTable().begin();
  921. uint32_t RanlibCount = 0;
  922. RanlibCount = read32le(Buf) / 8;
  923. // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
  924. // don't change the t.StringIndex as we don't want to reference a ranlib
  925. // past RanlibCount.
  926. if (t.SymbolIndex + 1 < RanlibCount) {
  927. const char *Ranlibs = Buf + 4;
  928. uint32_t CurRanStrx = 0;
  929. uint32_t NextRanStrx = 0;
  930. CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
  931. NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
  932. t.StringIndex -= CurRanStrx;
  933. t.StringIndex += NextRanStrx;
  934. }
  935. } else {
  936. // Go to one past next null.
  937. t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
  938. }
  939. ++t.SymbolIndex;
  940. return t;
  941. }
  942. Archive::symbol_iterator Archive::symbol_begin() const {
  943. if (!hasSymbolTable())
  944. return symbol_iterator(Symbol(this, 0, 0));
  945. const char *buf = getSymbolTable().begin();
  946. if (kind() == K_GNU) {
  947. uint32_t symbol_count = 0;
  948. symbol_count = read32be(buf);
  949. buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
  950. } else if (kind() == K_GNU64) {
  951. uint64_t symbol_count = read64be(buf);
  952. buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
  953. } else if (kind() == K_BSD) {
  954. // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
  955. // which is the number of bytes of ranlib structs that follow. The ranlib
  956. // structs are a pair of uint32_t's the first being a string table offset
  957. // and the second being the offset into the archive of the member that
  958. // define the symbol. After that the next uint32_t is the byte count of
  959. // the string table followed by the string table.
  960. uint32_t ranlib_count = 0;
  961. ranlib_count = read32le(buf) / 8;
  962. const char *ranlibs = buf + 4;
  963. uint32_t ran_strx = 0;
  964. ran_strx = read32le(ranlibs);
  965. buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
  966. // Skip the byte count of the string table.
  967. buf += sizeof(uint32_t);
  968. buf += ran_strx;
  969. } else if (kind() == K_DARWIN64) {
  970. // The __.SYMDEF_64 or "__.SYMDEF_64 SORTED" member starts with a uint64_t
  971. // which is the number of bytes of ranlib_64 structs that follow. The
  972. // ranlib_64 structs are a pair of uint64_t's the first being a string
  973. // table offset and the second being the offset into the archive of the
  974. // member that define the symbol. After that the next uint64_t is the byte
  975. // count of the string table followed by the string table.
  976. uint64_t ranlib_count = 0;
  977. ranlib_count = read64le(buf) / 16;
  978. const char *ranlibs = buf + 8;
  979. uint64_t ran_strx = 0;
  980. ran_strx = read64le(ranlibs);
  981. buf += sizeof(uint64_t) + (ranlib_count * (2 * (sizeof(uint64_t))));
  982. // Skip the byte count of the string table.
  983. buf += sizeof(uint64_t);
  984. buf += ran_strx;
  985. } else if (kind() == K_AIXBIG) {
  986. buf = getStringTable().begin();
  987. } else {
  988. uint32_t member_count = 0;
  989. uint32_t symbol_count = 0;
  990. member_count = read32le(buf);
  991. buf += 4 + (member_count * 4); // Skip offsets.
  992. symbol_count = read32le(buf);
  993. buf += 4 + (symbol_count * 2); // Skip indices.
  994. }
  995. uint32_t string_start_offset = buf - getSymbolTable().begin();
  996. return symbol_iterator(Symbol(this, 0, string_start_offset));
  997. }
  998. Archive::symbol_iterator Archive::symbol_end() const {
  999. return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
  1000. }
  1001. uint32_t Archive::getNumberOfSymbols() const {
  1002. if (!hasSymbolTable())
  1003. return 0;
  1004. const char *buf = getSymbolTable().begin();
  1005. if (kind() == K_GNU)
  1006. return read32be(buf);
  1007. if (kind() == K_GNU64 || kind() == K_AIXBIG)
  1008. return read64be(buf);
  1009. if (kind() == K_BSD)
  1010. return read32le(buf) / 8;
  1011. if (kind() == K_DARWIN64)
  1012. return read64le(buf) / 16;
  1013. uint32_t member_count = 0;
  1014. member_count = read32le(buf);
  1015. buf += 4 + (member_count * 4); // Skip offsets.
  1016. return read32le(buf);
  1017. }
  1018. Expected<std::optional<Archive::Child>> Archive::findSym(StringRef name) const {
  1019. Archive::symbol_iterator bs = symbol_begin();
  1020. Archive::symbol_iterator es = symbol_end();
  1021. for (; bs != es; ++bs) {
  1022. StringRef SymName = bs->getName();
  1023. if (SymName == name) {
  1024. if (auto MemberOrErr = bs->getMember())
  1025. return Child(*MemberOrErr);
  1026. else
  1027. return MemberOrErr.takeError();
  1028. }
  1029. }
  1030. return std::nullopt;
  1031. }
  1032. // Returns true if archive file contains no member file.
  1033. bool Archive::isEmpty() const {
  1034. return Data.getBufferSize() == getArchiveMagicLen();
  1035. }
  1036. bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }
  1037. BigArchive::BigArchive(MemoryBufferRef Source, Error &Err)
  1038. : Archive(Source, Err) {
  1039. ErrorAsOutParameter ErrAsOutParam(&Err);
  1040. StringRef Buffer = Data.getBuffer();
  1041. ArFixLenHdr = reinterpret_cast<const FixLenHdr *>(Buffer.data());
  1042. StringRef RawOffset = getFieldRawString(ArFixLenHdr->FirstChildOffset);
  1043. if (RawOffset.getAsInteger(10, FirstChildOffset))
  1044. // TODO: Out-of-line.
  1045. Err = malformedError("malformed AIX big archive: first member offset \"" +
  1046. RawOffset + "\" is not a number");
  1047. RawOffset = getFieldRawString(ArFixLenHdr->LastChildOffset);
  1048. if (RawOffset.getAsInteger(10, LastChildOffset))
  1049. // TODO: Out-of-line.
  1050. Err = malformedError("malformed AIX big archive: last member offset \"" +
  1051. RawOffset + "\" is not a number");
  1052. // Calculate the global symbol table.
  1053. uint64_t GlobSymOffset = 0;
  1054. RawOffset = getFieldRawString(ArFixLenHdr->GlobSymOffset);
  1055. if (RawOffset.getAsInteger(10, GlobSymOffset))
  1056. // TODO: add test case.
  1057. Err = malformedError(
  1058. "malformed AIX big archive: global symbol table offset \"" + RawOffset +
  1059. "\" is not a number");
  1060. if (Err)
  1061. return;
  1062. if (GlobSymOffset > 0) {
  1063. uint64_t BufferSize = Data.getBufferSize();
  1064. uint64_t GlobalSymTblContentOffset =
  1065. GlobSymOffset + sizeof(BigArMemHdrType);
  1066. if (GlobalSymTblContentOffset > BufferSize) {
  1067. Err = malformedError("global symbol table header at offset 0x" +
  1068. Twine::utohexstr(GlobSymOffset) + " and size 0x" +
  1069. Twine::utohexstr(sizeof(BigArMemHdrType)) +
  1070. " goes past the end of file");
  1071. return;
  1072. }
  1073. const char *GlobSymTblLoc = Data.getBufferStart() + GlobSymOffset;
  1074. const BigArMemHdrType *GlobalSymHdr =
  1075. reinterpret_cast<const BigArMemHdrType *>(GlobSymTblLoc);
  1076. RawOffset = getFieldRawString(GlobalSymHdr->Size);
  1077. uint64_t Size;
  1078. if (RawOffset.getAsInteger(10, Size)) {
  1079. // TODO: add test case.
  1080. Err = malformedError(
  1081. "malformed AIX big archive: global symbol table size \"" + RawOffset +
  1082. "\" is not a number");
  1083. return;
  1084. }
  1085. if (GlobalSymTblContentOffset + Size > BufferSize) {
  1086. Err = malformedError("global symbol table content at offset 0x" +
  1087. Twine::utohexstr(GlobalSymTblContentOffset) +
  1088. " and size 0x" + Twine::utohexstr(Size) +
  1089. " goes past the end of file");
  1090. return;
  1091. }
  1092. SymbolTable = StringRef(GlobSymTblLoc + sizeof(BigArMemHdrType), Size);
  1093. unsigned SymNum = getNumberOfSymbols();
  1094. unsigned SymOffsetsSize = 8 * (SymNum + 1);
  1095. uint64_t SymbolTableStringSize = Size - SymOffsetsSize;
  1096. StringTable =
  1097. StringRef(GlobSymTblLoc + sizeof(BigArMemHdrType) + SymOffsetsSize,
  1098. SymbolTableStringSize);
  1099. }
  1100. child_iterator I = child_begin(Err, false);
  1101. if (Err)
  1102. return;
  1103. child_iterator E = child_end();
  1104. if (I == E) {
  1105. Err = Error::success();
  1106. return;
  1107. }
  1108. setFirstRegular(*I);
  1109. Err = Error::success();
  1110. }