ArchiveWriter.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. //===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===//
  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 writeArchive function.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Object/ArchiveWriter.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/BinaryFormat/Magic.h"
  16. #include "llvm/IR/LLVMContext.h"
  17. #include "llvm/Object/Archive.h"
  18. #include "llvm/Object/ObjectFile.h"
  19. #include "llvm/Object/SymbolicFile.h"
  20. #include "llvm/Support/EndianStream.h"
  21. #include "llvm/Support/Errc.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/Format.h"
  24. #include "llvm/Support/Path.h"
  25. #include "llvm/Support/ToolOutputFile.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <map>
  28. #if !defined(_MSC_VER) && !defined(__MINGW32__)
  29. #include <unistd.h>
  30. #else
  31. #include <io.h>
  32. #endif
  33. using namespace llvm;
  34. NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
  35. : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
  36. MemberName(BufRef.getBufferIdentifier()) {}
  37. Expected<NewArchiveMember>
  38. NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
  39. bool Deterministic) {
  40. Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
  41. if (!BufOrErr)
  42. return BufOrErr.takeError();
  43. NewArchiveMember M;
  44. M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
  45. M.MemberName = M.Buf->getBufferIdentifier();
  46. if (!Deterministic) {
  47. auto ModTimeOrErr = OldMember.getLastModified();
  48. if (!ModTimeOrErr)
  49. return ModTimeOrErr.takeError();
  50. M.ModTime = ModTimeOrErr.get();
  51. Expected<unsigned> UIDOrErr = OldMember.getUID();
  52. if (!UIDOrErr)
  53. return UIDOrErr.takeError();
  54. M.UID = UIDOrErr.get();
  55. Expected<unsigned> GIDOrErr = OldMember.getGID();
  56. if (!GIDOrErr)
  57. return GIDOrErr.takeError();
  58. M.GID = GIDOrErr.get();
  59. Expected<sys::fs::perms> AccessModeOrErr = OldMember.getAccessMode();
  60. if (!AccessModeOrErr)
  61. return AccessModeOrErr.takeError();
  62. M.Perms = AccessModeOrErr.get();
  63. }
  64. return std::move(M);
  65. }
  66. Expected<NewArchiveMember> NewArchiveMember::getFile(StringRef FileName,
  67. bool Deterministic) {
  68. sys::fs::file_status Status;
  69. int FD;
  70. if (auto EC = sys::fs::openFileForRead(FileName, FD))
  71. return errorCodeToError(EC);
  72. assert(FD != -1);
  73. if (auto EC = sys::fs::status(FD, Status))
  74. return errorCodeToError(EC);
  75. // Opening a directory doesn't make sense. Let it fail.
  76. // Linux cannot open directories with open(2), although
  77. // cygwin and *bsd can.
  78. if (Status.type() == sys::fs::file_type::directory_file)
  79. return errorCodeToError(make_error_code(errc::is_a_directory));
  80. ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
  81. MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
  82. if (!MemberBufferOrErr)
  83. return errorCodeToError(MemberBufferOrErr.getError());
  84. if (close(FD) != 0)
  85. return errorCodeToError(std::error_code(errno, std::generic_category()));
  86. NewArchiveMember M;
  87. M.Buf = std::move(*MemberBufferOrErr);
  88. M.MemberName = M.Buf->getBufferIdentifier();
  89. if (!Deterministic) {
  90. M.ModTime = std::chrono::time_point_cast<std::chrono::seconds>(
  91. Status.getLastModificationTime());
  92. M.UID = Status.getUser();
  93. M.GID = Status.getGroup();
  94. M.Perms = Status.permissions();
  95. }
  96. return std::move(M);
  97. }
  98. template <typename T>
  99. static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
  100. uint64_t OldPos = OS.tell();
  101. OS << Data;
  102. unsigned SizeSoFar = OS.tell() - OldPos;
  103. assert(SizeSoFar <= Size && "Data doesn't fit in Size");
  104. OS.indent(Size - SizeSoFar);
  105. }
  106. static bool isDarwin(object::Archive::Kind Kind) {
  107. return Kind == object::Archive::K_DARWIN ||
  108. Kind == object::Archive::K_DARWIN64;
  109. }
  110. static bool isBSDLike(object::Archive::Kind Kind) {
  111. switch (Kind) {
  112. case object::Archive::K_GNU:
  113. case object::Archive::K_GNU64:
  114. return false;
  115. case object::Archive::K_BSD:
  116. case object::Archive::K_DARWIN:
  117. case object::Archive::K_DARWIN64:
  118. return true;
  119. case object::Archive::K_COFF:
  120. break;
  121. }
  122. llvm_unreachable("not supported for writting");
  123. }
  124. template <class T>
  125. static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val) {
  126. support::endian::write(Out, Val,
  127. isBSDLike(Kind) ? support::little : support::big);
  128. }
  129. static void printRestOfMemberHeader(
  130. raw_ostream &Out, const sys::TimePoint<std::chrono::seconds> &ModTime,
  131. unsigned UID, unsigned GID, unsigned Perms, unsigned Size) {
  132. printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
  133. // The format has only 6 chars for uid and gid. Truncate if the provided
  134. // values don't fit.
  135. printWithSpacePadding(Out, UID % 1000000, 6);
  136. printWithSpacePadding(Out, GID % 1000000, 6);
  137. printWithSpacePadding(Out, format("%o", Perms), 8);
  138. printWithSpacePadding(Out, Size, 10);
  139. Out << "`\n";
  140. }
  141. static void
  142. printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name,
  143. const sys::TimePoint<std::chrono::seconds> &ModTime,
  144. unsigned UID, unsigned GID, unsigned Perms,
  145. unsigned Size) {
  146. printWithSpacePadding(Out, Twine(Name) + "/", 16);
  147. printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
  148. }
  149. static void
  150. printBSDMemberHeader(raw_ostream &Out, uint64_t Pos, StringRef Name,
  151. const sys::TimePoint<std::chrono::seconds> &ModTime,
  152. unsigned UID, unsigned GID, unsigned Perms,
  153. unsigned Size) {
  154. uint64_t PosAfterHeader = Pos + 60 + Name.size();
  155. // Pad so that even 64 bit object files are aligned.
  156. unsigned Pad = OffsetToAlignment(PosAfterHeader, 8);
  157. unsigned NameWithPadding = Name.size() + Pad;
  158. printWithSpacePadding(Out, Twine("#1/") + Twine(NameWithPadding), 16);
  159. printRestOfMemberHeader(Out, ModTime, UID, GID, Perms,
  160. NameWithPadding + Size);
  161. Out << Name;
  162. while (Pad--)
  163. Out.write(uint8_t(0));
  164. }
  165. static bool useStringTable(bool Thin, StringRef Name) {
  166. return Thin || Name.size() >= 16 || Name.contains('/');
  167. }
  168. static bool is64BitKind(object::Archive::Kind Kind) {
  169. switch (Kind) {
  170. case object::Archive::K_GNU:
  171. case object::Archive::K_BSD:
  172. case object::Archive::K_DARWIN:
  173. case object::Archive::K_COFF:
  174. return false;
  175. case object::Archive::K_DARWIN64:
  176. case object::Archive::K_GNU64:
  177. return true;
  178. }
  179. llvm_unreachable("not supported for writting");
  180. }
  181. static void
  182. printMemberHeader(raw_ostream &Out, uint64_t Pos, raw_ostream &StringTable,
  183. StringMap<uint64_t> &MemberNames, object::Archive::Kind Kind,
  184. bool Thin, const NewArchiveMember &M,
  185. sys::TimePoint<std::chrono::seconds> ModTime, unsigned Size) {
  186. if (isBSDLike(Kind))
  187. return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
  188. M.Perms, Size);
  189. if (!useStringTable(Thin, M.MemberName))
  190. return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
  191. M.Perms, Size);
  192. Out << '/';
  193. uint64_t NamePos;
  194. if (Thin) {
  195. NamePos = StringTable.tell();
  196. StringTable << M.MemberName << "/\n";
  197. } else {
  198. auto Insertion = MemberNames.insert({M.MemberName, uint64_t(0)});
  199. if (Insertion.second) {
  200. Insertion.first->second = StringTable.tell();
  201. StringTable << M.MemberName << "/\n";
  202. }
  203. NamePos = Insertion.first->second;
  204. }
  205. printWithSpacePadding(Out, NamePos, 15);
  206. printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
  207. }
  208. namespace {
  209. struct MemberData {
  210. std::vector<unsigned> Symbols;
  211. std::string Header;
  212. StringRef Data;
  213. StringRef Padding;
  214. };
  215. } // namespace
  216. static MemberData computeStringTable(StringRef Names) {
  217. unsigned Size = Names.size();
  218. unsigned Pad = OffsetToAlignment(Size, 2);
  219. std::string Header;
  220. raw_string_ostream Out(Header);
  221. printWithSpacePadding(Out, "//", 48);
  222. printWithSpacePadding(Out, Size + Pad, 10);
  223. Out << "`\n";
  224. Out.flush();
  225. return {{}, std::move(Header), Names, Pad ? "\n" : ""};
  226. }
  227. static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
  228. using namespace std::chrono;
  229. if (!Deterministic)
  230. return time_point_cast<seconds>(system_clock::now());
  231. return sys::TimePoint<seconds>();
  232. }
  233. static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
  234. uint32_t Symflags = S.getFlags();
  235. if (Symflags & object::SymbolRef::SF_FormatSpecific)
  236. return false;
  237. if (!(Symflags & object::SymbolRef::SF_Global))
  238. return false;
  239. if (Symflags & object::SymbolRef::SF_Undefined)
  240. return false;
  241. return true;
  242. }
  243. static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
  244. uint64_t Val) {
  245. if (is64BitKind(Kind))
  246. print<uint64_t>(Out, Kind, Val);
  247. else
  248. print<uint32_t>(Out, Kind, Val);
  249. }
  250. static void writeSymbolTable(raw_ostream &Out, object::Archive::Kind Kind,
  251. bool Deterministic, ArrayRef<MemberData> Members,
  252. StringRef StringTable) {
  253. // We don't write a symbol table on an archive with no members -- except on
  254. // Darwin, where the linker will abort unless the archive has a symbol table.
  255. if (StringTable.empty() && !isDarwin(Kind))
  256. return;
  257. unsigned NumSyms = 0;
  258. for (const MemberData &M : Members)
  259. NumSyms += M.Symbols.size();
  260. unsigned Size = 0;
  261. unsigned OffsetSize = is64BitKind(Kind) ? sizeof(uint64_t) : sizeof(uint32_t);
  262. Size += OffsetSize; // Number of entries
  263. if (isBSDLike(Kind))
  264. Size += NumSyms * OffsetSize * 2; // Table
  265. else
  266. Size += NumSyms * OffsetSize; // Table
  267. if (isBSDLike(Kind))
  268. Size += OffsetSize; // byte count
  269. Size += StringTable.size();
  270. // ld64 expects the members to be 8-byte aligned for 64-bit content and at
  271. // least 4-byte aligned for 32-bit content. Opt for the larger encoding
  272. // uniformly.
  273. // We do this for all bsd formats because it simplifies aligning members.
  274. unsigned Alignment = isBSDLike(Kind) ? 8 : 2;
  275. unsigned Pad = OffsetToAlignment(Size, Alignment);
  276. Size += Pad;
  277. if (isBSDLike(Kind)) {
  278. const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
  279. printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
  280. Size);
  281. } else {
  282. const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
  283. printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
  284. }
  285. uint64_t Pos = Out.tell() + Size;
  286. if (isBSDLike(Kind))
  287. printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
  288. else
  289. printNBits(Out, Kind, NumSyms);
  290. for (const MemberData &M : Members) {
  291. for (unsigned StringOffset : M.Symbols) {
  292. if (isBSDLike(Kind))
  293. printNBits(Out, Kind, StringOffset);
  294. printNBits(Out, Kind, Pos); // member offset
  295. }
  296. Pos += M.Header.size() + M.Data.size() + M.Padding.size();
  297. }
  298. if (isBSDLike(Kind))
  299. // byte count of the string table
  300. printNBits(Out, Kind, StringTable.size());
  301. Out << StringTable;
  302. while (Pad--)
  303. Out.write(uint8_t(0));
  304. }
  305. static Expected<std::vector<unsigned>>
  306. getSymbols(MemoryBufferRef Buf, raw_ostream &SymNames, bool &HasObject) {
  307. std::vector<unsigned> Ret;
  308. // In the scenario when LLVMContext is populated SymbolicFile will contain a
  309. // reference to it, thus SymbolicFile should be destroyed first.
  310. LLVMContext Context;
  311. std::unique_ptr<object::SymbolicFile> Obj;
  312. if (identify_magic(Buf.getBuffer()) == file_magic::bitcode) {
  313. auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
  314. Buf, file_magic::bitcode, &Context);
  315. if (!ObjOrErr) {
  316. // FIXME: check only for "not an object file" errors.
  317. consumeError(ObjOrErr.takeError());
  318. return Ret;
  319. }
  320. Obj = std::move(*ObjOrErr);
  321. } else {
  322. auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
  323. if (!ObjOrErr) {
  324. // FIXME: check only for "not an object file" errors.
  325. consumeError(ObjOrErr.takeError());
  326. return Ret;
  327. }
  328. Obj = std::move(*ObjOrErr);
  329. }
  330. HasObject = true;
  331. for (const object::BasicSymbolRef &S : Obj->symbols()) {
  332. if (!isArchiveSymbol(S))
  333. continue;
  334. Ret.push_back(SymNames.tell());
  335. if (Error E = S.printName(SymNames))
  336. return std::move(E);
  337. SymNames << '\0';
  338. }
  339. return Ret;
  340. }
  341. static Expected<std::vector<MemberData>>
  342. computeMemberData(raw_ostream &StringTable, raw_ostream &SymNames,
  343. object::Archive::Kind Kind, bool Thin, bool Deterministic,
  344. ArrayRef<NewArchiveMember> NewMembers) {
  345. static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
  346. // This ignores the symbol table, but we only need the value mod 8 and the
  347. // symbol table is aligned to be a multiple of 8 bytes
  348. uint64_t Pos = 0;
  349. std::vector<MemberData> Ret;
  350. bool HasObject = false;
  351. // Deduplicate long member names in the string table and reuse earlier name
  352. // offsets. This especially saves space for COFF Import libraries where all
  353. // members have the same name.
  354. StringMap<uint64_t> MemberNames;
  355. // UniqueTimestamps is a special case to improve debugging on Darwin:
  356. //
  357. // The Darwin linker does not link debug info into the final
  358. // binary. Instead, it emits entries of type N_OSO in in the output
  359. // binary's symbol table, containing references to the linked-in
  360. // object files. Using that reference, the debugger can read the
  361. // debug data directly from the object files. Alternatively, an
  362. // invocation of 'dsymutil' will link the debug data from the object
  363. // files into a dSYM bundle, which can be loaded by the debugger,
  364. // instead of the object files.
  365. //
  366. // For an object file, the N_OSO entries contain the absolute path
  367. // path to the file, and the file's timestamp. For an object
  368. // included in an archive, the path is formatted like
  369. // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
  370. // archive member's timestamp, rather than the archive's timestamp.
  371. //
  372. // However, this doesn't always uniquely identify an object within
  373. // an archive -- an archive file can have multiple entries with the
  374. // same filename. (This will happen commonly if the original object
  375. // files started in different directories.) The only way they get
  376. // distinguished, then, is via the timestamp. But this process is
  377. // unable to find the correct object file in the archive when there
  378. // are two files of the same name and timestamp.
  379. //
  380. // Additionally, timestamp==0 is treated specially, and causes the
  381. // timestamp to be ignored as a match criteria.
  382. //
  383. // That will "usually" work out okay when creating an archive not in
  384. // deterministic timestamp mode, because the objects will probably
  385. // have been created at different timestamps.
  386. //
  387. // To ameliorate this problem, in deterministic archive mode (which
  388. // is the default), on Darwin we will emit a unique non-zero
  389. // timestamp for each entry with a duplicated name. This is still
  390. // deterministic: the only thing affecting that timestamp is the
  391. // order of the files in the resultant archive.
  392. //
  393. // See also the functions that handle the lookup:
  394. // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
  395. // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
  396. bool UniqueTimestamps = Deterministic && isDarwin(Kind);
  397. std::map<StringRef, unsigned> FilenameCount;
  398. if (UniqueTimestamps) {
  399. for (const NewArchiveMember &M : NewMembers)
  400. FilenameCount[M.MemberName]++;
  401. for (auto &Entry : FilenameCount)
  402. Entry.second = Entry.second > 1 ? 1 : 0;
  403. }
  404. for (const NewArchiveMember &M : NewMembers) {
  405. std::string Header;
  406. raw_string_ostream Out(Header);
  407. MemoryBufferRef Buf = M.Buf->getMemBufferRef();
  408. StringRef Data = Thin ? "" : Buf.getBuffer();
  409. // ld64 expects the members to be 8-byte aligned for 64-bit content and at
  410. // least 4-byte aligned for 32-bit content. Opt for the larger encoding
  411. // uniformly. This matches the behaviour with cctools and ensures that ld64
  412. // is happy with archives that we generate.
  413. unsigned MemberPadding =
  414. isDarwin(Kind) ? OffsetToAlignment(Data.size(), 8) : 0;
  415. unsigned TailPadding = OffsetToAlignment(Data.size() + MemberPadding, 2);
  416. StringRef Padding = StringRef(PaddingData, MemberPadding + TailPadding);
  417. sys::TimePoint<std::chrono::seconds> ModTime;
  418. if (UniqueTimestamps)
  419. // Increment timestamp for each file of a given name.
  420. ModTime = sys::toTimePoint(FilenameCount[M.MemberName]++);
  421. else
  422. ModTime = M.ModTime;
  423. printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, M,
  424. ModTime, Buf.getBufferSize() + MemberPadding);
  425. Out.flush();
  426. Expected<std::vector<unsigned>> Symbols =
  427. getSymbols(Buf, SymNames, HasObject);
  428. if (auto E = Symbols.takeError())
  429. return std::move(E);
  430. Pos += Header.size() + Data.size() + Padding.size();
  431. Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
  432. }
  433. // If there are no symbols, emit an empty symbol table, to satisfy Solaris
  434. // tools, older versions of which expect a symbol table in a non-empty
  435. // archive, regardless of whether there are any symbols in it.
  436. if (HasObject && SymNames.tell() == 0)
  437. SymNames << '\0' << '\0' << '\0';
  438. return Ret;
  439. }
  440. namespace llvm {
  441. // Compute the relative path from From to To.
  442. std::string computeArchiveRelativePath(StringRef From, StringRef To) {
  443. if (sys::path::is_absolute(From) || sys::path::is_absolute(To))
  444. return To;
  445. StringRef DirFrom = sys::path::parent_path(From);
  446. auto FromI = sys::path::begin(DirFrom);
  447. auto ToI = sys::path::begin(To);
  448. while (*FromI == *ToI) {
  449. ++FromI;
  450. ++ToI;
  451. }
  452. SmallString<128> Relative;
  453. for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
  454. sys::path::append(Relative, "..");
  455. for (auto ToE = sys::path::end(To); ToI != ToE; ++ToI)
  456. sys::path::append(Relative, *ToI);
  457. // Replace backslashes with slashes so that the path is portable between *nix
  458. // and Windows.
  459. return sys::path::convert_to_slash(Relative);
  460. }
  461. Error writeArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
  462. bool WriteSymtab, object::Archive::Kind Kind,
  463. bool Deterministic, bool Thin,
  464. std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
  465. assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
  466. SmallString<0> SymNamesBuf;
  467. raw_svector_ostream SymNames(SymNamesBuf);
  468. SmallString<0> StringTableBuf;
  469. raw_svector_ostream StringTable(StringTableBuf);
  470. Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
  471. StringTable, SymNames, Kind, Thin, Deterministic, NewMembers);
  472. if (Error E = DataOrErr.takeError())
  473. return E;
  474. std::vector<MemberData> &Data = *DataOrErr;
  475. if (!StringTableBuf.empty())
  476. Data.insert(Data.begin(), computeStringTable(StringTableBuf));
  477. // We would like to detect if we need to switch to a 64-bit symbol table.
  478. if (WriteSymtab) {
  479. uint64_t MaxOffset = 0;
  480. uint64_t LastOffset = MaxOffset;
  481. for (const auto &M : Data) {
  482. // Record the start of the member's offset
  483. LastOffset = MaxOffset;
  484. // Account for the size of each part associated with the member.
  485. MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
  486. // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
  487. MaxOffset += M.Symbols.size() * 4;
  488. }
  489. // The SYM64 format is used when an archive's member offsets are larger than
  490. // 32-bits can hold. The need for this shift in format is detected by
  491. // writeArchive. To test this we need to generate a file with a member that
  492. // has an offset larger than 32-bits but this demands a very slow test. To
  493. // speed the test up we use this environment variable to pretend like the
  494. // cutoff happens before 32-bits and instead happens at some much smaller
  495. // value.
  496. const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
  497. int Sym64Threshold = 32;
  498. if (Sym64Env)
  499. StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
  500. // If LastOffset isn't going to fit in a 32-bit varible we need to switch
  501. // to 64-bit. Note that the file can be larger than 4GB as long as the last
  502. // member starts before the 4GB offset.
  503. if (LastOffset >= (1ULL << Sym64Threshold)) {
  504. if (Kind == object::Archive::K_DARWIN)
  505. Kind = object::Archive::K_DARWIN64;
  506. else
  507. Kind = object::Archive::K_GNU64;
  508. }
  509. }
  510. Expected<sys::fs::TempFile> Temp =
  511. sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
  512. if (!Temp)
  513. return Temp.takeError();
  514. raw_fd_ostream Out(Temp->FD, false);
  515. if (Thin)
  516. Out << "!<thin>\n";
  517. else
  518. Out << "!<arch>\n";
  519. if (WriteSymtab)
  520. writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
  521. for (const MemberData &M : Data)
  522. Out << M.Header << M.Data << M.Padding;
  523. Out.flush();
  524. // At this point, we no longer need whatever backing memory
  525. // was used to generate the NewMembers. On Windows, this buffer
  526. // could be a mapped view of the file we want to replace (if
  527. // we're updating an existing archive, say). In that case, the
  528. // rename would still succeed, but it would leave behind a
  529. // temporary file (actually the original file renamed) because
  530. // a file cannot be deleted while there's a handle open on it,
  531. // only renamed. So by freeing this buffer, this ensures that
  532. // the last open handle on the destination file, if any, is
  533. // closed before we attempt to rename.
  534. OldArchiveBuf.reset();
  535. return Temp->keep(ArcName);
  536. }
  537. } // namespace llvm