LLVM 19.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 {
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 return isa<object::MachOObjectFile>(**OptionalObject)
68 : (isa<object::XCOFFObjectFile>(**OptionalObject)
71
72 // Squelch the error in case we had a non-object file.
73 consumeError(OptionalObject.takeError());
74
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) {
80 MemBufferRef, file_magic::bitcode, &Context)) {
81 auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
82 auto TargetTriple = Triple(IRObject.getTargetTriple());
83 return TargetTriple.isOSDarwin()
85 : (TargetTriple.isOSAIX() ? object::Archive::K_AIXBIG
87 } else {
88 // Squelch the error in case this was not a SymbolicFile.
89 consumeError(ObjOrErr.takeError());
90 }
91 }
92
94}
95
98 bool Deterministic) {
100 if (!BufOrErr)
101 return BufOrErr.takeError();
102
104 M.Buf = MemoryBuffer::getMemBuffer(*BufOrErr, false);
105 M.MemberName = M.Buf->getBufferIdentifier();
106 if (!Deterministic) {
107 auto ModTimeOrErr = OldMember.getLastModified();
108 if (!ModTimeOrErr)
109 return ModTimeOrErr.takeError();
110 M.ModTime = ModTimeOrErr.get();
111 Expected<unsigned> UIDOrErr = OldMember.getUID();
112 if (!UIDOrErr)
113 return UIDOrErr.takeError();
114 M.UID = UIDOrErr.get();
115 Expected<unsigned> GIDOrErr = OldMember.getGID();
116 if (!GIDOrErr)
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();
123 }
124 return std::move(M);
125}
126
128 bool Deterministic) {
130 auto FDOrErr = sys::fs::openNativeFileForRead(FileName);
131 if (!FDOrErr)
132 return FDOrErr.takeError();
133 sys::fs::file_t FD = *FDOrErr;
135
136 if (auto EC = sys::fs::status(FD, Status))
137 return errorCodeToError(EC);
138
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.
144
145 ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =
146 MemoryBuffer::getOpenFile(FD, FileName, Status.getSize(), false);
147 if (!MemberBufferOrErr)
148 return errorCodeToError(MemberBufferOrErr.getError());
149
150 if (auto EC = sys::fs::closeFile(FD))
151 return errorCodeToError(EC);
152
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();
162 }
163 return std::move(M);
164}
165
166template <typename T>
167static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
168 uint64_t OldPos = OS.tell();
169 OS << Data;
170 unsigned SizeSoFar = OS.tell() - OldPos;
171 assert(SizeSoFar <= Size && "Data doesn't fit in Size");
172 OS.indent(Size - SizeSoFar);
173}
174
178}
179
182}
183
186}
187
189 switch (Kind) {
194 return false;
198 return true;
199 }
200 llvm_unreachable("not supported for writting");
201}
202
203template <class T>
205 support::endian::write(Out, Val,
208}
209
210template <class T> static void printLE(raw_ostream &Out, T Val) {
212}
213
216 unsigned UID, unsigned GID, unsigned Perms, uint64_t Size) {
217 printWithSpacePadding(Out, sys::toTimeT(ModTime), 12);
218
219 // The format has only 6 chars for uid and gid. Truncate if the provided
220 // values don't fit.
221 printWithSpacePadding(Out, UID % 1000000, 6);
222 printWithSpacePadding(Out, GID % 1000000, 6);
223
224 printWithSpacePadding(Out, format("%o", Perms), 8);
225 printWithSpacePadding(Out, Size, 10);
226 Out << "`\n";
227}
228
229static void
232 unsigned UID, unsigned GID, unsigned Perms,
233 uint64_t Size) {
234 printWithSpacePadding(Out, Twine(Name) + "/", 16);
235 printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
236}
237
238static void
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);
249 Out << Name;
250 while (Pad--)
251 Out.write(uint8_t(0));
252}
253
254static void
257 unsigned UID, unsigned GID, unsigned Perms,
258 uint64_t Size, uint64_t PrevOffset,
259 uint64_t NextOffset) {
260 unsigned NameLen = Name.size();
261
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
271 if (NameLen) {
272 printWithSpacePadding(Out, Name, NameLen); // Name
273 if (NameLen % 2)
274 Out.write(uint8_t(0)); // Null byte padding
275 }
276 Out << "`\n"; // Terminator
277}
278
279static bool useStringTable(bool Thin, StringRef Name) {
280 return Thin || Name.size() >= 16 || Name.contains('/');
281}
282
284 switch (Kind) {
289 return false;
293 return true;
294 }
295 llvm_unreachable("not supported for writting");
296}
297
298static void
301 bool Thin, const NewArchiveMember &M,
303 if (isBSDLike(Kind))
304 return printBSDMemberHeader(Out, Pos, M.MemberName, ModTime, M.UID, M.GID,
305 M.Perms, Size);
306 if (!useStringTable(Thin, M.MemberName))
307 return printGNUSmallMemberHeader(Out, M.MemberName, ModTime, M.UID, M.GID,
308 M.Perms, Size);
309 Out << '/';
310 uint64_t NamePos;
311 if (Thin) {
312 NamePos = StringTable.tell();
313 StringTable << M.MemberName << "/\n";
314 } else {
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))
320 StringTable << '\0';
321 else
322 StringTable << "/\n";
323 }
324 NamePos = Insertion.first->second;
325 }
326 printWithSpacePadding(Out, NamePos, 15);
327 printRestOfMemberHeader(Out, ModTime, M.UID, M.GID, M.Perms, Size);
328}
329
330namespace {
331struct MemberData {
332 std::vector<unsigned> Symbols;
333 std::string Header;
334 StringRef Data;
336 uint64_t PreHeadPadSize = 0;
337 std::unique_ptr<SymbolicFile> SymFile = nullptr;
338};
339} // namespace
340
341static MemberData computeStringTable(StringRef Names) {
342 unsigned Size = Names.size();
343 unsigned Pad = offsetToAlignment(Size, Align(2));
344 std::string Header;
345 raw_string_ostream Out(Header);
346 printWithSpacePadding(Out, "//", 48);
347 printWithSpacePadding(Out, Size + Pad, 10);
348 Out << "`\n";
349 Out.flush();
350 return {{}, std::move(Header), Names, Pad ? "\n" : ""};
351}
352
353static sys::TimePoint<std::chrono::seconds> now(bool Deterministic) {
354 using namespace std::chrono;
355
356 if (!Deterministic)
357 return time_point_cast<seconds>(system_clock::now());
359}
360
362 Expected<uint32_t> SymFlagsOrErr = S.getFlags();
363 if (!SymFlagsOrErr)
364 // TODO: Actually report errors helpfully.
365 report_fatal_error(SymFlagsOrErr.takeError());
366 if (*SymFlagsOrErr & object::SymbolRef::SF_FormatSpecific)
367 return false;
368 if (!(*SymFlagsOrErr & object::SymbolRef::SF_Global))
369 return false;
370 if (*SymFlagsOrErr & object::SymbolRef::SF_Undefined)
371 return false;
372 return true;
373}
374
376 uint64_t Val) {
377 if (is64BitKind(Kind))
378 print<uint64_t>(Out, Kind, Val);
379 else
380 print<uint32_t>(Out, Kind, Val);
381}
382
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
389 if (isBSDLike(Kind))
390 Size += NumSyms * OffsetSize * 2; // Table
391 else
392 Size += NumSyms * OffsetSize; // Table
393 if (isBSDLike(Kind))
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
398 // uniformly.
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.
403 ? 0
405
406 Size += Pad;
407 if (Padding)
408 *Padding = Pad;
409 return Size;
410}
411
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
416
417 for (auto S : SymMap.Map)
418 Size += sizeof(uint16_t) + S.first.length() + 1;
419
421 Size += Pad;
422 if (Padding)
423 *Padding = Pad;
424 return Size;
425}
426
428 uint32_t *Padding = nullptr) {
429 uint64_t Size = sizeof(uint32_t); // Number of symbols
430
431 for (auto S : SymMap.ECMap)
432 Size += sizeof(uint16_t) + S.first.length() + 1;
433
435 Size += Pad;
436 if (Padding)
437 *Padding = Pad;
438 return Size;
439}
440
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,
448 Size);
449 } else if (isAIXBigArchive(Kind)) {
450 printBigArchiveMemberHeader(Out, "", now(Deterministic), 0, 0, 0, Size,
451 PrevMemberOffset, NextMemberOffset);
452 } else {
453 const char *Name = is64BitKind(Kind) ? "/SYM64" : "";
454 printGNUSmallMemberHeader(Out, Name, now(Deterministic), 0, 0, 0, Size);
455 }
456}
457
459 uint64_t NumMembers,
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();
470 };
471 uint32_t HeaderSize = computeSymbolTableHeaderSize();
472 uint64_t Size = strlen("!<arch>\n") + HeaderSize + SymtabSize;
473
474 if (SymMap) {
475 Size += HeaderSize + computeSymbolMapSize(NumMembers, *SymMap);
476 if (SymMap->ECMap.size())
477 Size += HeaderSize + computeECSymbolsSize(*SymMap);
478 }
479
480 return Size + StringMemberSize;
481}
482
486 // Don't attempt to read non-symbolic file types.
488 return nullptr;
489 if (Type == file_magic::bitcode) {
492 if (!ObjOrErr)
493 return ObjOrErr.takeError();
494 return std::move(*ObjOrErr);
495 } else {
496 auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf);
497 if (!ObjOrErr)
498 return ObjOrErr.takeError();
499 return std::move(*ObjOrErr);
500 }
501}
502
503static bool is64BitSymbolicFile(const SymbolicFile *SymObj) {
504 return SymObj != nullptr ? SymObj->is64Bit() : false;
505}
506
507// Log2 of PAGESIZE(4096) on an AIX system.
508static const uint32_t Log2OfAIXPageSize = 12;
509
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
513// byte.
515
516template <typename AuxiliaryHeader>
517uint16_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)
523
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))
530
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)
535
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)
540 // boundary.
541 uint16_t Log2OfAlign =
542 std::max(AuxHeader->MaxAlignOfText, AuxHeader->MaxAlignOfData);
543 return 1 << (Log2OfAlign > Log2OfAIXPageSize ? Log2OfMaxAlign : Log2OfAlign);
544}
545
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
549// memory.
551 XCOFFObjectFile *XCOFFObj = dyn_cast_or_null<XCOFFObjectFile>(SymObj);
552 if (!XCOFFObj)
554
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()
559 XCOFFObj->auxiliaryHeader64(),
562 XCOFFObj->auxiliaryHeader32(), 2);
563}
564
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))
574 return;
575
576 uint64_t OffsetSize = is64BitKind(Kind) ? 8 : 4;
577 uint32_t Pad;
578 uint64_t Size = computeSymbolTableSize(Kind, NumSyms, OffsetSize,
579 StringTable.size(), &Pad);
580 writeSymbolTableHeader(Out, Kind, Deterministic, Size, PrevMemberOffset,
581 NextMemberOffset);
582
583 if (isBSDLike(Kind))
584 printNBits(Out, Kind, NumSyms * 2 * OffsetSize);
585 else
586 printNBits(Out, Kind, NumSyms);
587
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();
594 continue;
595 }
596 }
597
598 for (unsigned StringOffset : M.Symbols) {
599 if (isBSDLike(Kind))
600 printNBits(Out, Kind, StringOffset);
601 printNBits(Out, Kind, Pos); // member offset
602 }
603 Pos += M.Header.size() + M.Data.size() + M.Padding.size();
604 }
605
606 if (isBSDLike(Kind))
607 // byte count of the string table
608 printNBits(Out, Kind, StringTable.size());
609 Out << StringTable;
610
611 while (Pad--)
612 Out.write(uint8_t(0));
613}
614
616 bool Deterministic, ArrayRef<MemberData> Members,
617 SymMap &SymMap, uint64_t MembersOffset) {
618 uint32_t Pad;
619 uint64_t Size = computeSymbolMapSize(Members.size(), SymMap, &Pad);
620 writeSymbolTableHeader(Out, Kind, Deterministic, Size, 0);
621
622 uint32_t Pos = MembersOffset;
623
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();
628 }
629
630 printLE<uint32_t>(Out, SymMap.Map.size());
631
632 for (auto S : SymMap.Map)
633 printLE(Out, S.second);
634 for (auto S : SymMap.Map)
635 Out << S.first << '\0';
636
637 while (Pad--)
638 Out.write(uint8_t(0));
639}
640
642 bool Deterministic, ArrayRef<MemberData> Members,
643 SymMap &SymMap) {
644 uint32_t Pad;
646 printGNUSmallMemberHeader(Out, "/<ECSYMBOLS>", now(Deterministic), 0, 0, 0,
647 Size);
648
649 printLE<uint32_t>(Out, SymMap.ECMap.size());
650
651 for (auto S : SymMap.ECMap)
652 printLE(Out, S.second);
653 for (auto S : SymMap.ECMap)
654 Out << S.first << '\0';
655 while (Pad--)
656 Out.write(uint8_t(0));
657}
658
660 if (Obj.isCOFF())
661 return cast<llvm::object::COFFObjectFile>(&Obj)->getMachine() !=
663
664 if (Obj.isCOFFImportFile())
665 return cast<llvm::object::COFFImportFile>(&Obj)->getMachine() !=
667
668 if (Obj.isIR()) {
669 Expected<std::string> TripleStr =
671 if (!TripleStr)
672 return false;
673 Triple T(*TripleStr);
674 return T.isWindowsArm64EC() || T.getArch() == Triple::x86_64;
675 }
676
677 return false;
678}
679
682 raw_ostream &SymNames,
683 SymMap *SymMap) {
684 std::vector<unsigned> Ret;
685
686 if (Obj == nullptr)
687 return Ret;
688
689 std::map<std::string, uint16_t> *Map = nullptr;
690 if (SymMap)
691 Map = SymMap->UseECMap && isECObject(*Obj) ? &SymMap->ECMap : &SymMap->Map;
692
693 for (const object::BasicSymbolRef &S : Obj->symbols()) {
694 if (!isArchiveSymbol(S))
695 continue;
696 if (Map) {
697 std::string Name;
698 raw_string_ostream NameStream(Name);
699 if (Error E = S.printName(NameStream))
700 return std::move(E);
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';
707 }
708 } else {
709 Ret.push_back(SymNames.tell());
710 if (Error E = S.printName(SymNames))
711 return std::move(E);
712 SymNames << '\0';
713 }
714 }
715 return Ret;
716}
717
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;
725 uint64_t Pos =
727
728 std::vector<MemberData> Ret;
729 bool HasObject = false;
730
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;
735
736 // UniqueTimestamps is a special case to improve debugging on Darwin:
737 //
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.
746 //
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.
752 //
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.
760 //
761 // Additionally, timestamp==0 is treated specially, and causes the
762 // timestamp to be ignored as a match criteria.
763 //
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.
767 //
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.
773 //
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;
784 }
785
786 // The big archive format needs to know the offset of the previous member
787 // header.
788 uint64_t PrevOffset = 0;
789 uint64_t NextMemHeadPadSize = 0;
790 std::unique_ptr<SymbolicFile> CurSymFile;
791 std::unique_ptr<SymbolicFile> NextSymFile;
792 uint16_t Index = 0;
793
794 for (auto M = NewMembers.begin(); M < NewMembers.end(); ++M) {
795 std::string Header;
796 raw_string_ostream Out(Header);
797
798 MemoryBufferRef Buf = M->Buf->getMemBufferRef();
799 StringRef Data = Thin ? "" : Buf.getBuffer();
800
801 Index++;
802
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);
812
814 if (UniqueTimestamps)
815 // Increment timestamp for each file of a given name.
816 ModTime = sys::toTimePoint(FilenameCount[M->MemberName]++);
817 else
818 ModTime = M->ModTime;
819
820 uint64_t Size = Buf.getBufferSize() + MemberPadding;
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);
826 }
827
828 if (NeedSymbols != SymtabWritingMode::NoSymtab || isAIXBigArchive(Kind)) {
829 auto SetNextSymFile = [&NextSymFile,
831 StringRef MemberName) -> Error {
834 if (!SymFileOrErr)
835 return createFileError(MemberName, SymFileOrErr.takeError());
836 NextSymFile = std::move(*SymFileOrErr);
837 return Error::success();
838 };
839
840 if (M == NewMembers.begin())
841 if (Error Err = SetNextSymFile(Buf, M->MemberName))
842 return std::move(Err);
843
844 CurSymFile = std::move(NextSymFile);
845
846 if ((M + 1) != NewMembers.end())
847 if (Error Err = SetNextSymFile((M + 1)->Buf->getMemBufferRef(),
848 (M + 1)->MemberName))
849 return std::move(Err);
850 }
851
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);
857
858 if (M == NewMembers.begin())
859 NextMemHeadPadSize =
860 alignToPowerOf2(OffsetToMemData,
861 getMemberAlignment(CurSymFile.get())) -
862 OffsetToMemData;
863
864 MemHeadPadSize = NextMemHeadPadSize;
865 Pos += MemHeadPadSize;
866 uint64_t NextOffset = Pos + sizeof(object::BigArMemHdrType) +
867 alignTo(M->MemberName.size(), 2) + alignTo(Size, 2);
868
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 +
874 alignTo((M + 1)->MemberName.size(), 2);
875 NextMemHeadPadSize =
876 alignToPowerOf2(OffsetToNextMemData,
877 getMemberAlignment(NextSymFile.get())) -
878 OffsetToNextMemData;
879 NextOffset += NextMemHeadPadSize;
880 }
881 printBigArchiveMemberHeader(Out, M->MemberName, ModTime, M->UID, M->GID,
882 M->Perms, Size, PrevOffset, NextOffset);
883 PrevOffset = Pos;
884 } else {
885 printMemberHeader(Out, Pos, StringTable, MemberNames, Kind, Thin, *M,
886 ModTime, Size);
887 }
888 Out.flush();
889
890 std::vector<unsigned> Symbols;
891 if (NeedSymbols != SymtabWritingMode::NoSymtab) {
892 Expected<std::vector<unsigned>> SymbolsOrErr =
893 getSymbols(CurSymFile.get(), Index, SymNames, SymMap);
894 if (!SymbolsOrErr)
895 return createFileError(M->MemberName, SymbolsOrErr.takeError());
896 Symbols = std::move(*SymbolsOrErr);
897 if (CurSymFile)
898 HasObject = true;
899 }
900
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)});
904 }
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);
911}
912
913namespace llvm {
914
916 SmallString<128> Ret = P;
917 std::error_code Err = sys::fs::make_absolute(Ret);
918 if (Err)
919 return Err;
920 sys::path::remove_dots(Ret, /*removedotdot*/ true);
921 return Ret;
922}
923
924// Compute the relative path from From to To.
928 if (!PathToOrErr || !DirFromOrErr)
929 return errorCodeToError(std::error_code(errno, std::generic_category()));
930
931 const SmallString<128> &PathTo = *PathToOrErr;
932 const SmallString<128> &DirFrom = sys::path::parent_path(*DirFromOrErr);
933
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);
937
938 // Skip common prefixes
939 auto FromTo =
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;
944
945 // Construct relative path
946 SmallString<128> Relative;
947 for (auto FromE = sys::path::end(DirFrom); FromI != FromE; ++FromI)
949
950 for (auto ToE = sys::path::end(PathTo); ToI != ToE; ++ToI)
952
953 return std::string(Relative);
954}
955
958 SymtabWritingMode WriteSymtab,
960 bool Deterministic, bool Thin, bool IsEC) {
961 assert((!Thin || !isBSDLike(Kind)) && "Only the gnu format has a thin mode");
962
963 SmallString<0> SymNamesBuf;
964 raw_svector_ostream SymNames(SymNamesBuf);
965 SmallString<0> StringTableBuf;
966 raw_svector_ostream StringTable(StringTableBuf);
968
969 // COFF symbol map uses 16-bit indexes, so we can't use it if there are too
970 // many members.
971 if (isCOFFArchive(Kind) && NewMembers.size() > 0xfffe)
973
974 // In the scenario when LLVMContext is populated SymbolicFile will contain a
975 // reference to it, thus SymbolicFile should be destroyed first.
977
978 SymMap.UseECMap = IsEC;
980 StringTable, SymNames, Kind, Thin, Deterministic, WriteSymtab,
981 isCOFFArchive(Kind) ? &SymMap : nullptr, Context, NewMembers);
982 if (Error E = DataOrErr.takeError())
983 return E;
984 std::vector<MemberData> &Data = *DataOrErr;
985
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();
993 }
994
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;
1001
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();
1009
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();
1018 }
1019 }
1020
1021 std::optional<uint64_t> HeadersSize;
1022
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);
1030
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
1037 // value.
1038 uint64_t Sym64Threshold = 1ULL << 32;
1039 const char *Sym64Env = std::getenv("SYM64_THRESHOLD");
1040 if (Sym64Env)
1041 StringRef(Sym64Env).getAsInteger(10, Sym64Threshold);
1042
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) {
1049 else
1051 HeadersSize.reset();
1052 }
1053 }
1054
1055 if (Thin)
1056 Out << "!<thin>\n";
1057 else if (isAIXBigArchive(Kind))
1058 Out << "<bigaf>\n";
1059 else
1060 Out << "!<arch>\n";
1061
1062 if (!isAIXBigArchive(Kind)) {
1063 if (ShouldWriteSymtab) {
1064 if (!HeadersSize)
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);
1070
1071 if (isCOFFArchive(Kind))
1072 writeSymbolMap(Out, Kind, Deterministic, Data, SymMap, *HeadersSize);
1073 }
1074
1075 if (StringTableSize)
1076 Out << StringTableMember.Header << StringTableMember.Data
1077 << StringTableMember.Padding;
1078
1079 if (ShouldWriteSymtab && SymMap.ECMap.size())
1080 writeECSymbols(Out, Kind, Deterministic, Data, SymMap);
1081
1082 for (const MemberData &M : Data)
1083 Out << M.Header << M.Data << M.Padding;
1084 } else {
1085 HeadersSize = sizeof(object::BigArchive::FixLenHdr);
1086 LastMemberEndOffset += *HeadersSize;
1087 LastMemberHeaderOffset += *HeadersSize;
1088
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
1103 // BigArMemHdrType.
1104 MemberEndOffset += sizeof(object::BigArMemHdrType) +
1105 alignTo(Data[I].Data.size(), 2) +
1106 alignTo(Member.MemberName.size(), 2);
1107 }
1108
1109 // AIX member table size.
1110 uint64_t MemberTableSize = 20 + // Number of members field
1111 20 * MemberOffsets.size() +
1112 MemberTableNameStrTblSize;
1113
1114 SmallString<0> SymNamesBuf32;
1115 SmallString<0> SymNamesBuf64;
1116 raw_svector_ostream SymNames32(SymNamesBuf32);
1117 raw_svector_ostream SymNames64(SymNamesBuf64);
1118
1119 if (ShouldWriteSymtab && NumSyms)
1120 // Generate the symbol names for the members.
1121 for (const auto &M : Data) {
1123 M.SymFile.get(), 0,
1124 is64BitSymbolicFile(M.SymFile.get()) ? SymNames64 : SymNames32,
1125 nullptr);
1126 if (!SymbolsOrErr)
1127 return SymbolsOrErr.takeError();
1128 }
1129
1130 uint64_t MemberTableEndOffset =
1131 LastMemberEndOffset +
1132 alignTo(sizeof(object::BigArMemHdrType) + MemberTableSize, 2);
1133
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
1141 : 0;
1142
1143 uint64_t GlobalSymbolOffset64 = 0;
1144 uint64_t NumSyms64 = NumSyms - NumSyms32;
1145 if (ShouldWriteSymtab && (WriteSymtab != SymtabWritingMode::BigArchive32) &&
1146 NumSyms64 > 0) {
1147 if (GlobalSymbolOffset == 0)
1148 GlobalSymbolOffset64 = MemberTableEndOffset;
1149 else
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);
1155 }
1156
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
1161 // symbol table.
1162 printWithSpacePadding(Out, GlobalSymbolOffset, 20);
1163 printWithSpacePadding(Out, GlobalSymbolOffset64, 20);
1165 NewMembers.size()
1167 Data[0].PreHeadPadSize
1168 : 0,
1169 20); // Offset to first archive member
1170 printWithSpacePadding(Out, NewMembers.size() ? LastMemberHeaderOffset : 0,
1171 20); // Offset to last archive member
1173 Out, 0,
1174 20); // Offset to first member of free list - Not supported yet
1175
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)
1180 Out << '\0';
1181 }
1182
1183 if (NewMembers.size()) {
1184 // Member table.
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.
1195
1196 if (MemberTableNameStrTblSize % 2)
1197 Out << '\0'; // Name table must be tail padded to an even number of
1198 // bytes.
1199
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))
1208 Out << '\0';
1209 }
1210
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,
1217 0, true);
1218 }
1219 }
1220 }
1221 Out.flush();
1222 return Error::success();
1223}
1224
1227 bool Deterministic, bool Thin,
1228 std::unique_ptr<MemoryBuffer> OldArchiveBuf, bool IsEC) {
1230 sys::fs::TempFile::create(ArcName + ".temp-archive-%%%%%%%.a");
1231 if (!Temp)
1232 return Temp.takeError();
1233 raw_fd_ostream Out(Temp->FD, false);
1234
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));
1239 return E;
1240 }
1241
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();
1253
1254 return Temp->keep(ArcName);
1255}
1256
1260 bool Deterministic, bool Thin) {
1261 SmallVector<char, 0> ArchiveBufferVector;
1262 raw_svector_ostream ArchiveStream(ArchiveBufferVector);
1263
1264 if (Error E = writeArchiveToStream(ArchiveStream, NewMembers, WriteSymtab,
1265 Kind, Deterministic, Thin, false))
1266 return std::move(E);
1267
1268 return std::make_unique<SmallVectorMemoryBuffer>(
1269 std::move(ArchiveBufferVector), /*RequiresNullTerminator=*/false);
1270}
1271
1272} // namespace llvm
This file defines the StringMap class.
#define offsetof(TYPE, MEMBER)
static void printNBits(raw_ostream &Out, object::Archive::Kind Kind, uint64_t Val)
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 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 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)
static const uint32_t Log2OfAIXPageSize
static bool isECObject(object::SymbolicFile &Obj)
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 void printMemberHeader(raw_ostream &Out, uint64_t Pos, raw_ostream &StringTable, StringMap< uint64_t > &MemberNames, object::Archive::Kind Kind, bool Thin, const NewArchiveMember &M, sys::TimePoint< std::chrono::seconds > ModTime, uint64_t Size)
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 Expected< std::unique_ptr< SymbolicFile > > getSymbolicFile(MemoryBufferRef Buf, LLVMContext &Context)
static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size)
BlockVerifier::State From
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::string Name
uint64_t Size
#define I(x, y, z)
Definition: MD5.cpp:58
LLVMContext & Context
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
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:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
reference get()
Returns a reference to the stored T value.
Definition: Error.h:571
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
size_t getBufferSize() const
StringRef getBuffer() const
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:51
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
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
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:307
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:466
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
Expected< unsigned > getGID() const
Definition: Archive.h:236
Expected< MemoryBufferRef > getMemoryBufferRef() const
Definition: Archive.cpp:646
Expected< unsigned > getUID() const
Definition: Archive.h:235
Expected< sys::fs::perms > getAccessMode() const
Definition: Archive.h:238
Expected< sys::TimePoint< std::chrono::seconds > > getLastModified() const
Definition: Archive.h:227
static const uint64_t MaxMemberSize
Size field is 10 decimal digits long.
Definition: Archive.h:335
static object::Archive::Kind getDefaultKindForHost()
Definition: Archive.cpp:972
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: SymbolicFile.h:103
Expected< uint32_t > getFlags() const
Get symbol flags (bitwise OR of SymbolRef::Flags)
Definition: SymbolicFile.h:206
bool isIR() const
Definition: Binary.h:145
bool isCOFFImportFile() const
Definition: Binary.h:141
MemoryBufferRef getMemoryBufferRef() const
Definition: Binary.cpp:43
bool isCOFF() const
Definition: Binary.h:131
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:209
static Expected< std::unique_ptr< SymbolicFile > > createSymbolicFile(MemoryBufferRef Object, llvm::file_magic Type, LLVMContext *Context, bool InitContent=true)
virtual bool is64Bit() const =0
basic_symbol_iterator_range symbols() const
Definition: SymbolicFile.h:165
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
bool is64Bit() const override
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:470
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:150
raw_ostream & write(unsigned char C)
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:690
static 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...
Definition: Path.cpp:1331
Represents the result of a call to sys::fs::status().
Definition: FileSystem.h:226
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_FILE_MACHINE_ARM64
Definition: COFF.h:100
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:91
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:908
const file_t kInvalidFile
std::error_code closeFile(file_t &F)
Close the file object.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
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.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:228
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:237
bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
In-place remove any '.
Definition: Path.cpp:717
StringRef root_name(StringRef path, Style style=Style::native)
Get root name.
Definition: Path.cpp:375
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:469
std::string convert_to_slash(StringRef path, Style style=Style::native)
Replaces backslashes with slashes if Windows.
Definition: Path.cpp:570
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:458
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.
Definition: AddressRanges.h:18
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:33
uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align)
Definition: MathExtras.h:382
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1325
std::error_code make_error_code(BitcodeError E)
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition: Error.h:431
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
static Error writeArchiveToStream(raw_ostream &Out, ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, bool IsEC)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
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:197
Error writeArchive(StringRef ArcName, ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, std::unique_ptr< MemoryBuffer > OldArchiveBuf=nullptr, bool IsEC=false)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
Expected< std::unique_ptr< MemoryBuffer > > writeArchiveToBuffer(ArrayRef< NewArchiveMember > NewMembers, SymtabWritingMode WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin)
Expected< std::string > computeArchiveRelativePath(StringRef From, StringRef To)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:103
static ErrorOr< SmallString< 128 > > canonicalizePath(StringRef P)
SymtabWritingMode
Definition: ArchiveWriter.h:43
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
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
object::Archive::Kind detectKindFromObject() const
static Expected< NewArchiveMember > getFile(StringRef FileName, bool Deterministic)
static Expected< NewArchiveMember > getOldMember(const object::Archive::Child &OldMember, bool Deterministic)
std::unique_ptr< MemoryBuffer > Buf
Definition: ArchiveWriter.h:21
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: Magic.h:20
@ bitcode
Bitcode file.
Definition: Magic.h:23
Fixed-Length Header.
Definition: Archive.h:399