1 //===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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/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"
31 #if !defined(_MSC_VER) && !defined(__MINGW32__)
39 NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
40 : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
41 MemberName(BufRef.getBufferIdentifier()) {}
43 Expected<NewArchiveMember>
44 NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
46 Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
48 return BufOrErr.takeError();
51 M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
52 M.MemberName = M.Buf->getBufferIdentifier();
54 auto ModTimeOrErr = OldMember.getLastModified();
56 return ModTimeOrErr.takeError();
57 M.ModTime = ModTimeOrErr.get();
58 Expected<unsigned> UIDOrErr = OldMember.getUID();
60 return UIDOrErr.takeError();
61 M.UID = UIDOrErr.get();
62 Expected<unsigned> GIDOrErr = OldMember.getGID();
64 return GIDOrErr.takeError();
65 M.GID = GIDOrErr.get();
66 Expected<sys::fs::perms> AccessModeOrErr = OldMember.getAccessMode();
68 return AccessModeOrErr.takeError();
69 M.Perms = AccessModeOrErr.get();
74 Expected<NewArchiveMember> NewArchiveMember::getFile(StringRef FileName,
76 sys::fs::file_status Status;
77 auto FDOrErr = sys::fs::openNativeFileForRead(FileName);
79 return FDOrErr.takeError();
80 sys::fs::file_t FD = *FDOrErr;
81 assert(FD != sys::fs::kInvalidFile);
83 if (auto EC = sys::fs::status(FD, Status))
84 return errorCodeToError(EC);
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));
92 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
93 MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
94 if (!MemberBufferOrErr)
95 return errorCodeToError(MemberBufferOrErr.getError());
97 if (auto EC = sys::fs::closeFile(FD))
98 return errorCodeToError(EC);
101 M.Buf = std::move(*MemberBufferOrErr);
102 M.MemberName = M.Buf->getBufferIdentifier();
103 if (!Deterministic) {
104 M.ModTime = std::chrono::time_point_cast<std::chrono::seconds>(
105 Status.getLastModificationTime());
106 M.UID = Status.getUser();
107 M.GID = Status.getGroup();
108 M.Perms = Status.permissions();
113 template <typename T>
114 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
115 uint64_t OldPos = OS.tell();
117 unsigned SizeSoFar = OS.tell() - OldPos;
118 assert(SizeSoFar <= Size && "Data doesn't fit in Size");
119 OS.indent(Size - SizeSoFar);
122 static bool isDarwin(object::Archive::Kind Kind) {
123 return Kind == object::Archive::K_DARWIN ||
124 Kind == object::Archive::K_DARWIN64;
127 static bool isBSDLike(object::Archive::Kind Kind) {
129 case object::Archive::K_GNU:
130 case object::Archive::K_GNU64:
132 case object::Archive::K_BSD:
133 case object::Archive::K_DARWIN:
134 case object::Archive::K_DARWIN64:
136 case object::Archive::K_COFF:
139 llvm_unreachable("not supported for writting");
143 static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val) {
144 support::endian::write(Out, Val,
145 isBSDLike(Kind) ? support::little : support::big);
148 static void printRestOfMemberHeader(
149 raw_ostream &Out, const sys::TimePoint<std::chrono::seconds> &ModTime,
150 unsigned UID, unsigned GID, unsigned Perms, unsigned Size) {
151 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
153 // The format has only 6 chars for uid and gid. Truncate if the provided
155 printWithSpacePadding(Out, UID % 1000000, 6);
156 printWithSpacePadding(Out, GID % 1000000, 6);
158 printWithSpacePadding(Out, format("%o", Perms), 8);
159 printWithSpacePadding(Out, Size, 10);
164 printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name,
165 const sys::TimePoint<std::chrono::seconds> &ModTime,
166 unsigned UID, unsigned GID, unsigned Perms,
168 printWithSpacePadding(Out, Twine(Name) + "/", 16);
169 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
173 printBSDMemberHeader(raw_ostream &Out, uint64_t Pos, StringRef Name,
174 const sys::TimePoint<std::chrono::seconds> &ModTime,
175 unsigned UID, unsigned GID, unsigned Perms,
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);
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) {
195 case object::Archive::K_GNU:
196 case object::Archive::K_BSD:
197 case object::Archive::K_DARWIN:
198 case object::Archive::K_COFF:
200 case object::Archive::K_DARWIN64:
201 case object::Archive::K_GNU64:
204 llvm_unreachable("not supported for writting");
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, unsigned Size) {
213 return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
215 if (!useStringTable(Thin, M.MemberName))
216 return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
221 NamePos = StringTable.tell();
222 StringTable << M.MemberName << "/\n";
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);
237 std::vector<unsigned> Symbols;
244 static MemberData computeStringTable(StringRef Names) {
245 unsigned Size = Names.size();
246 unsigned Pad = OffsetToAlignment(Size, 2);
248 raw_string_ostream Out(Header);
249 printWithSpacePadding(Out, "//", 48);
250 printWithSpacePadding(Out, Size + Pad, 10);
253 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
256 static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
257 using namespace std::chrono;
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)
268 if (!(Symflags & object::SymbolRef::SF_Global))
270 if (Symflags & object::SymbolRef::SF_Undefined)
275 static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
277 if (is64BitKind(Kind))
278 print<uint64_t>(Out, Kind, Val);
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))
291 unsigned NumSyms = 0;
292 for (const MemberData &M : Members)
293 NumSyms += M.Symbols.size();
296 unsigned OffsetSize = is64BitKind(Kind) ? sizeof(uint64_t) : sizeof(uint32_t);
298 Size += OffsetSize; // Number of entries
300 Size += NumSyms * OffsetSize * 2; // Table
302 Size += NumSyms * OffsetSize; // Table
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
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);
314 if (isBSDLike(Kind)) {
315 const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
316 printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
319 const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
320 printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
323 uint64_t Pos = Out.tell() + Size;
326 printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
328 printNBits(Out, Kind, NumSyms);
330 for (const MemberData &M : Members) {
331 for (unsigned StringOffset : M.Symbols) {
333 printNBits(Out, Kind, StringOffset);
334 printNBits(Out, Kind, Pos); // member offset
336 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
340 // byte count of the string table
341 printNBits(Out, Kind, StringTable.size());
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.
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);
360 // FIXME: check only for "not an object file" errors.
361 consumeError(ObjOrErr.takeError());
364 Obj = std::move(*ObjOrErr);
366 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
368 // FIXME: check only for "not an object file" errors.
369 consumeError(ObjOrErr.takeError());
372 Obj = std::move(*ObjOrErr);
376 for (const object::BasicSymbolRef &S : Obj->symbols()) {
377 if (!isArchiveSymbol(S))
379 Ret.push_back(SymNames.tell());
380 if (Error E = S.printName(SymNames))
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
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) {
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]++);
477 printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, M,
478 ModTime, Buf.getBufferSize() + MemberPadding);
481 Expected<std::vector<unsigned>> Symbols =
482 getSymbols(Buf, SymNames, HasObject);
483 if (auto E = Symbols.takeError())
486 Pos += Header.size() + Data.size() + Padding.size();
487 Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
489 // If there are no symbols, emit an empty symbol table, to satisfy Solaris
490 // tools, older versions of which expect a symbol table in a non-empty
491 // archive, regardless of whether there are any symbols in it.
492 if (HasObject && SymNames.tell() == 0)
493 SymNames << '\0' << '\0' << '\0';
499 static ErrorOr<SmallString<128>> canonicalizePath(StringRef P) {
500 SmallString<128> Ret = P;
501 std::error_code Err = sys::fs::make_absolute(Ret);
504 sys::path::remove_dots(Ret, /*removedotdot*/ true);
508 // Compute the relative path from From to To.
509 Expected<std::string> computeArchiveRelativePath(StringRef From, StringRef To) {
510 ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
511 ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
512 if (!PathToOrErr || !DirFromOrErr)
513 return errorCodeToError(std::error_code(errno, std::generic_category()));
515 const SmallString<128> &PathTo = *PathToOrErr;
516 const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
518 // Can't construct a relative path between different roots
519 if (sys::path::root_name(PathTo) != sys::path::root_name(DirFrom))
520 return sys::path::convert_to_slash(PathTo);
522 // Skip common prefixes
524 std::mismatch(sys::path::begin(DirFrom), sys::path::end(DirFrom),
525 sys::path::begin(PathTo));
526 auto FromI = FromTo.first;
527 auto ToI = FromTo.second;
529 // Construct relative path
530 SmallString<128> Relative;
531 for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
532 sys::path::append(Relative, sys::path::Style::posix, "..");
534 for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
535 sys::path::append(Relative, sys::path::Style::posix, *ToI);
537 return Relative.str();
540 Error writeArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
541 bool WriteSymtab, object::Archive::Kind Kind,
542 bool Deterministic, bool Thin,
543 std::unique_ptr<MemoryBuffer> OldArchiveBuf) {
544 assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
546 SmallString<0> SymNamesBuf;
547 raw_svector_ostream SymNames(SymNamesBuf);
548 SmallString<0> StringTableBuf;
549 raw_svector_ostream StringTable(StringTableBuf);
551 Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
552 StringTable, SymNames, Kind, Thin, Deterministic, NewMembers);
553 if (Error E = DataOrErr.takeError())
555 std::vector<MemberData> &Data = *DataOrErr;
557 if (!StringTableBuf.empty())
558 Data.insert(Data.begin(), computeStringTable(StringTableBuf));
560 // We would like to detect if we need to switch to a 64-bit symbol table.
562 uint64_t MaxOffset = 0;
563 uint64_t LastOffset = MaxOffset;
564 for (const auto &M : Data) {
565 // Record the start of the member's offset
566 LastOffset = MaxOffset;
567 // Account for the size of each part associated with the member.
568 MaxOffset += M.Header.size() + M.Data.size() + M.Padding.size();
569 // We assume 32-bit symbols to see if 32-bit symbols are possible or not.
570 MaxOffset += M.Symbols.size() * 4;
573 // The SYM64 format is used when an archive's member offsets are larger than
574 // 32-bits can hold. The need for this shift in format is detected by
575 // writeArchive. To test this we need to generate a file with a member that
576 // has an offset larger than 32-bits but this demands a very slow test. To
577 // speed the test up we use this environment variable to pretend like the
578 // cutoff happens before 32-bits and instead happens at some much smaller
580 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
581 int Sym64Threshold = 32;
583 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
585 // If LastOffset isn't going to fit in a 32-bit varible we need to switch
586 // to 64-bit. Note that the file can be larger than 4GB as long as the last
587 // member starts before the 4GB offset.
588 if (LastOffset >= (1ULL << Sym64Threshold)) {
589 if (Kind == object::Archive::K_DARWIN)
590 Kind = object::Archive::K_DARWIN64;
592 Kind = object::Archive::K_GNU64;
596 Expected<sys::fs::TempFile> Temp =
597 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
599 return Temp.takeError();
601 raw_fd_ostream Out(Temp->FD, false);
608 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
610 for (const MemberData &M : Data)
611 Out << M.Header << M.Data << M.Padding;
615 // At this point, we no longer need whatever backing memory
616 // was used to generate the NewMembers. On Windows, this buffer
617 // could be a mapped view of the file we want to replace (if
618 // we're updating an existing archive, say). In that case, the
619 // rename would still succeed, but it would leave behind a
620 // temporary file (actually the original file renamed) because
621 // a file cannot be deleted while there's a handle open on it,
622 // only renamed. So by freeing this buffer, this ensures that
623 // the last open handle on the destination file, if any, is
624 // closed before we attempt to rename.
625 OldArchiveBuf.reset();
627 return Temp->keep(ArcName);