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   if (identify_magic(Buf.getBuffer()) == file_magic::bitcode) {
363     auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
364         Buf, file_magic::bitcode, &Context);
365     if (!ObjOrErr) {
366       // FIXME: check only for "not an object file" errors.
367       consumeError(ObjOrErr.takeError());
368       return Ret;
369     }
370     Obj = std::move(*ObjOrErr);
371   } else {
372     auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
373     if (!ObjOrErr) {
374       // FIXME: check only for "not an object file" errors.
375       consumeError(ObjOrErr.takeError());
376       return Ret;
377     }
378     Obj = std::move(*ObjOrErr);
379   }
380 
381   HasObject = true;
382   for (const object::BasicSymbolRef &S : Obj->symbols()) {
383     if (!isArchiveSymbol(S))
384       continue;
385     Ret.push_back(SymNames.tell());
386     if (Error E = S.printName(SymNames))
387       return std::move(E);
388     SymNames << '\0';
389   }
390   return Ret;
391 }
392 
393 static Expected<std::vector<MemberData>>
394 computeMemberData(raw_ostream &StringTable, raw_ostream &SymNames,
395                   object::Archive::Kind Kind, bool Thin, bool Deterministic,
396                   ArrayRef<NewArchiveMember> NewMembers) {
397   static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
398 
399   // This ignores the symbol table, but we only need the value mod 8 and the
400   // symbol table is aligned to be a multiple of 8 bytes
401   uint64_t Pos = 0;
402 
403   std::vector<MemberData> Ret;
404   bool HasObject = false;
405 
406   // Deduplicate long member names in the string table and reuse earlier name
407   // offsets. This especially saves space for COFF Import libraries where all
408   // members have the same name.
409   StringMap<uint64_t> MemberNames;
410 
411   // UniqueTimestamps is a special case to improve debugging on Darwin:
412   //
413   // The Darwin linker does not link debug info into the final
414   // binary. Instead, it emits entries of type N_OSO in in the output
415   // binary's symbol table, containing references to the linked-in
416   // object files. Using that reference, the debugger can read the
417   // debug data directly from the object files. Alternatively, an
418   // invocation of 'dsymutil' will link the debug data from the object
419   // files into a dSYM bundle, which can be loaded by the debugger,
420   // instead of the object files.
421   //
422   // For an object file, the N_OSO entries contain the absolute path
423   // path to the file, and the file's timestamp. For an object
424   // included in an archive, the path is formatted like
425   // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
426   // archive member's timestamp, rather than the archive's timestamp.
427   //
428   // However, this doesn't always uniquely identify an object within
429   // an archive -- an archive file can have multiple entries with the
430   // same filename. (This will happen commonly if the original object
431   // files started in different directories.) The only way they get
432   // distinguished, then, is via the timestamp. But this process is
433   // unable to find the correct object file in the archive when there
434   // are two files of the same name and timestamp.
435   //
436   // Additionally, timestamp==0 is treated specially, and causes the
437   // timestamp to be ignored as a match criteria.
438   //
439   // That will "usually" work out okay when creating an archive not in
440   // deterministic timestamp mode, because the objects will probably
441   // have been created at different timestamps.
442   //
443   // To ameliorate this problem, in deterministic archive mode (which
444   // is the default), on Darwin we will emit a unique non-zero
445   // timestamp for each entry with a duplicated name. This is still
446   // deterministic: the only thing affecting that timestamp is the
447   // order of the files in the resultant archive.
448   //
449   // See also the functions that handle the lookup:
450   // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
451   // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
452   bool UniqueTimestamps = Deterministic && isDarwin(Kind);
453   std::map<StringRef, unsigned> FilenameCount;
454   if (UniqueTimestamps) {
455     for (const NewArchiveMember &M : NewMembers)
456       FilenameCount[M.MemberName]++;
457     for (auto &Entry : FilenameCount)
458       Entry.second = Entry.second > 1 ? 1 : 0;
459   }
460 
461   for (const NewArchiveMember &M : NewMembers) {
462     std::string Header;
463     raw_string_ostream Out(Header);
464 
465     MemoryBufferRef Buf = M.Buf->getMemBufferRef();
466     StringRef Data = Thin ? "" : Buf.getBuffer();
467 
468     // ld64 expects the members to be 8-byte aligned for 64-bit content and at
469     // least 4-byte aligned for 32-bit content.  Opt for the larger encoding
470     // uniformly.  This matches the behaviour with cctools and ensures that ld64
471     // is happy with archives that we generate.
472     unsigned MemberPadding =
473         isDarwin(Kind) ? offsetToAlignment(Data.size(), Align(8)) : 0;
474     unsigned TailPadding =
475         offsetToAlignment(Data.size() + MemberPadding, Align(2));
476     StringRef Padding = StringRef(PaddingData, MemberPadding + TailPadding);
477 
478     sys::TimePoint<std::chrono::seconds> ModTime;
479     if (UniqueTimestamps)
480       // Increment timestamp for each file of a given name.
481       ModTime = sys::toTimePoint(FilenameCount[M.MemberName]++);
482     else
483       ModTime = M.ModTime;
484 
485     uint64_t Size = Buf.getBufferSize() + MemberPadding;
486     if (Size > object::Archive::MaxMemberSize) {
487       std::string StringMsg =
488           "File " + M.MemberName.str() + " exceeds size limit";
489       return make_error<object::GenericBinaryError>(
490           std::move(StringMsg), object::object_error::parse_failed);
491     }
492 
493     printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, M,
494                       ModTime, Size);
495     Out.flush();
496 
497     Expected<std::vector<unsigned>> Symbols =
498         getSymbols(Buf, SymNames, HasObject);
499     if (auto E = Symbols.takeError())
500       return std::move(E);
501 
502     Pos += Header.size() + Data.size() + Padding.size();
503     Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
504   }
505   // If there are no symbols, emit an empty symbol table, to satisfy Solaris
506   // tools, older versions of which expect a symbol table in a non-empty
507   // archive, regardless of whether there are any symbols in it.
508   if (HasObject && SymNames.tell() == 0)
509     SymNames << '\0' << '\0' << '\0';
510   return Ret;
511 }
512 
513 namespace llvm {
514 
515 static ErrorOr<SmallString<128>> canonicalizePath(StringRef P) {
516   SmallString<128> Ret = P;
517   std::error_code Err = sys::fs::make_absolute(Ret);
518   if (Err)
519     return Err;
520   sys::path::remove_dots(Ret, /*removedotdot*/ true);
521   return Ret;
522 }
523 
524 // Compute the relative path from From to To.
525 Expected<std::string> computeArchiveRelativePath(StringRef From, StringRef To) {
526   ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
527   ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
528   if (!PathToOrErr || !DirFromOrErr)
529     return errorCodeToError(std::error_code(errno, std::generic_category()));
530 
531   const SmallString<128> &PathTo = *PathToOrErr;
532   const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
533 
534   // Can't construct a relative path between different roots
535   if (sys::path::root_name(PathTo) != sys::path::root_name(DirFrom))
536     return sys::path::convert_to_slash(PathTo);
537 
538   // Skip common prefixes
539   auto FromTo =
540       std::mismatch(sys::path::begin(DirFrom), sys::path::end(DirFrom),
541                     sys::path::begin(PathTo));
542   auto FromI = FromTo.first;
543   auto ToI = FromTo.second;
544 
545   // Construct relative path
546   SmallString<128> Relative;
547   for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
548     sys::path::append(Relative, sys::path::Style::posix, "..");
549 
550   for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
551     sys::path::append(Relative, sys::path::Style::posix, *ToI);
552 
553   return std::string(Relative.str());
554 }
555 
556 static Error writeArchiveToStream(raw_ostream &Out,
557                                   ArrayRef<NewArchiveMember> NewMembers,
558                                   bool WriteSymtab, object::Archive::Kind Kind,
559                                   bool Deterministic, bool Thin) {
560   assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
561 
562   SmallString<0> SymNamesBuf;
563   raw_svector_ostream SymNames(SymNamesBuf);
564   SmallString<0> StringTableBuf;
565   raw_svector_ostream StringTable(StringTableBuf);
566 
567   Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
568       StringTable, SymNames, Kind, Thin, Deterministic, NewMembers);
569   if (Error E = DataOrErr.takeError())
570     return E;
571   std::vector<MemberData> &Data = *DataOrErr;
572 
573   if (!StringTableBuf.empty())
574     Data.insert(Data.begin(), computeStringTable(StringTableBuf));
575 
576   // We would like to detect if we need to switch to a 64-bit symbol table.
577   if (WriteSymtab) {
578     uint64_t MaxOffset = 0;
579     uint64_t LastOffset = MaxOffset;
580     for (const auto &M : Data) {
581       // Record the start of the member's offset
582       LastOffset = MaxOffset;
583       // Account for the size of each part associated with the member.
584       MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
585       // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
586       MaxOffset += M.Symbols.size() * 4;
587     }
588 
589     // The SYM64 format is used when an archive's member offsets are larger than
590     // 32-bits can hold. The need for this shift in format is detected by
591     // writeArchive. To test this we need to generate a file with a member that
592     // has an offset larger than 32-bits but this demands a very slow test. To
593     // speed the test up we use this environment variable to pretend like the
594     // cutoff happens before 32-bits and instead happens at some much smaller
595     // value.
596     const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
597     int Sym64Threshold = 32;
598     if (Sym64Env)
599       StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
600 
601     // If LastOffset isn't going to fit in a 32-bit varible we need to switch
602     // to 64-bit. Note that the file can be larger than 4GB as long as the last
603     // member starts before the 4GB offset.
604     if (LastOffset >= (1ULL << Sym64Threshold)) {
605       if (Kind == object::Archive::K_DARWIN)
606         Kind = object::Archive::K_DARWIN64;
607       else
608         Kind = object::Archive::K_GNU64;
609     }
610   }
611 
612   if (Thin)
613     Out << "!<thin>\n";
614   else
615     Out << "!<arch>\n";
616 
617   if (WriteSymtab)
618     writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
619 
620   for (const MemberData &M : Data)
621     Out << M.Header << M.Data << M.Padding;
622 
623   Out.flush();
624   return Error::success();
625 }
626 
627 Error writeArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
628                    bool WriteSymtab, object::Archive::Kind Kind,
629                    bool Deterministic, bool Thin,
630                    std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
631   Expected<sys::fs::TempFile> Temp =
632       sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
633   if (!Temp)
634     return Temp.takeError();
635   raw_fd_ostream Out(Temp->FD, false);
636 
637   if (Error E = writeArchiveToStream(Out, NewMembers, WriteSymtab, Kind,
638                                      Deterministic, Thin)) {
639     if (Error DiscardError = Temp->discard())
640       return joinErrors(std::move(E), std::move(DiscardError));
641     return E;
642   }
643 
644   // At this point, we no longer need whatever backing memory
645   // was used to generate the NewMembers. On Windows, this buffer
646   // could be a mapped view of the file we want to replace (if
647   // we're updating an existing archive, say). In that case, the
648   // rename would still succeed, but it would leave behind a
649   // temporary file (actually the original file renamed) because
650   // a file cannot be deleted while there's a handle open on it,
651   // only renamed. So by freeing this buffer, this ensures that
652   // the last open handle on the destination file, if any, is
653   // closed before we attempt to rename.
654   OldArchiveBuf.reset();
655 
656   return Temp->keep(ArcName);
657 }
658 
659 Expected<std::unique_ptr<MemoryBuffer>>
660 writeArchiveToBuffer(ArrayRef<NewArchiveMember> NewMembers, bool WriteSymtab,
661                      object::Archive::Kind Kind, bool Deterministic,
662                      bool Thin) {
663   SmallVector<char, 0> ArchiveBufferVector;
664   raw_svector_ostream ArchiveStream(ArchiveBufferVector);
665 
666   if (Error E = writeArchiveToStream(ArchiveStream, NewMembers, WriteSymtab,
667                                      Kind, Deterministic, Thin))
668     return std::move(E);
669 
670   return std::make_unique<SmallVectorMemoryBuffer>(
671       std::move(ArchiveBufferVector));
672 }
673 
674 } // namespace llvm
675