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