45#define DEBUG_TYPE "mc"
49 IndirectSymBase.clear();
51 LocalSymbolData.clear();
52 ExternalSymbolData.clear();
53 UndefinedSymbolData.clear();
64 if (cast<MCSymbolMachO>(S).isWeakDefinition())
71bool MachObjectWriter::
72MachSymbolData::operator<(
const MachSymbolData &RHS)
const {
73 return Symbol->getName() <
RHS.Symbol->
getName();
103 if (
Target.getSymA() &&
Target.getSymA()->getSymbol().isUndefined())
106 if (
Target.getSymB() &&
Target.getSymB()->getSymbol().isUndefined())
136 unsigned NumLoadCommands,
137 unsigned LoadCommandsSize,
138 bool SubsectionsViaSymbols) {
141 if (SubsectionsViaSymbols)
186 unsigned SegmentLoadCommandSize =
194 writeWithPadding(
Name, 16);
218 uint64_t FileOffset,
unsigned Flags,
220 unsigned NumRelocations) {
225 if (Section.isVirtualSection()) {
236 writeWithPadding(Section.getName(), 16);
237 writeWithPadding(Section.getSegmentName(), 16);
316MachObjectWriter::MachSymbolData *
317MachObjectWriter::findSymbolData(
const MCSymbol &Sym) {
318 for (
auto *SymbolData :
319 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
320 for (MachSymbolData &Entry : *SymbolData)
321 if (Entry.Symbol == &Sym)
331 const auto *
Ref = dyn_cast<MCSymbolRefExpr>(
Value);
334 S = &
Ref->getSymbol();
341 const MCSymbol *Symbol = MSD.Symbol;
344 uint8_t SectionIndex = MSD.SectionIndex;
347 bool IsAlias = Symbol != AliasedSymbol;
349 const MCSymbol &OrigSymbol = *Symbol;
350 MachSymbolData *AliaseeInfo;
352 AliaseeInfo = findSymbolData(*AliasedSymbol);
354 SectionIndex = AliaseeInfo->SectionIndex;
355 Symbol = AliasedSymbol;
362 if (IsAlias && Symbol->isUndefined())
364 else if (Symbol->isUndefined())
366 else if (Symbol->isAbsolute())
373 if (
Data.isPrivateExtern())
377 if (
Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
381 if (IsAlias && Symbol->isUndefined())
382 Address = AliaseeInfo->StringIndex;
383 else if (Symbol->isDefined())
385 else if (Symbol->isCommon()) {
388 Address = Symbol->getCommonSize();
399 bool EncodeAsAltEntry =
400 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
401 W.
write<
uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
426 for (
const std::string &Option :
Options)
427 Size += Option.size() + 1;
432 const std::vector<std::string> &
Options)
442 for (
const std::string &Option :
Options) {
444 W.
OS << Option <<
'\0';
445 BytesWritten += Option.size() + 1;
469 Asm.getContext().reportError(
Fixup.getLoc(),
470 "unsupported relocation expression");
474 TargetObjectWriter->recordRelocation(
this, Asm, Layout, Fragment,
Fixup,
489 Asm.indirect_symbol_end())) {
490 const MCSectionMachO &Section = cast<MCSectionMachO>(*ISD.Section);
498 "' not in a symbol pointer or stub section");
503 unsigned IndirectIndex = 0;
505 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
506 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
513 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
515 Asm.registerSymbol(*it->Symbol);
521 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
522 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
529 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
535 Asm.registerSymbol(*it->Symbol, &Created);
537 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(
true);
543 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
544 std::vector<MachSymbolData> &ExternalSymbolData,
545 std::vector<MachSymbolData> &UndefinedSymbolData) {
550 ie = Asm.end(); it != ie; ++it, ++
Index)
551 SectionIndexMap[&*it] =
Index;
555 for (
const MCSymbol &Symbol : Asm.symbols()) {
556 if (!Asm.isSymbolLinkerVisible(Symbol))
559 StringTable.
add(Symbol.getName());
568 for (
const MCSymbol &Symbol : Asm.symbols()) {
570 if (!Asm.isSymbolLinkerVisible(Symbol))
573 if (!Symbol.isExternal() && !Symbol.isUndefined())
577 MSD.Symbol = &Symbol;
578 MSD.StringIndex = StringTable.
getOffset(Symbol.getName());
580 if (Symbol.isUndefined()) {
581 MSD.SectionIndex = 0;
582 UndefinedSymbolData.push_back(MSD);
583 }
else if (Symbol.isAbsolute()) {
584 MSD.SectionIndex = 0;
585 ExternalSymbolData.push_back(MSD);
587 MSD.SectionIndex = SectionIndexMap.
lookup(&Symbol.getSection());
588 assert(MSD.SectionIndex &&
"Invalid section index!");
589 ExternalSymbolData.push_back(MSD);
594 for (
const MCSymbol &Symbol : Asm.symbols()) {
596 if (!Asm.isSymbolLinkerVisible(Symbol))
599 if (Symbol.isExternal() || Symbol.isUndefined())
603 MSD.Symbol = &Symbol;
604 MSD.StringIndex = StringTable.
getOffset(Symbol.getName());
606 if (Symbol.isAbsolute()) {
607 MSD.SectionIndex = 0;
608 LocalSymbolData.push_back(MSD);
610 MSD.SectionIndex = SectionIndexMap.
lookup(&Symbol.getSection());
611 assert(MSD.SectionIndex &&
"Invalid section index!");
612 LocalSymbolData.push_back(MSD);
622 for (
auto *SymbolData :
623 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
624 for (MachSymbolData &Entry : *SymbolData)
625 Entry.Symbol->setIndex(
Index++);
628 for (RelAndSymbol &Rel : Relocations[&Section]) {
633 unsigned Index = Rel.Sym->getIndex();
636 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) |
Index | (1 << 27);
638 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) |
Index << 8 | (1 << 4);
647 StartAddress =
alignTo(StartAddress, Sec->getAlign());
648 SectionAddress[Sec] = StartAddress;
672 if (
A.isVariable() ||
B.isVariable())
680 bool InSet,
bool IsPCRel)
const {
707 bool hasReliableSymbolDifference =
isX86_64();
708 if (!hasReliableSymbolDifference) {
711 Asm.getSubsectionsViaSymbols()))
757 Asm.getContext().getObjectFileInfo()->getAddrSigSection();
758 unsigned Log2Size =
is64Bit() ? 3 : 2;
760 if (!S->isRegistered())
777 UndefinedSymbolData);
779 if (!Asm.CGProfile.empty()) {
780 MCSection *CGProfileSection = Asm.getContext().getMachOSection(
784 assert(Frag &&
"call graph profile section not reserved");
796 unsigned NumSections = Asm.size();
802 unsigned NumLoadCommands = 1;
808 if (VersionInfo.Major != 0) {
810 if (VersionInfo.EmitBuildVersion)
820 if (TargetVariantVersionInfo.Major != 0) {
822 assert(TargetVariantVersionInfo.EmitBuildVersion &&
823 "target variant should use build version");
828 unsigned NumDataRegions = Asm.getDataRegions().size();
829 if (NumDataRegions) {
835 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*
this, Layout);
843 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
844 UndefinedSymbolData.size();
846 NumLoadCommands += 2;
852 for (
const auto &Option : Asm.getLinkerOptions()) {
872 if (Sec.isVirtualSection())
875 SectionDataSize = std::max(SectionDataSize,
Address +
Size);
876 SectionDataFileSize = std::max(SectionDataFileSize,
Address + FileSize);
882 unsigned SectionDataPadding =
884 SectionDataFileSize += SectionDataPadding;
888 Asm.getSubsectionsViaSymbols());
892 SectionDataSize, Prot, Prot);
895 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
897 const auto &Sec = cast<MCSectionMachO>(Section);
898 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
899 unsigned NumRelocs = Relocs.size();
901 unsigned Flags = Sec.getTypeAndAttributes();
902 if (Sec.hasInstructions())
905 RelocTableEnd, NumRelocs);
910 auto EmitDeploymentTargetVersion =
913 assert(!V.empty() &&
"empty version");
914 unsigned Update = V.getSubminor().value_or(0);
915 unsigned Minor = V.getMinor().value_or(0);
916 assert(Update < 256 &&
"unencodable update target version");
917 assert(Minor < 256 &&
"unencodable minor target version");
918 assert(V.getMajor() < 65536 &&
"unencodable major target version");
919 return Update | (Minor << 8) | (V.getMajor() << 16);
922 VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
923 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
924 ? EncodeVersion(VersionInfo.SDKVersion)
926 if (VersionInfo.EmitBuildVersion) {
943 if (VersionInfo.Major != 0)
944 EmitDeploymentTargetVersion(VersionInfo);
945 if (TargetVariantVersionInfo.Major != 0)
946 EmitDeploymentTargetVersion(TargetVariantVersionInfo);
949 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
950 if (NumDataRegions) {
951 uint64_t DataRegionsOffset = RelocTableEnd;
952 uint64_t DataRegionsSize = NumDataRegions * 8;
958 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
961 DataInCodeTableEnd, LOHSize);
965 unsigned FirstLocalSymbol = 0;
966 unsigned NumLocalSymbols = LocalSymbolData.size();
967 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
968 unsigned NumExternalSymbols = ExternalSymbolData.size();
969 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
970 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
971 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
972 unsigned NumSymTabSymbols =
973 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
974 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
978 if (NumIndirectSymbols)
979 IndirectSymbolOffset = LOHTableEnd;
982 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
986 SymbolTableOffset + NumSymTabSymbols * (
is64Bit() ?
990 StringTableOffset, StringTable.
getSize());
993 FirstExternalSymbol, NumExternalSymbols,
994 FirstUndefinedSymbol, NumUndefinedSymbols,
995 IndirectSymbolOffset, NumIndirectSymbols);
999 for (
const auto &Option : Asm.getLinkerOptions())
1004 Asm.writeSectionData(
W.
OS, &Sec, Layout);
1017 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
1026 it = Asm.data_region_begin(), ie = Asm.data_region_end();
1037 <<
" start: " << Start <<
"(" <<
Data->Start->getName()
1039 <<
" end: " << End <<
"(" <<
Data->End->getName() <<
")"
1040 <<
" size: " << End - Start <<
"\n");
1051 Asm.getLOHContainer().emit(*
this, Layout);
1062 it = Asm.indirect_symbol_begin(),
1063 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1070 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
1072 if (it->Symbol->isAbsolute())
1085 for (
auto *SymbolData :
1086 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1087 for (MachSymbolData &Entry : *SymbolData)
1094 return W.
OS.
tell() - StartOffset;
1097std::unique_ptr<MCObjectWriter>
1100 return std::make_unique<MachObjectWriter>(std::move(MOTW),
OS,
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
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)
PowerPC TLS Dynamic Call Fixup
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool is64Bit(const char *name)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Encapsulates the layout of an assembly file at a particular point in time.
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
llvm::SmallVectorImpl< MCSection * > & getSectionOrder()
uint64_t getSectionFileSize(const MCSection *Sec) const
Get the data size of the given section, as emitted to the object file.
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
std::vector< IndirectSymbolData >::const_iterator const_indirect_symbol_iterator
std::vector< DataRegionData >::const_iterator const_data_region_iterator
const VersionInfoType & getVersionInfo() const
MachO deployment target version information.
std::vector< IndirectSymbolData >::iterator indirect_symbol_iterator
const VersionInfoType & getDarwinTargetVariantVersionInfo() const
{ bool EmitBuildVersion VersionInfoType
MachO specific deployment target version info.
Fragment for data and encoded instructions.
SmallVectorImpl< char > & getContents()
Base class for the full range of assembler expressions which are needed for parsing.
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) 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)...
const MCSymbol * getAtom() const
MCSection * getParent() const
std::vector< const MCSymbol * > & getAddrsigSyms()
virtual void reset()
lifetime management
virtual bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B, bool InSet) const
This represents a section on a Mach-O system (used by Mac OS X).
Instances of this class represent a uniqued identifier for a section in the current translation unit.
unsigned getLayoutOrder() const
MCSection::FragmentListType & getFragmentList()
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
const MCSymbol & getSymbol() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
const MCExpr * getVariableValue(bool SetUsed=true) const
getVariableValue - Get the value for variable symbols.
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
StringRef getName() const
getName - Get the symbol name.
bool isVariable() const
isVariable - Check if this is a variable symbol.
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
uint32_t getIndex() const
Get the (implementation defined) index.
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
MCFragment * getFragment(bool SetUsed=true) const
This represents an "assembler immediate".
bool doesSymbolRequireExternRelocation(const MCSymbol &S)
uint64_t getSymbolAddress(const MCSymbol &S, const MCAsmLayout &Layout) const
void computeSymbolTable(MCAssembler &Asm, std::vector< MachSymbolData > &LocalSymbolData, std::vector< MachSymbolData > &ExternalSymbolData, std::vector< MachSymbolData > &UndefinedSymbolData)
Compute the symbol table data.
uint64_t getSectionAddress(const MCSection *Sec) const
void addRelocation(const MCSymbol *RelSymbol, const MCSection *Sec, MachO::any_relocation_info &MRE)
uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override
Write the object file and returns the number of bytes written.
void populateAddrSigSection(MCAssembler &Asm)
bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind)
support::endian::Writer W
void executePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) override
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
void writeLinkerOptionsLoadCommand(const std::vector< std::string > &Options)
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)
void writeNlist(MachSymbolData &MSD, const MCAsmLayout &Layout)
const MCSymbol & findAliasedSymbol(const MCSymbol &Sym) const
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B, bool InSet) const override
void writeSection(const MCAsmLayout &Layout, const MCSection &Sec, uint64_t VMAddr, uint64_t FileOffset, unsigned Flags, uint64_t RelocationsStart, unsigned NumRelocations)
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.
void writeLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset, uint32_t DataSize)
void writeHeader(MachO::HeaderFileType Type, unsigned NumLoadCommands, unsigned LoadCommandsSize, bool SubsectionsViaSymbols)
uint64_t getFragmentAddress(const MCFragment *Fragment, const MCAsmLayout &Layout) const
void reset() override
lifetime management
void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override
Record a relocation entry.
void computeSectionAddresses(const MCAssembler &Asm, const MCAsmLayout &Layout)
void writeSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols, uint32_t StringTableOffset, uint32_t StringTableSize)
void bindIndirectSymbols(MCAssembler &Asm)
uint64_t getPaddingSize(const MCSection *SD, const MCAsmLayout &Layout) const
static SectionKind getMetadata()
StringRef - Represent a constant reference to a string, i.e.
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
void finalize()
Analyze the strings and build the final table.
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.
StringRef getName() const
Return a constant reference to the value's name.
Represents a version number in the form major[.minor[.subminor[.build]]].
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
An abstract base class for streams implementations that also support a pwrite operation.
A raw_ostream that writes to an SmallVector or SmallString.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
@ S_ATTR_SOME_INSTRUCTIONS
S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions.
@ 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
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.
std::unique_ptr< MCObjectWriter > createMachObjectWriter(std::unique_ptr< MCMachObjectTargetWriter > MOTW, raw_pwrite_stream &OS, bool IsLittleEndian)
Construct a new Mach-O writer instance.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
MCFixupKind
Extensible enumeration to represent the type of a fixup.
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.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
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.
const MCSymbolRefExpr * From
const MCSymbolRefExpr * To
Target independent information on a fixup kind.
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
unsigned Flags
Flags describing additional information on this fixup kind.
An iterator type that allows iterating over the pointees via some other iterator.
void write(ArrayRef< value_type > Val)