ArchiveWriter.cpp 33 KB

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