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/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"
33 #if !defined(_MSC_VER) && !defined(__MINGW32__)
41 NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
42 : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
43 MemberName(BufRef.getBufferIdentifier()) {}
45 Expected<NewArchiveMember>
46 NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
48 Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
50 return BufOrErr.takeError();
53 M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
54 M.MemberName = M.Buf->getBufferIdentifier();
56 auto ModTimeOrErr = OldMember.getLastModified();
58 return ModTimeOrErr.takeError();
59 M.ModTime = ModTimeOrErr.get();
60 Expected<unsigned> UIDOrErr = OldMember.getUID();
62 return UIDOrErr.takeError();
63 M.UID = UIDOrErr.get();
64 Expected<unsigned> GIDOrErr = OldMember.getGID();
66 return GIDOrErr.takeError();
67 M.GID = GIDOrErr.get();
68 Expected<sys::fs::perms> AccessModeOrErr = OldMember.getAccessMode();
70 return AccessModeOrErr.takeError();
71 M.Perms = AccessModeOrErr.get();
76 Expected<NewArchiveMember> NewArchiveMember::getFile(StringRef FileName,
78 sys::fs::file_status Status;
79 auto FDOrErr = sys::fs::openNativeFileForRead(FileName);
81 return FDOrErr.takeError();
82 sys::fs::file_t FD = *FDOrErr;
83 assert(FD != sys::fs::kInvalidFile);
85 if (auto EC = sys::fs::status(FD, Status))
86 return errorCodeToError(EC);
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));
94 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
95 MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
96 if (!MemberBufferOrErr)
97 return errorCodeToError(MemberBufferOrErr.getError());
99 if (auto EC = sys::fs::closeFile(FD))
100 return errorCodeToError(EC);
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();
115 template <typename T>
116 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
117 uint64_t OldPos = OS.tell();
119 unsigned SizeSoFar = OS.tell() - OldPos;
120 assert(SizeSoFar <= Size && "Data doesn't fit in Size");
121 OS.indent(Size - SizeSoFar);
124 static bool isDarwin(object::Archive::Kind Kind) {
125 return Kind == object::Archive::K_DARWIN ||
126 Kind == object::Archive::K_DARWIN64;
129 static bool isBSDLike(object::Archive::Kind Kind) {
131 case object::Archive::K_GNU:
132 case object::Archive::K_GNU64:
134 case object::Archive::K_BSD:
135 case object::Archive::K_DARWIN:
136 case object::Archive::K_DARWIN64:
138 case object::Archive::K_COFF:
141 llvm_unreachable("not supported for writting");
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);
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);
155 // The format has only 6 chars for uid and gid. Truncate if the provided
157 printWithSpacePadding(Out, UID % 1000000, 6);
158 printWithSpacePadding(Out, GID % 1000000, 6);
160 printWithSpacePadding(Out, format("%o", Perms), 8);
161 printWithSpacePadding(Out, Size, 10);
166 printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name,
167 const sys::TimePoint<std::chrono::seconds> &ModTime,
168 unsigned UID, unsigned GID, unsigned Perms,
170 printWithSpacePadding(Out, Twine(Name) + "/", 16);
171 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, 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);
187 Out.write(uint8_t(0));
190 static bool useStringTable(bool Thin, StringRef Name) {
191 return Thin || Name.size() >= 16 || Name.contains('/');
194 static bool is64BitKind(object::Archive::Kind 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:
201 case object::Archive::K_DARWIN64:
202 case object::Archive::K_GNU64:
205 llvm_unreachable("not supported for writting");
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) {
214 return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
216 if (!useStringTable(Thin, M.MemberName))
217 return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
222 NamePos = StringTable.tell();
223 StringTable << M.MemberName << "/\n";
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";
230 NamePos = Insertion.first->second;
232 printWithSpacePadding(Out, NamePos, 15);
233 printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
238 std::vector<unsigned> Symbols;
245 static MemberData computeStringTable(StringRef Names) {
246 unsigned Size = Names.size();
247 unsigned Pad = offsetToAlignment(Size, Align(2));
249 raw_string_ostream Out(Header);
250 printWithSpacePadding(Out, "//", 48);
251 printWithSpacePadding(Out, Size + Pad, 10);
254 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
257 static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
258 using namespace std::chrono;
261 return time_point_cast<seconds>(system_clock::now());
262 return sys::TimePoint<seconds>();
265 static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
266 uint32_t Symflags = S.getFlags();
267 if (Symflags & object::SymbolRef::SF_FormatSpecific)
269 if (!(Symflags & object::SymbolRef::SF_Global))
271 if (Symflags & object::SymbolRef::SF_Undefined)
276 static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
278 if (is64BitKind(Kind))
279 print<uint64_t>(Out, Kind, Val);
281 print<uint32_t>(Out, Kind, Val);
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))
292 unsigned NumSyms = 0;
293 for (const MemberData &M : Members)
294 NumSyms += M.Symbols.size();
297 unsigned OffsetSize = is64BitKind(Kind) ? sizeof(uint64_t) : sizeof(uint32_t);
299 Size += OffsetSize; // Number of entries
301 Size += NumSyms * OffsetSize * 2; // Table
303 Size += NumSyms * OffsetSize; // Table
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
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);
315 if (isBSDLike(Kind)) {
316 const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
317 printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
320 const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
321 printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
324 uint64_t Pos = Out.tell() + Size;
327 printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
329 printNBits(Out, Kind, NumSyms);
331 for (const MemberData &M : Members) {
332 for (unsigned StringOffset : M.Symbols) {
334 printNBits(Out, Kind, StringOffset);
335 printNBits(Out, Kind, Pos); // member offset
337 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
341 // byte count of the string table
342 printNBits(Out, Kind, StringTable.size());
346 Out.write(uint8_t(0));
349 static Expected<std::vector<unsigned>>
350 getSymbols(MemoryBufferRef Buf, raw_ostream &SymNames, bool &HasObject) {
351 std::vector<unsigned> Ret;
353 // In the scenario when LLVMContext is populated SymbolicFile will contain a
354 // reference to it, thus SymbolicFile should be destroyed first.
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);
361 // FIXME: check only for "not an object file" errors.
362 consumeError(ObjOrErr.takeError());
365 Obj = std::move(*ObjOrErr);
367 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
369 // FIXME: check only for "not an object file" errors.
370 consumeError(ObjOrErr.takeError());
373 Obj = std::move(*ObjOrErr);
377 for (const object::BasicSymbolRef &S : Obj->symbols()) {
378 if (!isArchiveSymbol(S))
380 Ret.push_back(SymNames.tell());
381 if (Error E = S.printName(SymNames))
388 static Expected<std::vector<MemberData>>
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'};
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
398 std::vector<MemberData> Ret;
399 bool HasObject = false;
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;
406 // UniqueTimestamps is a special case to improve debugging on Darwin:
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.
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.
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.
431 // Additionally, timestamp==0 is treated specially, and causes the
432 // timestamp to be ignored as a match criteria.
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.
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.
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;
456 for (const NewArchiveMember &M : NewMembers) {
458 raw_string_ostream Out(Header);
460 MemoryBufferRef Buf = M.Buf->getMemBufferRef();
461 StringRef Data = Thin ? "" : Buf.getBuffer();
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);
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]++);
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);
488 printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, M,
492 Expected<std::vector<unsigned>> Symbols =
493 getSymbols(Buf, SymNames, HasObject);
494 if (auto E = Symbols.takeError())
497 Pos += Header.size() + Data.size() + Padding.size();
498 Ret.push_back({std::move(*Symbols), std::move(Header), Data, Padding});
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';
510 static ErrorOr<SmallString<128>> canonicalizePath(StringRef P) {
511 SmallString<128> Ret = P;
512 std::error_code Err = sys::fs::make_absolute(Ret);
515 sys::path::remove_dots(Ret, /*removedotdot*/ true);
519 // Compute the relative path from From to 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()));
526 const SmallString<128> &PathTo = *PathToOrErr;
527 const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
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);
533 // Skip common prefixes
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;
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, "..");
545 for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
546 sys::path::append(Relative, sys::path::Style::posix, *ToI);
548 return Relative.str();
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");
557 SmallString<0> SymNamesBuf;
558 raw_svector_ostream SymNames(SymNamesBuf);
559 SmallString<0> StringTableBuf;
560 raw_svector_ostream StringTable(StringTableBuf);
562 Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
563 StringTable, SymNames, Kind, Thin, Deterministic, NewMembers);
564 if (Error E = DataOrErr.takeError())
566 std::vector<MemberData> &Data = *DataOrErr;
568 if (!StringTableBuf.empty())
569 Data.insert(Data.begin(), computeStringTable(StringTableBuf));
571 // We would like to detect if we need to switch to a 64-bit symbol table.
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;
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
591 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
592 int Sym64Threshold = 32;
594 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
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;
603 Kind = object::Archive::K_GNU64;
607 Expected<sys::fs::TempFile> Temp =
608 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
610 return Temp.takeError();
612 raw_fd_ostream Out(Temp->FD, false);
619 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf);
621 for (const MemberData &M : Data)
622 Out << M.Header << M.Data << M.Padding;
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();
638 return Temp->keep(ArcName);