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/StringMap.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/BinaryFormat/Magic.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/Object/Archive.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Object/COFFImportFile.h"
22 #include "llvm/Object/Error.h"
23 #include "llvm/Object/IRObjectFile.h"
24 #include "llvm/Object/MachO.h"
25 #include "llvm/Object/ObjectFile.h"
26 #include "llvm/Object/SymbolicFile.h"
27 #include "llvm/Object/XCOFFObjectFile.h"
28 #include "llvm/Support/Alignment.h"
29 #include "llvm/Support/EndianStream.h"
30 #include "llvm/Support/Errc.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SmallVectorMemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
41 #if !defined(_MSC_VER) && !defined(__MINGW32__)
48 using namespace llvm::object
;
52 std::map
<std::string
, uint16_t> Map
;
53 std::map
<std::string
, uint16_t> ECMap
;
56 NewArchiveMember::NewArchiveMember(MemoryBufferRef BufRef
)
57 : Buf(MemoryBuffer::getMemBuffer(BufRef
, false)),
58 MemberName(BufRef
.getBufferIdentifier()) {}
60 object::Archive::Kind
NewArchiveMember::detectKindFromObject() const {
61 auto MemBufferRef
= this->Buf
->getMemBufferRef();
62 Expected
<std::unique_ptr
<object::ObjectFile
>> OptionalObject
=
63 object::ObjectFile::createObjectFile(MemBufferRef
);
66 return isa
<object::MachOObjectFile
>(**OptionalObject
)
67 ? object::Archive::K_DARWIN
68 : (isa
<object::XCOFFObjectFile
>(**OptionalObject
)
69 ? object::Archive::K_AIXBIG
70 : object::Archive::K_GNU
);
72 // Squelch the error in case we had a non-object file.
73 consumeError(OptionalObject
.takeError());
75 // If we're adding a bitcode file to the archive, detect the Archive kind
76 // based on the target triple.
78 if (identify_magic(MemBufferRef
.getBuffer()) == file_magic::bitcode
) {
79 if (auto ObjOrErr
= object::SymbolicFile::createSymbolicFile(
80 MemBufferRef
, file_magic::bitcode
, &Context
)) {
81 auto &IRObject
= cast
<object::IRObjectFile
>(**ObjOrErr
);
82 auto TargetTriple
= Triple(IRObject
.getTargetTriple());
83 return TargetTriple
.isOSDarwin()
84 ? object::Archive::K_DARWIN
85 : (TargetTriple
.isOSAIX() ? object::Archive::K_AIXBIG
86 : object::Archive::K_GNU
);
88 // Squelch the error in case this was not a SymbolicFile.
89 consumeError(ObjOrErr
.takeError());
93 return object::Archive::getDefaultKindForHost();
96 Expected
<NewArchiveMember
>
97 NewArchiveMember::getOldMember(const object::Archive::Child
&OldMember
,
99 Expected
<llvm::MemoryBufferRef
> BufOrErr
= OldMember
.getMemoryBufferRef();
101 return BufOrErr
.takeError();
104 M
.Buf
= MemoryBuffer::getMemBuffer(*BufOrErr
, false);
105 M
.MemberName
= M
.Buf
->getBufferIdentifier();
106 if (!Deterministic
) {
107 auto ModTimeOrErr
= OldMember
.getLastModified();
109 return ModTimeOrErr
.takeError();
110 M
.ModTime
= ModTimeOrErr
.get();
111 Expected
<unsigned> UIDOrErr
= OldMember
.getUID();
113 return UIDOrErr
.takeError();
114 M
.UID
= UIDOrErr
.get();
115 Expected
<unsigned> GIDOrErr
= OldMember
.getGID();
117 return GIDOrErr
.takeError();
118 M
.GID
= GIDOrErr
.get();
119 Expected
<sys::fs::perms
> AccessModeOrErr
= OldMember
.getAccessMode();
120 if (!AccessModeOrErr
)
121 return AccessModeOrErr
.takeError();
122 M
.Perms
= AccessModeOrErr
.get();
127 Expected
<NewArchiveMember
> NewArchiveMember::getFile(StringRef FileName
,
128 bool Deterministic
) {
129 sys::fs::file_status Status
;
130 auto FDOrErr
= sys::fs::openNativeFileForRead(FileName
);
132 return FDOrErr
.takeError();
133 sys::fs::file_t FD
= *FDOrErr
;
134 assert(FD
!= sys::fs::kInvalidFile
);
136 if (auto EC
= sys::fs::status(FD
, Status
))
137 return errorCodeToError(EC
);
139 // Opening a directory doesn't make sense. Let it fail.
140 // Linux cannot open directories with open(2), although
141 // cygwin and *bsd can.
142 if (Status
.type() == sys::fs::file_type::directory_file
)
143 return errorCodeToError(make_error_code(errc::is_a_directory
));
145 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> MemberBufferOrErr
=
146 MemoryBuffer::getOpenFile(FD
, FileName
, Status
.getSize(), false);
147 if (!MemberBufferOrErr
)
148 return errorCodeToError(MemberBufferOrErr
.getError());
150 if (auto EC
= sys::fs::closeFile(FD
))
151 return errorCodeToError(EC
);
154 M
.Buf
= std::move(*MemberBufferOrErr
);
155 M
.MemberName
= M
.Buf
->getBufferIdentifier();
156 if (!Deterministic
) {
157 M
.ModTime
= std::chrono::time_point_cast
<std::chrono::seconds
>(
158 Status
.getLastModificationTime());
159 M
.UID
= Status
.getUser();
160 M
.GID
= Status
.getGroup();
161 M
.Perms
= Status
.permissions();
166 template <typename T
>
167 static void printWithSpacePadding(raw_ostream
&OS
, T Data
, unsigned Size
) {
168 uint64_t OldPos
= OS
.tell();
170 unsigned SizeSoFar
= OS
.tell() - OldPos
;
171 assert(SizeSoFar
<= Size
&& "Data doesn't fit in Size");
172 OS
.indent(Size
- SizeSoFar
);
175 static bool isDarwin(object::Archive::Kind Kind
) {
176 return Kind
== object::Archive::K_DARWIN
||
177 Kind
== object::Archive::K_DARWIN64
;
180 static bool isAIXBigArchive(object::Archive::Kind Kind
) {
181 return Kind
== object::Archive::K_AIXBIG
;
184 static bool isCOFFArchive(object::Archive::Kind Kind
) {
185 return Kind
== object::Archive::K_COFF
;
188 static bool isBSDLike(object::Archive::Kind Kind
) {
190 case object::Archive::K_GNU
:
191 case object::Archive::K_GNU64
:
192 case object::Archive::K_AIXBIG
:
193 case object::Archive::K_COFF
:
195 case object::Archive::K_BSD
:
196 case object::Archive::K_DARWIN
:
197 case object::Archive::K_DARWIN64
:
200 llvm_unreachable("not supported for writting");
204 static void print(raw_ostream
&Out
, object::Archive::Kind Kind
, T Val
) {
205 support::endian::write(Out
, Val
,
206 isBSDLike(Kind
) ? llvm::endianness::little
207 : llvm::endianness::big
);
210 template <class T
> static void printLE(raw_ostream
&Out
, T Val
) {
211 support::endian::write(Out
, Val
, llvm::endianness::little
);
214 static void printRestOfMemberHeader(
215 raw_ostream
&Out
, const sys::TimePoint
<std::chrono::seconds
> &ModTime
,
216 unsigned UID
, unsigned GID
, unsigned Perms
, uint64_t Size
) {
217 printWithSpacePadding(Out
, sys::toTimeT(ModTime
), 12);
219 // The format has only 6 chars for uid and gid. Truncate if the provided
221 printWithSpacePadding(Out
, UID
% 1000000, 6);
222 printWithSpacePadding(Out
, GID
% 1000000, 6);
224 printWithSpacePadding(Out
, format("%o", Perms
), 8);
225 printWithSpacePadding(Out
, Size
, 10);
230 printGNUSmallMemberHeader(raw_ostream
&Out
, StringRef Name
,
231 const sys::TimePoint
<std::chrono::seconds
> &ModTime
,
232 unsigned UID
, unsigned GID
, unsigned Perms
,
234 printWithSpacePadding(Out
, Twine(Name
) + "/", 16);
235 printRestOfMemberHeader(Out
, ModTime
, UID
, GID
, Perms
, Size
);
239 printBSDMemberHeader(raw_ostream
&Out
, uint64_t Pos
, StringRef Name
,
240 const sys::TimePoint
<std::chrono::seconds
> &ModTime
,
241 unsigned UID
, unsigned GID
, unsigned Perms
, uint64_t Size
) {
242 uint64_t PosAfterHeader
= Pos
+ 60 + Name
.size();
243 // Pad so that even 64 bit object files are aligned.
244 unsigned Pad
= offsetToAlignment(PosAfterHeader
, Align(8));
245 unsigned NameWithPadding
= Name
.size() + Pad
;
246 printWithSpacePadding(Out
, Twine("#1/") + Twine(NameWithPadding
), 16);
247 printRestOfMemberHeader(Out
, ModTime
, UID
, GID
, Perms
,
248 NameWithPadding
+ Size
);
251 Out
.write(uint8_t(0));
255 printBigArchiveMemberHeader(raw_ostream
&Out
, StringRef Name
,
256 const sys::TimePoint
<std::chrono::seconds
> &ModTime
,
257 unsigned UID
, unsigned GID
, unsigned Perms
,
258 uint64_t Size
, uint64_t PrevOffset
,
259 uint64_t NextOffset
) {
260 unsigned NameLen
= Name
.size();
262 printWithSpacePadding(Out
, Size
, 20); // File member size
263 printWithSpacePadding(Out
, NextOffset
, 20); // Next member header offset
264 printWithSpacePadding(Out
, PrevOffset
, 20); // Previous member header offset
265 printWithSpacePadding(Out
, sys::toTimeT(ModTime
), 12); // File member date
266 // The big archive format has 12 chars for uid and gid.
267 printWithSpacePadding(Out
, UID
% 1000000000000, 12); // UID
268 printWithSpacePadding(Out
, GID
% 1000000000000, 12); // GID
269 printWithSpacePadding(Out
, format("%o", Perms
), 12); // Permission
270 printWithSpacePadding(Out
, NameLen
, 4); // Name length
272 printWithSpacePadding(Out
, Name
, NameLen
); // Name
274 Out
.write(uint8_t(0)); // Null byte padding
276 Out
<< "`\n"; // Terminator
279 static bool useStringTable(bool Thin
, StringRef Name
) {
280 return Thin
|| Name
.size() >= 16 || Name
.contains('/');
283 static bool is64BitKind(object::Archive::Kind Kind
) {
285 case object::Archive::K_GNU
:
286 case object::Archive::K_BSD
:
287 case object::Archive::K_DARWIN
:
288 case object::Archive::K_COFF
:
290 case object::Archive::K_AIXBIG
:
291 case object::Archive::K_DARWIN64
:
292 case object::Archive::K_GNU64
:
295 llvm_unreachable("not supported for writting");
299 printMemberHeader(raw_ostream
&Out
, uint64_t Pos
, raw_ostream
&StringTable
,
300 StringMap
<uint64_t> &MemberNames
, object::Archive::Kind Kind
,
301 bool Thin
, const NewArchiveMember
&M
,
302 sys::TimePoint
<std::chrono::seconds
> ModTime
, uint64_t Size
) {
304 return printBSDMemberHeader(Out
, Pos
, M
.MemberName
, ModTime
, M
.UID
, M
.GID
,
306 if (!useStringTable(Thin
, M
.MemberName
))
307 return printGNUSmallMemberHeader(Out
, M
.MemberName
, ModTime
, M
.UID
, M
.GID
,
312 NamePos
= StringTable
.tell();
313 StringTable
<< M
.MemberName
<< "/\n";
315 auto Insertion
= MemberNames
.insert({M
.MemberName
, uint64_t(0)});
316 if (Insertion
.second
) {
317 Insertion
.first
->second
= StringTable
.tell();
318 StringTable
<< M
.MemberName
;
319 if (isCOFFArchive(Kind
))
322 StringTable
<< "/\n";
324 NamePos
= Insertion
.first
->second
;
326 printWithSpacePadding(Out
, NamePos
, 15);
327 printRestOfMemberHeader(Out
, ModTime
, M
.UID
, M
.GID
, M
.Perms
, Size
);
332 std::vector
<unsigned> Symbols
;
336 uint64_t PreHeadPadSize
= 0;
337 std::unique_ptr
<SymbolicFile
> SymFile
= nullptr;
341 static MemberData
computeStringTable(StringRef Names
) {
342 unsigned Size
= Names
.size();
343 unsigned Pad
= offsetToAlignment(Size
, Align(2));
345 raw_string_ostream
Out(Header
);
346 printWithSpacePadding(Out
, "//", 48);
347 printWithSpacePadding(Out
, Size
+ Pad
, 10);
350 return {{}, std::move(Header
), Names
, Pad
? "\n" : ""};
353 static sys::TimePoint
<std::chrono::seconds
> now(bool Deterministic
) {
354 using namespace std::chrono
;
357 return time_point_cast
<seconds
>(system_clock::now());
358 return sys::TimePoint
<seconds
>();
361 static bool isArchiveSymbol(const object::BasicSymbolRef
&S
) {
362 Expected
<uint32_t> SymFlagsOrErr
= S
.getFlags();
364 // TODO: Actually report errors helpfully.
365 report_fatal_error(SymFlagsOrErr
.takeError());
366 if (*SymFlagsOrErr
& object::SymbolRef::SF_FormatSpecific
)
368 if (!(*SymFlagsOrErr
& object::SymbolRef::SF_Global
))
370 if (*SymFlagsOrErr
& object::SymbolRef::SF_Undefined
)
375 static void printNBits(raw_ostream
&Out
, object::Archive::Kind Kind
,
377 if (is64BitKind(Kind
))
378 print
<uint64_t>(Out
, Kind
, Val
);
380 print
<uint32_t>(Out
, Kind
, Val
);
383 static uint64_t computeSymbolTableSize(object::Archive::Kind Kind
,
384 uint64_t NumSyms
, uint64_t OffsetSize
,
385 uint64_t StringTableSize
,
386 uint32_t *Padding
= nullptr) {
387 assert((OffsetSize
== 4 || OffsetSize
== 8) && "Unsupported OffsetSize");
388 uint64_t Size
= OffsetSize
; // Number of entries
390 Size
+= NumSyms
* OffsetSize
* 2; // Table
392 Size
+= NumSyms
* OffsetSize
; // Table
394 Size
+= OffsetSize
; // byte count
395 Size
+= StringTableSize
;
396 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
397 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
399 // We do this for all bsd formats because it simplifies aligning members.
400 // For the big archive format, the symbol table is the last member, so there
401 // is no need to align.
402 uint32_t Pad
= isAIXBigArchive(Kind
)
404 : offsetToAlignment(Size
, Align(isBSDLike(Kind
) ? 8 : 2));
412 static uint64_t computeSymbolMapSize(uint64_t NumObj
, SymMap
&SymMap
,
413 uint32_t *Padding
= nullptr) {
414 uint64_t Size
= sizeof(uint32_t) * 2; // Number of symbols and objects entries
415 Size
+= NumObj
* sizeof(uint32_t); // Offset table
417 for (auto S
: SymMap
.Map
)
418 Size
+= sizeof(uint16_t) + S
.first
.length() + 1;
420 uint32_t Pad
= offsetToAlignment(Size
, Align(2));
427 static uint64_t computeECSymbolsSize(SymMap
&SymMap
,
428 uint32_t *Padding
= nullptr) {
429 uint64_t Size
= sizeof(uint32_t); // Number of symbols
431 for (auto S
: SymMap
.ECMap
)
432 Size
+= sizeof(uint16_t) + S
.first
.length() + 1;
434 uint32_t Pad
= offsetToAlignment(Size
, Align(2));
441 static void writeSymbolTableHeader(raw_ostream
&Out
, object::Archive::Kind Kind
,
442 bool Deterministic
, uint64_t Size
,
443 uint64_t PrevMemberOffset
= 0,
444 uint64_t NextMemberOffset
= 0) {
445 if (isBSDLike(Kind
)) {
446 const char *Name
= is64BitKind(Kind
) ? "__.SYMDEF_64" : "__.SYMDEF";
447 printBSDMemberHeader(Out
, Out
.tell(), Name
, now(Deterministic
), 0, 0, 0,
449 } else if (isAIXBigArchive(Kind
)) {
450 printBigArchiveMemberHeader(Out
, "", now(Deterministic
), 0, 0, 0, Size
,
451 PrevMemberOffset
, NextMemberOffset
);
453 const char *Name
= is64BitKind(Kind
) ? "/SYM64" : "";
454 printGNUSmallMemberHeader(Out
, Name
, now(Deterministic
), 0, 0, 0, Size
);
458 static uint64_t computeHeadersSize(object::Archive::Kind Kind
,
460 uint64_t StringMemberSize
, uint64_t NumSyms
,
461 uint64_t SymNamesSize
, SymMap
*SymMap
) {
462 uint32_t OffsetSize
= is64BitKind(Kind
) ? 8 : 4;
463 uint64_t SymtabSize
=
464 computeSymbolTableSize(Kind
, NumSyms
, OffsetSize
, SymNamesSize
);
465 auto computeSymbolTableHeaderSize
= [=] {
466 SmallString
<0> TmpBuf
;
467 raw_svector_ostream
Tmp(TmpBuf
);
468 writeSymbolTableHeader(Tmp
, Kind
, true, SymtabSize
);
469 return TmpBuf
.size();
471 uint32_t HeaderSize
= computeSymbolTableHeaderSize();
472 uint64_t Size
= strlen("!<arch>\n") + HeaderSize
+ SymtabSize
;
475 Size
+= HeaderSize
+ computeSymbolMapSize(NumMembers
, *SymMap
);
476 if (SymMap
->ECMap
.size())
477 Size
+= HeaderSize
+ computeECSymbolsSize(*SymMap
);
480 return Size
+ StringMemberSize
;
483 static Expected
<std::unique_ptr
<SymbolicFile
>>
484 getSymbolicFile(MemoryBufferRef Buf
, LLVMContext
&Context
) {
485 const file_magic Type
= identify_magic(Buf
.getBuffer());
486 // Don't attempt to read non-symbolic file types.
487 if (!object::SymbolicFile::isSymbolicFile(Type
, &Context
))
489 if (Type
== file_magic::bitcode
) {
490 auto ObjOrErr
= object::SymbolicFile::createSymbolicFile(
491 Buf
, file_magic::bitcode
, &Context
);
493 return ObjOrErr
.takeError();
494 return std::move(*ObjOrErr
);
496 auto ObjOrErr
= object::SymbolicFile::createSymbolicFile(Buf
);
498 return ObjOrErr
.takeError();
499 return std::move(*ObjOrErr
);
503 static bool is64BitSymbolicFile(const SymbolicFile
*SymObj
) {
504 return SymObj
!= nullptr ? SymObj
->is64Bit() : false;
507 // Log2 of PAGESIZE(4096) on an AIX system.
508 static const uint32_t Log2OfAIXPageSize
= 12;
510 // In the AIX big archive format, since the data content follows the member file
511 // name, if the name ends on an odd byte, an extra byte will be added for
512 // padding. This ensures that the data within the member file starts at an even
514 static const uint32_t MinBigArchiveMemDataAlign
= 2;
516 template <typename AuxiliaryHeader
>
517 uint16_t getAuxMaxAlignment(uint16_t AuxHeaderSize
, AuxiliaryHeader
*AuxHeader
,
518 uint16_t Log2OfMaxAlign
) {
519 // If the member doesn't have an auxiliary header, it isn't a loadable object
520 // and so it just needs aligning at the minimum value.
521 if (AuxHeader
== nullptr)
522 return MinBigArchiveMemDataAlign
;
524 // If the auxiliary header does not have both MaxAlignOfData and
525 // MaxAlignOfText field, it is not a loadable shared object file, so align at
526 // the minimum value. The 'ModuleType' member is located right after
527 // 'MaxAlignOfData' in the AuxiliaryHeader.
528 if (AuxHeaderSize
< offsetof(AuxiliaryHeader
, ModuleType
))
529 return MinBigArchiveMemDataAlign
;
531 // If the XCOFF object file does not have a loader section, it is not
532 // loadable, so align at the minimum value.
533 if (AuxHeader
->SecNumOfLoader
== 0)
534 return MinBigArchiveMemDataAlign
;
536 // The content of the loadable member file needs to be aligned at MAX(maximum
537 // alignment of .text, maximum alignment of .data) if there are both fields.
538 // If the desired alignment is > PAGESIZE, 32-bit members are aligned on a
539 // word boundary, while 64-bit members are aligned on a PAGESIZE(2^12=4096)
541 uint16_t Log2OfAlign
=
542 std::max(AuxHeader
->MaxAlignOfText
, AuxHeader
->MaxAlignOfData
);
543 return 1 << (Log2OfAlign
> Log2OfAIXPageSize
? Log2OfMaxAlign
: Log2OfAlign
);
546 // AIX big archives may contain shared object members. The AIX OS requires these
547 // members to be aligned if they are 64-bit and recommends it for 32-bit
548 // members. This ensures that when these members are loaded they are aligned in
550 static uint32_t getMemberAlignment(SymbolicFile
*SymObj
) {
551 XCOFFObjectFile
*XCOFFObj
= dyn_cast_or_null
<XCOFFObjectFile
>(SymObj
);
553 return MinBigArchiveMemDataAlign
;
555 // If the desired alignment is > PAGESIZE, 32-bit members are aligned on a
556 // word boundary, while 64-bit members are aligned on a PAGESIZE boundary.
557 return XCOFFObj
->is64Bit()
558 ? getAuxMaxAlignment(XCOFFObj
->fileHeader64()->AuxHeaderSize
,
559 XCOFFObj
->auxiliaryHeader64(),
561 : getAuxMaxAlignment(XCOFFObj
->fileHeader32()->AuxHeaderSize
,
562 XCOFFObj
->auxiliaryHeader32(), 2);
565 static void writeSymbolTable(raw_ostream
&Out
, object::Archive::Kind Kind
,
566 bool Deterministic
, ArrayRef
<MemberData
> Members
,
567 StringRef StringTable
, uint64_t MembersOffset
,
568 unsigned NumSyms
, uint64_t PrevMemberOffset
= 0,
569 uint64_t NextMemberOffset
= 0,
570 bool Is64Bit
= false) {
571 // We don't write a symbol table on an archive with no members -- except on
572 // Darwin, where the linker will abort unless the archive has a symbol table.
573 if (StringTable
.empty() && !isDarwin(Kind
) && !isCOFFArchive(Kind
))
576 uint64_t OffsetSize
= is64BitKind(Kind
) ? 8 : 4;
578 uint64_t Size
= computeSymbolTableSize(Kind
, NumSyms
, OffsetSize
,
579 StringTable
.size(), &Pad
);
580 writeSymbolTableHeader(Out
, Kind
, Deterministic
, Size
, PrevMemberOffset
,
584 printNBits(Out
, Kind
, NumSyms
* 2 * OffsetSize
);
586 printNBits(Out
, Kind
, NumSyms
);
588 uint64_t Pos
= MembersOffset
;
589 for (const MemberData
&M
: Members
) {
590 if (isAIXBigArchive(Kind
)) {
591 Pos
+= M
.PreHeadPadSize
;
592 if (is64BitSymbolicFile(M
.SymFile
.get()) != Is64Bit
) {
593 Pos
+= M
.Header
.size() + M
.Data
.size() + M
.Padding
.size();
598 for (unsigned StringOffset
: M
.Symbols
) {
600 printNBits(Out
, Kind
, StringOffset
);
601 printNBits(Out
, Kind
, Pos
); // member offset
603 Pos
+= M
.Header
.size() + M
.Data
.size() + M
.Padding
.size();
607 // byte count of the string table
608 printNBits(Out
, Kind
, StringTable
.size());
612 Out
.write(uint8_t(0));
615 static void writeSymbolMap(raw_ostream
&Out
, object::Archive::Kind Kind
,
616 bool Deterministic
, ArrayRef
<MemberData
> Members
,
617 SymMap
&SymMap
, uint64_t MembersOffset
) {
619 uint64_t Size
= computeSymbolMapSize(Members
.size(), SymMap
, &Pad
);
620 writeSymbolTableHeader(Out
, Kind
, Deterministic
, Size
, 0);
622 uint32_t Pos
= MembersOffset
;
624 printLE
<uint32_t>(Out
, Members
.size());
625 for (const MemberData
&M
: Members
) {
626 printLE(Out
, Pos
); // member offset
627 Pos
+= M
.Header
.size() + M
.Data
.size() + M
.Padding
.size();
630 printLE
<uint32_t>(Out
, SymMap
.Map
.size());
632 for (auto S
: SymMap
.Map
)
633 printLE(Out
, S
.second
);
634 for (auto S
: SymMap
.Map
)
635 Out
<< S
.first
<< '\0';
638 Out
.write(uint8_t(0));
641 static void writeECSymbols(raw_ostream
&Out
, object::Archive::Kind Kind
,
642 bool Deterministic
, ArrayRef
<MemberData
> Members
,
645 uint64_t Size
= computeECSymbolsSize(SymMap
, &Pad
);
646 printGNUSmallMemberHeader(Out
, "/<ECSYMBOLS>", now(Deterministic
), 0, 0, 0,
649 printLE
<uint32_t>(Out
, SymMap
.ECMap
.size());
651 for (auto S
: SymMap
.ECMap
)
652 printLE(Out
, S
.second
);
653 for (auto S
: SymMap
.ECMap
)
654 Out
<< S
.first
<< '\0';
656 Out
.write(uint8_t(0));
659 static bool isECObject(object::SymbolicFile
&Obj
) {
661 return cast
<llvm::object::COFFObjectFile
>(&Obj
)->getMachine() !=
662 COFF::IMAGE_FILE_MACHINE_ARM64
;
664 if (Obj
.isCOFFImportFile())
665 return cast
<llvm::object::COFFImportFile
>(&Obj
)->getMachine() !=
666 COFF::IMAGE_FILE_MACHINE_ARM64
;
669 Expected
<std::string
> TripleStr
=
670 getBitcodeTargetTriple(Obj
.getMemoryBufferRef());
673 Triple
T(*TripleStr
);
674 return T
.isWindowsArm64EC() || T
.getArch() == Triple::x86_64
;
680 static Expected
<std::vector
<unsigned>> getSymbols(SymbolicFile
*Obj
,
682 raw_ostream
&SymNames
,
684 std::vector
<unsigned> Ret
;
689 std::map
<std::string
, uint16_t> *Map
= nullptr;
691 Map
= SymMap
->UseECMap
&& isECObject(*Obj
) ? &SymMap
->ECMap
: &SymMap
->Map
;
693 for (const object::BasicSymbolRef
&S
: Obj
->symbols()) {
694 if (!isArchiveSymbol(S
))
698 raw_string_ostream
NameStream(Name
);
699 if (Error E
= S
.printName(NameStream
))
701 if (Map
->find(Name
) != Map
->end())
702 continue; // ignore duplicated symbol
703 (*Map
)[Name
] = Index
;
704 if (Map
== &SymMap
->Map
) {
705 Ret
.push_back(SymNames
.tell());
706 SymNames
<< Name
<< '\0';
709 Ret
.push_back(SymNames
.tell());
710 if (Error E
= S
.printName(SymNames
))
718 static Expected
<std::vector
<MemberData
>>
719 computeMemberData(raw_ostream
&StringTable
, raw_ostream
&SymNames
,
720 object::Archive::Kind Kind
, bool Thin
, bool Deterministic
,
721 SymtabWritingMode NeedSymbols
, SymMap
*SymMap
,
722 LLVMContext
&Context
, ArrayRef
<NewArchiveMember
> NewMembers
) {
723 static char PaddingData
[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
724 uint64_t MemHeadPadSize
= 0;
726 isAIXBigArchive(Kind
) ? sizeof(object::BigArchive::FixLenHdr
) : 0;
728 std::vector
<MemberData
> Ret
;
729 bool HasObject
= false;
731 // Deduplicate long member names in the string table and reuse earlier name
732 // offsets. This especially saves space for COFF Import libraries where all
733 // members have the same name.
734 StringMap
<uint64_t> MemberNames
;
736 // UniqueTimestamps is a special case to improve debugging on Darwin:
738 // The Darwin linker does not link debug info into the final
739 // binary. Instead, it emits entries of type N_OSO in the output
740 // binary's symbol table, containing references to the linked-in
741 // object files. Using that reference, the debugger can read the
742 // debug data directly from the object files. Alternatively, an
743 // invocation of 'dsymutil' will link the debug data from the object
744 // files into a dSYM bundle, which can be loaded by the debugger,
745 // instead of the object files.
747 // For an object file, the N_OSO entries contain the absolute path
748 // path to the file, and the file's timestamp. For an object
749 // included in an archive, the path is formatted like
750 // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
751 // archive member's timestamp, rather than the archive's timestamp.
753 // However, this doesn't always uniquely identify an object within
754 // an archive -- an archive file can have multiple entries with the
755 // same filename. (This will happen commonly if the original object
756 // files started in different directories.) The only way they get
757 // distinguished, then, is via the timestamp. But this process is
758 // unable to find the correct object file in the archive when there
759 // are two files of the same name and timestamp.
761 // Additionally, timestamp==0 is treated specially, and causes the
762 // timestamp to be ignored as a match criteria.
764 // That will "usually" work out okay when creating an archive not in
765 // deterministic timestamp mode, because the objects will probably
766 // have been created at different timestamps.
768 // To ameliorate this problem, in deterministic archive mode (which
769 // is the default), on Darwin we will emit a unique non-zero
770 // timestamp for each entry with a duplicated name. This is still
771 // deterministic: the only thing affecting that timestamp is the
772 // order of the files in the resultant archive.
774 // See also the functions that handle the lookup:
775 // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
776 // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
777 bool UniqueTimestamps
= Deterministic
&& isDarwin(Kind
);
778 std::map
<StringRef
, unsigned> FilenameCount
;
779 if (UniqueTimestamps
) {
780 for (const NewArchiveMember
&M
: NewMembers
)
781 FilenameCount
[M
.MemberName
]++;
782 for (auto &Entry
: FilenameCount
)
783 Entry
.second
= Entry
.second
> 1 ? 1 : 0;
786 // The big archive format needs to know the offset of the previous member
788 uint64_t PrevOffset
= 0;
789 uint64_t NextMemHeadPadSize
= 0;
790 std::unique_ptr
<SymbolicFile
> CurSymFile
;
791 std::unique_ptr
<SymbolicFile
> NextSymFile
;
794 for (auto M
= NewMembers
.begin(); M
< NewMembers
.end(); ++M
) {
796 raw_string_ostream
Out(Header
);
798 MemoryBufferRef Buf
= M
->Buf
->getMemBufferRef();
799 StringRef Data
= Thin
? "" : Buf
.getBuffer();
803 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
804 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
805 // uniformly. This matches the behaviour with cctools and ensures that ld64
806 // is happy with archives that we generate.
807 unsigned MemberPadding
=
808 isDarwin(Kind
) ? offsetToAlignment(Data
.size(), Align(8)) : 0;
809 unsigned TailPadding
=
810 offsetToAlignment(Data
.size() + MemberPadding
, Align(2));
811 StringRef Padding
= StringRef(PaddingData
, MemberPadding
+ TailPadding
);
813 sys::TimePoint
<std::chrono::seconds
> ModTime
;
814 if (UniqueTimestamps
)
815 // Increment timestamp for each file of a given name.
816 ModTime
= sys::toTimePoint(FilenameCount
[M
->MemberName
]++);
818 ModTime
= M
->ModTime
;
820 uint64_t Size
= Buf
.getBufferSize() + MemberPadding
;
821 if (Size
> object::Archive::MaxMemberSize
) {
822 std::string StringMsg
=
823 "File " + M
->MemberName
.str() + " exceeds size limit";
824 return make_error
<object::GenericBinaryError
>(
825 std::move(StringMsg
), object::object_error::parse_failed
);
828 if (NeedSymbols
!= SymtabWritingMode::NoSymtab
|| isAIXBigArchive(Kind
)) {
829 auto SetNextSymFile
= [&NextSymFile
,
830 &Context
](MemoryBufferRef Buf
,
831 StringRef MemberName
) -> Error
{
832 Expected
<std::unique_ptr
<SymbolicFile
>> SymFileOrErr
=
833 getSymbolicFile(Buf
, Context
);
835 return createFileError(MemberName
, SymFileOrErr
.takeError());
836 NextSymFile
= std::move(*SymFileOrErr
);
837 return Error::success();
840 if (M
== NewMembers
.begin())
841 if (Error Err
= SetNextSymFile(Buf
, M
->MemberName
))
842 return std::move(Err
);
844 CurSymFile
= std::move(NextSymFile
);
846 if ((M
+ 1) != NewMembers
.end())
847 if (Error Err
= SetNextSymFile((M
+ 1)->Buf
->getMemBufferRef(),
848 (M
+ 1)->MemberName
))
849 return std::move(Err
);
852 // In the big archive file format, we need to calculate and include the next
853 // member offset and previous member offset in the file member header.
854 if (isAIXBigArchive(Kind
)) {
855 uint64_t OffsetToMemData
= Pos
+ sizeof(object::BigArMemHdrType
) +
856 alignTo(M
->MemberName
.size(), 2);
858 if (M
== NewMembers
.begin())
860 alignToPowerOf2(OffsetToMemData
,
861 getMemberAlignment(CurSymFile
.get())) -
864 MemHeadPadSize
= NextMemHeadPadSize
;
865 Pos
+= MemHeadPadSize
;
866 uint64_t NextOffset
= Pos
+ sizeof(object::BigArMemHdrType
) +
867 alignTo(M
->MemberName
.size(), 2) + alignTo(Size
, 2);
869 // If there is another member file after this, we need to calculate the
870 // padding before the header.
871 if ((M
+ 1) != NewMembers
.end()) {
872 uint64_t OffsetToNextMemData
= NextOffset
+
873 sizeof(object::BigArMemHdrType
) +
874 alignTo((M
+ 1)->MemberName
.size(), 2);
876 alignToPowerOf2(OffsetToNextMemData
,
877 getMemberAlignment(NextSymFile
.get())) -
879 NextOffset
+= NextMemHeadPadSize
;
881 printBigArchiveMemberHeader(Out
, M
->MemberName
, ModTime
, M
->UID
, M
->GID
,
882 M
->Perms
, Size
, PrevOffset
, NextOffset
);
885 printMemberHeader(Out
, Pos
, StringTable
, MemberNames
, Kind
, Thin
, *M
,
890 std::vector
<unsigned> Symbols
;
891 if (NeedSymbols
!= SymtabWritingMode::NoSymtab
) {
892 Expected
<std::vector
<unsigned>> SymbolsOrErr
=
893 getSymbols(CurSymFile
.get(), Index
, SymNames
, SymMap
);
895 return createFileError(M
->MemberName
, SymbolsOrErr
.takeError());
896 Symbols
= std::move(*SymbolsOrErr
);
901 Pos
+= Header
.size() + Data
.size() + Padding
.size();
902 Ret
.push_back({std::move(Symbols
), std::move(Header
), Data
, Padding
,
903 MemHeadPadSize
, std::move(CurSymFile
)});
905 // If there are no symbols, emit an empty symbol table, to satisfy Solaris
906 // tools, older versions of which expect a symbol table in a non-empty
907 // archive, regardless of whether there are any symbols in it.
908 if (HasObject
&& SymNames
.tell() == 0 && !isCOFFArchive(Kind
))
909 SymNames
<< '\0' << '\0' << '\0';
910 return std::move(Ret
);
915 static ErrorOr
<SmallString
<128>> canonicalizePath(StringRef P
) {
916 SmallString
<128> Ret
= P
;
917 std::error_code Err
= sys::fs::make_absolute(Ret
);
920 sys::path::remove_dots(Ret
, /*removedotdot*/ true);
924 // Compute the relative path from From to To.
925 Expected
<std::string
> computeArchiveRelativePath(StringRef From
, StringRef To
) {
926 ErrorOr
<SmallString
<128>> PathToOrErr
= canonicalizePath(To
);
927 ErrorOr
<SmallString
<128>> DirFromOrErr
= canonicalizePath(From
);
928 if (!PathToOrErr
|| !DirFromOrErr
)
929 return errorCodeToError(std::error_code(errno
, std::generic_category()));
931 const SmallString
<128> &PathTo
= *PathToOrErr
;
932 const SmallString
<128> &DirFrom
= sys::path::parent_path(*DirFromOrErr
);
934 // Can't construct a relative path between different roots
935 if (sys::path::root_name(PathTo
) != sys::path::root_name(DirFrom
))
936 return sys::path::convert_to_slash(PathTo
);
938 // Skip common prefixes
940 std::mismatch(sys::path::begin(DirFrom
), sys::path::end(DirFrom
),
941 sys::path::begin(PathTo
));
942 auto FromI
= FromTo
.first
;
943 auto ToI
= FromTo
.second
;
945 // Construct relative path
946 SmallString
<128> Relative
;
947 for (auto FromE
= sys::path::end(DirFrom
); FromI
!= FromE
; ++FromI
)
948 sys::path::append(Relative
, sys::path::Style::posix
, "..");
950 for (auto ToE
= sys::path::end(PathTo
); ToI
!= ToE
; ++ToI
)
951 sys::path::append(Relative
, sys::path::Style::posix
, *ToI
);
953 return std::string(Relative
.str());
956 static Error
writeArchiveToStream(raw_ostream
&Out
,
957 ArrayRef
<NewArchiveMember
> NewMembers
,
958 SymtabWritingMode WriteSymtab
,
959 object::Archive::Kind Kind
,
960 bool Deterministic
, bool Thin
, bool IsEC
) {
961 assert((!Thin
|| !isBSDLike(Kind
)) && "Only the gnu format has a thin mode");
963 SmallString
<0> SymNamesBuf
;
964 raw_svector_ostream
SymNames(SymNamesBuf
);
965 SmallString
<0> StringTableBuf
;
966 raw_svector_ostream
StringTable(StringTableBuf
);
969 // COFF symbol map uses 16-bit indexes, so we can't use it if there are too
971 if (isCOFFArchive(Kind
) && NewMembers
.size() > 0xfffe)
972 Kind
= object::Archive::K_GNU
;
974 // In the scenario when LLVMContext is populated SymbolicFile will contain a
975 // reference to it, thus SymbolicFile should be destroyed first.
978 SymMap
.UseECMap
= IsEC
;
979 Expected
<std::vector
<MemberData
>> DataOrErr
= computeMemberData(
980 StringTable
, SymNames
, Kind
, Thin
, Deterministic
, WriteSymtab
,
981 isCOFFArchive(Kind
) ? &SymMap
: nullptr, Context
, NewMembers
);
982 if (Error E
= DataOrErr
.takeError())
984 std::vector
<MemberData
> &Data
= *DataOrErr
;
986 uint64_t StringTableSize
= 0;
987 MemberData StringTableMember
;
988 if (!StringTableBuf
.empty() && !isAIXBigArchive(Kind
)) {
989 StringTableMember
= computeStringTable(StringTableBuf
);
990 StringTableSize
= StringTableMember
.Header
.size() +
991 StringTableMember
.Data
.size() +
992 StringTableMember
.Padding
.size();
995 // We would like to detect if we need to switch to a 64-bit symbol table.
996 uint64_t LastMemberEndOffset
= 0;
997 uint64_t LastMemberHeaderOffset
= 0;
998 uint64_t NumSyms
= 0;
999 uint64_t NumSyms32
= 0; // Store symbol number of 32-bit member files.
1000 bool ShouldWriteSymtab
= WriteSymtab
!= SymtabWritingMode::NoSymtab
;
1002 for (const auto &M
: Data
) {
1003 // Record the start of the member's offset
1004 LastMemberEndOffset
+= M
.PreHeadPadSize
;
1005 LastMemberHeaderOffset
= LastMemberEndOffset
;
1006 // Account for the size of each part associated with the member.
1007 LastMemberEndOffset
+= M
.Header
.size() + M
.Data
.size() + M
.Padding
.size();
1008 NumSyms
+= M
.Symbols
.size();
1010 // AIX big archive files may contain two global symbol tables. The
1011 // first global symbol table locates 32-bit file members that define global
1012 // symbols; the second global symbol table does the same for 64-bit file
1013 // members. As a big archive can have both 32-bit and 64-bit file members,
1014 // we need to know the number of symbols in each symbol table individually.
1015 if (isAIXBigArchive(Kind
) && ShouldWriteSymtab
) {
1016 if (!is64BitSymbolicFile(M
.SymFile
.get()))
1017 NumSyms32
+= M
.Symbols
.size();
1021 std::optional
<uint64_t> HeadersSize
;
1023 // The symbol table is put at the end of the big archive file. The symbol
1024 // table is at the start of the archive file for other archive formats.
1025 if (ShouldWriteSymtab
&& !is64BitKind(Kind
)) {
1026 // We assume 32-bit offsets to see if 32-bit symbols are possible or not.
1027 HeadersSize
= computeHeadersSize(Kind
, Data
.size(), StringTableSize
,
1028 NumSyms
, SymNamesBuf
.size(),
1029 isCOFFArchive(Kind
) ? &SymMap
: nullptr);
1031 // The SYM64 format is used when an archive's member offsets are larger than
1032 // 32-bits can hold. The need for this shift in format is detected by
1033 // writeArchive. To test this we need to generate a file with a member that
1034 // has an offset larger than 32-bits but this demands a very slow test. To
1035 // speed the test up we use this environment variable to pretend like the
1036 // cutoff happens before 32-bits and instead happens at some much smaller
1038 uint64_t Sym64Threshold
= 1ULL << 32;
1039 const char *Sym64Env
= std::getenv("SYM64_THRESHOLD");
1041 StringRef(Sym64Env
).getAsInteger(10, Sym64Threshold
);
1043 // If LastMemberHeaderOffset isn't going to fit in a 32-bit varible we need
1044 // to switch to 64-bit. Note that the file can be larger than 4GB as long as
1045 // the last member starts before the 4GB offset.
1046 if (*HeadersSize
+ LastMemberHeaderOffset
>= Sym64Threshold
) {
1047 if (Kind
== object::Archive::K_DARWIN
)
1048 Kind
= object::Archive::K_DARWIN64
;
1050 Kind
= object::Archive::K_GNU64
;
1051 HeadersSize
.reset();
1057 else if (isAIXBigArchive(Kind
))
1062 if (!isAIXBigArchive(Kind
)) {
1063 if (ShouldWriteSymtab
) {
1065 HeadersSize
= computeHeadersSize(
1066 Kind
, Data
.size(), StringTableSize
, NumSyms
, SymNamesBuf
.size(),
1067 isCOFFArchive(Kind
) ? &SymMap
: nullptr);
1068 writeSymbolTable(Out
, Kind
, Deterministic
, Data
, SymNamesBuf
,
1069 *HeadersSize
, NumSyms
);
1071 if (isCOFFArchive(Kind
))
1072 writeSymbolMap(Out
, Kind
, Deterministic
, Data
, SymMap
, *HeadersSize
);
1075 if (StringTableSize
)
1076 Out
<< StringTableMember
.Header
<< StringTableMember
.Data
1077 << StringTableMember
.Padding
;
1079 if (ShouldWriteSymtab
&& SymMap
.ECMap
.size())
1080 writeECSymbols(Out
, Kind
, Deterministic
, Data
, SymMap
);
1082 for (const MemberData
&M
: Data
)
1083 Out
<< M
.Header
<< M
.Data
<< M
.Padding
;
1085 HeadersSize
= sizeof(object::BigArchive::FixLenHdr
);
1086 LastMemberEndOffset
+= *HeadersSize
;
1087 LastMemberHeaderOffset
+= *HeadersSize
;
1089 // For the big archive (AIX) format, compute a table of member names and
1090 // offsets, used in the member table.
1091 uint64_t MemberTableNameStrTblSize
= 0;
1092 std::vector
<size_t> MemberOffsets
;
1093 std::vector
<StringRef
> MemberNames
;
1094 // Loop across object to find offset and names.
1095 uint64_t MemberEndOffset
= sizeof(object::BigArchive::FixLenHdr
);
1096 for (size_t I
= 0, Size
= NewMembers
.size(); I
!= Size
; ++I
) {
1097 const NewArchiveMember
&Member
= NewMembers
[I
];
1098 MemberTableNameStrTblSize
+= Member
.MemberName
.size() + 1;
1099 MemberEndOffset
+= Data
[I
].PreHeadPadSize
;
1100 MemberOffsets
.push_back(MemberEndOffset
);
1101 MemberNames
.push_back(Member
.MemberName
);
1102 // File member name ended with "`\n". The length is included in
1104 MemberEndOffset
+= sizeof(object::BigArMemHdrType
) +
1105 alignTo(Data
[I
].Data
.size(), 2) +
1106 alignTo(Member
.MemberName
.size(), 2);
1109 // AIX member table size.
1110 uint64_t MemberTableSize
= 20 + // Number of members field
1111 20 * MemberOffsets
.size() +
1112 MemberTableNameStrTblSize
;
1114 SmallString
<0> SymNamesBuf32
;
1115 SmallString
<0> SymNamesBuf64
;
1116 raw_svector_ostream
SymNames32(SymNamesBuf32
);
1117 raw_svector_ostream
SymNames64(SymNamesBuf64
);
1119 if (ShouldWriteSymtab
&& NumSyms
)
1120 // Generate the symbol names for the members.
1121 for (const auto &M
: Data
) {
1122 Expected
<std::vector
<unsigned>> SymbolsOrErr
= getSymbols(
1124 is64BitSymbolicFile(M
.SymFile
.get()) ? SymNames64
: SymNames32
,
1127 return SymbolsOrErr
.takeError();
1130 uint64_t MemberTableEndOffset
=
1131 LastMemberEndOffset
+
1132 alignTo(sizeof(object::BigArMemHdrType
) + MemberTableSize
, 2);
1134 // In AIX OS, The 'GlobSymOffset' field in the fixed-length header contains
1135 // the offset to the 32-bit global symbol table, and the 'GlobSym64Offset'
1136 // contains the offset to the 64-bit global symbol table.
1137 uint64_t GlobalSymbolOffset
=
1138 (ShouldWriteSymtab
&&
1139 (WriteSymtab
!= SymtabWritingMode::BigArchive64
) && NumSyms32
> 0)
1140 ? MemberTableEndOffset
1143 uint64_t GlobalSymbolOffset64
= 0;
1144 uint64_t NumSyms64
= NumSyms
- NumSyms32
;
1145 if (ShouldWriteSymtab
&& (WriteSymtab
!= SymtabWritingMode::BigArchive32
) &&
1147 if (GlobalSymbolOffset
== 0)
1148 GlobalSymbolOffset64
= MemberTableEndOffset
;
1150 // If there is a global symbol table for 32-bit members,
1151 // the 64-bit global symbol table is after the 32-bit one.
1152 GlobalSymbolOffset64
=
1153 GlobalSymbolOffset
+ sizeof(object::BigArMemHdrType
) +
1154 (NumSyms32
+ 1) * 8 + alignTo(SymNamesBuf32
.size(), 2);
1157 // Fixed Sized Header.
1158 printWithSpacePadding(Out
, NewMembers
.size() ? LastMemberEndOffset
: 0,
1159 20); // Offset to member table
1160 // If there are no file members in the archive, there will be no global
1162 printWithSpacePadding(Out
, GlobalSymbolOffset
, 20);
1163 printWithSpacePadding(Out
, GlobalSymbolOffset64
, 20);
1164 printWithSpacePadding(Out
,
1166 ? sizeof(object::BigArchive::FixLenHdr
) +
1167 Data
[0].PreHeadPadSize
1169 20); // Offset to first archive member
1170 printWithSpacePadding(Out
, NewMembers
.size() ? LastMemberHeaderOffset
: 0,
1171 20); // Offset to last archive member
1172 printWithSpacePadding(
1174 20); // Offset to first member of free list - Not supported yet
1176 for (const MemberData
&M
: Data
) {
1177 Out
<< std::string(M
.PreHeadPadSize
, '\0');
1178 Out
<< M
.Header
<< M
.Data
;
1179 if (M
.Data
.size() % 2)
1183 if (NewMembers
.size()) {
1185 printBigArchiveMemberHeader(Out
, "", sys::toTimePoint(0), 0, 0, 0,
1186 MemberTableSize
, LastMemberHeaderOffset
,
1187 GlobalSymbolOffset
? GlobalSymbolOffset
1188 : GlobalSymbolOffset64
);
1189 printWithSpacePadding(Out
, MemberOffsets
.size(), 20); // Number of members
1190 for (uint64_t MemberOffset
: MemberOffsets
)
1191 printWithSpacePadding(Out
, MemberOffset
,
1192 20); // Offset to member file header.
1193 for (StringRef MemberName
: MemberNames
)
1194 Out
<< MemberName
<< '\0'; // Member file name, null byte padding.
1196 if (MemberTableNameStrTblSize
% 2)
1197 Out
<< '\0'; // Name table must be tail padded to an even number of
1200 if (ShouldWriteSymtab
) {
1201 // Write global symbol table for 32-bit file members.
1202 if (GlobalSymbolOffset
) {
1203 writeSymbolTable(Out
, Kind
, Deterministic
, Data
, SymNamesBuf32
,
1204 *HeadersSize
, NumSyms32
, LastMemberEndOffset
,
1205 GlobalSymbolOffset64
);
1206 // Add padding between the symbol tables, if needed.
1207 if (GlobalSymbolOffset64
&& (SymNamesBuf32
.size() % 2))
1211 // Write global symbol table for 64-bit file members.
1212 if (GlobalSymbolOffset64
)
1213 writeSymbolTable(Out
, Kind
, Deterministic
, Data
, SymNamesBuf64
,
1214 *HeadersSize
, NumSyms64
,
1215 GlobalSymbolOffset
? GlobalSymbolOffset
1216 : LastMemberEndOffset
,
1222 return Error::success();
1225 Error
writeArchive(StringRef ArcName
, ArrayRef
<NewArchiveMember
> NewMembers
,
1226 SymtabWritingMode WriteSymtab
, object::Archive::Kind Kind
,
1227 bool Deterministic
, bool Thin
,
1228 std::unique_ptr
<MemoryBuffer
> OldArchiveBuf
, bool IsEC
) {
1229 Expected
<sys::fs::TempFile
> Temp
=
1230 sys::fs::TempFile::create(ArcName
+ ".temp-archive-%%%%%%%.a");
1232 return Temp
.takeError();
1233 raw_fd_ostream
Out(Temp
->FD
, false);
1235 if (Error E
= writeArchiveToStream(Out
, NewMembers
, WriteSymtab
, Kind
,
1236 Deterministic
, Thin
, IsEC
)) {
1237 if (Error DiscardError
= Temp
->discard())
1238 return joinErrors(std::move(E
), std::move(DiscardError
));
1242 // At this point, we no longer need whatever backing memory
1243 // was used to generate the NewMembers. On Windows, this buffer
1244 // could be a mapped view of the file we want to replace (if
1245 // we're updating an existing archive, say). In that case, the
1246 // rename would still succeed, but it would leave behind a
1247 // temporary file (actually the original file renamed) because
1248 // a file cannot be deleted while there's a handle open on it,
1249 // only renamed. So by freeing this buffer, this ensures that
1250 // the last open handle on the destination file, if any, is
1251 // closed before we attempt to rename.
1252 OldArchiveBuf
.reset();
1254 return Temp
->keep(ArcName
);
1257 Expected
<std::unique_ptr
<MemoryBuffer
>>
1258 writeArchiveToBuffer(ArrayRef
<NewArchiveMember
> NewMembers
,
1259 SymtabWritingMode WriteSymtab
, object::Archive::Kind Kind
,
1260 bool Deterministic
, bool Thin
) {
1261 SmallVector
<char, 0> ArchiveBufferVector
;
1262 raw_svector_ostream
ArchiveStream(ArchiveBufferVector
);
1264 if (Error E
= writeArchiveToStream(ArchiveStream
, NewMembers
, WriteSymtab
,
1265 Kind
, Deterministic
, Thin
, false))
1266 return std::move(E
);
1268 return std::make_unique
<SmallVectorMemoryBuffer
>(
1269 std::move(ArchiveBufferVector
), /*RequiresNullTerminator=*/false);