ArchiveWriter.cpp 25 KB

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