54 #define DEBUG_TYPE "WinCOFFObjectWriter" 82 COFFSymbol *
Other =
nullptr;
91 int64_t getIndex()
const {
return Index; }
92 void setIndex(
int Value) {
95 MC->
setIndex(static_cast<uint32_t>(Value));
100 struct COFFRelocation {
102 COFFSymbol *Symb =
nullptr;
104 COFFRelocation() =
default;
109 using relocations = std::vector<COFFRelocation>;
118 COFFSymbol *
Symbol =
nullptr;
119 relocations Relocations;
128 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
129 using sections = std::vector<std::unique_ptr<COFFSection>>;
134 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
143 section_map SectionMap;
148 bool EmitAddrsigSection =
false;
150 std::vector<const MCSymbol *> AddrsigSyms;
152 WinCOFFObjectWriter(std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW,
155 void reset()
override {
156 memset(&Header, 0,
sizeof(Header));
157 Header.
Machine = TargetObjectWriter->getMachine();
168 COFFSection *createSection(
StringRef Name);
172 COFFSymbol *getLinkedSymbol(
const MCSymbol &Symbol);
176 void SetSymbolName(COFFSymbol &S);
177 void SetSectionName(COFFSection &S);
179 bool IsPhysicalSection(COFFSection *S);
184 void WriteSymbol(
const COFFSymbol &S);
186 void writeSectionHeaders();
191 const COFFSection &Sec,
const MCSection &MCSec);
198 bool isSymbolRefDifferenceFullyResolvedImpl(
const MCAssembler &Asm,
201 bool IsPCRel)
const override;
208 void assignSectionNumbers();
211 void emitAddrsigSection()
override { EmitAddrsigSection =
true; }
212 void addAddrsigSymbol(
const MCSymbol *Sym)
override {
213 AddrsigSyms.push_back(Sym);
235 WinCOFFObjectWriter::WinCOFFObjectWriter(
238 Header.Machine = TargetObjectWriter->getMachine();
241 COFFSymbol *WinCOFFObjectWriter::createSymbol(
StringRef Name) {
242 Symbols.push_back(std::make_unique<COFFSymbol>(Name));
243 return Symbols.back().get();
246 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(
const MCSymbol *
Symbol) {
249 Ret = createSymbol(Symbol->
getName());
253 COFFSection *WinCOFFObjectWriter::createSection(
StringRef Name) {
254 Sections.emplace_back(std::make_unique<COFFSection>(Name));
255 return Sections.back().get();
294 void WinCOFFObjectWriter::defineSection(
const MCSectionCOFF &MCSec) {
304 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
305 if (COMDATSymbol->Section)
307 COMDATSymbol->Section =
Section;
312 Symbol->Aux.resize(1);
314 Symbol->Aux[0].AuxType = ATSectionDefinition;
315 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.
getSelection();
322 Section->MCSection = &MCSec;
338 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(
const MCSymbol &Symbol) {
350 return GetOrCreateCOFFSymbol(&Aliasee);
355 void WinCOFFObjectWriter::DefineSymbol(
const MCSymbol &MCSym,
358 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
360 COFFSection *Sec =
nullptr;
363 if (Sym->Section && Sym->Section != Sec)
367 COFFSymbol *Local =
nullptr;
368 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
371 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
373 std::string WeakName = (
".weak." + MCSym.
getName() +
".default").str();
374 WeakDefault = createSymbol(WeakName);
378 WeakDefault->Section = Sec;
382 Sym->Other = WeakDefault;
386 memset(&Sym->Aux[0], 0,
sizeof(Sym->Aux[0]));
387 Sym->Aux[0].AuxType = ATWeakExternal;
388 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
389 Sym->Aux[0].Aux.WeakExternal.Characteristics =
402 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
403 Local->Data.Type = SymbolCOFF.
getType();
404 Local->Data.StorageClass = SymbolCOFF.
getClass();
428 "Illegal section name encoding for value");
430 static const char Alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" 431 "abcdefghijklmnopqrstuvwxyz" 437 char *Ptr = Buffer + 7;
438 for (
unsigned i = 0; i < 6; ++i) {
439 unsigned Rem = Value % 64;
441 *(Ptr--) = Alphabet[Rem];
445 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
447 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
451 uint64_t StringTableEntry = Strings.getOffset(S.Name);
456 std::memcpy(S.Header.Name, Buffer.
data(), Buffer.
size());
467 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
469 S.set_name_offset(Strings.getOffset(S.Name));
471 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
474 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
482 void WinCOFFObjectWriter::WriteFileHeader(
const COFF::header &Header) {
508 void WinCOFFObjectWriter::WriteSymbol(
const COFFSymbol &S) {
514 W.write<
uint16_t>(
static_cast<int16_t
>(S.Data.SectionNumber));
516 W.OS <<
char(S.Data.StorageClass);
517 W.OS <<
char(S.Data.NumberOfAuxSymbols);
518 WriteAuxiliarySymbols(S.Aux);
521 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
523 for (
const AuxSymbol &i : S) {
526 W.write<
uint32_t>(i.Aux.WeakExternal.TagIndex);
527 W.write<
uint32_t>(i.Aux.WeakExternal.Characteristics);
528 W.OS.write_zeros(
sizeof(i.Aux.WeakExternal.unused));
533 W.OS.write(reinterpret_cast<const char *>(&i.Aux),
536 case ATSectionDefinition:
537 W.write<
uint32_t>(i.Aux.SectionDefinition.Length);
538 W.write<
uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
539 W.write<
uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
540 W.write<
uint32_t>(i.Aux.SectionDefinition.CheckSum);
541 W.write<
uint16_t>(
static_cast<int16_t
>(i.Aux.SectionDefinition.Number));
542 W.OS <<
char(i.Aux.SectionDefinition.Selection);
543 W.OS.write_zeros(
sizeof(i.Aux.SectionDefinition.unused));
544 W.write<
uint16_t>(
static_cast<int16_t
>(i.Aux.SectionDefinition.Number >> 16));
553 void WinCOFFObjectWriter::writeSectionHeaders() {
557 std::vector<COFFSection *> Arr;
560 llvm::sort(Arr, [](
const COFFSection *A,
const COFFSection *
B) {
561 return A->Number < B->Number;
569 if (
Section->Relocations.size() >= 0xffff)
612 void WinCOFFObjectWriter::writeSection(
MCAssembler &Asm,
614 const COFFSection &Sec,
616 if (Sec.Number == -1)
620 if (Sec.Header.PointerToRawData != 0) {
621 assert(
W.OS.tell() == Sec.Header.PointerToRawData &&
622 "Section::PointerToRawData is insane!");
624 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
627 COFFSection *Sec = SectionMap[&MCSec];
629 assert(AuxSyms.
size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
630 AuxSymbol &SecDef = AuxSyms[0];
631 SecDef.Aux.SectionDefinition.CheckSum = CRC;
635 if (Sec.Relocations.empty()) {
636 assert(Sec.Header.PointerToRelocations == 0 &&
637 "Section::PointerToRelocations is insane!");
641 assert(
W.OS.tell() == Sec.Header.PointerToRelocations &&
642 "Section::PointerToRelocations is insane!");
644 if (Sec.Relocations.size() >= 0xffff) {
654 for (
const auto &Relocation : Sec.Relocations)
655 WriteRelocation(Relocation.Data);
661 void WinCOFFObjectWriter::executePostLayoutBinding(
MCAssembler &Asm,
663 if (EmitAddrsigSection) {
672 for (
const auto &
Section : Asm)
673 defineSection(static_cast<const MCSectionCOFF &>(
Section));
675 for (
const MCSymbol &Symbol : Asm.symbols())
677 DefineSymbol(Symbol, Asm, Layout);
680 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
682 bool InSet,
bool IsPCRel)
const {
696 void WinCOFFObjectWriter::recordRelocation(
MCAssembler &Asm,
700 uint64_t &FixedValue) {
701 assert(Target.
getSymA() &&
"Relocation must reference a symbol!");
704 if (!A.isRegistered()) {
706 Twine(
"symbol '") + A.getName() +
707 "' can not be undefined");
710 if (A.isTemporary() && A.isUndefined()) {
712 Twine(
"assembler label '") + A.getName() +
713 "' can not be undefined");
720 assert(SectionMap.find(MCSec) != SectionMap.end() &&
721 "Section must already have been defined in executePostLayoutBinding!");
723 COFFSection *Sec = SectionMap[MCSec];
732 "' can not be undefined in a subtraction expression");
740 int64_t OffsetOfRelocation =
743 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.
getConstant();
748 COFFRelocation Reloc;
750 Reloc.Data.SymbolTableIndex = 0;
754 if (A.isTemporary()) {
755 MCSection *TargetSection = &A.getSection();
757 SectionMap.find(TargetSection) != SectionMap.end() &&
758 "Section must already have been defined in executePostLayoutBinding!");
759 Reloc.Symb = SectionMap[TargetSection]->Symbol;
764 "Symbol must already have been defined in executePostLayoutBinding!");
768 ++Reloc.Symb->Relocations;
770 Reloc.Data.VirtualAddress += Fixup.
getOffset();
771 Reloc.Data.Type = TargetObjectWriter->getRelocType(
783 switch (Reloc.Data.Type) {
815 FixedValue = FixedValue + 4;
824 if (TargetObjectWriter->recordRelocation(Fixup))
825 Sec->Relocations.push_back(Reloc);
829 std::time_t Now = time(
nullptr);
836 void WinCOFFObjectWriter::createFileSymbols(
MCAssembler &Asm) {
840 unsigned Count = (Name.
size() + SymbolSize - 1) / SymbolSize;
842 COFFSymbol *
File = createSymbol(
".file");
845 File->Aux.resize(Count);
848 unsigned Length = Name.
size();
849 for (
auto &Aux : File->Aux) {
850 Aux.AuxType = ATFile;
852 if (Length > SymbolSize) {
853 memcpy(&Aux.Aux, Name.c_str() +
Offset, SymbolSize);
854 Length = Length - SymbolSize;
856 memcpy(&Aux.Aux, Name.c_str() +
Offset, Length);
857 memset((
char *)&Aux.Aux + Length, 0, SymbolSize - Length);
861 Offset += SymbolSize;
867 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
871 void WinCOFFObjectWriter::assignSectionNumbers() {
873 auto Assign = [&](COFFSection &
Section) {
875 Section.Symbol->Data.SectionNumber =
I;
876 Section.Symbol->Aux[0].Aux.SectionDefinition.Number =
I;
883 for (
const std::unique_ptr<COFFSection> &
Section : Sections)
886 for (
const std::unique_ptr<COFFSection> &
Section : Sections)
892 void WinCOFFObjectWriter::assignFileOffsets(
MCAssembler &Asm,
894 unsigned Offset =
W.OS.tell();
899 for (
const auto &
Section : Asm) {
900 COFFSection *Sec = SectionMap[&
Section];
902 if (Sec->Number == -1)
907 if (IsPhysicalSection(Sec)) {
908 Sec->Header.PointerToRawData =
Offset;
909 Offset += Sec->Header.SizeOfRawData;
912 if (!Sec->Relocations.empty()) {
913 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
915 if (RelocationsOverflow) {
918 Sec->Header.NumberOfRelocations = 0xffff;
920 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
922 Sec->Header.PointerToRelocations =
Offset;
924 if (RelocationsOverflow) {
931 for (
auto &Relocation : Sec->Relocations) {
932 assert(Relocation.Symb->getIndex() != -1);
933 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
937 assert(Sec->Symbol->Aux.size() == 1 &&
938 "Section's symbol must have one aux!");
939 AuxSymbol &Aux = Sec->Symbol->Aux[0];
940 assert(Aux.AuxType == ATSectionDefinition &&
941 "Section's symbol's aux symbol must be a Section Definition!");
942 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
943 Aux.Aux.SectionDefinition.NumberOfRelocations =
944 Sec->Header.NumberOfRelocations;
945 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
946 Sec->Header.NumberOfLineNumbers;
952 uint64_t WinCOFFObjectWriter::writeObject(
MCAssembler &Asm,
954 uint64_t StartOffset =
W.OS.tell();
956 if (Sections.size() > INT32_MAX)
958 "PE COFF object files can't have more than 2147483647 sections");
964 assignSectionNumbers();
965 createFileSymbols(Asm);
967 for (
auto &Symbol : Symbols) {
970 Symbol->Data.SectionNumber = Symbol->Section->Number;
973 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
978 for (
const auto &S : Sections)
980 Strings.add(S->Name);
981 for (
const auto &S : Symbols)
983 Strings.add(S->Name);
987 for (
const auto &S : Sections)
989 for (
auto &S : Symbols)
993 for (
auto &Symbol : Symbols) {
996 assert(Symbol->Aux.size() == 1 &&
"Symbol must contain one aux symbol!");
997 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
998 "Symbol's aux symbol must be a Weak External!");
999 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->
getIndex();
1004 for (
auto &
Section : Sections) {
1005 if (
Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1018 Twine(
" associative with sectionless symbol ") +
1023 const auto *AssocMCSec = cast<MCSectionCOFF>(&AssocMCSym->
getSection());
1024 assert(SectionMap.count(AssocMCSec));
1025 COFFSection *AssocSec = SectionMap[AssocMCSec];
1028 if (AssocSec->Number == -1)
1031 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = AssocSec->Number;
1035 if (EmitAddrsigSection) {
1037 Frag->setLayoutOrder(0);
1039 for (
const MCSymbol *S : AddrsigSyms) {
1040 if (!S->isTemporary()) {
1045 MCSection *TargetSection = &S->getSection();
1046 assert(SectionMap.find(TargetSection) != SectionMap.end() &&
1047 "Section must already have been defined in " 1048 "executePostLayoutBinding!");
1053 assignFileOffsets(Asm, Layout);
1065 WriteFileHeader(Header);
1066 writeSectionHeaders();
1069 sections::iterator
I = Sections.begin();
1070 sections::iterator
IE = Sections.end();
1073 for (; I != IE && J != JE; ++
I, ++J)
1074 writeSection(Asm, Layout, **I, *J);
1077 "Header::PointerToSymbolTable is insane!");
1080 for (
auto &Symbol : Symbols)
1082 WriteSymbol(*Symbol);
1085 Strings.write(
W.OS);
1087 return W.OS.tell() - StartOffset;
1094 void MCWinCOFFObjectTargetWriter::anchor() {}
1101 return std::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS);
constexpr bool isUInt< 32 >(uint64_t x)
Instances of this class represent a uniqued identifier for a section in the current translation unit...
static uint64_t getSymbolValue(const MCSymbol &Symbol, const MCAsmLayout &Layout)
uint32_t getIndex() const
Get the (implementation defined) index.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
bool isVariable() const
isVariable - Check if this is a variable symbol.
This represents an "assembler immediate".
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static void encodeBase64StringEntry(char *Buffer, uint64_t Value)
static std::time_t getTime()
A raw_ostream that writes to an SmallVector or SmallString.
void write32le(void *P, uint32_t V)
bool isCommon() const
Is this a 'common' symbol.
Defines the object file and target independent interfaces used by the assembler backend to write nati...
static const char BigObjMagic[]
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, SectionKind Kind, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID, const char *BeginSymName=nullptr)
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
unsigned getAlignment() const
This represents a section on Windows.
MCContext & getContext() const
int64_t getConstant() const
const MCSymbolRefExpr * getSymB() const
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Encapsulates the layout of an assembly file at a particular point in time.
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute)...
bool registerSection(MCSection &Section)
Represent a reference to a symbol from inside an expression.
const int32_t MaxNumberOfSections16
ArrayRef< std::string > getFileNames()
Utility for building string tables with deduplicated suffixes.
A two-byte section relative fixup.
unsigned getCharacteristics() const
LLVM_NODISCARD size_t size() const
size - Get the string size.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
COFF::MachineTypes Machine
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
MCWinCOFFObjectTargetWriter(unsigned Machine_)
iterator find(const_arg_type_t< KeyT > Val)
uint32_t SymbolTableIndex
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
The instances of the Type class are immutable: once they are created, they are never changed...
Instrumentation for Order File
virtual void reset()
lifetime management
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
const MCSymbolRefExpr * getSymA() const
uint64_t getCommonSize() const
Return the size of a 'common' symbol.
void reportError(SMLoc L, const Twine &Msg)
DenseMap< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
uint32_t getOffset() const
void writeSectionData(raw_ostream &OS, const MCSection *Section, const MCAsmLayout &Layout) const
Emit the section contents to OS.
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
StringRef getSectionName() const
static wasm::ValType getType(const TargetRegisterClass *RC)
uint16_t NumberOfLineNumbers
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::unique_ptr< MCObjectWriter > createWinCOFFObjectWriter(std::unique_ptr< MCWinCOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS)
Construct a new Win COFF writer instance.
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
void sort(IteratorTy Start, IteratorTy End)
PowerPC TLS Dynamic Call Fixup
COFFYAML::AuxSymbolType AuxType
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
uint32_t PointerToRelocations
MCAsmBackend & getBackend() const
MCSymbol * getCOMDATSymbol() const
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
const MCSymbol & getSymbol() const
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
MCFragment * getFragment(bool SetUsed=true) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
An iterator type that allows iterating over the pointees via some other iterator. ...
static SectionKind getMetadata()
uint32_t PointerToRawData
Target - Wrapper for Target specific information.
MCSection * getParent() const
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
virtual bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B, bool InSet) const
Adapter to write values to a stream in a particular byte order.
void update(ArrayRef< uint8_t > Data)
pointer data()
Return a pointer to the vector's buffer, even if empty().
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
uint16_t getClass() const
StringRef getName() const
getName - Get the symbol name.
An abstract base class for streams implementations that also support a pwrite operation.
Fragment for data and encoded instructions.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
uint16_t NumberOfRelocations
bool isIncrementalLinkerCompatible() const
const MCExpr * getVariableValue(bool SetUsed=true) const
getVariableValue - Get the value for variable symbols.
LLVM Value Representation.
uint32_t PointerToLineNumbers
StringRef - Represent a constant reference to a string, i.e.
Represents a location in source code.
static bool isAssociative(const COFFSection &Section)
void setIndex(uint32_t Value) const
Set the (implementation defined) index.
Twine concat(const Twine &Suffix) const
const MCSymbol * getBaseSymbol(const MCSymbol &Symbol) const
If this symbol is equivalent to A + Constant, return A.
A function that returns a base type.