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