41#define DEBUG_TYPE "mc"
45 IndirectSymBase.clear();
46 IndirectSymbols.clear();
48 SectionAddress.clear();
51 LocalSymbolData.clear();
52 ExternalSymbolData.clear();
53 UndefinedSymbolData.clear();
55 VersionInfo.Major = 0;
57 TargetVariantVersionInfo.Major = 0;
59 LinkerOptions.clear();
65 TargetObjectWriter->setAssembler(
Asm);
82bool MachObjectWriter::
83MachSymbolData::operator<(
const MachSymbolData &RHS)
const {
84 return Symbol->getName() < RHS.Symbol->getName();
91 Asm.getFragmentOffset(*Fragment);
107 if (
Target.getAddSym() &&
Target.getAddSym()->isUndefined())
110 if (
Target.getSubSym() &&
Target.getSubSym()->isUndefined())
123 Asm->getSymbolOffset(S);
131 if (
Next >= SectionOrder.size())
142 if (!Symbol.isTemporary())
145 if (Symbol.isUsedInReloc())
171 unsigned NumLoadCommands,
172 unsigned LoadCommandsSize,
187 W.write<
uint32_t>(TargetObjectWriter->getCPUType());
189 uint32_t Cpusubtype = TargetObjectWriter->getCPUSubtype();
232 unsigned SegmentLoadCommandSize =
236 W.write<
uint32_t>(SegmentLoadCommandSize +
240 writeWithPadding(Name, 16);
244 W.write<
uint64_t>(SectionDataStartOffset);
249 W.write<
uint32_t>(SectionDataStartOffset);
259 assert(
W.OS.tell() - Start == SegmentLoadCommandSize);
264 uint64_t FileOffset,
unsigned Flags,
266 unsigned NumRelocations) {
269 assert(
Asm.getSectionFileSize(Sec) == 0 &&
"Invalid file size!");
276 uint64_t SectionSize =
Asm.getSectionAddressSize(Sec);
279 writeWithPadding(Sec.
getName(), 16);
293 "Cannot encode offset of relocations");
294 W.write<
uint32_t>(NumRelocations ? RelocationsStart : 0);
297 W.write<
uint32_t>(IndirectSymBase.lookup(&Sec));
362MachObjectWriter::MachSymbolData *
363MachObjectWriter::findSymbolData(
const MCSymbol &Sym) {
364 for (
auto *SymbolData :
365 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
366 for (MachSymbolData &Entry : *SymbolData)
367 if (Entry.Symbol == &Sym)
380 S = &
Ref->getSymbol();
386 auto *Symbol = MSD.Symbol;
388 auto *AliasedSymbol =
390 uint8_t SectionIndex = MSD.SectionIndex;
393 bool IsAlias = Symbol != AliasedSymbol;
396 MachSymbolData *AliaseeInfo;
398 AliaseeInfo = findSymbolData(*AliasedSymbol);
400 SectionIndex = AliaseeInfo->SectionIndex;
401 Symbol = AliasedSymbol;
408 if (IsAlias && Symbol->isUndefined())
410 else if (Symbol->isUndefined())
412 else if (Symbol->isAbsolute())
419 if (
Data.isPrivateExtern())
423 if (
Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
427 if (IsAlias && Symbol->isUndefined())
428 Address = AliaseeInfo->StringIndex;
429 else if (Symbol->isDefined())
431 else if (Symbol->isCommon()) {
434 Address = Symbol->getCommonSize();
441 W.OS <<
char(SectionIndex);
445 bool EncodeAsAltEntry = IsAlias && OrigSymbol.
isAltEntry();
446 W.write<
uint16_t>(Symbol->getEncodedFlags(EncodeAsAltEntry));
471 for (
const std::string &Option :
Options)
472 Size += Option.size() + 1;
477 const std::vector<std::string> &
Options)
483 W.write<
uint32_t>(MachO::LC_LINKER_OPTION);
487 for (
const std::string &Option :
Options) {
489 W.OS << Option <<
'\0';
490 BytesWritten += Option.size() + 1;
513 "unsupported relocation expression");
531 for (IndirectSymbolData &
ISD : IndirectSymbols) {
540 "' not in a symbol pointer or stub section");
545 for (
auto [IndirectIndex,
ISD] :
enumerate(IndirectSymbols)) {
553 IndirectSymBase.insert(std::make_pair(
ISD.Section, IndirectIndex));
555 Asm.registerSymbol(*
ISD.Symbol);
559 for (
auto [IndirectIndex,
ISD] :
enumerate(IndirectSymbols)) {
567 IndirectSymBase.insert(std::make_pair(
ISD.Section, IndirectIndex));
572 if (
Asm.registerSymbol(*
ISD.Symbol))
573 ISD.Symbol->setReferenceTypeUndefinedLazy(
true);
580 std::vector<MachSymbolData> &ExternalSymbolData,
581 std::vector<MachSymbolData> &UndefinedSymbolData) {
586 SectionIndexMap[&Sec] = Index++;
599 StringTable.add(Symbol.getName());
601 StringTable.finalize();
611 if (!Sym.isSymbolLinkerVisible())
619 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
621 if (Symbol.isUndefined()) {
622 MSD.SectionIndex = 0;
623 UndefinedSymbolData.push_back(MSD);
624 }
else if (Symbol.isAbsolute()) {
625 MSD.SectionIndex = 0;
626 ExternalSymbolData.push_back(MSD);
628 MSD.SectionIndex = SectionIndexMap.
lookup(&Symbol.getSection());
629 if (!MSD.SectionIndex)
631 ExternalSymbolData.push_back(MSD);
639 if (!Sym.isSymbolLinkerVisible())
647 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
649 if (Symbol.isAbsolute()) {
650 MSD.SectionIndex = 0;
651 LocalSymbolData.push_back(MSD);
653 MSD.SectionIndex = SectionIndexMap.
lookup(&Symbol.getSection());
654 if (!MSD.SectionIndex)
656 LocalSymbolData.push_back(MSD);
666 for (
auto *SymbolData :
667 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
668 for (MachSymbolData &Entry : *SymbolData)
669 Entry.Symbol->setIndex(Index++);
672 for (RelAndSymbol &Rel : Relocations[&Section]) {
677 unsigned Index = Rel.Sym->getIndex();
680 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
682 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
692 if (!Sec.isBssSection()) {
693 SectionOrder.push_back(&Sec);
698 if (Sec.isBssSection()) {
699 SectionOrder.push_back(&Sec);
705 for (
const MCSection *Sec : SectionOrder) {
706 StartAddress =
alignTo(StartAddress, Sec->getAlign());
707 SectionAddress[Sec] = StartAddress;
708 StartAddress +=
Asm.getSectionAddressSize(*Sec);
726 bool IsPCRel)
const {
753 bool hasReliableSymbolDifference =
isX86_64();
754 if (!hasReliableSymbolDifference) {
784 unsigned Log2Size =
is64Bit() ? 3 : 2;
786 if (!S->isRegistered())
798 auto NumBytesWritten = [&] {
return W.OS.tell() - StartOffset; };
804 UndefinedSymbolData);
810 uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
811 uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
821 unsigned NumSections =
Asm.end() -
Asm.begin();
825 unsigned NumLoadCommands = 1;
831 if (VersionInfo.Major != 0) {
833 if (VersionInfo.EmitBuildVersion)
840 if (TargetVariantVersionInfo.Major != 0) {
842 assert(TargetVariantVersionInfo.EmitBuildVersion &&
843 "target variant should use build version");
848 uint32_t TargetTripleCommandSize = 0;
853 TargetTripleCommandSize =
856 LoadCommandsSize += TargetTripleCommandSize;
860 unsigned NumDataRegions = DataRegions.size();
861 if (NumDataRegions) {
867 uint64_t LOHRawSize = LOHContainer.getEmitSize(
Asm, *
this);
875 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
876 UndefinedSymbolData.size();
878 NumLoadCommands += 2;
884 for (
const auto &Option : LinkerOptions) {
904 if (Sec.isBssSection())
907 SectionDataSize = std::max(SectionDataSize,
Address +
Size);
908 SectionDataFileSize = std::max(SectionDataFileSize,
Address + FileSize);
914 unsigned SectionDataPadding =
916 SectionDataFileSize += SectionDataPadding;
924 SectionDataSize, Prot, Prot);
927 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
930 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
931 unsigned NumRelocs = Relocs.size();
933 unsigned Flags = Sec.getTypeAndAttributes();
934 if (Sec.hasInstructions())
939 SMLoc(),
"cannot encode offset of section; object file too large");
940 return NumBytesWritten();
942 if (NumRelocs && !
isUInt<32>(RelocTableEnd)) {
945 "cannot encode offset of relocations; object file too large");
946 return NumBytesWritten();
949 RelocTableEnd, NumRelocs);
954 auto EmitDeploymentTargetVersion =
957 assert(!V.empty() &&
"empty version");
958 unsigned Update = V.getSubminor().value_or(0);
959 unsigned Minor = V.getMinor().value_or(0);
960 assert(Update < 256 &&
"unencodable update target version");
961 assert(Minor < 256 &&
"unencodable minor target version");
962 assert(V.getMajor() < 65536 &&
"unencodable major target version");
963 return Update | (Minor << 8) | (V.getMajor() << 16);
966 VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
967 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
968 ? EncodeVersion(VersionInfo.SDKVersion)
970 if (VersionInfo.EmitBuildVersion) {
972 W.write<
uint32_t>(MachO::LC_BUILD_VERSION);
974 W.write<
uint32_t>(VersionInfo.TypeOrPlatform.Platform);
987 if (VersionInfo.Major != 0)
988 EmitDeploymentTargetVersion(VersionInfo);
989 if (TargetVariantVersionInfo.Major != 0)
990 EmitDeploymentTargetVersion(TargetVariantVersionInfo);
995 "target triple load command size is too small");
998 W.write<
uint32_t>(MachO::LC_TARGET_TRIPLE);
999 W.write<
uint32_t>(TargetTripleCommandSize);
1007 writeWithPadding(*TargetTriple, RemainingSize);
1011 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
1012 if (NumDataRegions) {
1013 uint64_t DataRegionsOffset = RelocTableEnd;
1014 uint64_t DataRegionsSize = NumDataRegions * 8;
1020 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
1023 DataInCodeTableEnd, LOHSize);
1027 unsigned FirstLocalSymbol = 0;
1028 unsigned NumLocalSymbols = LocalSymbolData.size();
1029 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1030 unsigned NumExternalSymbols = ExternalSymbolData.size();
1031 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1032 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1033 unsigned NumIndirectSymbols = IndirectSymbols.size();
1034 unsigned NumSymTabSymbols =
1035 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1036 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1040 if (NumIndirectSymbols)
1041 IndirectSymbolOffset = LOHTableEnd;
1044 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
1048 SymbolTableOffset + NumSymTabSymbols * (
is64Bit() ?
1052 StringTableOffset, StringTable.getSize());
1055 FirstExternalSymbol, NumExternalSymbols,
1056 FirstUndefinedSymbol, NumUndefinedSymbols,
1057 IndirectSymbolOffset, NumIndirectSymbols);
1061 for (
const auto &Option : LinkerOptions)
1066 Asm.writeSectionData(
W.OS, &Sec);
1069 W.OS.write_zeros(Pad);
1073 W.OS.write_zeros(SectionDataPadding);
1079 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
1096 <<
" start: " << Start <<
"(" <<
Data.Start->getName()
1097 <<
")" <<
" end: " << End <<
"(" <<
Data.End->getName()
1098 <<
")" <<
" size: " << End - Start <<
"\n");
1107 unsigned Start =
W.OS.tell();
1109 LOHContainer.emit(
Asm, *
this);
1113 assert(
W.OS.tell() - Start == LOHSize);
1119 for (
auto &
ISD : IndirectSymbols) {
1126 if (
ISD.Symbol->isDefined() && !
ISD.Symbol->isExternal()) {
1128 if (
ISD.Symbol->isAbsolute())
1141 for (
auto *SymbolData :
1142 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1143 for (MachSymbolData &Entry : *SymbolData)
1147 StringTable.write(
W.OS);
1150 return NumBytesWritten();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file defines the DenseMap class.
static unsigned ComputeLinkerOptionsLoadCommandSize(const std::vector< std::string > &Options, bool is64Bit)
static bool isFixupTargetValid(const MCValue &Target)
static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type)
static bool isSymbolLinkerVisible(const MCSymbol &Symbol)
PowerPC TLS Dynamic Call Fixup
static bool is64Bit(const char *name)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
static bool isSectionAtomizableBySymbols(const MCSection &Section)
True if the section is atomized using the symbols in it.
const MCObjectFileInfo * getObjectFileInfo() const
LLVM_ABI MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
Base class for the full range of assembler expressions which are needed for parsing.
LLVM_ABI bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm) const
Try to evaluate the expression to a relocatable value, i.e.
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
LLVM_ABI const MCSymbol * getAtom() const
MCSection * getParent() const
MutableArrayRef< char > getVarContents()
MCSection * getAddrSigSection() const
SmallVector< CGProfileEntry, 0 > CGProfile
virtual void setAssembler(MCAssembler *A)
bool SubsectionsViaSymbols
std::vector< const MCSymbol * > & getAddrsigSyms()
virtual void reset()
lifetime management
MCContext & getContext() const
This represents a section on a Mach-O system (used by Mac OS X).
StringRef getSegmentName() const
unsigned getStubSize() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
bool isBssSection() const
Check whether this section is "virtual", that is has no actual object file contents.
StringRef getName() const
FragList * curFragList() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
bool isUndefined() const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
StringRef getName() const
getName - Get the symbol name.
bool isVariable() const
isVariable - Check if this is a variable symbol.
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
const MCExpr * getVariableValue() const
Get the expression of the variable symbol.
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
MCFragment * getFragment() const
uint64_t getPaddingSize(const MCAssembler &Asm, const MCSection *SD) const
void computeSectionAddresses(const MCAssembler &Asm)
bool doesSymbolRequireExternRelocation(const MCSymbol &S)
void recordRelocation(const MCFragment &F, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override
Record a relocation entry.
void computeSymbolTable(MCAssembler &Asm, std::vector< MachSymbolData > &LocalSymbolData, std::vector< MachSymbolData > &ExternalSymbolData, std::vector< MachSymbolData > &UndefinedSymbolData)
Compute the symbol table data.
uint64_t writeObject() override
Write the object file and returns the number of bytes written.
uint64_t getFragmentAddress(const MCAssembler &Asm, const MCFragment *Fragment) const
bool isSymbolRefDifferenceFullyResolvedImpl(const MCSymbol &SymA, const MCFragment &FB, bool InSet, bool IsPCRel) const override
uint64_t getSectionAddress(const MCSection *Sec) const
void addRelocation(const MCSymbol *RelSymbol, const MCSection *Sec, MachO::any_relocation_info &MRE)
void writeSection(const MCAssembler &Asm, const MCSectionMachO &Sec, uint64_t VMAddr, uint64_t FileOffset, unsigned Flags, uint64_t RelocationsStart, unsigned NumRelocations)
void populateAddrSigSection(MCAssembler &Asm)
support::endian::Writer W
void writeLinkerOptionsLoadCommand(const std::vector< std::string > &Options)
void executePostLayoutBinding() override
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
void writeNlist(MachSymbolData &MSD, const MCAssembler &Asm)
void writeDysymtabLoadCommand(uint32_t FirstLocalSymbol, uint32_t NumLocalSymbols, uint32_t FirstExternalSymbol, uint32_t NumExternalSymbols, uint32_t FirstUndefinedSymbol, uint32_t NumUndefinedSymbols, uint32_t IndirectSymbolOffset, uint32_t NumIndirectSymbols)
const MCSymbol & findAliasedSymbol(const MCSymbol &Sym) const
void writeSegmentLoadCommand(StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize, uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt, uint32_t InitProt)
Write a segment load command.
const MCSymbol * getAtom(const MCSymbol &S) const
void writeLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset, uint32_t DataSize)
void writeHeader(MachO::HeaderFileType Type, unsigned NumLoadCommands, unsigned LoadCommandsSize, bool SubsectionsViaSymbols)
void setAssembler(MCAssembler *Asm) override
void reset() override
lifetime management
void writeSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols, uint32_t StringTableOffset, uint32_t StringTableSize)
void bindIndirectSymbols(MCAssembler &Asm)
uint64_t getSymbolAddress(const MCSymbol &S) const
struct { bool EmitBuildVersion; union { MCVersionMinType Type; MachO::PlatformType Platform; } TypeOrPlatform; unsigned Major; unsigned Minor; unsigned Update; VersionTuple SDKVersion; } VersionInfoType
Represents a location in source code.
static SectionKind getMetadata()
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Represent a constant reference to a string, i.e.
Target - Wrapper for Target specific information.
const char * getName() const
getName - Get the target name.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
Represents a version number in the form major[.minor[.subminor[.build]]].
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
@ S_THREAD_LOCAL_VARIABLE_POINTERS
S_THREAD_LOCAL_VARIABLE_POINTERS - Section with pointers to thread local structures.
@ S_LAZY_SYMBOL_POINTERS
S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers.
@ S_NON_LAZY_SYMBOL_POINTERS
S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers.
@ S_SYMBOL_STUBS
S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in the Reserved2 field.
@ MH_SUBSECTIONS_VIA_SYMBOLS
uint32_t CPU_SUBTYPE_ARM64E_WITH_PTRAUTH_VERSION(unsigned PtrAuthABIVersion, bool PtrAuthKernelABIVersion)
@ S_ATTR_SOME_INSTRUCTIONS
S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions.
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
This is an optimization pass for GlobalISel generic memory operations.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
@ MCVM_WatchOSVersionMin
.watchos_version_min
@ MCVM_OSXVersionMin
.macosx_version_min
@ MCVM_TvOSVersionMin
.tvos_version_min
@ MCVM_IOSVersionMin
.ios_version_min
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
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...
@ Ref
The access may reference the value stored in memory.
OutputIt copy(R &&Range, OutputIt Out)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
unsigned Log2(Align A)
Returns the log2 of the alignment.
This struct is a compact representation of a valid (non-zero power of two) alignment.