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