10b57cec5SDimitry Andric //===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the writeArchive function.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "llvm/Object/ArchiveWriter.h"
140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
155ffd83dbSDimitry Andric #include "llvm/ADT/StringMap.h"
160b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
170b57cec5SDimitry Andric #include "llvm/BinaryFormat/Magic.h"
180b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
190b57cec5SDimitry Andric #include "llvm/Object/Archive.h"
2006c3fb27SDimitry Andric #include "llvm/Object/COFF.h"
215f757f3fSDimitry Andric #include "llvm/Object/COFFImportFile.h"
228bcb0991SDimitry Andric #include "llvm/Object/Error.h"
2381ad6265SDimitry Andric #include "llvm/Object/IRObjectFile.h"
2481ad6265SDimitry Andric #include "llvm/Object/MachO.h"
250b57cec5SDimitry Andric #include "llvm/Object/ObjectFile.h"
260b57cec5SDimitry Andric #include "llvm/Object/SymbolicFile.h"
2781ad6265SDimitry Andric #include "llvm/Object/XCOFFObjectFile.h"
288bcb0991SDimitry Andric #include "llvm/Support/Alignment.h"
290b57cec5SDimitry Andric #include "llvm/Support/EndianStream.h"
300b57cec5SDimitry Andric #include "llvm/Support/Errc.h"
310b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
320b57cec5SDimitry Andric #include "llvm/Support/Format.h"
3381ad6265SDimitry Andric #include "llvm/Support/MathExtras.h"
340b57cec5SDimitry Andric #include "llvm/Support/Path.h"
35e8d8bef9SDimitry Andric #include "llvm/Support/SmallVectorMemoryBuffer.h"
360b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
370b57cec5SDimitry Andric
3806c3fb27SDimitry Andric #include <cerrno>
390b57cec5SDimitry Andric #include <map>
400b57cec5SDimitry Andric
410b57cec5SDimitry Andric #if !defined(_MSC_VER) && !defined(__MINGW32__)
420b57cec5SDimitry Andric #include <unistd.h>
430b57cec5SDimitry Andric #else
440b57cec5SDimitry Andric #include <io.h>
450b57cec5SDimitry Andric #endif
460b57cec5SDimitry Andric
470b57cec5SDimitry Andric using namespace llvm;
4806c3fb27SDimitry Andric using namespace llvm::object;
4906c3fb27SDimitry Andric
5006c3fb27SDimitry Andric struct SymMap {
5106c3fb27SDimitry Andric bool UseECMap;
5206c3fb27SDimitry Andric std::map<std::string, uint16_t> Map;
5306c3fb27SDimitry Andric std::map<std::string, uint16_t> ECMap;
5406c3fb27SDimitry Andric };
550b57cec5SDimitry Andric
NewArchiveMember(MemoryBufferRef BufRef)560b57cec5SDimitry Andric NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef)
570b57cec5SDimitry Andric : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
580b57cec5SDimitry Andric MemberName(BufRef.getBufferIdentifier()) {}
590b57cec5SDimitry Andric
detectKindFromObject() const6081ad6265SDimitry Andric object::Archive::Kind NewArchiveMember::detectKindFromObject() const {
6181ad6265SDimitry Andric auto MemBufferRef = this->Buf->getMemBufferRef();
6281ad6265SDimitry Andric Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
6381ad6265SDimitry Andric object::ObjectFile::createObjectFile(MemBufferRef);
6481ad6265SDimitry Andric
6581ad6265SDimitry Andric if (OptionalObject)
6681ad6265SDimitry Andric return isa<object::MachOObjectFile>(**OptionalObject)
6781ad6265SDimitry Andric ? object::Archive::K_DARWIN
6881ad6265SDimitry Andric : (isa<object::XCOFFObjectFile>(**OptionalObject)
6981ad6265SDimitry Andric ? object::Archive::K_AIXBIG
7081ad6265SDimitry Andric : object::Archive::K_GNU);
7181ad6265SDimitry Andric
7281ad6265SDimitry Andric // Squelch the error in case we had a non-object file.
7381ad6265SDimitry Andric consumeError(OptionalObject.takeError());
7481ad6265SDimitry Andric
7581ad6265SDimitry Andric // If we're adding a bitcode file to the archive, detect the Archive kind
7681ad6265SDimitry Andric // based on the target triple.
7781ad6265SDimitry Andric LLVMContext Context;
7881ad6265SDimitry Andric if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) {
7981ad6265SDimitry Andric if (auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
8081ad6265SDimitry Andric MemBufferRef, file_magic::bitcode, &Context)) {
8181ad6265SDimitry Andric auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
8206c3fb27SDimitry Andric auto TargetTriple = Triple(IRObject.getTargetTriple());
8306c3fb27SDimitry Andric return TargetTriple.isOSDarwin()
8481ad6265SDimitry Andric ? object::Archive::K_DARWIN
8506c3fb27SDimitry Andric : (TargetTriple.isOSAIX() ? object::Archive::K_AIXBIG
8606c3fb27SDimitry Andric : object::Archive::K_GNU);
8781ad6265SDimitry Andric } else {
8881ad6265SDimitry Andric // Squelch the error in case this was not a SymbolicFile.
8981ad6265SDimitry Andric consumeError(ObjOrErr.takeError());
9081ad6265SDimitry Andric }
9181ad6265SDimitry Andric }
9281ad6265SDimitry Andric
9381ad6265SDimitry Andric return object::Archive::getDefaultKindForHost();
9481ad6265SDimitry Andric }
9581ad6265SDimitry Andric
960b57cec5SDimitry Andric Expected<NewArchiveMember>
getOldMember(const object::Archive::Child & OldMember,bool Deterministic)970b57cec5SDimitry Andric NewArchiveMember::getOldMember(const object::Archive::Child &OldMember,
980b57cec5SDimitry Andric bool Deterministic) {
990b57cec5SDimitry Andric Expected<llvm::MemoryBufferRef> BufOrErr = OldMember.getMemoryBufferRef();
1000b57cec5SDimitry Andric if (!BufOrErr)
1010b57cec5SDimitry Andric return BufOrErr.takeError();
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric NewArchiveMember M;
1040b57cec5SDimitry Andric M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
1050b57cec5SDimitry Andric M.MemberName = M.Buf->getBufferIdentifier();
1060b57cec5SDimitry Andric if (!Deterministic) {
1070b57cec5SDimitry Andric auto ModTimeOrErr = OldMember.getLastModified();
1080b57cec5SDimitry Andric if (!ModTimeOrErr)
1090b57cec5SDimitry Andric return ModTimeOrErr.takeError();
1100b57cec5SDimitry Andric M.ModTime = ModTimeOrErr.get();
1110b57cec5SDimitry Andric Expected<unsigned> UIDOrErr = OldMember.getUID();
1120b57cec5SDimitry Andric if (!UIDOrErr)
1130b57cec5SDimitry Andric return UIDOrErr.takeError();
1140b57cec5SDimitry Andric M.UID = UIDOrErr.get();
1150b57cec5SDimitry Andric Expected<unsigned> GIDOrErr = OldMember.getGID();
1160b57cec5SDimitry Andric if (!GIDOrErr)
1170b57cec5SDimitry Andric return GIDOrErr.takeError();
1180b57cec5SDimitry Andric M.GID = GIDOrErr.get();
1190b57cec5SDimitry Andric Expected<sys::fs::perms> AccessModeOrErr = OldMember.getAccessMode();
1200b57cec5SDimitry Andric if (!AccessModeOrErr)
1210b57cec5SDimitry Andric return AccessModeOrErr.takeError();
1220b57cec5SDimitry Andric M.Perms = AccessModeOrErr.get();
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric return std::move(M);
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric
getFile(StringRef FileName,bool Deterministic)1270b57cec5SDimitry Andric Expected<NewArchiveMember> NewArchiveMember::getFile(StringRef FileName,
1280b57cec5SDimitry Andric bool Deterministic) {
1290b57cec5SDimitry Andric sys::fs::file_status Status;
1300b57cec5SDimitry Andric auto FDOrErr = sys::fs::openNativeFileForRead(FileName);
1310b57cec5SDimitry Andric if (!FDOrErr)
1320b57cec5SDimitry Andric return FDOrErr.takeError();
1330b57cec5SDimitry Andric sys::fs::file_t FD = *FDOrErr;
1340b57cec5SDimitry Andric assert(FD != sys::fs::kInvalidFile);
1350b57cec5SDimitry Andric
1360b57cec5SDimitry Andric if (auto EC = sys::fs::status(FD, Status))
1370b57cec5SDimitry Andric return errorCodeToError(EC);
1380b57cec5SDimitry Andric
1390b57cec5SDimitry Andric // Opening a directory doesn't make sense. Let it fail.
1400b57cec5SDimitry Andric // Linux cannot open directories with open(2), although
1410b57cec5SDimitry Andric // cygwin and *bsd can.
1420b57cec5SDimitry Andric if (Status.type() == sys::fs::file_type::directory_file)
1430b57cec5SDimitry Andric return errorCodeToError(make_error_code(errc::is_a_directory));
1440b57cec5SDimitry Andric
1450b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
1460b57cec5SDimitry Andric MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
1470b57cec5SDimitry Andric if (!MemberBufferOrErr)
1480b57cec5SDimitry Andric return errorCodeToError(MemberBufferOrErr.getError());
1490b57cec5SDimitry Andric
1500b57cec5SDimitry Andric if (auto EC = sys::fs::closeFile(FD))
1510b57cec5SDimitry Andric return errorCodeToError(EC);
1520b57cec5SDimitry Andric
1530b57cec5SDimitry Andric NewArchiveMember M;
1540b57cec5SDimitry Andric M.Buf = std::move(*MemberBufferOrErr);
1550b57cec5SDimitry Andric M.MemberName = M.Buf->getBufferIdentifier();
1560b57cec5SDimitry Andric if (!Deterministic) {
1570b57cec5SDimitry Andric M.ModTime = std::chrono::time_point_cast<std::chrono::seconds>(
1580b57cec5SDimitry Andric Status.getLastModificationTime());
1590b57cec5SDimitry Andric M.UID = Status.getUser();
1600b57cec5SDimitry Andric M.GID = Status.getGroup();
1610b57cec5SDimitry Andric M.Perms = Status.permissions();
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric return std::move(M);
1640b57cec5SDimitry Andric }
1650b57cec5SDimitry Andric
1660b57cec5SDimitry Andric template <typename T>
printWithSpacePadding(raw_ostream & OS,T Data,unsigned Size)1670b57cec5SDimitry Andric static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
1680b57cec5SDimitry Andric uint64_t OldPos = OS.tell();
1690b57cec5SDimitry Andric OS << Data;
1700b57cec5SDimitry Andric unsigned SizeSoFar = OS.tell() - OldPos;
1710b57cec5SDimitry Andric assert(SizeSoFar <= Size && "Data doesn't fit in Size");
1720b57cec5SDimitry Andric OS.indent(Size - SizeSoFar);
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric
isDarwin(object::Archive::Kind Kind)1750b57cec5SDimitry Andric static bool isDarwin(object::Archive::Kind Kind) {
1760b57cec5SDimitry Andric return Kind == object::Archive::K_DARWIN ||
1770b57cec5SDimitry Andric Kind == object::Archive::K_DARWIN64;
1780b57cec5SDimitry Andric }
1790b57cec5SDimitry Andric
isAIXBigArchive(object::Archive::Kind Kind)18081ad6265SDimitry Andric static bool isAIXBigArchive(object::Archive::Kind Kind) {
18181ad6265SDimitry Andric return Kind == object::Archive::K_AIXBIG;
18281ad6265SDimitry Andric }
18381ad6265SDimitry Andric
isCOFFArchive(object::Archive::Kind Kind)18406c3fb27SDimitry Andric static bool isCOFFArchive(object::Archive::Kind Kind) {
18506c3fb27SDimitry Andric return Kind == object::Archive::K_COFF;
18606c3fb27SDimitry Andric }
18706c3fb27SDimitry Andric
isBSDLike(object::Archive::Kind Kind)1880b57cec5SDimitry Andric static bool isBSDLike(object::Archive::Kind Kind) {
1890b57cec5SDimitry Andric switch (Kind) {
1900b57cec5SDimitry Andric case object::Archive::K_GNU:
1910b57cec5SDimitry Andric case object::Archive::K_GNU64:
19281ad6265SDimitry Andric case object::Archive::K_AIXBIG:
19306c3fb27SDimitry Andric case object::Archive::K_COFF:
1940b57cec5SDimitry Andric return false;
1950b57cec5SDimitry Andric case object::Archive::K_BSD:
1960b57cec5SDimitry Andric case object::Archive::K_DARWIN:
1970b57cec5SDimitry Andric case object::Archive::K_DARWIN64:
1980b57cec5SDimitry Andric return true;
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric llvm_unreachable("not supported for writting");
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric template <class T>
print(raw_ostream & Out,object::Archive::Kind Kind,T Val)2040b57cec5SDimitry Andric static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val) {
2050b57cec5SDimitry Andric support::endian::write(Out, Val,
2065f757f3fSDimitry Andric isBSDLike(Kind) ? llvm::endianness::little
2075f757f3fSDimitry Andric : llvm::endianness::big);
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric
printLE(raw_ostream & Out,T Val)21006c3fb27SDimitry Andric template <class T> static void printLE(raw_ostream &Out, T Val) {
2115f757f3fSDimitry Andric support::endian::write(Out, Val, llvm::endianness::little);
21206c3fb27SDimitry Andric }
21306c3fb27SDimitry Andric
printRestOfMemberHeader(raw_ostream & Out,const sys::TimePoint<std::chrono::seconds> & ModTime,unsigned UID,unsigned GID,unsigned Perms,uint64_t Size)2140b57cec5SDimitry Andric static void printRestOfMemberHeader(
2150b57cec5SDimitry Andric raw_ostream &Out, const sys::TimePoint<std::chrono::seconds> &ModTime,
2168bcb0991SDimitry Andric unsigned UID, unsigned GID, unsigned Perms, uint64_t Size) {
2170b57cec5SDimitry Andric printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
2180b57cec5SDimitry Andric
2190b57cec5SDimitry Andric // The format has only 6 chars for uid and gid. Truncate if the provided
2200b57cec5SDimitry Andric // values don't fit.
2210b57cec5SDimitry Andric printWithSpacePadding(Out, UID % 1000000, 6);
2220b57cec5SDimitry Andric printWithSpacePadding(Out, GID % 1000000, 6);
2230b57cec5SDimitry Andric
2240b57cec5SDimitry Andric printWithSpacePadding(Out, format("%o", Perms), 8);
2250b57cec5SDimitry Andric printWithSpacePadding(Out, Size, 10);
2260b57cec5SDimitry Andric Out << "`\n";
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric
2290b57cec5SDimitry Andric static void
printGNUSmallMemberHeader(raw_ostream & Out,StringRef Name,const sys::TimePoint<std::chrono::seconds> & ModTime,unsigned UID,unsigned GID,unsigned Perms,uint64_t Size)2300b57cec5SDimitry Andric printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name,
2310b57cec5SDimitry Andric const sys::TimePoint<std::chrono::seconds> &ModTime,
2320b57cec5SDimitry Andric unsigned UID, unsigned GID, unsigned Perms,
2338bcb0991SDimitry Andric uint64_t Size) {
2340b57cec5SDimitry Andric printWithSpacePadding(Out, Twine(Name) + "/", 16);
2350b57cec5SDimitry Andric printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
2360b57cec5SDimitry Andric }
2370b57cec5SDimitry Andric
2380b57cec5SDimitry Andric 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)2390b57cec5SDimitry Andric printBSDMemberHeader(raw_ostream &Out, uint64_t Pos, StringRef Name,
2400b57cec5SDimitry Andric const sys::TimePoint<std::chrono::seconds> &ModTime,
2418bcb0991SDimitry Andric unsigned UID, unsigned GID, unsigned Perms, uint64_t Size) {
2420b57cec5SDimitry Andric uint64_t PosAfterHeader = Pos + 60 + Name.size();
2430b57cec5SDimitry Andric // Pad so that even 64 bit object files are aligned.
2448bcb0991SDimitry Andric unsigned Pad = offsetToAlignment(PosAfterHeader, Align(8));
2450b57cec5SDimitry Andric unsigned NameWithPadding = Name.size() + Pad;
2460b57cec5SDimitry Andric printWithSpacePadding(Out, Twine("#1/") + Twine(NameWithPadding), 16);
2470b57cec5SDimitry Andric printRestOfMemberHeader(Out, ModTime, UID, GID, Perms,
2480b57cec5SDimitry Andric NameWithPadding + Size);
2490b57cec5SDimitry Andric Out << Name;
2500b57cec5SDimitry Andric while (Pad--)
2510b57cec5SDimitry Andric Out.write(uint8_t(0));
2520b57cec5SDimitry Andric }
2530b57cec5SDimitry Andric
25481ad6265SDimitry Andric static void
printBigArchiveMemberHeader(raw_ostream & Out,StringRef Name,const sys::TimePoint<std::chrono::seconds> & ModTime,unsigned UID,unsigned GID,unsigned Perms,uint64_t Size,uint64_t PrevOffset,uint64_t NextOffset)25581ad6265SDimitry Andric printBigArchiveMemberHeader(raw_ostream &Out, StringRef Name,
25681ad6265SDimitry Andric const sys::TimePoint<std::chrono::seconds> &ModTime,
25781ad6265SDimitry Andric unsigned UID, unsigned GID, unsigned Perms,
25806c3fb27SDimitry Andric uint64_t Size, uint64_t PrevOffset,
25906c3fb27SDimitry Andric uint64_t NextOffset) {
26081ad6265SDimitry Andric unsigned NameLen = Name.size();
26181ad6265SDimitry Andric
26281ad6265SDimitry Andric printWithSpacePadding(Out, Size, 20); // File member size
26381ad6265SDimitry Andric printWithSpacePadding(Out, NextOffset, 20); // Next member header offset
26481ad6265SDimitry Andric printWithSpacePadding(Out, PrevOffset, 20); // Previous member header offset
26581ad6265SDimitry Andric printWithSpacePadding(Out, sys::toTimeT(ModTime), 12); // File member date
26681ad6265SDimitry Andric // The big archive format has 12 chars for uid and gid.
26781ad6265SDimitry Andric printWithSpacePadding(Out, UID % 1000000000000, 12); // UID
26881ad6265SDimitry Andric printWithSpacePadding(Out, GID % 1000000000000, 12); // GID
26981ad6265SDimitry Andric printWithSpacePadding(Out, format("%o", Perms), 12); // Permission
27081ad6265SDimitry Andric printWithSpacePadding(Out, NameLen, 4); // Name length
27181ad6265SDimitry Andric if (NameLen) {
27281ad6265SDimitry Andric printWithSpacePadding(Out, Name, NameLen); // Name
27381ad6265SDimitry Andric if (NameLen % 2)
27481ad6265SDimitry Andric Out.write(uint8_t(0)); // Null byte padding
27581ad6265SDimitry Andric }
27681ad6265SDimitry Andric Out << "`\n"; // Terminator
27781ad6265SDimitry Andric }
27881ad6265SDimitry Andric
useStringTable(bool Thin,StringRef Name)2790b57cec5SDimitry Andric static bool useStringTable(bool Thin, StringRef Name) {
2800b57cec5SDimitry Andric return Thin || Name.size() >= 16 || Name.contains('/');
2810b57cec5SDimitry Andric }
2820b57cec5SDimitry Andric
is64BitKind(object::Archive::Kind Kind)2830b57cec5SDimitry Andric static bool is64BitKind(object::Archive::Kind Kind) {
2840b57cec5SDimitry Andric switch (Kind) {
2850b57cec5SDimitry Andric case object::Archive::K_GNU:
2860b57cec5SDimitry Andric case object::Archive::K_BSD:
2870b57cec5SDimitry Andric case object::Archive::K_DARWIN:
2880b57cec5SDimitry Andric case object::Archive::K_COFF:
2890b57cec5SDimitry Andric return false;
29081ad6265SDimitry Andric case object::Archive::K_AIXBIG:
2910b57cec5SDimitry Andric case object::Archive::K_DARWIN64:
2920b57cec5SDimitry Andric case object::Archive::K_GNU64:
2930b57cec5SDimitry Andric return true;
2940b57cec5SDimitry Andric }
2950b57cec5SDimitry Andric llvm_unreachable("not supported for writting");
2960b57cec5SDimitry Andric }
2970b57cec5SDimitry Andric
2980b57cec5SDimitry Andric 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)2990b57cec5SDimitry Andric printMemberHeader(raw_ostream &Out, uint64_t Pos, raw_ostream &StringTable,
3000b57cec5SDimitry Andric StringMap<uint64_t> &MemberNames, object::Archive::Kind Kind,
3010b57cec5SDimitry Andric bool Thin, const NewArchiveMember &M,
3028bcb0991SDimitry Andric sys::TimePoint<std::chrono::seconds> ModTime, uint64_t Size) {
3030b57cec5SDimitry Andric if (isBSDLike(Kind))
3040b57cec5SDimitry Andric return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
3050b57cec5SDimitry Andric M.Perms, Size);
3060b57cec5SDimitry Andric if (!useStringTable(Thin, M.MemberName))
3070b57cec5SDimitry Andric return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
3080b57cec5SDimitry Andric M.Perms, Size);
3090b57cec5SDimitry Andric Out << '/';
3100b57cec5SDimitry Andric uint64_t NamePos;
3110b57cec5SDimitry Andric if (Thin) {
3120b57cec5SDimitry Andric NamePos = StringTable.tell();
3130b57cec5SDimitry Andric StringTable << M.MemberName << "/\n";
3140b57cec5SDimitry Andric } else {
3150b57cec5SDimitry Andric auto Insertion = MemberNames.insert({M.MemberName, uint64_t(0)});
3160b57cec5SDimitry Andric if (Insertion.second) {
3170b57cec5SDimitry Andric Insertion.first->second = StringTable.tell();
31806c3fb27SDimitry Andric StringTable << M.MemberName;
31906c3fb27SDimitry Andric if (isCOFFArchive(Kind))
32006c3fb27SDimitry Andric StringTable << '\0';
32106c3fb27SDimitry Andric else
32206c3fb27SDimitry Andric StringTable << "/\n";
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric NamePos = Insertion.first->second;
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric printWithSpacePadding(Out, NamePos, 15);
3270b57cec5SDimitry Andric printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric
3300b57cec5SDimitry Andric namespace {
3310b57cec5SDimitry Andric struct MemberData {
3320b57cec5SDimitry Andric std::vector<unsigned> Symbols;
3330b57cec5SDimitry Andric std::string Header;
3340b57cec5SDimitry Andric StringRef Data;
3350b57cec5SDimitry Andric StringRef Padding;
3365f757f3fSDimitry Andric uint64_t PreHeadPadSize = 0;
3375f757f3fSDimitry Andric std::unique_ptr<SymbolicFile> SymFile = nullptr;
3380b57cec5SDimitry Andric };
3390b57cec5SDimitry Andric } // namespace
3400b57cec5SDimitry Andric
computeStringTable(StringRef Names)3410b57cec5SDimitry Andric static MemberData computeStringTable(StringRef Names) {
3420b57cec5SDimitry Andric unsigned Size = Names.size();
3438bcb0991SDimitry Andric unsigned Pad = offsetToAlignment(Size, Align(2));
3440b57cec5SDimitry Andric std::string Header;
3450b57cec5SDimitry Andric raw_string_ostream Out(Header);
3460b57cec5SDimitry Andric printWithSpacePadding(Out, "//", 48);
3470b57cec5SDimitry Andric printWithSpacePadding(Out, Size + Pad, 10);
3480b57cec5SDimitry Andric Out << "`\n";
3490b57cec5SDimitry Andric Out.flush();
3500b57cec5SDimitry Andric return {{}, std::move(Header), Names, Pad ? "\n" : ""};
3510b57cec5SDimitry Andric }
3520b57cec5SDimitry Andric
now(bool Deterministic)3530b57cec5SDimitry Andric static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
3540b57cec5SDimitry Andric using namespace std::chrono;
3550b57cec5SDimitry Andric
3560b57cec5SDimitry Andric if (!Deterministic)
3570b57cec5SDimitry Andric return time_point_cast<seconds>(system_clock::now());
3580b57cec5SDimitry Andric return sys::TimePoint<seconds>();
3590b57cec5SDimitry Andric }
3600b57cec5SDimitry Andric
isArchiveSymbol(const object::BasicSymbolRef & S)3610b57cec5SDimitry Andric static bool isArchiveSymbol(const object::BasicSymbolRef &S) {
3625ffd83dbSDimitry Andric Expected<uint32_t> SymFlagsOrErr = S.getFlags();
3635ffd83dbSDimitry Andric if (!SymFlagsOrErr)
3645ffd83dbSDimitry Andric // TODO: Actually report errors helpfully.
3655ffd83dbSDimitry Andric report_fatal_error(SymFlagsOrErr.takeError());
3665ffd83dbSDimitry Andric if (*SymFlagsOrErr & object::SymbolRef::SF_FormatSpecific)
3670b57cec5SDimitry Andric return false;
3685ffd83dbSDimitry Andric if (!(*SymFlagsOrErr & object::SymbolRef::SF_Global))
3690b57cec5SDimitry Andric return false;
3705ffd83dbSDimitry Andric if (*SymFlagsOrErr & object::SymbolRef::SF_Undefined)
3710b57cec5SDimitry Andric return false;
3720b57cec5SDimitry Andric return true;
3730b57cec5SDimitry Andric }
3740b57cec5SDimitry Andric
printNBits(raw_ostream & Out,object::Archive::Kind Kind,uint64_t Val)3750b57cec5SDimitry Andric static void printNBits(raw_ostream &Out, object::Archive::Kind Kind,
3760b57cec5SDimitry Andric uint64_t Val) {
3770b57cec5SDimitry Andric if (is64BitKind(Kind))
3780b57cec5SDimitry Andric print<uint64_t>(Out, Kind, Val);
3790b57cec5SDimitry Andric else
3800b57cec5SDimitry Andric print<uint32_t>(Out, Kind, Val);
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric
computeSymbolTableSize(object::Archive::Kind Kind,uint64_t NumSyms,uint64_t OffsetSize,uint64_t StringTableSize,uint32_t * Padding=nullptr)383e8d8bef9SDimitry Andric static uint64_t computeSymbolTableSize(object::Archive::Kind Kind,
384e8d8bef9SDimitry Andric uint64_t NumSyms, uint64_t OffsetSize,
38506c3fb27SDimitry Andric uint64_t StringTableSize,
386e8d8bef9SDimitry Andric uint32_t *Padding = nullptr) {
387e8d8bef9SDimitry Andric assert((OffsetSize == 4 || OffsetSize == 8) && "Unsupported OffsetSize");
388e8d8bef9SDimitry Andric uint64_t Size = OffsetSize; // Number of entries
389e8d8bef9SDimitry Andric if (isBSDLike(Kind))
390e8d8bef9SDimitry Andric Size += NumSyms * OffsetSize * 2; // Table
391e8d8bef9SDimitry Andric else
392e8d8bef9SDimitry Andric Size += NumSyms * OffsetSize; // Table
393e8d8bef9SDimitry Andric if (isBSDLike(Kind))
394e8d8bef9SDimitry Andric Size += OffsetSize; // byte count
39506c3fb27SDimitry Andric Size += StringTableSize;
396e8d8bef9SDimitry Andric // ld64 expects the members to be 8-byte aligned for 64-bit content and at
397e8d8bef9SDimitry Andric // least 4-byte aligned for 32-bit content. Opt for the larger encoding
398e8d8bef9SDimitry Andric // uniformly.
399e8d8bef9SDimitry Andric // We do this for all bsd formats because it simplifies aligning members.
40081ad6265SDimitry Andric // For the big archive format, the symbol table is the last member, so there
40181ad6265SDimitry Andric // is no need to align.
40281ad6265SDimitry Andric uint32_t Pad = isAIXBigArchive(Kind)
40381ad6265SDimitry Andric ? 0
40481ad6265SDimitry Andric : offsetToAlignment(Size, Align(isBSDLike(Kind) ? 8 : 2));
40506c3fb27SDimitry Andric
40606c3fb27SDimitry Andric Size += Pad;
40706c3fb27SDimitry Andric if (Padding)
40806c3fb27SDimitry Andric *Padding = Pad;
40906c3fb27SDimitry Andric return Size;
41006c3fb27SDimitry Andric }
41106c3fb27SDimitry Andric
computeSymbolMapSize(uint64_t NumObj,SymMap & SymMap,uint32_t * Padding=nullptr)41206c3fb27SDimitry Andric static uint64_t computeSymbolMapSize(uint64_t NumObj, SymMap &SymMap,
41306c3fb27SDimitry Andric uint32_t *Padding = nullptr) {
41406c3fb27SDimitry Andric uint64_t Size = sizeof(uint32_t) * 2; // Number of symbols and objects entries
41506c3fb27SDimitry Andric Size += NumObj * sizeof(uint32_t); // Offset table
41606c3fb27SDimitry Andric
41706c3fb27SDimitry Andric for (auto S : SymMap.Map)
41806c3fb27SDimitry Andric Size += sizeof(uint16_t) + S.first.length() + 1;
41906c3fb27SDimitry Andric
42006c3fb27SDimitry Andric uint32_t Pad = offsetToAlignment(Size, Align(2));
42106c3fb27SDimitry Andric Size += Pad;
42206c3fb27SDimitry Andric if (Padding)
42306c3fb27SDimitry Andric *Padding = Pad;
42406c3fb27SDimitry Andric return Size;
42506c3fb27SDimitry Andric }
42606c3fb27SDimitry Andric
computeECSymbolsSize(SymMap & SymMap,uint32_t * Padding=nullptr)42706c3fb27SDimitry Andric static uint64_t computeECSymbolsSize(SymMap &SymMap,
42806c3fb27SDimitry Andric uint32_t *Padding = nullptr) {
42906c3fb27SDimitry Andric uint64_t Size = sizeof(uint32_t); // Number of symbols
43006c3fb27SDimitry Andric
43106c3fb27SDimitry Andric for (auto S : SymMap.ECMap)
43206c3fb27SDimitry Andric Size += sizeof(uint16_t) + S.first.length() + 1;
43306c3fb27SDimitry Andric
43406c3fb27SDimitry Andric uint32_t Pad = offsetToAlignment(Size, Align(2));
435e8d8bef9SDimitry Andric Size += Pad;
436e8d8bef9SDimitry Andric if (Padding)
437e8d8bef9SDimitry Andric *Padding = Pad;
438e8d8bef9SDimitry Andric return Size;
439e8d8bef9SDimitry Andric }
440e8d8bef9SDimitry Andric
writeSymbolTableHeader(raw_ostream & Out,object::Archive::Kind Kind,bool Deterministic,uint64_t Size,uint64_t PrevMemberOffset=0,uint64_t NextMemberOffset=0)441e8d8bef9SDimitry Andric static void writeSymbolTableHeader(raw_ostream &Out, object::Archive::Kind Kind,
44281ad6265SDimitry Andric bool Deterministic, uint64_t Size,
44306c3fb27SDimitry Andric uint64_t PrevMemberOffset = 0,
44406c3fb27SDimitry Andric uint64_t NextMemberOffset = 0) {
445e8d8bef9SDimitry Andric if (isBSDLike(Kind)) {
446e8d8bef9SDimitry Andric const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
447e8d8bef9SDimitry Andric printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
448e8d8bef9SDimitry Andric Size);
44981ad6265SDimitry Andric } else if (isAIXBigArchive(Kind)) {
45006c3fb27SDimitry Andric printBigArchiveMemberHeader(Out, "", now(Deterministic), 0, 0, 0, Size,
45106c3fb27SDimitry Andric PrevMemberOffset, NextMemberOffset);
452e8d8bef9SDimitry Andric } else {
453e8d8bef9SDimitry Andric const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
454e8d8bef9SDimitry Andric printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
455e8d8bef9SDimitry Andric }
456e8d8bef9SDimitry Andric }
457e8d8bef9SDimitry Andric
computeHeadersSize(object::Archive::Kind Kind,uint64_t NumMembers,uint64_t StringMemberSize,uint64_t NumSyms,uint64_t SymNamesSize,SymMap * SymMap)45806c3fb27SDimitry Andric static uint64_t computeHeadersSize(object::Archive::Kind Kind,
45906c3fb27SDimitry Andric uint64_t NumMembers,
46006c3fb27SDimitry Andric uint64_t StringMemberSize, uint64_t NumSyms,
46106c3fb27SDimitry Andric uint64_t SymNamesSize, SymMap *SymMap) {
46206c3fb27SDimitry Andric uint32_t OffsetSize = is64BitKind(Kind) ? 8 : 4;
46306c3fb27SDimitry Andric uint64_t SymtabSize =
46406c3fb27SDimitry Andric computeSymbolTableSize(Kind, NumSyms, OffsetSize, SymNamesSize);
46506c3fb27SDimitry Andric auto computeSymbolTableHeaderSize = [=] {
46606c3fb27SDimitry Andric SmallString<0> TmpBuf;
46706c3fb27SDimitry Andric raw_svector_ostream Tmp(TmpBuf);
46806c3fb27SDimitry Andric writeSymbolTableHeader(Tmp, Kind, true, SymtabSize);
46906c3fb27SDimitry Andric return TmpBuf.size();
47006c3fb27SDimitry Andric };
47106c3fb27SDimitry Andric uint32_t HeaderSize = computeSymbolTableHeaderSize();
47206c3fb27SDimitry Andric uint64_t Size = strlen("!<arch>\n") + HeaderSize + SymtabSize;
47306c3fb27SDimitry Andric
47406c3fb27SDimitry Andric if (SymMap) {
47506c3fb27SDimitry Andric Size += HeaderSize + computeSymbolMapSize(NumMembers, *SymMap);
47606c3fb27SDimitry Andric if (SymMap->ECMap.size())
47706c3fb27SDimitry Andric Size += HeaderSize + computeECSymbolsSize(*SymMap);
47806c3fb27SDimitry Andric }
47906c3fb27SDimitry Andric
48006c3fb27SDimitry Andric return Size + StringMemberSize;
48106c3fb27SDimitry Andric }
48206c3fb27SDimitry Andric
48306c3fb27SDimitry Andric static Expected<std::unique_ptr<SymbolicFile>>
getSymbolicFile(MemoryBufferRef Buf,LLVMContext & Context)48406c3fb27SDimitry Andric getSymbolicFile(MemoryBufferRef Buf, LLVMContext &Context) {
48506c3fb27SDimitry Andric const file_magic Type = identify_magic(Buf.getBuffer());
48606c3fb27SDimitry Andric // Don't attempt to read non-symbolic file types.
48706c3fb27SDimitry Andric if (!object::SymbolicFile::isSymbolicFile(Type, &Context))
48806c3fb27SDimitry Andric return nullptr;
48906c3fb27SDimitry Andric if (Type == file_magic::bitcode) {
49006c3fb27SDimitry Andric auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
49106c3fb27SDimitry Andric Buf, file_magic::bitcode, &Context);
49206c3fb27SDimitry Andric if (!ObjOrErr)
49306c3fb27SDimitry Andric return ObjOrErr.takeError();
49406c3fb27SDimitry Andric return std::move(*ObjOrErr);
49506c3fb27SDimitry Andric } else {
49606c3fb27SDimitry Andric auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
49706c3fb27SDimitry Andric if (!ObjOrErr)
49806c3fb27SDimitry Andric return ObjOrErr.takeError();
49906c3fb27SDimitry Andric return std::move(*ObjOrErr);
50006c3fb27SDimitry Andric }
50106c3fb27SDimitry Andric }
50206c3fb27SDimitry Andric
is64BitSymbolicFile(const SymbolicFile * SymObj)5035f757f3fSDimitry Andric static bool is64BitSymbolicFile(const SymbolicFile *SymObj) {
5045f757f3fSDimitry Andric return SymObj != nullptr ? SymObj->is64Bit() : false;
5055f757f3fSDimitry Andric }
50606c3fb27SDimitry Andric
5075f757f3fSDimitry Andric // Log2 of PAGESIZE(4096) on an AIX system.
5085f757f3fSDimitry Andric static const uint32_t Log2OfAIXPageSize = 12;
50906c3fb27SDimitry Andric
5105f757f3fSDimitry Andric // In the AIX big archive format, since the data content follows the member file
5115f757f3fSDimitry Andric // name, if the name ends on an odd byte, an extra byte will be added for
5125f757f3fSDimitry Andric // padding. This ensures that the data within the member file starts at an even
5135f757f3fSDimitry Andric // byte.
5145f757f3fSDimitry Andric static const uint32_t MinBigArchiveMemDataAlign = 2;
5155f757f3fSDimitry Andric
5165f757f3fSDimitry Andric template <typename AuxiliaryHeader>
getAuxMaxAlignment(uint16_t AuxHeaderSize,AuxiliaryHeader * AuxHeader,uint16_t Log2OfMaxAlign)5175f757f3fSDimitry Andric uint16_t getAuxMaxAlignment(uint16_t AuxHeaderSize, AuxiliaryHeader *AuxHeader,
5185f757f3fSDimitry Andric uint16_t Log2OfMaxAlign) {
5195f757f3fSDimitry Andric // If the member doesn't have an auxiliary header, it isn't a loadable object
5205f757f3fSDimitry Andric // and so it just needs aligning at the minimum value.
5215f757f3fSDimitry Andric if (AuxHeader == nullptr)
5225f757f3fSDimitry Andric return MinBigArchiveMemDataAlign;
5235f757f3fSDimitry Andric
5245f757f3fSDimitry Andric // If the auxiliary header does not have both MaxAlignOfData and
5255f757f3fSDimitry Andric // MaxAlignOfText field, it is not a loadable shared object file, so align at
5265f757f3fSDimitry Andric // the minimum value. The 'ModuleType' member is located right after
5275f757f3fSDimitry Andric // 'MaxAlignOfData' in the AuxiliaryHeader.
5285f757f3fSDimitry Andric if (AuxHeaderSize < offsetof(AuxiliaryHeader, ModuleType))
5295f757f3fSDimitry Andric return MinBigArchiveMemDataAlign;
5305f757f3fSDimitry Andric
5315f757f3fSDimitry Andric // If the XCOFF object file does not have a loader section, it is not
5325f757f3fSDimitry Andric // loadable, so align at the minimum value.
5335f757f3fSDimitry Andric if (AuxHeader->SecNumOfLoader == 0)
5345f757f3fSDimitry Andric return MinBigArchiveMemDataAlign;
5355f757f3fSDimitry Andric
5365f757f3fSDimitry Andric // The content of the loadable member file needs to be aligned at MAX(maximum
5375f757f3fSDimitry Andric // alignment of .text, maximum alignment of .data) if there are both fields.
5385f757f3fSDimitry Andric // If the desired alignment is > PAGESIZE, 32-bit members are aligned on a
5395f757f3fSDimitry Andric // word boundary, while 64-bit members are aligned on a PAGESIZE(2^12=4096)
5405f757f3fSDimitry Andric // boundary.
5415f757f3fSDimitry Andric uint16_t Log2OfAlign =
5425f757f3fSDimitry Andric std::max(AuxHeader->MaxAlignOfText, AuxHeader->MaxAlignOfData);
5435f757f3fSDimitry Andric return 1 << (Log2OfAlign > Log2OfAIXPageSize ? Log2OfMaxAlign : Log2OfAlign);
5445f757f3fSDimitry Andric }
5455f757f3fSDimitry Andric
5465f757f3fSDimitry Andric // AIX big archives may contain shared object members. The AIX OS requires these
5475f757f3fSDimitry Andric // members to be aligned if they are 64-bit and recommends it for 32-bit
5485f757f3fSDimitry Andric // members. This ensures that when these members are loaded they are aligned in
5495f757f3fSDimitry Andric // memory.
getMemberAlignment(SymbolicFile * SymObj)5505f757f3fSDimitry Andric static uint32_t getMemberAlignment(SymbolicFile *SymObj) {
5515f757f3fSDimitry Andric XCOFFObjectFile *XCOFFObj = dyn_cast_or_null<XCOFFObjectFile>(SymObj);
5525f757f3fSDimitry Andric if (!XCOFFObj)
5535f757f3fSDimitry Andric return MinBigArchiveMemDataAlign;
5545f757f3fSDimitry Andric
5555f757f3fSDimitry Andric // If the desired alignment is > PAGESIZE, 32-bit members are aligned on a
5565f757f3fSDimitry Andric // word boundary, while 64-bit members are aligned on a PAGESIZE boundary.
5575f757f3fSDimitry Andric return XCOFFObj->is64Bit()
5585f757f3fSDimitry Andric ? getAuxMaxAlignment(XCOFFObj->fileHeader64()->AuxHeaderSize,
5595f757f3fSDimitry Andric XCOFFObj->auxiliaryHeader64(),
5605f757f3fSDimitry Andric Log2OfAIXPageSize)
5615f757f3fSDimitry Andric : getAuxMaxAlignment(XCOFFObj->fileHeader32()->AuxHeaderSize,
5625f757f3fSDimitry Andric XCOFFObj->auxiliaryHeader32(), 2);
56306c3fb27SDimitry Andric }
56406c3fb27SDimitry Andric
writeSymbolTable(raw_ostream & Out,object::Archive::Kind Kind,bool Deterministic,ArrayRef<MemberData> Members,StringRef StringTable,uint64_t MembersOffset,unsigned NumSyms,uint64_t PrevMemberOffset=0,uint64_t NextMemberOffset=0,bool Is64Bit=false)5650b57cec5SDimitry Andric static void writeSymbolTable(raw_ostream &Out, object::Archive::Kind Kind,
5660b57cec5SDimitry Andric bool Deterministic, ArrayRef<MemberData> Members,
56706c3fb27SDimitry Andric StringRef StringTable, uint64_t MembersOffset,
56806c3fb27SDimitry Andric unsigned NumSyms, uint64_t PrevMemberOffset = 0,
56906c3fb27SDimitry Andric uint64_t NextMemberOffset = 0,
57006c3fb27SDimitry Andric bool Is64Bit = false) {
5710b57cec5SDimitry Andric // We don't write a symbol table on an archive with no members -- except on
5720b57cec5SDimitry Andric // Darwin, where the linker will abort unless the archive has a symbol table.
57306c3fb27SDimitry Andric if (StringTable.empty() && !isDarwin(Kind) && !isCOFFArchive(Kind))
5740b57cec5SDimitry Andric return;
5750b57cec5SDimitry Andric
576e8d8bef9SDimitry Andric uint64_t OffsetSize = is64BitKind(Kind) ? 8 : 4;
577e8d8bef9SDimitry Andric uint32_t Pad;
57806c3fb27SDimitry Andric uint64_t Size = computeSymbolTableSize(Kind, NumSyms, OffsetSize,
57906c3fb27SDimitry Andric StringTable.size(), &Pad);
58006c3fb27SDimitry Andric writeSymbolTableHeader(Out, Kind, Deterministic, Size, PrevMemberOffset,
58106c3fb27SDimitry Andric NextMemberOffset);
5820b57cec5SDimitry Andric
5830b57cec5SDimitry Andric if (isBSDLike(Kind))
5840b57cec5SDimitry Andric printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
5850b57cec5SDimitry Andric else
5860b57cec5SDimitry Andric printNBits(Out, Kind, NumSyms);
5870b57cec5SDimitry Andric
58806c3fb27SDimitry Andric uint64_t Pos = MembersOffset;
5890b57cec5SDimitry Andric for (const MemberData &M : Members) {
59006c3fb27SDimitry Andric if (isAIXBigArchive(Kind)) {
5915f757f3fSDimitry Andric Pos += M.PreHeadPadSize;
5925f757f3fSDimitry Andric if (is64BitSymbolicFile(M.SymFile.get()) != Is64Bit) {
59306c3fb27SDimitry Andric Pos += M.Header.size() + M.Data.size() + M.Padding.size();
59406c3fb27SDimitry Andric continue;
59506c3fb27SDimitry Andric }
59606c3fb27SDimitry Andric }
59706c3fb27SDimitry Andric
5980b57cec5SDimitry Andric for (unsigned StringOffset : M.Symbols) {
5990b57cec5SDimitry Andric if (isBSDLike(Kind))
6000b57cec5SDimitry Andric printNBits(Out, Kind, StringOffset);
6010b57cec5SDimitry Andric printNBits(Out, Kind, Pos); // member offset
6020b57cec5SDimitry Andric }
6030b57cec5SDimitry Andric Pos += M.Header.size() + M.Data.size() + M.Padding.size();
6040b57cec5SDimitry Andric }
6050b57cec5SDimitry Andric
6060b57cec5SDimitry Andric if (isBSDLike(Kind))
6070b57cec5SDimitry Andric // byte count of the string table
6080b57cec5SDimitry Andric printNBits(Out, Kind, StringTable.size());
6090b57cec5SDimitry Andric Out << StringTable;
6100b57cec5SDimitry Andric
6110b57cec5SDimitry Andric while (Pad--)
6120b57cec5SDimitry Andric Out.write(uint8_t(0));
6130b57cec5SDimitry Andric }
6140b57cec5SDimitry Andric
writeSymbolMap(raw_ostream & Out,object::Archive::Kind Kind,bool Deterministic,ArrayRef<MemberData> Members,SymMap & SymMap,uint64_t MembersOffset)61506c3fb27SDimitry Andric static void writeSymbolMap(raw_ostream &Out, object::Archive::Kind Kind,
61606c3fb27SDimitry Andric bool Deterministic, ArrayRef<MemberData> Members,
61706c3fb27SDimitry Andric SymMap &SymMap, uint64_t MembersOffset) {
61806c3fb27SDimitry Andric uint32_t Pad;
61906c3fb27SDimitry Andric uint64_t Size = computeSymbolMapSize(Members.size(), SymMap, &Pad);
62006c3fb27SDimitry Andric writeSymbolTableHeader(Out, Kind, Deterministic, Size, 0);
6210b57cec5SDimitry Andric
62206c3fb27SDimitry Andric uint32_t Pos = MembersOffset;
62306c3fb27SDimitry Andric
62406c3fb27SDimitry Andric printLE<uint32_t>(Out, Members.size());
62506c3fb27SDimitry Andric for (const MemberData &M : Members) {
62606c3fb27SDimitry Andric printLE(Out, Pos); // member offset
62706c3fb27SDimitry Andric Pos += M.Header.size() + M.Data.size() + M.Padding.size();
62806c3fb27SDimitry Andric }
62906c3fb27SDimitry Andric
63006c3fb27SDimitry Andric printLE<uint32_t>(Out, SymMap.Map.size());
63106c3fb27SDimitry Andric
63206c3fb27SDimitry Andric for (auto S : SymMap.Map)
63306c3fb27SDimitry Andric printLE(Out, S.second);
63406c3fb27SDimitry Andric for (auto S : SymMap.Map)
63506c3fb27SDimitry Andric Out << S.first << '\0';
63606c3fb27SDimitry Andric
63706c3fb27SDimitry Andric while (Pad--)
63806c3fb27SDimitry Andric Out.write(uint8_t(0));
63906c3fb27SDimitry Andric }
64006c3fb27SDimitry Andric
writeECSymbols(raw_ostream & Out,object::Archive::Kind Kind,bool Deterministic,ArrayRef<MemberData> Members,SymMap & SymMap)64106c3fb27SDimitry Andric static void writeECSymbols(raw_ostream &Out, object::Archive::Kind Kind,
64206c3fb27SDimitry Andric bool Deterministic, ArrayRef<MemberData> Members,
64306c3fb27SDimitry Andric SymMap &SymMap) {
64406c3fb27SDimitry Andric uint32_t Pad;
64506c3fb27SDimitry Andric uint64_t Size = computeECSymbolsSize(SymMap, &Pad);
64606c3fb27SDimitry Andric printGNUSmallMemberHeader(Out, "/<ECSYMBOLS>", now(Deterministic), 0, 0, 0,
64706c3fb27SDimitry Andric Size);
64806c3fb27SDimitry Andric
64906c3fb27SDimitry Andric printLE<uint32_t>(Out, SymMap.ECMap.size());
65006c3fb27SDimitry Andric
65106c3fb27SDimitry Andric for (auto S : SymMap.ECMap)
65206c3fb27SDimitry Andric printLE(Out, S.second);
65306c3fb27SDimitry Andric for (auto S : SymMap.ECMap)
65406c3fb27SDimitry Andric Out << S.first << '\0';
65506c3fb27SDimitry Andric while (Pad--)
65606c3fb27SDimitry Andric Out.write(uint8_t(0));
65706c3fb27SDimitry Andric }
65806c3fb27SDimitry Andric
isECObject(object::SymbolicFile & Obj)65906c3fb27SDimitry Andric static bool isECObject(object::SymbolicFile &Obj) {
66006c3fb27SDimitry Andric if (Obj.isCOFF())
66106c3fb27SDimitry Andric return cast<llvm::object::COFFObjectFile>(&Obj)->getMachine() !=
66206c3fb27SDimitry Andric COFF::IMAGE_FILE_MACHINE_ARM64;
66306c3fb27SDimitry Andric
6645f757f3fSDimitry Andric if (Obj.isCOFFImportFile())
6655f757f3fSDimitry Andric return cast<llvm::object::COFFImportFile>(&Obj)->getMachine() !=
6665f757f3fSDimitry Andric COFF::IMAGE_FILE_MACHINE_ARM64;
6675f757f3fSDimitry Andric
66806c3fb27SDimitry Andric if (Obj.isIR()) {
66906c3fb27SDimitry Andric Expected<std::string> TripleStr =
67006c3fb27SDimitry Andric getBitcodeTargetTriple(Obj.getMemoryBufferRef());
67106c3fb27SDimitry Andric if (!TripleStr)
67206c3fb27SDimitry Andric return false;
67306c3fb27SDimitry Andric Triple T(*TripleStr);
67406c3fb27SDimitry Andric return T.isWindowsArm64EC() || T.getArch() == Triple::x86_64;
67506c3fb27SDimitry Andric }
67606c3fb27SDimitry Andric
67706c3fb27SDimitry Andric return false;
67806c3fb27SDimitry Andric }
67906c3fb27SDimitry Andric
isImportDescriptor(StringRef Name)680439352acSDimitry Andric bool isImportDescriptor(StringRef Name) {
681439352acSDimitry Andric return Name.starts_with(ImportDescriptorPrefix) ||
682439352acSDimitry Andric Name == StringRef{NullImportDescriptorSymbolName} ||
683439352acSDimitry Andric (Name.starts_with(NullThunkDataPrefix) &&
684439352acSDimitry Andric Name.ends_with(NullThunkDataSuffix));
685439352acSDimitry Andric }
686439352acSDimitry Andric
getSymbols(SymbolicFile * Obj,uint16_t Index,raw_ostream & SymNames,SymMap * SymMap)6875f757f3fSDimitry Andric static Expected<std::vector<unsigned>> getSymbols(SymbolicFile *Obj,
6885f757f3fSDimitry Andric uint16_t Index,
6895f757f3fSDimitry Andric raw_ostream &SymNames,
6905f757f3fSDimitry Andric SymMap *SymMap) {
69106c3fb27SDimitry Andric std::vector<unsigned> Ret;
69206c3fb27SDimitry Andric
6935f757f3fSDimitry Andric if (Obj == nullptr)
694e8d8bef9SDimitry Andric return Ret;
6950b57cec5SDimitry Andric
69606c3fb27SDimitry Andric std::map<std::string, uint16_t> *Map = nullptr;
69706c3fb27SDimitry Andric if (SymMap)
69806c3fb27SDimitry Andric Map = SymMap->UseECMap && isECObject(*Obj) ? &SymMap->ECMap : &SymMap->Map;
6995f757f3fSDimitry Andric
7000b57cec5SDimitry Andric for (const object::BasicSymbolRef &S : Obj->symbols()) {
7010b57cec5SDimitry Andric if (!isArchiveSymbol(S))
7020b57cec5SDimitry Andric continue;
70306c3fb27SDimitry Andric if (Map) {
70406c3fb27SDimitry Andric std::string Name;
70506c3fb27SDimitry Andric raw_string_ostream NameStream(Name);
70606c3fb27SDimitry Andric if (Error E = S.printName(NameStream))
70706c3fb27SDimitry Andric return std::move(E);
70806c3fb27SDimitry Andric if (Map->find(Name) != Map->end())
70906c3fb27SDimitry Andric continue; // ignore duplicated symbol
71006c3fb27SDimitry Andric (*Map)[Name] = Index;
71106c3fb27SDimitry Andric if (Map == &SymMap->Map) {
71206c3fb27SDimitry Andric Ret.push_back(SymNames.tell());
71306c3fb27SDimitry Andric SymNames << Name << '\0';
714439352acSDimitry Andric // If EC is enabled, then the import descriptors are NOT put into EC
715439352acSDimitry Andric // objects so we need to copy them to the EC map manually.
716439352acSDimitry Andric if (SymMap->UseECMap && isImportDescriptor(Name))
717439352acSDimitry Andric SymMap->ECMap[Name] = Index;
71806c3fb27SDimitry Andric }
71906c3fb27SDimitry Andric } else {
7200b57cec5SDimitry Andric Ret.push_back(SymNames.tell());
7210b57cec5SDimitry Andric if (Error E = S.printName(SymNames))
7220b57cec5SDimitry Andric return std::move(E);
7230b57cec5SDimitry Andric SymNames << '\0';
7240b57cec5SDimitry Andric }
72506c3fb27SDimitry Andric }
7260b57cec5SDimitry Andric return Ret;
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric
7290b57cec5SDimitry Andric static Expected<std::vector<MemberData>>
computeMemberData(raw_ostream & StringTable,raw_ostream & SymNames,object::Archive::Kind Kind,bool Thin,bool Deterministic,SymtabWritingMode NeedSymbols,SymMap * SymMap,LLVMContext & Context,ArrayRef<NewArchiveMember> NewMembers)7300b57cec5SDimitry Andric computeMemberData(raw_ostream &StringTable, raw_ostream &SymNames,
7310b57cec5SDimitry Andric object::Archive::Kind Kind, bool Thin, bool Deterministic,
7325f757f3fSDimitry Andric SymtabWritingMode NeedSymbols, SymMap *SymMap,
7335f757f3fSDimitry Andric LLVMContext &Context, ArrayRef<NewArchiveMember> NewMembers) {
7340b57cec5SDimitry Andric static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
7355f757f3fSDimitry Andric uint64_t MemHeadPadSize = 0;
73681ad6265SDimitry Andric uint64_t Pos =
73781ad6265SDimitry Andric isAIXBigArchive(Kind) ? sizeof(object::BigArchive::FixLenHdr) : 0;
7380b57cec5SDimitry Andric
7390b57cec5SDimitry Andric std::vector<MemberData> Ret;
7400b57cec5SDimitry Andric bool HasObject = false;
7410b57cec5SDimitry Andric
7420b57cec5SDimitry Andric // Deduplicate long member names in the string table and reuse earlier name
7430b57cec5SDimitry Andric // offsets. This especially saves space for COFF Import libraries where all
7440b57cec5SDimitry Andric // members have the same name.
7450b57cec5SDimitry Andric StringMap<uint64_t> MemberNames;
7460b57cec5SDimitry Andric
7470b57cec5SDimitry Andric // UniqueTimestamps is a special case to improve debugging on Darwin:
7480b57cec5SDimitry Andric //
7490b57cec5SDimitry Andric // The Darwin linker does not link debug info into the final
7505f757f3fSDimitry Andric // binary. Instead, it emits entries of type N_OSO in the output
7510b57cec5SDimitry Andric // binary's symbol table, containing references to the linked-in
7520b57cec5SDimitry Andric // object files. Using that reference, the debugger can read the
7530b57cec5SDimitry Andric // debug data directly from the object files. Alternatively, an
7540b57cec5SDimitry Andric // invocation of 'dsymutil' will link the debug data from the object
7550b57cec5SDimitry Andric // files into a dSYM bundle, which can be loaded by the debugger,
7560b57cec5SDimitry Andric // instead of the object files.
7570b57cec5SDimitry Andric //
7580b57cec5SDimitry Andric // For an object file, the N_OSO entries contain the absolute path
7590b57cec5SDimitry Andric // path to the file, and the file's timestamp. For an object
7600b57cec5SDimitry Andric // included in an archive, the path is formatted like
7610b57cec5SDimitry Andric // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
7620b57cec5SDimitry Andric // archive member's timestamp, rather than the archive's timestamp.
7630b57cec5SDimitry Andric //
7640b57cec5SDimitry Andric // However, this doesn't always uniquely identify an object within
7650b57cec5SDimitry Andric // an archive -- an archive file can have multiple entries with the
7660b57cec5SDimitry Andric // same filename. (This will happen commonly if the original object
7670b57cec5SDimitry Andric // files started in different directories.) The only way they get
7680b57cec5SDimitry Andric // distinguished, then, is via the timestamp. But this process is
7690b57cec5SDimitry Andric // unable to find the correct object file in the archive when there
7700b57cec5SDimitry Andric // are two files of the same name and timestamp.
7710b57cec5SDimitry Andric //
7720b57cec5SDimitry Andric // Additionally, timestamp==0 is treated specially, and causes the
7730b57cec5SDimitry Andric // timestamp to be ignored as a match criteria.
7740b57cec5SDimitry Andric //
7750b57cec5SDimitry Andric // That will "usually" work out okay when creating an archive not in
7760b57cec5SDimitry Andric // deterministic timestamp mode, because the objects will probably
7770b57cec5SDimitry Andric // have been created at different timestamps.
7780b57cec5SDimitry Andric //
7790b57cec5SDimitry Andric // To ameliorate this problem, in deterministic archive mode (which
7800b57cec5SDimitry Andric // is the default), on Darwin we will emit a unique non-zero
7810b57cec5SDimitry Andric // timestamp for each entry with a duplicated name. This is still
7820b57cec5SDimitry Andric // deterministic: the only thing affecting that timestamp is the
7830b57cec5SDimitry Andric // order of the files in the resultant archive.
7840b57cec5SDimitry Andric //
7850b57cec5SDimitry Andric // See also the functions that handle the lookup:
7860b57cec5SDimitry Andric // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
7870b57cec5SDimitry Andric // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
7880b57cec5SDimitry Andric bool UniqueTimestamps = Deterministic && isDarwin(Kind);
7890b57cec5SDimitry Andric std::map<StringRef, unsigned> FilenameCount;
7900b57cec5SDimitry Andric if (UniqueTimestamps) {
7910b57cec5SDimitry Andric for (const NewArchiveMember &M : NewMembers)
7920b57cec5SDimitry Andric FilenameCount[M.MemberName]++;
7930b57cec5SDimitry Andric for (auto &Entry : FilenameCount)
7940b57cec5SDimitry Andric Entry.second = Entry.second > 1 ? 1 : 0;
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric
79781ad6265SDimitry Andric // The big archive format needs to know the offset of the previous member
79881ad6265SDimitry Andric // header.
79906c3fb27SDimitry Andric uint64_t PrevOffset = 0;
8005f757f3fSDimitry Andric uint64_t NextMemHeadPadSize = 0;
8015f757f3fSDimitry Andric std::unique_ptr<SymbolicFile> CurSymFile;
8025f757f3fSDimitry Andric std::unique_ptr<SymbolicFile> NextSymFile;
80306c3fb27SDimitry Andric uint16_t Index = 0;
8045f757f3fSDimitry Andric
8055f757f3fSDimitry Andric for (auto M = NewMembers.begin(); M < NewMembers.end(); ++M) {
8060b57cec5SDimitry Andric std::string Header;
8070b57cec5SDimitry Andric raw_string_ostream Out(Header);
8080b57cec5SDimitry Andric
8095f757f3fSDimitry Andric MemoryBufferRef Buf = M->Buf->getMemBufferRef();
8100b57cec5SDimitry Andric StringRef Data = Thin ? "" : Buf.getBuffer();
8110b57cec5SDimitry Andric
81206c3fb27SDimitry Andric Index++;
81306c3fb27SDimitry Andric
8140b57cec5SDimitry Andric // ld64 expects the members to be 8-byte aligned for 64-bit content and at
8150b57cec5SDimitry Andric // least 4-byte aligned for 32-bit content. Opt for the larger encoding
8160b57cec5SDimitry Andric // uniformly. This matches the behaviour with cctools and ensures that ld64
8170b57cec5SDimitry Andric // is happy with archives that we generate.
8180b57cec5SDimitry Andric unsigned MemberPadding =
8198bcb0991SDimitry Andric isDarwin(Kind) ? offsetToAlignment(Data.size(), Align(8)) : 0;
8208bcb0991SDimitry Andric unsigned TailPadding =
8218bcb0991SDimitry Andric offsetToAlignment(Data.size() + MemberPadding, Align(2));
8220b57cec5SDimitry Andric StringRef Padding = StringRef(PaddingData, MemberPadding + TailPadding);
8230b57cec5SDimitry Andric
8240b57cec5SDimitry Andric sys::TimePoint<std::chrono::seconds> ModTime;
8250b57cec5SDimitry Andric if (UniqueTimestamps)
8260b57cec5SDimitry Andric // Increment timestamp for each file of a given name.
8275f757f3fSDimitry Andric ModTime = sys::toTimePoint(FilenameCount[M->MemberName]++);
8280b57cec5SDimitry Andric else
8295f757f3fSDimitry Andric ModTime = M->ModTime;
8308bcb0991SDimitry Andric
8318bcb0991SDimitry Andric uint64_t Size = Buf.getBufferSize() + MemberPadding;
8328bcb0991SDimitry Andric if (Size > object::Archive::MaxMemberSize) {
8338bcb0991SDimitry Andric std::string StringMsg =
8345f757f3fSDimitry Andric "File " + M->MemberName.str() + " exceeds size limit";
8358bcb0991SDimitry Andric return make_error<object::GenericBinaryError>(
8368bcb0991SDimitry Andric std::move(StringMsg), object::object_error::parse_failed);
8378bcb0991SDimitry Andric }
8388bcb0991SDimitry Andric
8395f757f3fSDimitry Andric if (NeedSymbols != SymtabWritingMode::NoSymtab || isAIXBigArchive(Kind)) {
8405f757f3fSDimitry Andric auto SetNextSymFile = [&NextSymFile,
8415f757f3fSDimitry Andric &Context](MemoryBufferRef Buf,
8425f757f3fSDimitry Andric StringRef MemberName) -> Error {
8435f757f3fSDimitry Andric Expected<std::unique_ptr<SymbolicFile>> SymFileOrErr =
8445f757f3fSDimitry Andric getSymbolicFile(Buf, Context);
8455f757f3fSDimitry Andric if (!SymFileOrErr)
8465f757f3fSDimitry Andric return createFileError(MemberName, SymFileOrErr.takeError());
8475f757f3fSDimitry Andric NextSymFile = std::move(*SymFileOrErr);
8485f757f3fSDimitry Andric return Error::success();
8495f757f3fSDimitry Andric };
8505f757f3fSDimitry Andric
8515f757f3fSDimitry Andric if (M == NewMembers.begin())
8525f757f3fSDimitry Andric if (Error Err = SetNextSymFile(Buf, M->MemberName))
8535f757f3fSDimitry Andric return std::move(Err);
8545f757f3fSDimitry Andric
8555f757f3fSDimitry Andric CurSymFile = std::move(NextSymFile);
8565f757f3fSDimitry Andric
8575f757f3fSDimitry Andric if ((M + 1) != NewMembers.end())
8585f757f3fSDimitry Andric if (Error Err = SetNextSymFile((M + 1)->Buf->getMemBufferRef(),
8595f757f3fSDimitry Andric (M + 1)->MemberName))
8605f757f3fSDimitry Andric return std::move(Err);
8615f757f3fSDimitry Andric }
8625f757f3fSDimitry Andric
8635f757f3fSDimitry Andric // In the big archive file format, we need to calculate and include the next
8645f757f3fSDimitry Andric // member offset and previous member offset in the file member header.
86581ad6265SDimitry Andric if (isAIXBigArchive(Kind)) {
8665f757f3fSDimitry Andric uint64_t OffsetToMemData = Pos + sizeof(object::BigArMemHdrType) +
8675f757f3fSDimitry Andric alignTo(M->MemberName.size(), 2);
8685f757f3fSDimitry Andric
8695f757f3fSDimitry Andric if (M == NewMembers.begin())
8705f757f3fSDimitry Andric NextMemHeadPadSize =
8715f757f3fSDimitry Andric alignToPowerOf2(OffsetToMemData,
8725f757f3fSDimitry Andric getMemberAlignment(CurSymFile.get())) -
8735f757f3fSDimitry Andric OffsetToMemData;
8745f757f3fSDimitry Andric
8755f757f3fSDimitry Andric MemHeadPadSize = NextMemHeadPadSize;
8765f757f3fSDimitry Andric Pos += MemHeadPadSize;
87706c3fb27SDimitry Andric uint64_t NextOffset = Pos + sizeof(object::BigArMemHdrType) +
8785f757f3fSDimitry Andric alignTo(M->MemberName.size(), 2) + alignTo(Size, 2);
8795f757f3fSDimitry Andric
8805f757f3fSDimitry Andric // If there is another member file after this, we need to calculate the
8815f757f3fSDimitry Andric // padding before the header.
8825f757f3fSDimitry Andric if ((M + 1) != NewMembers.end()) {
8835f757f3fSDimitry Andric uint64_t OffsetToNextMemData = NextOffset +
8845f757f3fSDimitry Andric sizeof(object::BigArMemHdrType) +
8855f757f3fSDimitry Andric alignTo((M + 1)->MemberName.size(), 2);
8865f757f3fSDimitry Andric NextMemHeadPadSize =
8875f757f3fSDimitry Andric alignToPowerOf2(OffsetToNextMemData,
8885f757f3fSDimitry Andric getMemberAlignment(NextSymFile.get())) -
8895f757f3fSDimitry Andric OffsetToNextMemData;
8905f757f3fSDimitry Andric NextOffset += NextMemHeadPadSize;
8915f757f3fSDimitry Andric }
8925f757f3fSDimitry Andric printBigArchiveMemberHeader(Out, M->MemberName, ModTime, M->UID, M->GID,
8935f757f3fSDimitry Andric M->Perms, Size, PrevOffset, NextOffset);
89481ad6265SDimitry Andric PrevOffset = Pos;
89581ad6265SDimitry Andric } else {
8965f757f3fSDimitry Andric printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, *M,
8978bcb0991SDimitry Andric ModTime, Size);
89881ad6265SDimitry Andric }
8990b57cec5SDimitry Andric Out.flush();
9000b57cec5SDimitry Andric
901e8d8bef9SDimitry Andric std::vector<unsigned> Symbols;
9025f757f3fSDimitry Andric if (NeedSymbols != SymtabWritingMode::NoSymtab) {
903e8d8bef9SDimitry Andric Expected<std::vector<unsigned>> SymbolsOrErr =
9045f757f3fSDimitry Andric getSymbols(CurSymFile.get(), Index, SymNames, SymMap);
905bdd1243dSDimitry Andric if (!SymbolsOrErr)
9065f757f3fSDimitry Andric return createFileError(M->MemberName, SymbolsOrErr.takeError());
907e8d8bef9SDimitry Andric Symbols = std::move(*SymbolsOrErr);
9085f757f3fSDimitry Andric if (CurSymFile)
9095f757f3fSDimitry Andric HasObject = true;
910e8d8bef9SDimitry Andric }
9110b57cec5SDimitry Andric
9120b57cec5SDimitry Andric Pos += Header.size() + Data.size() + Padding.size();
9135f757f3fSDimitry Andric Ret.push_back({std::move(Symbols), std::move(Header), Data, Padding,
9145f757f3fSDimitry Andric MemHeadPadSize, std::move(CurSymFile)});
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric // If there are no symbols, emit an empty symbol table, to satisfy Solaris
9170b57cec5SDimitry Andric // tools, older versions of which expect a symbol table in a non-empty
9180b57cec5SDimitry Andric // archive, regardless of whether there are any symbols in it.
91906c3fb27SDimitry Andric if (HasObject && SymNames.tell() == 0 && !isCOFFArchive(Kind))
9200b57cec5SDimitry Andric SymNames << '\0' << '\0' << '\0';
9215f757f3fSDimitry Andric return std::move(Ret);
9220b57cec5SDimitry Andric }
9230b57cec5SDimitry Andric
9240b57cec5SDimitry Andric namespace llvm {
9250b57cec5SDimitry Andric
canonicalizePath(StringRef P)9260b57cec5SDimitry Andric static ErrorOr<SmallString<128>> canonicalizePath(StringRef P) {
9270b57cec5SDimitry Andric SmallString<128> Ret = P;
9280b57cec5SDimitry Andric std::error_code Err = sys::fs::make_absolute(Ret);
9290b57cec5SDimitry Andric if (Err)
9300b57cec5SDimitry Andric return Err;
9310b57cec5SDimitry Andric sys::path::remove_dots(Ret, /*removedotdot*/ true);
9320b57cec5SDimitry Andric return Ret;
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric
9350b57cec5SDimitry Andric // Compute the relative path from From to To.
computeArchiveRelativePath(StringRef From,StringRef To)9360b57cec5SDimitry Andric Expected<std::string> computeArchiveRelativePath(StringRef From, StringRef To) {
9370b57cec5SDimitry Andric ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
9380b57cec5SDimitry Andric ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
9390b57cec5SDimitry Andric if (!PathToOrErr || !DirFromOrErr)
9400b57cec5SDimitry Andric return errorCodeToError(std::error_code(errno, std::generic_category()));
9410b57cec5SDimitry Andric
9420b57cec5SDimitry Andric const SmallString<128> &PathTo = *PathToOrErr;
9430b57cec5SDimitry Andric const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
9440b57cec5SDimitry Andric
9450b57cec5SDimitry Andric // Can't construct a relative path between different roots
9460b57cec5SDimitry Andric if (sys::path::root_name(PathTo) != sys::path::root_name(DirFrom))
9470b57cec5SDimitry Andric return sys::path::convert_to_slash(PathTo);
9480b57cec5SDimitry Andric
9490b57cec5SDimitry Andric // Skip common prefixes
9500b57cec5SDimitry Andric auto FromTo =
9510b57cec5SDimitry Andric std::mismatch(sys::path::begin(DirFrom), sys::path::end(DirFrom),
9520b57cec5SDimitry Andric sys::path::begin(PathTo));
9530b57cec5SDimitry Andric auto FromI = FromTo.first;
9540b57cec5SDimitry Andric auto ToI = FromTo.second;
9550b57cec5SDimitry Andric
9560b57cec5SDimitry Andric // Construct relative path
9570b57cec5SDimitry Andric SmallString<128> Relative;
9580b57cec5SDimitry Andric for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
9590b57cec5SDimitry Andric sys::path::append(Relative, sys::path::Style::posix, "..");
9600b57cec5SDimitry Andric
9610b57cec5SDimitry Andric for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
9620b57cec5SDimitry Andric sys::path::append(Relative, sys::path::Style::posix, *ToI);
9630b57cec5SDimitry Andric
9647a6dacacSDimitry Andric return std::string(Relative);
9650b57cec5SDimitry Andric }
9660b57cec5SDimitry Andric
writeArchiveToStream(raw_ostream & Out,ArrayRef<NewArchiveMember> NewMembers,SymtabWritingMode WriteSymtab,object::Archive::Kind Kind,bool Deterministic,bool Thin,bool IsEC)967e8d8bef9SDimitry Andric static Error writeArchiveToStream(raw_ostream &Out,
968e8d8bef9SDimitry Andric ArrayRef<NewArchiveMember> NewMembers,
9695f757f3fSDimitry Andric SymtabWritingMode WriteSymtab,
9705f757f3fSDimitry Andric object::Archive::Kind Kind,
97106c3fb27SDimitry Andric bool Deterministic, bool Thin, bool IsEC) {
9720b57cec5SDimitry Andric assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
9730b57cec5SDimitry Andric
9740b57cec5SDimitry Andric SmallString<0> SymNamesBuf;
9750b57cec5SDimitry Andric raw_svector_ostream SymNames(SymNamesBuf);
9760b57cec5SDimitry Andric SmallString<0> StringTableBuf;
9770b57cec5SDimitry Andric raw_svector_ostream StringTable(StringTableBuf);
97806c3fb27SDimitry Andric SymMap SymMap;
9790b57cec5SDimitry Andric
98006c3fb27SDimitry Andric // COFF symbol map uses 16-bit indexes, so we can't use it if there are too
98106c3fb27SDimitry Andric // many members.
98206c3fb27SDimitry Andric if (isCOFFArchive(Kind) && NewMembers.size() > 0xfffe)
98306c3fb27SDimitry Andric Kind = object::Archive::K_GNU;
98406c3fb27SDimitry Andric
9855f757f3fSDimitry Andric // In the scenario when LLVMContext is populated SymbolicFile will contain a
9865f757f3fSDimitry Andric // reference to it, thus SymbolicFile should be destroyed first.
9875f757f3fSDimitry Andric LLVMContext Context;
9885f757f3fSDimitry Andric
98906c3fb27SDimitry Andric SymMap.UseECMap = IsEC;
99006c3fb27SDimitry Andric Expected<std::vector<MemberData>> DataOrErr = computeMemberData(
99106c3fb27SDimitry Andric StringTable, SymNames, Kind, Thin, Deterministic, WriteSymtab,
9925f757f3fSDimitry Andric isCOFFArchive(Kind) ? &SymMap : nullptr, Context, NewMembers);
9930b57cec5SDimitry Andric if (Error E = DataOrErr.takeError())
9940b57cec5SDimitry Andric return E;
9950b57cec5SDimitry Andric std::vector<MemberData> &Data = *DataOrErr;
9960b57cec5SDimitry Andric
99706c3fb27SDimitry Andric uint64_t StringTableSize = 0;
99806c3fb27SDimitry Andric MemberData StringTableMember;
99906c3fb27SDimitry Andric if (!StringTableBuf.empty() && !isAIXBigArchive(Kind)) {
100006c3fb27SDimitry Andric StringTableMember = computeStringTable(StringTableBuf);
100106c3fb27SDimitry Andric StringTableSize = StringTableMember.Header.size() +
100206c3fb27SDimitry Andric StringTableMember.Data.size() +
100306c3fb27SDimitry Andric StringTableMember.Padding.size();
100406c3fb27SDimitry Andric }
10050b57cec5SDimitry Andric
10060b57cec5SDimitry Andric // We would like to detect if we need to switch to a 64-bit symbol table.
100706c3fb27SDimitry Andric uint64_t LastMemberEndOffset = 0;
100806c3fb27SDimitry Andric uint64_t LastMemberHeaderOffset = 0;
1009e8d8bef9SDimitry Andric uint64_t NumSyms = 0;
101006c3fb27SDimitry Andric uint64_t NumSyms32 = 0; // Store symbol number of 32-bit member files.
10115f757f3fSDimitry Andric bool ShouldWriteSymtab = WriteSymtab != SymtabWritingMode::NoSymtab;
101206c3fb27SDimitry Andric
10130b57cec5SDimitry Andric for (const auto &M : Data) {
10140b57cec5SDimitry Andric // Record the start of the member's offset
10155f757f3fSDimitry Andric LastMemberEndOffset += M.PreHeadPadSize;
101681ad6265SDimitry Andric LastMemberHeaderOffset = LastMemberEndOffset;
10170b57cec5SDimitry Andric // Account for the size of each part associated with the member.
101881ad6265SDimitry Andric LastMemberEndOffset += M.Header.size() + M.Data.size() + M.Padding.size();
1019e8d8bef9SDimitry Andric NumSyms += M.Symbols.size();
102006c3fb27SDimitry Andric
102106c3fb27SDimitry Andric // AIX big archive files may contain two global symbol tables. The
102206c3fb27SDimitry Andric // first global symbol table locates 32-bit file members that define global
102306c3fb27SDimitry Andric // symbols; the second global symbol table does the same for 64-bit file
102406c3fb27SDimitry Andric // members. As a big archive can have both 32-bit and 64-bit file members,
102506c3fb27SDimitry Andric // we need to know the number of symbols in each symbol table individually.
10265f757f3fSDimitry Andric if (isAIXBigArchive(Kind) && ShouldWriteSymtab) {
10275f757f3fSDimitry Andric if (!is64BitSymbolicFile(M.SymFile.get()))
102806c3fb27SDimitry Andric NumSyms32 += M.Symbols.size();
10290b57cec5SDimitry Andric }
103006c3fb27SDimitry Andric }
103106c3fb27SDimitry Andric
103206c3fb27SDimitry Andric std::optional<uint64_t> HeadersSize;
10330b57cec5SDimitry Andric
103481ad6265SDimitry Andric // The symbol table is put at the end of the big archive file. The symbol
103581ad6265SDimitry Andric // table is at the start of the archive file for other archive formats.
10365f757f3fSDimitry Andric if (ShouldWriteSymtab && !is64BitKind(Kind)) {
1037e8d8bef9SDimitry Andric // We assume 32-bit offsets to see if 32-bit symbols are possible or not.
103806c3fb27SDimitry Andric HeadersSize = computeHeadersSize(Kind, Data.size(), StringTableSize,
103906c3fb27SDimitry Andric NumSyms, SymNamesBuf.size(),
104006c3fb27SDimitry Andric isCOFFArchive(Kind) ? &SymMap : nullptr);
1041e8d8bef9SDimitry Andric
10420b57cec5SDimitry Andric // The SYM64 format is used when an archive's member offsets are larger than
10430b57cec5SDimitry Andric // 32-bits can hold. The need for this shift in format is detected by
10440b57cec5SDimitry Andric // writeArchive. To test this we need to generate a file with a member that
10450b57cec5SDimitry Andric // has an offset larger than 32-bits but this demands a very slow test. To
10460b57cec5SDimitry Andric // speed the test up we use this environment variable to pretend like the
10470b57cec5SDimitry Andric // cutoff happens before 32-bits and instead happens at some much smaller
10480b57cec5SDimitry Andric // value.
1049e8d8bef9SDimitry Andric uint64_t Sym64Threshold = 1ULL << 32;
10500b57cec5SDimitry Andric const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
10510b57cec5SDimitry Andric if (Sym64Env)
10520b57cec5SDimitry Andric StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
10530b57cec5SDimitry Andric
105481ad6265SDimitry Andric // If LastMemberHeaderOffset isn't going to fit in a 32-bit varible we need
105581ad6265SDimitry Andric // to switch to 64-bit. Note that the file can be larger than 4GB as long as
105681ad6265SDimitry Andric // the last member starts before the 4GB offset.
105706c3fb27SDimitry Andric if (*HeadersSize + LastMemberHeaderOffset >= Sym64Threshold) {
10580b57cec5SDimitry Andric if (Kind == object::Archive::K_DARWIN)
10590b57cec5SDimitry Andric Kind = object::Archive::K_DARWIN64;
10600b57cec5SDimitry Andric else
10610b57cec5SDimitry Andric Kind = object::Archive::K_GNU64;
106206c3fb27SDimitry Andric HeadersSize.reset();
10630b57cec5SDimitry Andric }
10640b57cec5SDimitry Andric }
10650b57cec5SDimitry Andric
10660b57cec5SDimitry Andric if (Thin)
10670b57cec5SDimitry Andric Out << "!<thin>\n";
106881ad6265SDimitry Andric else if (isAIXBigArchive(Kind))
106981ad6265SDimitry Andric Out << "<bigaf>\n";
10700b57cec5SDimitry Andric else
10710b57cec5SDimitry Andric Out << "!<arch>\n";
10720b57cec5SDimitry Andric
107381ad6265SDimitry Andric if (!isAIXBigArchive(Kind)) {
10745f757f3fSDimitry Andric if (ShouldWriteSymtab) {
107506c3fb27SDimitry Andric if (!HeadersSize)
107606c3fb27SDimitry Andric HeadersSize = computeHeadersSize(
107706c3fb27SDimitry Andric Kind, Data.size(), StringTableSize, NumSyms, SymNamesBuf.size(),
107806c3fb27SDimitry Andric isCOFFArchive(Kind) ? &SymMap : nullptr);
107906c3fb27SDimitry Andric writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf,
108006c3fb27SDimitry Andric *HeadersSize, NumSyms);
108106c3fb27SDimitry Andric
108206c3fb27SDimitry Andric if (isCOFFArchive(Kind))
108306c3fb27SDimitry Andric writeSymbolMap(Out, Kind, Deterministic, Data, SymMap, *HeadersSize);
108406c3fb27SDimitry Andric }
108506c3fb27SDimitry Andric
108606c3fb27SDimitry Andric if (StringTableSize)
108706c3fb27SDimitry Andric Out << StringTableMember.Header << StringTableMember.Data
108806c3fb27SDimitry Andric << StringTableMember.Padding;
108906c3fb27SDimitry Andric
10905f757f3fSDimitry Andric if (ShouldWriteSymtab && SymMap.ECMap.size())
109106c3fb27SDimitry Andric writeECSymbols(Out, Kind, Deterministic, Data, SymMap);
109206c3fb27SDimitry Andric
10930b57cec5SDimitry Andric for (const MemberData &M : Data)
10940b57cec5SDimitry Andric Out << M.Header << M.Data << M.Padding;
109581ad6265SDimitry Andric } else {
109606c3fb27SDimitry Andric HeadersSize = sizeof(object::BigArchive::FixLenHdr);
109706c3fb27SDimitry Andric LastMemberEndOffset += *HeadersSize;
109806c3fb27SDimitry Andric LastMemberHeaderOffset += *HeadersSize;
109906c3fb27SDimitry Andric
110081ad6265SDimitry Andric // For the big archive (AIX) format, compute a table of member names and
110181ad6265SDimitry Andric // offsets, used in the member table.
110281ad6265SDimitry Andric uint64_t MemberTableNameStrTblSize = 0;
110381ad6265SDimitry Andric std::vector<size_t> MemberOffsets;
110481ad6265SDimitry Andric std::vector<StringRef> MemberNames;
110581ad6265SDimitry Andric // Loop across object to find offset and names.
110681ad6265SDimitry Andric uint64_t MemberEndOffset = sizeof(object::BigArchive::FixLenHdr);
110781ad6265SDimitry Andric for (size_t I = 0, Size = NewMembers.size(); I != Size; ++I) {
110881ad6265SDimitry Andric const NewArchiveMember &Member = NewMembers[I];
110981ad6265SDimitry Andric MemberTableNameStrTblSize += Member.MemberName.size() + 1;
11105f757f3fSDimitry Andric MemberEndOffset += Data[I].PreHeadPadSize;
111181ad6265SDimitry Andric MemberOffsets.push_back(MemberEndOffset);
111281ad6265SDimitry Andric MemberNames.push_back(Member.MemberName);
111381ad6265SDimitry Andric // File member name ended with "`\n". The length is included in
111481ad6265SDimitry Andric // BigArMemHdrType.
111581ad6265SDimitry Andric MemberEndOffset += sizeof(object::BigArMemHdrType) +
111681ad6265SDimitry Andric alignTo(Data[I].Data.size(), 2) +
111781ad6265SDimitry Andric alignTo(Member.MemberName.size(), 2);
111881ad6265SDimitry Andric }
11190b57cec5SDimitry Andric
112081ad6265SDimitry Andric // AIX member table size.
112106c3fb27SDimitry Andric uint64_t MemberTableSize = 20 + // Number of members field
112281ad6265SDimitry Andric 20 * MemberOffsets.size() +
112381ad6265SDimitry Andric MemberTableNameStrTblSize;
112481ad6265SDimitry Andric
112506c3fb27SDimitry Andric SmallString<0> SymNamesBuf32;
112606c3fb27SDimitry Andric SmallString<0> SymNamesBuf64;
112706c3fb27SDimitry Andric raw_svector_ostream SymNames32(SymNamesBuf32);
112806c3fb27SDimitry Andric raw_svector_ostream SymNames64(SymNamesBuf64);
112906c3fb27SDimitry Andric
11305f757f3fSDimitry Andric if (ShouldWriteSymtab && NumSyms)
113106c3fb27SDimitry Andric // Generate the symbol names for the members.
11325f757f3fSDimitry Andric for (const auto &M : Data) {
11335f757f3fSDimitry Andric Expected<std::vector<unsigned>> SymbolsOrErr = getSymbols(
11345f757f3fSDimitry Andric M.SymFile.get(), 0,
11355f757f3fSDimitry Andric is64BitSymbolicFile(M.SymFile.get()) ? SymNames64 : SymNames32,
11365f757f3fSDimitry Andric nullptr);
113706c3fb27SDimitry Andric if (!SymbolsOrErr)
113806c3fb27SDimitry Andric return SymbolsOrErr.takeError();
113906c3fb27SDimitry Andric }
114006c3fb27SDimitry Andric
114106c3fb27SDimitry Andric uint64_t MemberTableEndOffset =
114206c3fb27SDimitry Andric LastMemberEndOffset +
114306c3fb27SDimitry Andric alignTo(sizeof(object::BigArMemHdrType) + MemberTableSize, 2);
114406c3fb27SDimitry Andric
114506c3fb27SDimitry Andric // In AIX OS, The 'GlobSymOffset' field in the fixed-length header contains
114606c3fb27SDimitry Andric // the offset to the 32-bit global symbol table, and the 'GlobSym64Offset'
114706c3fb27SDimitry Andric // contains the offset to the 64-bit global symbol table.
114806c3fb27SDimitry Andric uint64_t GlobalSymbolOffset =
11495f757f3fSDimitry Andric (ShouldWriteSymtab &&
11505f757f3fSDimitry Andric (WriteSymtab != SymtabWritingMode::BigArchive64) && NumSyms32 > 0)
11515f757f3fSDimitry Andric ? MemberTableEndOffset
11525f757f3fSDimitry Andric : 0;
115306c3fb27SDimitry Andric
115406c3fb27SDimitry Andric uint64_t GlobalSymbolOffset64 = 0;
115506c3fb27SDimitry Andric uint64_t NumSyms64 = NumSyms - NumSyms32;
11565f757f3fSDimitry Andric if (ShouldWriteSymtab && (WriteSymtab != SymtabWritingMode::BigArchive32) &&
11575f757f3fSDimitry Andric NumSyms64 > 0) {
115806c3fb27SDimitry Andric if (GlobalSymbolOffset == 0)
115906c3fb27SDimitry Andric GlobalSymbolOffset64 = MemberTableEndOffset;
116006c3fb27SDimitry Andric else
116106c3fb27SDimitry Andric // If there is a global symbol table for 32-bit members,
116206c3fb27SDimitry Andric // the 64-bit global symbol table is after the 32-bit one.
116306c3fb27SDimitry Andric GlobalSymbolOffset64 =
116406c3fb27SDimitry Andric GlobalSymbolOffset + sizeof(object::BigArMemHdrType) +
116506c3fb27SDimitry Andric (NumSyms32 + 1) * 8 + alignTo(SymNamesBuf32.size(), 2);
116606c3fb27SDimitry Andric }
116781ad6265SDimitry Andric
116881ad6265SDimitry Andric // Fixed Sized Header.
116981ad6265SDimitry Andric printWithSpacePadding(Out, NewMembers.size() ? LastMemberEndOffset : 0,
117081ad6265SDimitry Andric 20); // Offset to member table
117181ad6265SDimitry Andric // If there are no file members in the archive, there will be no global
117281ad6265SDimitry Andric // symbol table.
117306c3fb27SDimitry Andric printWithSpacePadding(Out, GlobalSymbolOffset, 20);
117406c3fb27SDimitry Andric printWithSpacePadding(Out, GlobalSymbolOffset64, 20);
11755f757f3fSDimitry Andric printWithSpacePadding(Out,
11765f757f3fSDimitry Andric NewMembers.size()
11775f757f3fSDimitry Andric ? sizeof(object::BigArchive::FixLenHdr) +
11785f757f3fSDimitry Andric Data[0].PreHeadPadSize
11795f757f3fSDimitry Andric : 0,
118081ad6265SDimitry Andric 20); // Offset to first archive member
118181ad6265SDimitry Andric printWithSpacePadding(Out, NewMembers.size() ? LastMemberHeaderOffset : 0,
118281ad6265SDimitry Andric 20); // Offset to last archive member
118381ad6265SDimitry Andric printWithSpacePadding(
118481ad6265SDimitry Andric Out, 0,
118581ad6265SDimitry Andric 20); // Offset to first member of free list - Not supported yet
118681ad6265SDimitry Andric
118781ad6265SDimitry Andric for (const MemberData &M : Data) {
11885f757f3fSDimitry Andric Out << std::string(M.PreHeadPadSize, '\0');
118981ad6265SDimitry Andric Out << M.Header << M.Data;
119081ad6265SDimitry Andric if (M.Data.size() % 2)
119181ad6265SDimitry Andric Out << '\0';
119281ad6265SDimitry Andric }
119381ad6265SDimitry Andric
119481ad6265SDimitry Andric if (NewMembers.size()) {
119581ad6265SDimitry Andric // Member table.
119681ad6265SDimitry Andric printBigArchiveMemberHeader(Out, "", sys::toTimePoint(0), 0, 0, 0,
119781ad6265SDimitry Andric MemberTableSize, LastMemberHeaderOffset,
119806c3fb27SDimitry Andric GlobalSymbolOffset ? GlobalSymbolOffset
119906c3fb27SDimitry Andric : GlobalSymbolOffset64);
120081ad6265SDimitry Andric printWithSpacePadding(Out, MemberOffsets.size(), 20); // Number of members
120181ad6265SDimitry Andric for (uint64_t MemberOffset : MemberOffsets)
120281ad6265SDimitry Andric printWithSpacePadding(Out, MemberOffset,
120381ad6265SDimitry Andric 20); // Offset to member file header.
120481ad6265SDimitry Andric for (StringRef MemberName : MemberNames)
120581ad6265SDimitry Andric Out << MemberName << '\0'; // Member file name, null byte padding.
120681ad6265SDimitry Andric
120781ad6265SDimitry Andric if (MemberTableNameStrTblSize % 2)
120881ad6265SDimitry Andric Out << '\0'; // Name table must be tail padded to an even number of
120981ad6265SDimitry Andric // bytes.
121081ad6265SDimitry Andric
12115f757f3fSDimitry Andric if (ShouldWriteSymtab) {
121206c3fb27SDimitry Andric // Write global symbol table for 32-bit file members.
121306c3fb27SDimitry Andric if (GlobalSymbolOffset) {
121406c3fb27SDimitry Andric writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf32,
121506c3fb27SDimitry Andric *HeadersSize, NumSyms32, LastMemberEndOffset,
121606c3fb27SDimitry Andric GlobalSymbolOffset64);
121706c3fb27SDimitry Andric // Add padding between the symbol tables, if needed.
121806c3fb27SDimitry Andric if (GlobalSymbolOffset64 && (SymNamesBuf32.size() % 2))
121906c3fb27SDimitry Andric Out << '\0';
122006c3fb27SDimitry Andric }
122106c3fb27SDimitry Andric
122206c3fb27SDimitry Andric // Write global symbol table for 64-bit file members.
122306c3fb27SDimitry Andric if (GlobalSymbolOffset64)
122406c3fb27SDimitry Andric writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf64,
122506c3fb27SDimitry Andric *HeadersSize, NumSyms64,
122606c3fb27SDimitry Andric GlobalSymbolOffset ? GlobalSymbolOffset
122706c3fb27SDimitry Andric : LastMemberEndOffset,
122806c3fb27SDimitry Andric 0, true);
122906c3fb27SDimitry Andric }
123081ad6265SDimitry Andric }
123181ad6265SDimitry Andric }
12320b57cec5SDimitry Andric Out.flush();
1233e8d8bef9SDimitry Andric return Error::success();
1234e8d8bef9SDimitry Andric }
1235e8d8bef9SDimitry Andric
writeArchive(StringRef ArcName,ArrayRef<NewArchiveMember> NewMembers,SymtabWritingMode WriteSymtab,object::Archive::Kind Kind,bool Deterministic,bool Thin,std::unique_ptr<MemoryBuffer> OldArchiveBuf,bool IsEC)1236e8d8bef9SDimitry Andric Error writeArchive(StringRef ArcName, ArrayRef<NewArchiveMember> NewMembers,
12375f757f3fSDimitry Andric SymtabWritingMode WriteSymtab, object::Archive::Kind Kind,
1238e8d8bef9SDimitry Andric bool Deterministic, bool Thin,
123906c3fb27SDimitry Andric std::unique_ptr<MemoryBuffer> OldArchiveBuf, bool IsEC) {
1240e8d8bef9SDimitry Andric Expected<sys::fs::TempFile> Temp =
1241e8d8bef9SDimitry Andric sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
1242e8d8bef9SDimitry Andric if (!Temp)
1243e8d8bef9SDimitry Andric return Temp.takeError();
1244e8d8bef9SDimitry Andric raw_fd_ostream Out(Temp->FD, false);
1245e8d8bef9SDimitry Andric
1246e8d8bef9SDimitry Andric if (Error E = writeArchiveToStream(Out, NewMembers, WriteSymtab, Kind,
124706c3fb27SDimitry Andric Deterministic, Thin, IsEC)) {
1248e8d8bef9SDimitry Andric if (Error DiscardError = Temp->discard())
1249e8d8bef9SDimitry Andric return joinErrors(std::move(E), std::move(DiscardError));
1250e8d8bef9SDimitry Andric return E;
1251e8d8bef9SDimitry Andric }
12520b57cec5SDimitry Andric
12530b57cec5SDimitry Andric // At this point, we no longer need whatever backing memory
12540b57cec5SDimitry Andric // was used to generate the NewMembers. On Windows, this buffer
12550b57cec5SDimitry Andric // could be a mapped view of the file we want to replace (if
12560b57cec5SDimitry Andric // we're updating an existing archive, say). In that case, the
12570b57cec5SDimitry Andric // rename would still succeed, but it would leave behind a
12580b57cec5SDimitry Andric // temporary file (actually the original file renamed) because
12590b57cec5SDimitry Andric // a file cannot be deleted while there's a handle open on it,
12600b57cec5SDimitry Andric // only renamed. So by freeing this buffer, this ensures that
12610b57cec5SDimitry Andric // the last open handle on the destination file, if any, is
12620b57cec5SDimitry Andric // closed before we attempt to rename.
12630b57cec5SDimitry Andric OldArchiveBuf.reset();
12640b57cec5SDimitry Andric
12650b57cec5SDimitry Andric return Temp->keep(ArcName);
12660b57cec5SDimitry Andric }
12670b57cec5SDimitry Andric
1268e8d8bef9SDimitry Andric Expected<std::unique_ptr<MemoryBuffer>>
writeArchiveToBuffer(ArrayRef<NewArchiveMember> NewMembers,SymtabWritingMode WriteSymtab,object::Archive::Kind Kind,bool Deterministic,bool Thin)12695f757f3fSDimitry Andric writeArchiveToBuffer(ArrayRef<NewArchiveMember> NewMembers,
12705f757f3fSDimitry Andric SymtabWritingMode WriteSymtab, object::Archive::Kind Kind,
12715f757f3fSDimitry Andric bool Deterministic, bool Thin) {
1272e8d8bef9SDimitry Andric SmallVector<char, 0> ArchiveBufferVector;
1273e8d8bef9SDimitry Andric raw_svector_ostream ArchiveStream(ArchiveBufferVector);
1274e8d8bef9SDimitry Andric
1275e8d8bef9SDimitry Andric if (Error E = writeArchiveToStream(ArchiveStream, NewMembers, WriteSymtab,
127606c3fb27SDimitry Andric Kind, Deterministic, Thin, false))
1277e8d8bef9SDimitry Andric return std::move(E);
1278e8d8bef9SDimitry Andric
1279e8d8bef9SDimitry Andric return std::make_unique<SmallVectorMemoryBuffer>(
12800eae32dcSDimitry Andric std::move(ArchiveBufferVector), /*RequiresNullTerminator=*/false);
1281e8d8bef9SDimitry Andric }
1282e8d8bef9SDimitry Andric
12830b57cec5SDimitry Andric } // namespace llvm
1284