ArchiveWriter.cpp 25 KB

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