LLVM 23.0.0git
ArchiveWriter.cpp
Go to the documentation of this file.
1//===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the writeArchive function.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/StringMap.h"
16#include "llvm/ADT/StringRef.h"
18#include "llvm/IR/LLVMContext.h"
19#include "llvm/Object/Archive.h"
20#include "llvm/Object/COFF.h"
22#include "llvm/Object/Error.h"
24#include "llvm/Object/MachO.h"
30#include "llvm/Support/Errc.h"
32#include "llvm/Support/Format.h"
34#include "llvm/Support/Path.h"
37
38#include <cerrno>
39#include <map>
40
41#if !defined(_MSC_VER) && !defined(__MINGW32__)
42#include <unistd.h>
43#else
44#include <io.h>
45#endif
46
47using namespace llvm;
48using namespace llvm::object;
49
50struct SymMap {
51 bool UseECMap = false;
52 std::map<std::string, uint16_t> Map;
53 std::map<std::string, uint16_t> ECMap;
54};
55
57 : Buf(MemoryBuffer::getMemBuffer(BufRef, false)),
58 MemberName(BufRef.getBufferIdentifier()) {}
59
61 auto MemBufferRef = this->Buf->getMemBufferRef();
64
65 if (OptionalObject) {
66 if (isa<object::MachOObjectFile>(**OptionalObject))
68 if (isa<object::XCOFFObjectFile>(**OptionalObject))
70 if (isa<object::COFFObjectFile>(**OptionalObject) ||
71 isa<object::COFFImportFile>(**OptionalObject))
74 }
75
76 // Squelch the error in case we had a non-object file.
77 consumeError(OptionalObject.takeError());
78
79 // If we're adding a bitcode file to the archive, detect the Archive kind
80 // based on the target triple.
81 LLVMContext Context;
82 if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) {
84 MemBufferRef, file_magic::bitcode, &Context)) {
85 auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
86 auto TargetTriple = Triple(IRObject.getTargetTriple());
88 } else {
89 // Squelch the error in case this was not a SymbolicFile.
90 consumeError(ObjOrErr.takeError());
91 }
92 }
93
95}
96
99 bool Deterministic) {
101 if (!BufOrErr)
102 return BufOrErr.takeError();
103
105 M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
106 M.MemberName = M.Buf->getBufferIdentifier();
107 if (!Deterministic) {
108 auto ModTimeOrErr = OldMember.getLastModified();
109 if (!ModTimeOrErr)
110 return ModTimeOrErr.takeError();
111 M.ModTime = ModTimeOrErr.get();
112 Expected<unsigned> UIDOrErr = OldMember.getUID();
113 if (!UIDOrErr)
114 return UIDOrErr.takeError();
115 M.UID = UIDOrErr.get();
116 Expected<unsigned> GIDOrErr = OldMember.getGID();
117 if (!GIDOrErr)
118 return GIDOrErr.takeError();
119 M.GID = GIDOrErr.get();
120 Expected<sys::fs::perms> AccessModeOrErr = OldMember.getAccessMode();
121 if (!AccessModeOrErr)
122 return AccessModeOrErr.takeError();
123 M.Perms = AccessModeOrErr.get();
124 }
125 return std::move(M);
126}
127
129 bool Deterministic) {
131 auto FDOrErr = sys::fs::openNativeFileForRead(FileName);
132 if (!FDOrErr)
133 return FDOrErr.takeError();
134 sys::fs::file_t FD = *FDOrErr;
136
137 if (auto EC = sys::fs::status(FD, Status))
138 return errorCodeToError(EC);
139
140 // Opening a directory doesn't make sense. Let it fail.
141 // Linux cannot open directories with open(2), although
142 // cygwin and *bsd can.
145
146 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
147 MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
148 if (!MemberBufferOrErr)
149 return errorCodeToError(MemberBufferOrErr.getError());
150
151 if (auto EC = sys::fs::closeFile(FD))
152 return errorCodeToError(EC);
153
155 M.Buf = std::move(*MemberBufferOrErr);
156 M.MemberName = M.Buf->getBufferIdentifier();
157 if (!Deterministic) {
158 M.ModTime = std::chrono::time_point_cast<std::chrono::seconds>(
159 Status.getLastModificationTime());
160 M.UID = Status.getUser();
161 M.GID = Status.getGroup();
162 M.Perms = Status.permissions();
163 }
164 return std::move(M);
165}
166
167template <typename T>
168static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
169 uint64_t OldPos = OS.tell();
170 OS << Data;
171 unsigned SizeSoFar = OS.tell() - OldPos;
172 assert(SizeSoFar <= Size && "Data doesn't fit in Size");
173 OS.indent(Size - SizeSoFar);
174}
175
180
184
188
190 switch (Kind) {
196 return false;
200 return true;
201 }
202 llvm_unreachable("not supported for writting");
203}
204
205template <class T>
211
212template <class T> static void printLE(raw_ostream &Out, T Val) {
214}
215
218 unsigned UID, unsigned GID, unsigned Perms, uint64_t Size) {
219 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
220
221 // The format has only 6 chars for uid and gid. Truncate if the provided
222 // values don't fit.
223 printWithSpacePadding(Out, UID % 1000000, 6);
224 printWithSpacePadding(Out, GID % 1000000, 6);
225
226 printWithSpacePadding(Out, format("%o", Perms), 8);
227 printWithSpacePadding(Out, Size, 10);
228 Out << "`\n";
229}
230
231static void
234 unsigned UID, unsigned GID, unsigned Perms,
235 uint64_t Size) {
236 printWithSpacePadding(Out, Twine(Name) + "/", 16);
237 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
238}
239
240static void
243 unsigned UID, unsigned GID, unsigned Perms, uint64_t Size) {
244 uint64_t PosAfterHeader = Pos + 60 + Name.size();
245 // Pad so that even 64 bit object files are aligned.
246 unsigned Pad = offsetToAlignment(PosAfterHeader, Align(8));
247 unsigned NameWithPadding = Name.size() + Pad;
248 printWithSpacePadding(Out, Twine("#1/") + Twine(NameWithPadding), 16);
249 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms,
250 NameWithPadding + Size);
251 Out << Name;
252 while (Pad--)
253 Out.write(uint8_t(0));
254}
255
256static void
259 unsigned UID, unsigned GID, unsigned Perms,
260 uint64_t Size, uint64_t PrevOffset,
261 uint64_t NextOffset) {
262 unsigned NameLen = Name.size();
263
264 printWithSpacePadding(Out, Size, 20); // File member size
265 printWithSpacePadding(Out, NextOffset, 20); // Next member header offset
266 printWithSpacePadding(Out, PrevOffset, 20); // Previous member header offset
267 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12); // File member date
268 // The big archive format has 12 chars for uid and gid.
269 printWithSpacePadding(Out, UID % 1000000000000, 12); // UID
270 printWithSpacePadding(Out, GID % 1000000000000, 12); // GID
271 printWithSpacePadding(Out, format("%o", Perms), 12); // Permission
272 printWithSpacePadding(Out, NameLen, 4); // Name length
273 if (NameLen) {
274 printWithSpacePadding(Out, Name, NameLen); // Name
275 if (NameLen % 2)
276 Out.write(uint8_t(0)); // Null byte padding
277 }
278 Out << "`\n"; // Terminator
279}
280
281static bool useStringTable(bool Thin, StringRef Name) {
282 return Thin || Name.size() >= 16 || Name.contains('/');
283}
284
286 switch (Kind) {
292 return false;
296 return true;
297 }
298 llvm_unreachable("not supported for writting");
299}
300
301static void
304 bool Thin, const NewArchiveMember &M, StringRef MemberName,
306 if (isBSDLike(Kind))
307 return printBSDMemberHeader(Out, Pos, MemberName, ModTime, M.UID, M.GID,
308 M.Perms, Size);
309 if (!useStringTable(Thin, MemberName))
310 return printGNUSmallMemberHeader(Out, MemberName, ModTime, M.UID, M.GID,
311 M.Perms, Size);
312 Out << '/';
313 uint64_t NamePos;
314 if (Thin) {
315 NamePos = StringTable.tell();
316 StringTable << MemberName << "/\n";
317 } else {
318 auto Insertion = MemberNames.insert({MemberName, uint64_t(0)});
319 if (Insertion.second) {
320 Insertion.first->second = StringTable.tell();
321 StringTable << MemberName;
322 if (isCOFFArchive(Kind))
323 StringTable << '\0';
324 else
325 StringTable << "/\n";
326 }
327 NamePos = Insertion.first->second;
328 }
329 printWithSpacePadding(Out, NamePos, 15);
330 printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
331}
332
333namespace {
334struct MemberData {
335 std::vector<unsigned> Symbols;
336 std::string Header;
337 StringRef Data;
338 StringRef Padding;
339 uint64_t PreHeadPadSize = 0;
340 std::unique_ptr<SymbolicFile> SymFile = nullptr;
341 std::string HybridName = "";
342 std::unique_ptr<MemoryBuffer> NativeBuf = nullptr;
343};
344} // namespace
345
346static MemberData computeStringTable(StringRef Names) {
347 unsigned Size = Names.size();
348 unsigned Pad = offsetToAlignment(Size, Align(2));
349 std::string Header;
350 raw_string_ostream Out(Header);
351 printWithSpacePadding(Out, "//", 48);
352 printWithSpacePadding(Out, Size + Pad, 10);
353 Out << "`\n";
354 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
355}
356
357static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
358 using namespace std::chrono;
359
360 if (!Deterministic)
361 return time_point_cast<seconds>(system_clock::now());
363}
364
366 Expected<uint32_t> SymFlagsOrErr = S.getFlags();
367 if (!SymFlagsOrErr)
368 // TODO: Actually report errors helpfully.
369 report_fatal_error(SymFlagsOrErr.takeError());
370 if (*SymFlagsOrErr & object::SymbolRef::SF_FormatSpecific)
371 return false;
372 if (!(*SymFlagsOrErr & object::SymbolRef::SF_Global))
373 return false;
374 if (*SymFlagsOrErr & object::SymbolRef::SF_Undefined)
375 return false;
376 return true;
377}
378
380 uint64_t Val) {
381 if (is64BitKind(Kind))
382 print<uint64_t>(Out, Kind, Val);
383 else
384 print<uint32_t>(Out, Kind, Val);
385}
386
388 uint64_t NumSyms, uint64_t OffsetSize,
389 uint64_t StringTableSize,
390 uint32_t *Padding = nullptr) {
391 assert((OffsetSize == 4 || OffsetSize == 8) && "Unsupported OffsetSize");
392 uint64_t Size = OffsetSize; // Number of entries
393 if (isBSDLike(Kind))
394 Size += NumSyms * OffsetSize * 2; // Table
395 else
396 Size += NumSyms * OffsetSize; // Table
397 if (isBSDLike(Kind))
398 Size += OffsetSize; // byte count
399 Size += StringTableSize;
400 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
401 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
402 // uniformly.
403 // We do this for all bsd formats because it simplifies aligning members.
404 // For the big archive format, the symbol table is the last member, so there
405 // is no need to align.
407 ? 0
409
410 Size += Pad;
411 if (Padding)
412 *Padding = Pad;
413 return Size;
414}
415
417 uint32_t *Padding = nullptr) {
418 uint64_t Size = sizeof(uint32_t) * 2; // Number of symbols and objects entries
419 Size += NumObj * sizeof(uint32_t); // Offset table
420
421 for (auto S : SymMap.Map)
422 Size += sizeof(uint16_t) + S.first.length() + 1;
423
425 Size += Pad;
426 if (Padding)
427 *Padding = Pad;
428 return Size;
429}
430
432 uint32_t *Padding = nullptr) {
433 uint64_t Size = sizeof(uint32_t); // Number of symbols
434
435 for (auto S : SymMap.ECMap)
436 Size += sizeof(uint16_t) + S.first.length() + 1;
437
439 Size += Pad;
440 if (Padding)
441 *Padding = Pad;
442 return Size;
443}
444
446 bool Deterministic, uint64_t Size,
447 uint64_t PrevMemberOffset = 0,
448 uint64_t NextMemberOffset = 0) {
449 if (isBSDLike(Kind)) {
450 const char *Name = is64BitKind(Kind) ? "__.SYMDEF_64" : "__.SYMDEF";
451 printBSDMemberHeader(Out, Out.tell(), Name, now(Deterministic), 0, 0, 0,
452 Size);
453 } else if (isAIXBigArchive(Kind)) {
454 printBigArchiveMemberHeader(Out, "", now(Deterministic), 0, 0, 0, Size,
455 PrevMemberOffset, NextMemberOffset);
456 } else {
457 const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
458 printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
459 }
460}
461
463 uint64_t NumMembers,
464 uint64_t StringMemberSize, uint64_t NumSyms,
465 uint64_t SymNamesSize, SymMap *SymMap) {
466 uint32_t OffsetSize = is64BitKind(Kind) ? 8 : 4;
467 uint64_t SymtabSize =
468 computeSymbolTableSize(Kind, NumSyms, OffsetSize, SymNamesSize);
469 auto computeSymbolTableHeaderSize = [=] {
470 SmallString<0> TmpBuf;
471 raw_svector_ostream Tmp(TmpBuf);
472 writeSymbolTableHeader(Tmp, Kind, true, SymtabSize);
473 return TmpBuf.size();
474 };
475 uint32_t HeaderSize = computeSymbolTableHeaderSize();
476 uint64_t Size = strlen("!<arch>\n") + HeaderSize + SymtabSize;
477
478 if (SymMap) {
479 Size += HeaderSize + computeSymbolMapSize(NumMembers, *SymMap);
480 if (SymMap->ECMap.size())
481 Size += HeaderSize + computeECSymbolsSize(*SymMap);
482 }
483
484 return Size + StringMemberSize;
485}
486
491 // Don't attempt to read non-symbolic file types.
493 return nullptr;
494 if (Type == file_magic::bitcode) {
496 Buf, file_magic::bitcode, &Context);
497 // An error reading a bitcode file most likely indicates that the file
498 // was created by a compiler from the future. Normally we don't try to
499 // implement forwards compatibility for bitcode files, but when creating an
500 // archive we can implement best-effort forwards compatibility by treating
501 // the file as a blob and not creating symbol index entries for it. lld and
502 // mold ignore the archive symbol index, so provided that you use one of
503 // these linkers, LTO will work as long as lld or the gold plugin is newer
504 // than the compiler. We only ignore errors if the archive format is one
505 // that is supported by a linker that is known to ignore the index,
506 // otherwise there's no chance of this working so we may as well error out.
507 // We print a warning on read failure so that users of linkers that rely on
508 // the symbol index can diagnose the issue.
509 //
510 // This is the same behavior as GNU ar when the linker plugin returns an
511 // error when reading the input file. If the bitcode file is actually
512 // malformed, it will be diagnosed at link time.
513 if (!ObjOrErr) {
514 switch (Kind) {
518 Warn(ObjOrErr.takeError());
519 return nullptr;
525 return ObjOrErr.takeError();
526 }
527 }
528 return std::move(*ObjOrErr);
529 } else {
530 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
531 if (!ObjOrErr)
532 return ObjOrErr.takeError();
533 return std::move(*ObjOrErr);
534 }
535}
536
537static bool is64BitSymbolicFile(const SymbolicFile *SymObj) {
538 return SymObj != nullptr ? SymObj->is64Bit() : false;
539}
540
541// Log2 of PAGESIZE(4096) on an AIX system.
542static const uint32_t Log2OfAIXPageSize = 12;
543
544// In the AIX big archive format, since the data content follows the member file
545// name, if the name ends on an odd byte, an extra byte will be added for
546// padding. This ensures that the data within the member file starts at an even
547// byte.
549
550template <typename AuxiliaryHeader>
551uint16_t getAuxMaxAlignment(uint16_t AuxHeaderSize, AuxiliaryHeader *AuxHeader,
552 uint16_t Log2OfMaxAlign) {
553 // If the member doesn't have an auxiliary header, it isn't a loadable object
554 // and so it just needs aligning at the minimum value.
555 if (AuxHeader == nullptr)
557
558 // If the auxiliary header does not have both MaxAlignOfData and
559 // MaxAlignOfText field, it is not a loadable shared object file, so align at
560 // the minimum value. The 'ModuleType' member is located right after
561 // 'MaxAlignOfData' in the AuxiliaryHeader.
562 if (AuxHeaderSize < offsetof(AuxiliaryHeader, ModuleType))
564
565 // If the XCOFF object file does not have a loader section, it is not
566 // loadable, so align at the minimum value.
567 if (AuxHeader->SecNumOfLoader == 0)
569
570 // The content of the loadable member file needs to be aligned at MAX(maximum
571 // alignment of .text, maximum alignment of .data) if there are both fields.
572 // If the desired alignment is > PAGESIZE, 32-bit members are aligned on a
573 // word boundary, while 64-bit members are aligned on a PAGESIZE(2^12=4096)
574 // boundary.
575 uint16_t Log2OfAlign =
576 std::max(AuxHeader->MaxAlignOfText, AuxHeader->MaxAlignOfData);
577 return 1 << (Log2OfAlign > Log2OfAIXPageSize ? Log2OfMaxAlign : Log2OfAlign);
578}
579
580// AIX big archives may contain shared object members. The AIX OS requires these
581// members to be aligned if they are 64-bit and recommends it for 32-bit
582// members. This ensures that when these members are loaded they are aligned in
583// memory.
586 if (!XCOFFObj)
588
589 // If the desired alignment is > PAGESIZE, 32-bit members are aligned on a
590 // word boundary, while 64-bit members are aligned on a PAGESIZE boundary.
591 return XCOFFObj->is64Bit()
593 XCOFFObj->auxiliaryHeader64(),
596 XCOFFObj->auxiliaryHeader32(), 2);
597}
598
600 bool Deterministic, ArrayRef<MemberData> Members,
601 StringRef StringTable, uint64_t MembersOffset,
602 unsigned NumSyms, uint64_t PrevMemberOffset = 0,
603 uint64_t NextMemberOffset = 0,
604 bool Is64Bit = false) {
605 // We don't write a symbol table on an archive with no members -- except on
606 // Darwin, where the linker will abort unless the archive has a symbol table.
607 if (StringTable.empty() && !isDarwin(Kind) && !isCOFFArchive(Kind))
608 return;
609
610 uint64_t OffsetSize = is64BitKind(Kind) ? 8 : 4;
611 uint32_t Pad;
612 uint64_t Size = computeSymbolTableSize(Kind, NumSyms, OffsetSize,
613 StringTable.size(), &Pad);
614 writeSymbolTableHeader(Out, Kind, Deterministic, Size, PrevMemberOffset,
615 NextMemberOffset);
616
617 if (isBSDLike(Kind))
618 printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
619 else
620 printNBits(Out, Kind, NumSyms);
621
622 uint64_t Pos = MembersOffset;
623 for (const MemberData &M : Members) {
624 if (isAIXBigArchive(Kind)) {
625 Pos += M.PreHeadPadSize;
626 if (is64BitSymbolicFile(M.SymFile.get()) != Is64Bit) {
627 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
628 continue;
629 }
630 }
631
632 for (unsigned StringOffset : M.Symbols) {
633 if (isBSDLike(Kind))
634 printNBits(Out, Kind, StringOffset);
635 printNBits(Out, Kind, Pos); // member offset
636 }
637 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
638 }
639
640 if (isBSDLike(Kind))
641 // byte count of the string table
643 Out << StringTable;
644
645 while (Pad--)
646 Out.write(uint8_t(0));
647}
648
650 bool Deterministic, ArrayRef<MemberData> Members,
651 SymMap &SymMap, uint64_t MembersOffset) {
652 uint32_t Pad;
653 uint64_t Size = computeSymbolMapSize(Members.size(), SymMap, &Pad);
654 writeSymbolTableHeader(Out, Kind, Deterministic, Size, 0);
655
656 uint32_t Pos = MembersOffset;
657
658 printLE<uint32_t>(Out, Members.size());
659 for (const MemberData &M : Members) {
660 printLE(Out, Pos); // member offset
661 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
662 }
663
664 printLE<uint32_t>(Out, SymMap.Map.size());
665
666 for (auto S : SymMap.Map)
667 printLE(Out, S.second);
668 for (auto S : SymMap.Map)
669 Out << S.first << '\0';
670
671 while (Pad--)
672 Out.write(uint8_t(0));
673}
674
676 bool Deterministic, ArrayRef<MemberData> Members,
677 SymMap &SymMap) {
678 uint32_t Pad;
680 printGNUSmallMemberHeader(Out, "/<ECSYMBOLS>", now(Deterministic), 0, 0, 0,
681 Size);
682
683 printLE<uint32_t>(Out, SymMap.ECMap.size());
684
685 for (auto S : SymMap.ECMap)
686 printLE(Out, S.second);
687 for (auto S : SymMap.ECMap)
688 Out << S.first << '\0';
689 while (Pad--)
690 Out.write(uint8_t(0));
691}
692
694 if (Obj.isCOFF())
695 return cast<llvm::object::COFFObjectFile>(&Obj)->getMachine() !=
697
698 if (Obj.isCOFFImportFile())
699 return cast<llvm::object::COFFImportFile>(&Obj)->getMachine() !=
701
702 if (Obj.isIR()) {
703 Expected<std::string> TripleStr =
704 getBitcodeTargetTriple(Obj.getMemoryBufferRef());
705 if (!TripleStr)
706 return false;
707 Triple T(std::move(*TripleStr));
708 return T.isWindowsArm64EC() || T.getArch() == Triple::x86_64;
709 }
710
711 return false;
712}
713
715 if (Obj.isCOFF())
716 return COFF::isAnyArm64(cast<COFFObjectFile>(&Obj)->getMachine());
717
718 if (Obj.isCOFFImportFile())
719 return COFF::isAnyArm64(cast<COFFImportFile>(&Obj)->getMachine());
720
721 if (Obj.isIR()) {
722 Expected<std::string> TripleStr =
723 getBitcodeTargetTriple(Obj.getMemoryBufferRef());
724 if (!TripleStr)
725 return false;
726 Triple T(std::move(*TripleStr));
727 return T.isOSWindows() && T.getArch() == Triple::aarch64;
728 }
729
730 return false;
731}
732
734 return Name.starts_with(ImportDescriptorPrefix) ||
736 (Name.starts_with(NullThunkDataPrefix) &&
737 Name.ends_with(NullThunkDataSuffix));
738}
739
741 uint16_t Index,
742 raw_ostream &SymNames,
743 SymMap *SymMap) {
744 std::vector<unsigned> Ret;
745
746 if (Obj == nullptr)
747 return Ret;
748
749 std::map<std::string, uint16_t> *Map = nullptr;
750 if (SymMap)
751 Map = SymMap->UseECMap && isECObject(*Obj) ? &SymMap->ECMap : &SymMap->Map;
752
753 for (const object::BasicSymbolRef &S : Obj->symbols()) {
754 if (!isArchiveSymbol(S))
755 continue;
756 if (Map) {
757 std::string Name;
758 raw_string_ostream NameStream(Name);
759 if (Error E = S.printName(NameStream))
760 return std::move(E);
761 if (!Map->try_emplace(Name, Index).second)
762 continue; // ignore duplicated symbol
763 if (Map == &SymMap->Map) {
764 Ret.push_back(SymNames.tell());
765 SymNames << Name << '\0';
766 // If EC is enabled, then the import descriptors are NOT put into EC
767 // objects so we need to copy them to the EC map manually.
768 if (SymMap->UseECMap && isImportDescriptor(Name))
769 SymMap->ECMap[Name] = Index;
770 }
771 } else {
772 Ret.push_back(SymNames.tell());
773 if (Error E = S.printName(SymNames))
774 return std::move(E);
775 SymNames << '\0';
776 }
777 }
778 return Ret;
779}
780
783 object::Archive::Kind Kind, bool Thin, bool Deterministic,
784 SymtabWritingMode NeedSymbols, SymMap *SymMap,
785 LLVMContext &Context, ArrayRef<NewArchiveMember> NewMembers,
786 std::optional<bool> IsEC, function_ref<void(Error)> Warn) {
787 static char PaddingData[8] = {'\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n'};
788 uint64_t Pos =
790
791 std::vector<MemberData> Ret;
792 bool HasObject = false;
793
794 // Deduplicate long member names in the string table and reuse earlier name
795 // offsets. This especially saves space for COFF Import libraries where all
796 // members have the same name.
797 StringMap<uint64_t> MemberNames;
798
799 // UniqueTimestamps is a special case to improve debugging on Darwin:
800 //
801 // The Darwin linker does not link debug info into the final
802 // binary. Instead, it emits entries of type N_OSO in the output
803 // binary's symbol table, containing references to the linked-in
804 // object files. Using that reference, the debugger can read the
805 // debug data directly from the object files. Alternatively, an
806 // invocation of 'dsymutil' will link the debug data from the object
807 // files into a dSYM bundle, which can be loaded by the debugger,
808 // instead of the object files.
809 //
810 // For an object file, the N_OSO entries contain the absolute path
811 // path to the file, and the file's timestamp. For an object
812 // included in an archive, the path is formatted like
813 // "/absolute/path/to/archive.a(member.o)", and the timestamp is the
814 // archive member's timestamp, rather than the archive's timestamp.
815 //
816 // However, this doesn't always uniquely identify an object within
817 // an archive -- an archive file can have multiple entries with the
818 // same filename. (This will happen commonly if the original object
819 // files started in different directories.) The only way they get
820 // distinguished, then, is via the timestamp. But this process is
821 // unable to find the correct object file in the archive when there
822 // are two files of the same name and timestamp.
823 //
824 // Additionally, timestamp==0 is treated specially, and causes the
825 // timestamp to be ignored as a match criteria.
826 //
827 // That will "usually" work out okay when creating an archive not in
828 // deterministic timestamp mode, because the objects will probably
829 // have been created at different timestamps.
830 //
831 // To ameliorate this problem, in deterministic archive mode (which
832 // is the default), on Darwin we will emit a unique non-zero
833 // timestamp for each entry with a duplicated name. This is still
834 // deterministic: the only thing affecting that timestamp is the
835 // order of the files in the resultant archive.
836 //
837 // See also the functions that handle the lookup:
838 // in lldb: ObjectContainerBSDArchive::Archive::FindObject()
839 // in llvm/tools/dsymutil: BinaryHolder::GetArchiveMemberBuffers().
840 bool UniqueTimestamps = Deterministic && isDarwin(Kind);
841 std::map<StringRef, unsigned> FilenameCount;
842 if (UniqueTimestamps) {
843 for (const NewArchiveMember &M : NewMembers)
844 FilenameCount[M.MemberName]++;
845 for (auto &Entry : FilenameCount)
846 Entry.second = Entry.second > 1 ? 1 : 0;
847 }
848
849 for (const NewArchiveMember &M : NewMembers) {
850 MemberData &D = Ret.emplace_back();
851 D.Data = M.Buf->getBuffer();
852
853 if (NeedSymbols != SymtabWritingMode::NoSymtab || isAIXBigArchive(Kind)) {
855 M.Buf->getMemBufferRef(), Context, Kind, [&](Error Err) {
856 Warn(createFileError(M.MemberName, std::move(Err)));
857 });
858 if (!SymFileOrErr)
859 return createFileError(M.MemberName, SymFileOrErr.takeError());
860 D.SymFile = std::move(*SymFileOrErr);
861
862 if (SymMap && D.SymFile.get()) {
863 auto COFFObj = dyn_cast<COFFObjectFile>(D.SymFile.get());
864 std::optional<MemoryBufferRef> HybridView;
865 if (COFFObj && (HybridView = COFFObj->findHybridObjectSection())) {
866 // Strip the hybrid section.
867 D.NativeBuf = COFFObj->stripHybridSection();
868 D.Data = D.NativeBuf->getBuffer();
869
870 // Create a separate archive member for the hybrid ARM64X object.
871 MemberData &ECData = Ret.emplace_back();
872 ECData.Data = HybridView->getBuffer();
873
874 SymFileOrErr =
875 getSymbolicFile(*HybridView, Context, Kind, [&](Error Err) {
876 Warn(createFileError(M.MemberName, std::move(Err)));
877 });
878 if (!SymFileOrErr)
879 return createFileError(M.MemberName, SymFileOrErr.takeError());
880 ECData.SymFile = std::move(*SymFileOrErr);
881
882 // Use obj.arm64ec subdirectory for the hybrid object name.
883 size_t Pos = M.MemberName.find_last_of("/\\");
884 Pos = Pos == StringRef::npos ? 0 : Pos + 1;
885 ECData.HybridName = (M.MemberName.substr(0, Pos) + "obj.arm64ec/" +
886 M.MemberName.substr(Pos))
887 .str();
888 }
889 }
890 }
891 }
892
893 if (SymMap) {
894 if (IsEC) {
895 SymMap->UseECMap = *IsEC;
896 } else {
897 // When IsEC is not specified by the caller, use it when we have both
898 // any ARM64 object (ARM64 or ARM64EC) and any EC object (ARM64EC or
899 // AMD64). This may be a single ARM64EC object, but may also be separate
900 // ARM64 and AMD64 objects.
901 bool HaveArm64 = false, HaveEC = false;
902 for (const MemberData &D : Ret) {
903 if (!D.SymFile)
904 continue;
905 if (!HaveArm64)
906 HaveArm64 = isAnyArm64COFF(*D.SymFile);
907 if (!HaveEC)
908 HaveEC = isECObject(*D.SymFile);
909 if (HaveArm64 && HaveEC) {
910 SymMap->UseECMap = true;
911 break;
912 }
913 }
914 }
915 }
916
917 // The big archive format needs to know the offset of the previous member
918 // header.
919 uint64_t PrevOffset = 0;
920 uint64_t NextMemHeadPadSize = 0;
921
922 for (uint32_t Index = 0, MemberIndex = 0; Index < Ret.size(); ++Index) {
923 MemberData &D = Ret[Index];
924 const NewArchiveMember *M = &NewMembers[MemberIndex];
925 // Native COFF members (resulting from stripping a hybrid object section)
926 // are followed by an extracted hybrid object member, using the same
927 // NewArchiveMember.
928 if (!D.NativeBuf.get())
929 ++MemberIndex;
930 raw_string_ostream Out(D.Header);
931
932 uint64_t Size = D.Data.size();
933 if (Thin)
934 D.Data = "";
935
936 // ld64 expects the members to be 8-byte aligned for 64-bit content and at
937 // least 4-byte aligned for 32-bit content. Opt for the larger encoding
938 // uniformly. This matches the behaviour with cctools and ensures that ld64
939 // is happy with archives that we generate.
940 unsigned MemberPadding =
941 isDarwin(Kind) ? offsetToAlignment(D.Data.size(), Align(8)) : 0;
942 unsigned TailPadding =
943 offsetToAlignment(D.Data.size() + MemberPadding, Align(2));
944 D.Padding = StringRef(PaddingData, MemberPadding + TailPadding);
945
946 StringRef MemberName = D.HybridName.size() ? D.HybridName : M->MemberName;
947
949 if (UniqueTimestamps)
950 // Increment timestamp for each file of a given name.
951 ModTime = sys::toTimePoint(FilenameCount[MemberName]++);
952 else
953 ModTime = M->ModTime;
954
955 Size += MemberPadding;
957 std::string StringMsg =
958 "File " + MemberName.str() + " exceeds size limit";
960 std::move(StringMsg), object::object_error::parse_failed);
961 }
962
963 // In the big archive file format, we need to calculate and include the next
964 // member offset and previous member offset in the file member header.
965 if (isAIXBigArchive(Kind)) {
966 uint64_t OffsetToMemData =
967 Pos + sizeof(object::BigArMemHdrType) + alignTo(MemberName.size(), 2);
968
969 if (Index == 0)
970 NextMemHeadPadSize =
971 alignToPowerOf2(OffsetToMemData,
972 getMemberAlignment(D.SymFile.get())) -
973 OffsetToMemData;
974
975 D.PreHeadPadSize = NextMemHeadPadSize;
976 Pos += D.PreHeadPadSize;
977 uint64_t NextOffset = Pos + sizeof(object::BigArMemHdrType) +
978 alignTo(MemberName.size(), 2) + alignTo(Size, 2);
979
980 // If there is another member file after this, we need to calculate the
981 // padding before the header.
982 if (Index + 1 != Ret.size()) {
983 uint64_t OffsetToNextMemData =
984 NextOffset + sizeof(object::BigArMemHdrType) +
985 alignTo(NewMembers[MemberIndex].MemberName.size(), 2);
986 NextMemHeadPadSize =
987 alignToPowerOf2(OffsetToNextMemData,
988 getMemberAlignment(Ret[Index + 1].SymFile.get())) -
989 OffsetToNextMemData;
990 NextOffset += NextMemHeadPadSize;
991 }
992 printBigArchiveMemberHeader(Out, MemberName, ModTime, M->UID, M->GID,
993 M->Perms, Size, PrevOffset, NextOffset);
994 PrevOffset = Pos;
995 } else {
996 printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, *M,
997 MemberName, ModTime, Size);
998 }
999
1000 if (NeedSymbols != SymtabWritingMode::NoSymtab) {
1001 Expected<std::vector<unsigned>> SymbolsOrErr =
1002 getSymbols(D.SymFile.get(), Index + 1, SymNames, SymMap);
1003 if (!SymbolsOrErr)
1004 return createFileError(MemberName, SymbolsOrErr.takeError());
1005 D.Symbols = std::move(*SymbolsOrErr);
1006 if (D.SymFile)
1007 HasObject = true;
1008 }
1009
1010 Pos += D.Header.size() + D.Data.size() + D.Padding.size();
1011 }
1012 // If there are no symbols, emit an empty symbol table, to satisfy Solaris
1013 // tools, older versions of which expect a symbol table in a non-empty
1014 // archive, regardless of whether there are any symbols in it.
1015 if (HasObject && SymNames.tell() == 0 && !isCOFFArchive(Kind))
1016 SymNames << '\0' << '\0' << '\0';
1017 return std::move(Ret);
1018}
1019
1020namespace llvm {
1021
1023 SmallString<128> Ret = P;
1024 std::error_code Err = sys::fs::make_absolute(Ret);
1025 if (Err)
1026 return Err;
1027 sys::path::remove_dots(Ret, /*removedotdot*/ true);
1028 return Ret;
1029}
1030
1031// Compute the relative path from From to To.
1033 ErrorOr<SmallString<128>> PathToOrErr = canonicalizePath(To);
1034 ErrorOr<SmallString<128>> DirFromOrErr = canonicalizePath(From);
1035 if (!PathToOrErr || !DirFromOrErr)
1037
1038 const SmallString<128> &PathTo = *PathToOrErr;
1039 const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
1040
1041 // Can't construct a relative path between different roots
1042 if (sys::path::root_name(PathTo) != sys::path::root_name(DirFrom))
1043 return sys::path::convert_to_slash(PathTo);
1044
1045 // Skip common prefixes
1046 auto FromTo =
1047 std::mismatch(sys::path::begin(DirFrom), sys::path::end(DirFrom),
1048 sys::path::begin(PathTo));
1049 auto FromI = FromTo.first;
1050 auto ToI = FromTo.second;
1051
1052 // Construct relative path
1053 SmallString<128> Relative;
1054 for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
1056
1057 for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
1059
1060 return std::string(Relative);
1061}
1062
1064 ArrayRef<NewArchiveMember> NewMembers,
1065 SymtabWritingMode WriteSymtab,
1066 object::Archive::Kind Kind, bool Deterministic,
1067 bool Thin, std::optional<bool> IsEC,
1068 function_ref<void(Error)> Warn) {
1069 assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
1070
1071 SmallString<0> SymNamesBuf;
1072 raw_svector_ostream SymNames(SymNamesBuf);
1073 SmallString<0> StringTableBuf;
1074 raw_svector_ostream StringTable(StringTableBuf);
1075 SymMap SymMap;
1076 bool ShouldWriteSymtab = WriteSymtab != SymtabWritingMode::NoSymtab;
1077
1078 // COFF symbol map uses 16-bit indexes, so we can't use it if there are too
1079 // many members. COFF format also requires symbol table presence, so use
1080 // GNU format when NoSymtab is requested.
1081 if (isCOFFArchive(Kind) && (NewMembers.size() > 0xfffe || !ShouldWriteSymtab))
1083
1084 // In the scenario when LLVMContext is populated SymbolicFile will contain a
1085 // reference to it, thus SymbolicFile should be destroyed first.
1086 LLVMContext Context;
1087
1089 StringTable, SymNames, Kind, Thin, Deterministic, WriteSymtab,
1090 isCOFFArchive(Kind) ? &SymMap : nullptr, Context, NewMembers, IsEC, Warn);
1091 if (Error E = DataOrErr.takeError())
1092 return E;
1093 std::vector<MemberData> &Data = *DataOrErr;
1094
1095 uint64_t StringTableSize = 0;
1096 MemberData StringTableMember;
1097 if (!StringTableBuf.empty() && !isAIXBigArchive(Kind)) {
1098 StringTableMember = computeStringTable(StringTableBuf);
1099 StringTableSize = StringTableMember.Header.size() +
1100 StringTableMember.Data.size() +
1101 StringTableMember.Padding.size();
1102 }
1103
1104 // We would like to detect if we need to switch to a 64-bit symbol table.
1105 uint64_t LastMemberEndOffset = 0;
1106 uint64_t LastMemberHeaderOffset = 0;
1107 uint64_t NumSyms = 0;
1108 uint64_t NumSyms32 = 0; // Store symbol number of 32-bit member files.
1109
1110 for (const auto &M : Data) {
1111 // Record the start of the member's offset
1112 LastMemberEndOffset += M.PreHeadPadSize;
1113 LastMemberHeaderOffset = LastMemberEndOffset;
1114 // Account for the size of each part associated with the member.
1115 LastMemberEndOffset += M.Header.size() + M.Data.size() + M.Padding.size();
1116 NumSyms += M.Symbols.size();
1117
1118 // AIX big archive files may contain two global symbol tables. The
1119 // first global symbol table locates 32-bit file members that define global
1120 // symbols; the second global symbol table does the same for 64-bit file
1121 // members. As a big archive can have both 32-bit and 64-bit file members,
1122 // we need to know the number of symbols in each symbol table individually.
1123 if (isAIXBigArchive(Kind) && ShouldWriteSymtab) {
1124 if (!is64BitSymbolicFile(M.SymFile.get()))
1125 NumSyms32 += M.Symbols.size();
1126 }
1127 }
1128
1129 std::optional<uint64_t> HeadersSize;
1130
1131 // The symbol table is put at the end of the big archive file. The symbol
1132 // table is at the start of the archive file for other archive formats.
1133 if (ShouldWriteSymtab && !is64BitKind(Kind)) {
1134 // We assume 32-bit offsets to see if 32-bit symbols are possible or not.
1135 HeadersSize = computeHeadersSize(Kind, Data.size(), StringTableSize,
1136 NumSyms, SymNamesBuf.size(),
1137 isCOFFArchive(Kind) ? &SymMap : nullptr);
1138
1139 // The SYM64 format is used when an archive's member offsets are larger than
1140 // 32-bits can hold. The need for this shift in format is detected by
1141 // writeArchive. To test this we need to generate a file with a member that
1142 // has an offset larger than 32-bits but this demands a very slow test. To
1143 // speed the test up we use this environment variable to pretend like the
1144 // cutoff happens before 32-bits and instead happens at some much smaller
1145 // value.
1146 uint64_t Sym64Threshold = 1ULL << 32;
1147 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
1148 if (Sym64Env)
1149 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
1150
1151 // If LastMemberHeaderOffset isn't going to fit in a 32-bit varible we need
1152 // to switch to 64-bit. Note that the file can be larger than 4GB as long as
1153 // the last member starts before the 4GB offset.
1154 if (*HeadersSize + LastMemberHeaderOffset >= Sym64Threshold) {
1155 switch (Kind) {
1157 // COFF format has no 64-bit version, so we use GNU64 instead.
1158 if (!SymMap.Map.empty() && !SymMap.ECMap.empty())
1159 // Only the COFF format supports the ECSYMBOLS section, so don’t use
1160 // GNU64 when two symbol maps are required.
1162 "Archive is too large: ARM64X does not support archives larger "
1163 "than 4GB");
1164 // Since this changes the headers, we need to recalculate everything.
1165 return writeArchiveToStream(Out, NewMembers, WriteSymtab,
1166 object::Archive::K_GNU64, Deterministic,
1167 Thin, IsEC, Warn);
1170 break;
1171 default:
1173 break;
1174 }
1175 HeadersSize.reset();
1176 }
1177 }
1178
1179 if (Thin)
1180 Out << "!<thin>\n";
1181 else if (isAIXBigArchive(Kind))
1182 Out << "<bigaf>\n";
1183 else
1184 Out << "!<arch>\n";
1185
1186 if (!isAIXBigArchive(Kind)) {
1187 if (ShouldWriteSymtab) {
1188 if (!HeadersSize)
1189 HeadersSize = computeHeadersSize(
1190 Kind, Data.size(), StringTableSize, NumSyms, SymNamesBuf.size(),
1191 isCOFFArchive(Kind) ? &SymMap : nullptr);
1192 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf,
1193 *HeadersSize, NumSyms);
1194
1195 if (isCOFFArchive(Kind))
1196 writeSymbolMap(Out, Kind, Deterministic, Data, SymMap, *HeadersSize);
1197 }
1198
1199 if (StringTableSize)
1200 Out << StringTableMember.Header << StringTableMember.Data
1201 << StringTableMember.Padding;
1202
1203 if (ShouldWriteSymtab && SymMap.ECMap.size())
1204 writeECSymbols(Out, Kind, Deterministic, Data, SymMap);
1205
1206 for (const MemberData &M : Data)
1207 Out << M.Header << M.Data << M.Padding;
1208 } else {
1209 HeadersSize = sizeof(object::BigArchive::FixLenHdr);
1210 LastMemberEndOffset += *HeadersSize;
1211 LastMemberHeaderOffset += *HeadersSize;
1212
1213 // For the big archive (AIX) format, compute a table of member names and
1214 // offsets, used in the member table.
1215 uint64_t MemberTableNameStrTblSize = 0;
1216 std::vector<size_t> MemberOffsets;
1217 std::vector<StringRef> MemberNames;
1218 // Loop across object to find offset and names.
1219 uint64_t MemberEndOffset = sizeof(object::BigArchive::FixLenHdr);
1220 for (size_t I = 0, Size = NewMembers.size(); I != Size; ++I) {
1221 const NewArchiveMember &Member = NewMembers[I];
1222 MemberTableNameStrTblSize += Member.MemberName.size() + 1;
1223 MemberEndOffset += Data[I].PreHeadPadSize;
1224 MemberOffsets.push_back(MemberEndOffset);
1225 MemberNames.push_back(Member.MemberName);
1226 // File member name ended with "`\n". The length is included in
1227 // BigArMemHdrType.
1228 MemberEndOffset += sizeof(object::BigArMemHdrType) +
1229 alignTo(Data[I].Data.size(), 2) +
1230 alignTo(Member.MemberName.size(), 2);
1231 }
1232
1233 // AIX member table size.
1234 uint64_t MemberTableSize = 20 + // Number of members field
1235 20 * MemberOffsets.size() +
1236 MemberTableNameStrTblSize;
1237
1238 SmallString<0> SymNamesBuf32;
1239 SmallString<0> SymNamesBuf64;
1240 raw_svector_ostream SymNames32(SymNamesBuf32);
1241 raw_svector_ostream SymNames64(SymNamesBuf64);
1242
1243 if (ShouldWriteSymtab && NumSyms)
1244 // Generate the symbol names for the members.
1245 for (const auto &M : Data) {
1247 M.SymFile.get(), 0,
1248 is64BitSymbolicFile(M.SymFile.get()) ? SymNames64 : SymNames32,
1249 nullptr);
1250 if (!SymbolsOrErr)
1251 return SymbolsOrErr.takeError();
1252 }
1253
1254 uint64_t MemberTableEndOffset =
1255 LastMemberEndOffset +
1256 alignTo(sizeof(object::BigArMemHdrType) + MemberTableSize, 2);
1257
1258 // In AIX OS, The 'GlobSymOffset' field in the fixed-length header contains
1259 // the offset to the 32-bit global symbol table, and the 'GlobSym64Offset'
1260 // contains the offset to the 64-bit global symbol table.
1261 uint64_t GlobalSymbolOffset =
1262 (ShouldWriteSymtab &&
1263 (WriteSymtab != SymtabWritingMode::BigArchive64) && NumSyms32 > 0)
1264 ? MemberTableEndOffset
1265 : 0;
1266
1267 uint64_t GlobalSymbolOffset64 = 0;
1268 uint64_t NumSyms64 = NumSyms - NumSyms32;
1269 if (ShouldWriteSymtab && (WriteSymtab != SymtabWritingMode::BigArchive32) &&
1270 NumSyms64 > 0) {
1271 if (GlobalSymbolOffset == 0)
1272 GlobalSymbolOffset64 = MemberTableEndOffset;
1273 else
1274 // If there is a global symbol table for 32-bit members,
1275 // the 64-bit global symbol table is after the 32-bit one.
1276 GlobalSymbolOffset64 =
1277 GlobalSymbolOffset + sizeof(object::BigArMemHdrType) +
1278 (NumSyms32 + 1) * 8 + alignTo(SymNamesBuf32.size(), 2);
1279 }
1280
1281 // Fixed Sized Header.
1282 printWithSpacePadding(Out, NewMembers.size() ? LastMemberEndOffset : 0,
1283 20); // Offset to member table
1284 // If there are no file members in the archive, there will be no global
1285 // symbol table.
1286 printWithSpacePadding(Out, GlobalSymbolOffset, 20);
1287 printWithSpacePadding(Out, GlobalSymbolOffset64, 20);
1289 NewMembers.size()
1291 Data[0].PreHeadPadSize
1292 : 0,
1293 20); // Offset to first archive member
1294 printWithSpacePadding(Out, NewMembers.size() ? LastMemberHeaderOffset : 0,
1295 20); // Offset to last archive member
1297 Out, 0,
1298 20); // Offset to first member of free list - Not supported yet
1299
1300 for (const MemberData &M : Data) {
1301 Out << std::string(M.PreHeadPadSize, '\0');
1302 Out << M.Header << M.Data;
1303 if (M.Data.size() % 2)
1304 Out << '\0';
1305 }
1306
1307 if (NewMembers.size()) {
1308 // Member table.
1309 printBigArchiveMemberHeader(Out, "", sys::toTimePoint(0), 0, 0, 0,
1310 MemberTableSize, LastMemberHeaderOffset,
1311 GlobalSymbolOffset ? GlobalSymbolOffset
1312 : GlobalSymbolOffset64);
1313 printWithSpacePadding(Out, MemberOffsets.size(), 20); // Number of members
1314 for (uint64_t MemberOffset : MemberOffsets)
1315 printWithSpacePadding(Out, MemberOffset,
1316 20); // Offset to member file header.
1317 for (StringRef MemberName : MemberNames)
1318 Out << MemberName << '\0'; // Member file name, null byte padding.
1319
1320 if (MemberTableNameStrTblSize % 2)
1321 Out << '\0'; // Name table must be tail padded to an even number of
1322 // bytes.
1323
1324 if (ShouldWriteSymtab) {
1325 // Write global symbol table for 32-bit file members.
1326 if (GlobalSymbolOffset) {
1327 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf32,
1328 *HeadersSize, NumSyms32, LastMemberEndOffset,
1329 GlobalSymbolOffset64);
1330 // Add padding between the symbol tables, if needed.
1331 if (GlobalSymbolOffset64 && (SymNamesBuf32.size() % 2))
1332 Out << '\0';
1333 }
1334
1335 // Write global symbol table for 64-bit file members.
1336 if (GlobalSymbolOffset64)
1337 writeSymbolTable(Out, Kind, Deterministic, Data, SymNamesBuf64,
1338 *HeadersSize, NumSyms64,
1339 GlobalSymbolOffset ? GlobalSymbolOffset
1340 : LastMemberEndOffset,
1341 0, true);
1342 }
1343 }
1344 }
1345 Out.flush();
1346 return Error::success();
1347}
1348
1350 llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "warning: ");
1351}
1352
1355 bool Deterministic, bool Thin,
1356 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
1357 std::optional<bool> IsEC, function_ref<void(Error)> Warn) {
1359 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
1360 if (!Temp)
1361 return Temp.takeError();
1362 raw_fd_ostream Out(Temp->FD, false);
1363
1364 if (Error E = writeArchiveToStream(Out, NewMembers, WriteSymtab, Kind,
1365 Deterministic, Thin, IsEC, Warn)) {
1366 if (Error DiscardError = Temp->discard())
1367 return joinErrors(std::move(E), std::move(DiscardError));
1368 return E;
1369 }
1370
1371 // At this point, we no longer need whatever backing memory
1372 // was used to generate the NewMembers. On Windows, this buffer
1373 // could be a mapped view of the file we want to replace (if
1374 // we're updating an existing archive, say). In that case, the
1375 // rename would still succeed, but it would leave behind a
1376 // temporary file (actually the original file renamed) because
1377 // a file cannot be deleted while there's a handle open on it,
1378 // only renamed. So by freeing this buffer, this ensures that
1379 // the last open handle on the destination file, if any, is
1380 // closed before we attempt to rename.
1381 OldArchiveBuf.reset();
1382
1383 return Temp->keep(ArcName);
1384}
1385
1389 bool Deterministic, bool Thin,
1390 function_ref<void(Error)> Warn) {
1391 SmallVector<char, 0> ArchiveBufferVector;
1392 raw_svector_ostream ArchiveStream(ArchiveBufferVector);
1393
1394 if (Error E =
1395 writeArchiveToStream(ArchiveStream, NewMembers, WriteSymtab, Kind,
1396 Deterministic, Thin, std::nullopt, Warn))
1397 return std::move(E);
1398
1399 return std::make_unique<SmallVectorMemoryBuffer>(
1400 std::move(ArchiveBufferVector), /*RequiresNullTerminator=*/false);
1401}
1402
1403} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static void printNBits(raw_ostream &Out, object::Archive::Kind Kind, uint64_t Val)
bool isImportDescriptor(StringRef Name)
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
static bool isDarwin(object::Archive::Kind Kind)
static uint64_t computeECSymbolsSize(SymMap &SymMap, uint32_t *Padding=nullptr)
static Expected< std::vector< unsigned > > getSymbols(SymbolicFile *Obj, uint16_t Index, raw_ostream &SymNames, SymMap *SymMap)
static bool is64BitSymbolicFile(const SymbolicFile *SymObj)
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, StringRef MemberName, sys::TimePoint< std::chrono::seconds > ModTime, uint64_t Size)
static uint64_t computeHeadersSize(object::Archive::Kind Kind, uint64_t NumMembers, uint64_t StringMemberSize, uint64_t NumSyms, uint64_t SymNamesSize, SymMap *SymMap)
static bool isBSDLike(object::Archive::Kind Kind)
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)
static void 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)
static const uint32_t MinBigArchiveMemDataAlign
static void writeSymbolMap(raw_ostream &Out, object::Archive::Kind Kind, bool Deterministic, ArrayRef< MemberData > Members, SymMap &SymMap, uint64_t MembersOffset)
static MemberData computeStringTable(StringRef Names)
uint16_t getAuxMaxAlignment(uint16_t AuxHeaderSize, AuxiliaryHeader *AuxHeader, uint16_t Log2OfMaxAlign)
static const uint32_t Log2OfAIXPageSize
static bool isECObject(object::SymbolicFile &Obj)
static Expected< std::unique_ptr< SymbolicFile > > getSymbolicFile(MemoryBufferRef Buf, LLVMContext &Context, object::Archive::Kind Kind, function_ref< void(Error)> Warn)
static bool isAIXBigArchive(object::Archive::Kind Kind)
static void writeSymbolTableHeader(raw_ostream &Out, object::Archive::Kind Kind, bool Deterministic, uint64_t Size, uint64_t PrevMemberOffset=0, uint64_t NextMemberOffset=0)
static void printRestOfMemberHeader(raw_ostream &Out, const sys::TimePoint< std::chrono::seconds > &ModTime, unsigned UID, unsigned GID, unsigned Perms, uint64_t Size)
static uint64_t computeSymbolTableSize(object::Archive::Kind Kind, uint64_t NumSyms, uint64_t OffsetSize, uint64_t StringTableSize, uint32_t *Padding=nullptr)
static bool isArchiveSymbol(const object::BasicSymbolRef &S)
static bool isCOFFArchive(object::Archive::Kind Kind)
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, std::optional< bool > IsEC, function_ref< void(Error)> Warn)
static void writeECSymbols(raw_ostream &Out, object::Archive::Kind Kind, bool Deterministic, ArrayRef< MemberData > Members, SymMap &SymMap)
static uint64_t computeSymbolMapSize(uint64_t NumObj, SymMap &SymMap, uint32_t *Padding=nullptr)
static void printLE(raw_ostream &Out, T Val)
static void printGNUSmallMemberHeader(raw_ostream &Out, StringRef Name, const sys::TimePoint< std::chrono::seconds > &ModTime, unsigned UID, unsigned GID, unsigned Perms, uint64_t Size)
static bool useStringTable(bool Thin, StringRef Name)
static bool is64BitKind(object::Archive::Kind Kind)
static uint32_t getMemberAlignment(SymbolicFile *SymObj)
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)
static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size)
static bool isAnyArm64COFF(object::SymbolicFile &Obj)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define offsetof(TYPE, MEMBER)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
StringRef getBuffer() const
This interface provides simple read-only access to a block of memory, and provides simple methods for...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:128
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:310
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
A table of densely packed, null-terminated strings indexed by offset.
Definition StringTable.h:34
constexpr size_t size() const
Returns the byte size of the table.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
An efficient, type-erasing, non-owning reference to a callable.
Expected< unsigned > getGID() const
Definition Archive.h:281
LLVM_ABI Expected< MemoryBufferRef > getMemoryBufferRef() const
Definition Archive.cpp:762
Expected< unsigned > getUID() const
Definition Archive.h:280
Expected< sys::fs::perms > getAccessMode() const
Definition Archive.h:283
Expected< sys::TimePoint< std::chrono::seconds > > getLastModified() const
Definition Archive.h:272
static object::Archive::Kind getDefaultKind()
Definition Archive.cpp:1110
static object::Archive::Kind getDefaultKindForTriple(const Triple &T)
Definition Archive.cpp:1098
static const uint64_t MaxMemberSize
Size field is 10 decimal digits long.
Definition Archive.h:384
This is a value type class that represents a single symbol in the list of symbols in the object file.
Expected< uint32_t > getFlags() const
Get symbol flags (bitwise OR of SymbolRef::Flags)
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
static Expected< std::unique_ptr< SymbolicFile > > createSymbolicFile(MemoryBufferRef Object, llvm::file_magic Type, LLVMContext *Context, bool InitContent=true)
virtual bool is64Bit() const =0
static bool isSymbolicFile(file_magic Type, const LLVMContext *Context)
const XCOFFAuxiliaryHeader32 * auxiliaryHeader32() const
const XCOFFFileHeader64 * fileHeader64() const
const XCOFFFileHeader32 * fileHeader32() const
const XCOFFAuxiliaryHeader64 * auxiliaryHeader64() const
A raw_ostream that writes to a file descriptor.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
uint64_t tell() const
tell - Return the current offset with the file.
raw_ostream & write(unsigned char C)
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
static LLVM_ABI Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:222
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_FILE_MACHINE_ARM64
Definition COFF.h:101
bool isAnyArm64(T Machine)
Definition COFF.h:130
constexpr std::string_view NullImportDescriptorSymbolName
constexpr std::string_view NullThunkDataPrefix
constexpr std::string_view NullThunkDataSuffix
constexpr std::string_view ImportDescriptorPrefix
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:96
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI const file_t kInvalidFile
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:979
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
Definition Path.cpp:237
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
Definition Path.cpp:779
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:478
LLVM_ABI std::string convert_to_slash(StringRef path, Style style=Style::native)
Replaces backslashes with slashes if Windows.
Definition Path.cpp:585
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
Definition Path.cpp:384
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
Definition Path.cpp:246
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition Chrono.h:34
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
Definition Chrono.h:65
std::time_t toTimeT(TimePoint<> TP)
Convert a TimePoint to std::time_t.
Definition Chrono.h:50
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition Magic.cpp:33
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
LLVM_ABI Expected< std::unique_ptr< MemoryBuffer > > writeArchiveToBuffer(ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, function_ref< void(Error)> Warn=warnToStderr)
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI Error writeArchive(StringRef ArcName, ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, std::unique_ptr< MemoryBuffer > OldArchiveBuf=nullptr, std::optional< bool > IsEC=std::nullopt, function_ref< void(Error)> Warn=warnToStderr)
std::error_code make_error_code(BitcodeError E)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
@ is_a_directory
Definition Errc.h:59
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition MathExtras.h:493
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:94
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition Alignment.h:186
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void warnToStderr(Error Err)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Expected< std::string > computeArchiveRelativePath(StringRef From, StringRef To)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
static ErrorOr< SmallString< 128 > > canonicalizePath(StringRef P)
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1256
LLVM_ABI Error writeArchiveToStream(raw_ostream &Out, ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, std::optional< bool > IsEC=std::nullopt, function_ref< void(Error)> Warn=warnToStderr)
SymtabWritingMode
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
std::map< std::string, uint16_t > ECMap
bool UseECMap
std::map< std::string, uint16_t > Map
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
LLVM_ABI object::Archive::Kind detectKindFromObject() const
static LLVM_ABI Expected< NewArchiveMember > getFile(StringRef FileName, bool Deterministic)
static LLVM_ABI Expected< NewArchiveMember > getOldMember(const object::Archive::Child &OldMember, bool Deterministic)
std::unique_ptr< MemoryBuffer > Buf
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition Magic.h:21
@ bitcode
Bitcode file.
Definition Magic.h:24