[Alignment][NFC] Use Align with TargetLowering::setMinFunctionAlignment
[llvm-core.git] / lib / Object / ArchiveWriter.cpp
blobf12f1e521a9c02acfcb23324d5a9d88206e1eca7
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.
11 //===----------------------------------------------------------------------===//
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/Error.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Object/SymbolicFile.h"
22 #include "llvm/Support/EndianStream.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/ToolOutputFile.h"
28 #include "llvm/Support/raw_ostream.h"
30 #include <map>
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
33 #include <unistd.h>
34 #else
35 #include <io.h>
36 #endif
38 using namespace llvm;
40 NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
41 : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
42 MemberName(BufRef.getBufferIdentifier()) {}
44 Expected<NewArchiveMember>
45 NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
46 bool Deterministic) {
47 Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
48 if (!BufOrErr)
49 return BufOrErr.takeError();
51 NewArchiveMember M;
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();
72 return std::move(M);
75 Expected<NewArchiveMember> NewArchiveMember::getFile(StringRef FileName,
76 bool Deterministic) {
77 sys::fs::file_status Status;
78 auto FDOrErr = sys::fs::openNativeFileForRead(FileName);
79 if (!FDOrErr)
80 return FDOrErr.takeError();
81 sys::fs::file_t FD = *FDOrErr;
82 assert(FD != sys::fs::kInvalidFile);
84 if (auto EC = sys::fs::status(FD, Status))
85 return errorCodeToError(EC);
87 // Opening a directory doesn't make sense. Let it fail.
88 // Linux cannot open directories with open(2), although
89 // cygwin and *bsd can.
90 if (Status.type() == sys::fs::file_type::directory_file)
91 return errorCodeToError(make_error_code(errc::is_a_directory));
93 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
94 MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
95 if (!MemberBufferOrErr)
96 return errorCodeToError(MemberBufferOrErr.getError());
98 if (auto EC = sys::fs::closeFile(FD))
99 return errorCodeToError(EC);
101 NewArchiveMember M;
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();
111 return std::move(M);
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);
123 static bool isDarwin(object::Archive::Kind Kind) {
124 return Kind == object::Archive::K_DARWIN ||
125 Kind == object::Archive::K_DARWIN64;
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;
140 llvm_unreachable("not supported for writting");
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);
149 static void printRestOfMemberHeader(
150 raw_ostream &Out, const sys::TimePoint<std::chrono::seconds> &ModTime,
151 unsigned UID, unsigned GID, unsigned Perms, uint64_t Size) {
152 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
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);
159 printWithSpacePadding(Out, format("%o", Perms), 8);
160 printWithSpacePadding(Out, Size, 10);
161 Out << "`\n";
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 uint64_t Size) {
169 printWithSpacePadding(Out, Twine(Name) + "/", 16);
170 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
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, uint64_t Size) {
177 uint64_t PosAfterHeader = Pos + 60 + Name.size();
178 // Pad so that even 64 bit object files are aligned.
179 unsigned Pad = OffsetToAlignment(PosAfterHeader, 8);
180 unsigned NameWithPadding = Name.size() + Pad;
181 printWithSpacePadding(Out, Twine("#1/") + Twine(NameWithPadding), 16);
182 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms,
183 NameWithPadding + Size);
184 Out << Name;
185 while (Pad--)
186 Out.write(uint8_t(0));
189 static bool useStringTable(bool Thin, StringRef Name) {
190 return Thin || Name.size() >= 16 || Name.contains('/');
193 static bool is64BitKind(object::Archive::Kind Kind) {
194 switch (Kind) {
195 case object::Archive::K_GNU:
196 case object::Archive::K_BSD:
197 case object::Archive::K_DARWIN:
198 case object::Archive::K_COFF:
199 return false;
200 case object::Archive::K_DARWIN64:
201 case object::Archive::K_GNU64:
202 return true;
204 llvm_unreachable("not supported for writting");
207 static void
208 printMemberHeader(raw_ostream &Out, uint64_t Pos, raw_ostream &StringTable,
209 StringMap<uint64_t> &MemberNames, object::Archive::Kind Kind,
210 bool Thin, const NewArchiveMember &M,
211 sys::TimePoint<std::chrono::seconds> ModTime, uint64_t Size) {
212 if (isBSDLike(Kind))
213 return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
214 M.Perms, Size);
215 if (!useStringTable(Thin, M.MemberName))
216 return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
217 M.Perms, Size);
218 Out << '/';
219 uint64_t NamePos;
220 if (Thin) {
221 NamePos = StringTable.tell();
222 StringTable << M.MemberName << "/\n";
223 } else {
224 auto Insertion = MemberNames.insert({M.MemberName, uint64_t(0)});
225 if (Insertion.second) {
226 Insertion.first->second = StringTable.tell();
227 StringTable << M.MemberName << "/\n";
229 NamePos = Insertion.first->second;
231 printWithSpacePadding(Out, NamePos, 15);
232 printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
235 namespace {
236 struct MemberData {
237 std::vector<unsigned> Symbols;
238 std::string Header;
239 StringRef Data;
240 StringRef Padding;
242 } // namespace
244 static MemberData computeStringTable(StringRef Names) {
245 unsigned Size = Names.size();
246 unsigned Pad = OffsetToAlignment(Size, 2);
247 std::string Header;
248 raw_string_ostream Out(Header);
249 printWithSpacePadding(Out, "//", 48);
250 printWithSpacePadding(Out, Size + Pad, 10);
251 Out << "`\n";
252 Out.flush();
253 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
256 static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
257 using namespace std::chrono;
259 if (!Deterministic)
260 return time_point_cast<seconds>(system_clock::now());
261 return sys::TimePoint<seconds>();
264 static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
265 uint32_t Symflags = S.getFlags();
266 if (Symflags & object::SymbolRef::SF_FormatSpecific)
267 return false;
268 if (!(Symflags & object::SymbolRef::SF_Global))
269 return false;
270 if (Symflags & object::SymbolRef::SF_Undefined)
271 return false;
272 return true;
275 static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
276 uint64_t Val) {
277 if (is64BitKind(Kind))
278 print<uint64_t>(Out, Kind, Val);
279 else
280 print<uint32_t>(Out, Kind, Val);
283 static void writeSymbolTable(raw_ostream &Out, object::Archive::Kind Kind,
284 bool Deterministic, ArrayRef<MemberData> Members,
285 StringRef StringTable) {
286 // We don't write a symbol table on an archive with no members -- except on
287 // Darwin, where the linker will abort unless the archive has a symbol table.
288 if (StringTable.empty() && !isDarwin(Kind))
289 return;
291 unsigned NumSyms = 0;
292 for (const MemberData &M : Members)
293 NumSyms += M.Symbols.size();
295 unsigned Size = 0;
296 unsigned OffsetSize = is64BitKind(Kind) ? sizeof(uint64_t) : sizeof(uint32_t);
298 Size += OffsetSize; // Number of entries
299 if (isBSDLike(Kind))
300 Size += NumSyms * OffsetSize * 2; // Table
301 else
302 Size += NumSyms * OffsetSize; // Table
303 if (isBSDLike(Kind))
304 Size += OffsetSize; // byte count
305 Size += StringTable.size();
306 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
307 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
308 // uniformly.
309 // We do this for all bsd formats because it simplifies aligning members.
310 unsigned Alignment = isBSDLike(Kind) ? 8 : 2;
311 unsigned Pad = OffsetToAlignment(Size, Alignment);
312 Size += Pad;
314 if (isBSDLike(Kind)) {
315 const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
316 printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
317 Size);
318 } else {
319 const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
320 printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
323 uint64_t Pos = Out.tell() + Size;
325 if (isBSDLike(Kind))
326 printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
327 else
328 printNBits(Out, Kind, NumSyms);
330 for (const MemberData &M : Members) {
331 for (unsigned StringOffset : M.Symbols) {
332 if (isBSDLike(Kind))
333 printNBits(Out, Kind, StringOffset);
334 printNBits(Out, Kind, Pos); // member offset
336 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
339 if (isBSDLike(Kind))
340 // byte count of the string table
341 printNBits(Out, Kind, StringTable.size());
342 Out << StringTable;
344 while (Pad--)
345 Out.write(uint8_t(0));
348 static Expected<std::vector<unsigned>>
349 getSymbols(MemoryBufferRef Buf, raw_ostream &SymNames, bool &HasObject) {
350 std::vector<unsigned> Ret;
352 // In the scenario when LLVMContext is populated SymbolicFile will contain a
353 // reference to it, thus SymbolicFile should be destroyed first.
354 LLVMContext Context;
355 std::unique_ptr<object::SymbolicFile> Obj;
356 if (identify_magic(Buf.getBuffer()) == file_magic::bitcode) {
357 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
358 Buf, file_magic::bitcode, &Context);
359 if (!ObjOrErr) {
360 // FIXME: check only for "not an object file" errors.
361 consumeError(ObjOrErr.takeError());
362 return Ret;
364 Obj = std::move(*ObjOrErr);
365 } else {
366 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
367 if (!ObjOrErr) {
368 // FIXME: check only for "not an object file" errors.
369 consumeError(ObjOrErr.takeError());
370 return Ret;
372 Obj = std::move(*ObjOrErr);
375 HasObject = true;
376 for (const object::BasicSymbolRef &S : Obj->symbols()) {
377 if (!isArchiveSymbol(S))
378 continue;
379 Ret.push_back(SymNames.tell());
380 if (Error E = S.printName(SymNames))
381 return std::move(E);
382 SymNames << '\0';
384 return Ret;
387 static Expected<std::vector<MemberData>>
388 computeMemberData(raw_ostream &StringTable, raw_ostream &SymNames,
389 object::Archive::Kind Kind, bool Thin, bool Deterministic,
390 ArrayRef<NewArchiveMember> NewMembers) {
391 static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
393 // This ignores the symbol table, but we only need the value mod 8 and the
394 // symbol table is aligned to be a multiple of 8 bytes
395 uint64_t Pos = 0;
397 std::vector<MemberData> Ret;
398 bool HasObject = false;
400 // Deduplicate long member names in the string table and reuse earlier name
401 // offsets. This especially saves space for COFF Import libraries where all
402 // members have the same name.
403 StringMap<uint64_t> MemberNames;
405 // UniqueTimestamps is a special case to improve debugging on Darwin:
407 // The Darwin linker does not link debug info into the final
408 // binary. Instead, it emits entries of type N_OSO in in the output
409 // binary's symbol table, containing references to the linked-in
410 // object files. Using that reference, the debugger can read the
411 // debug data directly from the object files. Alternatively, an
412 // invocation of 'dsymutil' will link the debug data from the object
413 // files into a dSYM bundle, which can be loaded by the debugger,
414 // instead of the object files.
416 // For an object file, the N_OSO entries contain the absolute path
417 // path to the file, and the file's timestamp. For an object
418 // included in an archive, the path is formatted like
419 // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
420 // archive member's timestamp, rather than the archive's timestamp.
422 // However, this doesn't always uniquely identify an object within
423 // an archive -- an archive file can have multiple entries with the
424 // same filename. (This will happen commonly if the original object
425 // files started in different directories.) The only way they get
426 // distinguished, then, is via the timestamp. But this process is
427 // unable to find the correct object file in the archive when there
428 // are two files of the same name and timestamp.
430 // Additionally, timestamp==0 is treated specially, and causes the
431 // timestamp to be ignored as a match criteria.
433 // That will "usually" work out okay when creating an archive not in
434 // deterministic timestamp mode, because the objects will probably
435 // have been created at different timestamps.
437 // To ameliorate this problem, in deterministic archive mode (which
438 // is the default), on Darwin we will emit a unique non-zero
439 // timestamp for each entry with a duplicated name. This is still
440 // deterministic: the only thing affecting that timestamp is the
441 // order of the files in the resultant archive.
443 // See also the functions that handle the lookup:
444 // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
445 // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
446 bool UniqueTimestamps = Deterministic && isDarwin(Kind);
447 std::map<StringRef, unsigned> FilenameCount;
448 if (UniqueTimestamps) {
449 for (const NewArchiveMember &M : NewMembers)
450 FilenameCount[M.MemberName]++;
451 for (auto &Entry : FilenameCount)
452 Entry.second = Entry.second > 1 ? 1 : 0;
455 for (const NewArchiveMember &M : NewMembers) {
456 std::string Header;
457 raw_string_ostream Out(Header);
459 MemoryBufferRef Buf = M.Buf->getMemBufferRef();
460 StringRef Data = Thin ? "" : Buf.getBuffer();
462 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
463 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
464 // uniformly. This matches the behaviour with cctools and ensures that ld64
465 // is happy with archives that we generate.
466 unsigned MemberPadding =
467 isDarwin(Kind) ? OffsetToAlignment(Data.size(), 8) : 0;
468 unsigned TailPadding = OffsetToAlignment(Data.size() + MemberPadding, 2);
469 StringRef Padding = StringRef(PaddingData, MemberPadding + TailPadding);
471 sys::TimePoint<std::chrono::seconds> ModTime;
472 if (UniqueTimestamps)
473 // Increment timestamp for each file of a given name.
474 ModTime = sys::toTimePoint(FilenameCount[M.MemberName]++);
475 else
476 ModTime = M.ModTime;
478 uint64_t Size = Buf.getBufferSize() + MemberPadding;
479 if (Size > object::Archive::MaxMemberSize) {
480 std::string StringMsg =
481 "File " + M.MemberName.str() + " exceeds size limit";
482 return make_error<object::GenericBinaryError>(
483 std::move(StringMsg), object::object_error::parse_failed);
486 printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, M,
487 ModTime, Size);
488 Out.flush();
490 Expected<std::vector<unsigned>> Symbols =
491 getSymbols(Buf, SymNames, HasObject);
492 if (auto E = Symbols.takeError())
493 return std::move(E);
495 Pos += Header.size() + Data.size() + Padding.size();
496 Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
498 // If there are no symbols, emit an empty symbol table, to satisfy Solaris
499 // tools, older versions of which expect a symbol table in a non-empty
500 // archive, regardless of whether there are any symbols in it.
501 if (HasObject && SymNames.tell() == 0)
502 SymNames << '\0' << '\0' << '\0';
503 return Ret;
506 namespace llvm {
508 static ErrorOr<SmallString<128>> canonicalizePath(StringRef P) {
509 SmallString<128> Ret = P;
510 std::error_code Err = sys::fs::make_absolute(Ret);
511 if (Err)
512 return Err;
513 sys::path::remove_dots(Ret, /*removedotdot*/ true);
514 return Ret;
517 // Compute the relative path from From to To.
518 Expected<std::string> computeArchiveRelativePath(StringRef From, StringRef To) {
519 ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
520 ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
521 if (!PathToOrErr || !DirFromOrErr)
522 return errorCodeToError(std::error_code(errno, std::generic_category()));
524 const SmallString<128> &PathTo = *PathToOrErr;
525 const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
527 // Can't construct a relative path between different roots
528 if (sys::path::root_name(PathTo) != sys::path::root_name(DirFrom))
529 return sys::path::convert_to_slash(PathTo);
531 // Skip common prefixes
532 auto FromTo =
533 std::mismatch(sys::path::begin(DirFrom), sys::path::end(DirFrom),
534 sys::path::begin(PathTo));
535 auto FromI = FromTo.first;
536 auto ToI = FromTo.second;
538 // Construct relative path
539 SmallString<128> Relative;
540 for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
541 sys::path::append(Relative, sys::path::Style::posix, "..");
543 for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
544 sys::path::append(Relative, sys::path::Style::posix, *ToI);
546 return Relative.str();
549 Error writeArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
550 bool WriteSymtab, object::Archive::Kind Kind,
551 bool Deterministic, bool Thin,
552 std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
553 assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
555 SmallString<0> SymNamesBuf;
556 raw_svector_ostream SymNames(SymNamesBuf);
557 SmallString<0> StringTableBuf;
558 raw_svector_ostream StringTable(StringTableBuf);
560 Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
561 StringTable, SymNames, Kind, Thin, Deterministic, NewMembers);
562 if (Error E = DataOrErr.takeError())
563 return E;
564 std::vector<MemberData> &Data = *DataOrErr;
566 if (!StringTableBuf.empty())
567 Data.insert(Data.begin(), computeStringTable(StringTableBuf));
569 // We would like to detect if we need to switch to a 64-bit symbol table.
570 if (WriteSymtab) {
571 uint64_t MaxOffset = 0;
572 uint64_t LastOffset = MaxOffset;
573 for (const auto &M : Data) {
574 // Record the start of the member's offset
575 LastOffset = MaxOffset;
576 // Account for the size of each part associated with the member.
577 MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
578 // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
579 MaxOffset += M.Symbols.size() * 4;
582 // The SYM64 format is used when an archive's member offsets are larger than
583 // 32-bits can hold. The need for this shift in format is detected by
584 // writeArchive. To test this we need to generate a file with a member that
585 // has an offset larger than 32-bits but this demands a very slow test. To
586 // speed the test up we use this environment variable to pretend like the
587 // cutoff happens before 32-bits and instead happens at some much smaller
588 // value.
589 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
590 int Sym64Threshold = 32;
591 if (Sym64Env)
592 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
594 // If LastOffset isn't going to fit in a 32-bit varible we need to switch
595 // to 64-bit. Note that the file can be larger than 4GB as long as the last
596 // member starts before the 4GB offset.
597 if (LastOffset >= (1ULL << Sym64Threshold)) {
598 if (Kind == object::Archive::K_DARWIN)
599 Kind = object::Archive::K_DARWIN64;
600 else
601 Kind = object::Archive::K_GNU64;
605 Expected<sys::fs::TempFile> Temp =
606 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
607 if (!Temp)
608 return Temp.takeError();
610 raw_fd_ostream Out(Temp->FD, false);
611 if (Thin)
612 Out << "!<thin>\n";
613 else
614 Out << "!<arch>\n";
616 if (WriteSymtab)
617 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
619 for (const MemberData &M : Data)
620 Out << M.Header << M.Data << M.Padding;
622 Out.flush();
624 // At this point, we no longer need whatever backing memory
625 // was used to generate the NewMembers. On Windows, this buffer
626 // could be a mapped view of the file we want to replace (if
627 // we're updating an existing archive, say). In that case, the
628 // rename would still succeed, but it would leave behind a
629 // temporary file (actually the original file renamed) because
630 // a file cannot be deleted while there's a handle open on it,
631 // only renamed. So by freeing this buffer, this ensures that
632 // the last open handle on the destination file, if any, is
633 // closed before we attempt to rename.
634 OldArchiveBuf.reset();
636 return Temp->keep(ArcName);
639 } // namespace llvm