54 #define DEBUG_TYPE "WinCOFFObjectWriter" 84 COFFSymbol *
Other =
nullptr;
93 int64_t getIndex()
const {
return Index; }
94 void setIndex(
int Value) {
97 MC->
setIndex(static_cast<uint32_t>(Value));
102 struct COFFRelocation {
104 COFFSymbol *Symb =
nullptr;
106 COFFRelocation() =
default;
111 using relocations = std::vector<COFFRelocation>;
120 COFFSymbol *
Symbol =
nullptr;
121 relocations Relocations;
130 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
131 using sections = std::vector<std::unique_ptr<COFFSection>>;
136 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
145 section_map SectionMap;
150 WinCOFFObjectWriter(std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW,
153 void reset()
override {
154 memset(&Header, 0,
sizeof(Header));
155 Header.
Machine = TargetObjectWriter->getMachine();
166 COFFSection *createSection(
StringRef Name);
170 COFFSymbol *getLinkedSymbol(
const MCSymbol &Symbol);
174 void SetSymbolName(COFFSymbol &S);
175 void SetSectionName(COFFSection &S);
177 bool IsPhysicalSection(COFFSection *S);
182 void WriteSymbol(
const COFFSymbol &S);
184 void writeSectionHeaders();
189 const COFFSection &Sec,
const MCSection &MCSec);
196 bool isSymbolRefDifferenceFullyResolvedImpl(
const MCAssembler &Asm,
199 bool IsPCRel)
const override;
206 void assignSectionNumbers();
228 WinCOFFObjectWriter::WinCOFFObjectWriter(
231 Header.Machine = TargetObjectWriter->getMachine();
234 COFFSymbol *WinCOFFObjectWriter::createSymbol(
StringRef Name) {
235 Symbols.push_back(make_unique<COFFSymbol>(Name));
236 return Symbols.back().get();
239 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(
const MCSymbol *
Symbol) {
242 Ret = createSymbol(Symbol->
getName());
246 COFFSection *WinCOFFObjectWriter::createSection(
StringRef Name) {
247 Sections.emplace_back(make_unique<COFFSection>(Name));
248 return Sections.back().get();
287 void WinCOFFObjectWriter::defineSection(
const MCSectionCOFF &MCSec) {
297 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
298 if (COMDATSymbol->Section)
300 COMDATSymbol->Section =
Section;
305 Symbol->Aux.resize(1);
307 Symbol->Aux[0].AuxType = ATSectionDefinition;
308 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.
getSelection();
315 Section->MCSection = &MCSec;
331 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(
const MCSymbol &Symbol) {
343 return GetOrCreateCOFFSymbol(&Aliasee);
348 void WinCOFFObjectWriter::DefineSymbol(
const MCSymbol &MCSym,
351 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
353 COFFSection *Sec =
nullptr;
356 if (Sym->Section && Sym->Section != Sec)
360 COFFSymbol *Local =
nullptr;
361 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
364 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
366 std::string WeakName = (
".weak." + MCSym.
getName() +
".default").str();
367 WeakDefault = createSymbol(WeakName);
371 WeakDefault->Section = Sec;
375 Sym->Other = WeakDefault;
379 memset(&Sym->Aux[0], 0,
sizeof(Sym->Aux[0]));
380 Sym->Aux[0].AuxType = ATWeakExternal;
381 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
382 Sym->Aux[0].Aux.WeakExternal.Characteristics =
395 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
396 Local->Data.Type = SymbolCOFF.
getType();
397 Local->Data.StorageClass = SymbolCOFF.
getClass();
421 "Illegal section name encoding for value");
423 static const char Alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" 424 "abcdefghijklmnopqrstuvwxyz" 430 char *
Ptr = Buffer + 7;
431 for (
unsigned i = 0; i < 6; ++i) {
432 unsigned Rem = Value % 64;
434 *(Ptr--) = Alphabet[Rem];
438 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
440 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
444 uint64_t StringTableEntry = Strings.getOffset(S.Name);
449 std::memcpy(S.Header.Name, Buffer.
data(), Buffer.
size());
460 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
462 S.set_name_offset(Strings.getOffset(S.Name));
464 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
467 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
475 void WinCOFFObjectWriter::WriteFileHeader(
const COFF::header &Header) {
478 W.write<uint16_t>(0xFFFF);
501 void WinCOFFObjectWriter::WriteSymbol(
const COFFSymbol &S) {
507 W.write<uint16_t>(
static_cast<int16_t
>(S.Data.SectionNumber));
508 W.write<uint16_t>(S.Data.Type);
509 W.OS <<
char(S.Data.StorageClass);
510 W.OS <<
char(S.Data.NumberOfAuxSymbols);
511 WriteAuxiliarySymbols(S.Aux);
514 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
516 for (
const AuxSymbol &i : S) {
518 case ATFunctionDefinition:
519 W.write<
uint32_t>(i.Aux.FunctionDefinition.TagIndex);
520 W.write<
uint32_t>(i.Aux.FunctionDefinition.TotalSize);
521 W.write<
uint32_t>(i.Aux.FunctionDefinition.PointerToLinenumber);
522 W.write<
uint32_t>(i.Aux.FunctionDefinition.PointerToNextFunction);
523 W.OS.write_zeros(
sizeof(i.Aux.FunctionDefinition.unused));
527 case ATbfAndefSymbol:
528 W.OS.write_zeros(
sizeof(i.Aux.bfAndefSymbol.unused1));
529 W.write<uint16_t>(i.Aux.bfAndefSymbol.Linenumber);
530 W.OS.write_zeros(
sizeof(i.Aux.bfAndefSymbol.unused2));
531 W.write<
uint32_t>(i.Aux.bfAndefSymbol.PointerToNextFunction);
532 W.OS.write_zeros(
sizeof(i.Aux.bfAndefSymbol.unused3));
537 W.write<
uint32_t>(i.Aux.WeakExternal.TagIndex);
538 W.write<
uint32_t>(i.Aux.WeakExternal.Characteristics);
539 W.OS.write_zeros(
sizeof(i.Aux.WeakExternal.unused));
544 W.OS.write(reinterpret_cast<const char *>(&i.Aux),
547 case ATSectionDefinition:
548 W.write<
uint32_t>(i.Aux.SectionDefinition.Length);
549 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
550 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
551 W.write<
uint32_t>(i.Aux.SectionDefinition.CheckSum);
552 W.write<uint16_t>(
static_cast<int16_t
>(i.Aux.SectionDefinition.Number));
553 W.OS <<
char(i.Aux.SectionDefinition.Selection);
554 W.OS.write_zeros(
sizeof(i.Aux.SectionDefinition.unused));
555 W.write<uint16_t>(
static_cast<int16_t
>(i.Aux.SectionDefinition.Number >> 16));
564 void WinCOFFObjectWriter::writeSectionHeaders() {
568 std::vector<COFFSection *> Arr;
572 [](
const COFFSection *A,
const COFFSection *
B) {
573 return A->Number <
B->Number;
581 if (
Section->Relocations.size() >= 0xffff)
599 W.write<uint16_t>(R.
Type);
624 void WinCOFFObjectWriter::writeSection(
MCAssembler &Asm,
626 const COFFSection &Sec,
628 if (Sec.Number == -1)
632 if (Sec.Header.PointerToRawData != 0) {
633 assert(
W.OS.tell() <= Sec.Header.PointerToRawData &&
634 "Section::PointerToRawData is insane!");
636 unsigned PaddingSize = Sec.Header.PointerToRawData -
W.OS.tell();
638 "Should only need at most three bytes of padding!");
639 W.OS.write_zeros(PaddingSize);
641 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
644 COFFSection *Sec = SectionMap[&MCSec];
646 assert(AuxSyms.
size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
647 AuxSymbol &SecDef = AuxSyms[0];
648 SecDef.Aux.SectionDefinition.CheckSum = CRC;
652 if (Sec.Relocations.empty()) {
653 assert(Sec.Header.PointerToRelocations == 0 &&
654 "Section::PointerToRelocations is insane!");
658 assert(
W.OS.tell() == Sec.Header.PointerToRelocations &&
659 "Section::PointerToRelocations is insane!");
661 if (Sec.Relocations.size() >= 0xffff) {
671 for (
const auto &Relocation : Sec.Relocations)
672 WriteRelocation(Relocation.Data);
678 void WinCOFFObjectWriter::executePostLayoutBinding(
MCAssembler &Asm,
682 for (
const auto &
Section : Asm)
683 defineSection(static_cast<const MCSectionCOFF &>(
Section));
685 for (
const MCSymbol &Symbol : Asm.symbols())
687 DefineSymbol(Symbol, Asm, Layout);
690 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
692 bool InSet,
bool IsPCRel)
const {
699 uint16_t
Type = cast<MCSymbolCOFF>(SymA).
getType();
706 void WinCOFFObjectWriter::recordRelocation(
MCAssembler &Asm,
710 uint64_t &FixedValue) {
711 assert(Target.
getSymA() &&
"Relocation must reference a symbol!");
714 if (!A.isRegistered()) {
716 Twine(
"symbol '") + A.getName() +
717 "' can not be undefined");
720 if (A.isTemporary() && A.isUndefined()) {
722 Twine(
"assembler label '") + A.getName() +
723 "' can not be undefined");
730 assert(SectionMap.find(MCSec) != SectionMap.end() &&
731 "Section must already have been defined in executePostLayoutBinding!");
733 COFFSection *Sec = SectionMap[MCSec];
742 "' can not be undefined in a subtraction expression");
750 int64_t OffsetOfRelocation =
753 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.
getConstant();
758 COFFRelocation Reloc;
760 Reloc.Data.SymbolTableIndex = 0;
764 if (A.isTemporary()) {
765 MCSection *TargetSection = &A.getSection();
767 SectionMap.find(TargetSection) != SectionMap.end() &&
768 "Section must already have been defined in executePostLayoutBinding!");
769 Reloc.Symb = SectionMap[TargetSection]->Symbol;
774 "Symbol must already have been defined in executePostLayoutBinding!");
778 ++Reloc.Symb->Relocations;
780 Reloc.Data.VirtualAddress += Fixup.
getOffset();
781 Reloc.Data.Type = TargetObjectWriter->getRelocType(
793 switch (Reloc.Data.Type) {
825 FixedValue = FixedValue + 4;
834 if (TargetObjectWriter->recordRelocation(Fixup))
835 Sec->Relocations.push_back(Reloc);
839 std::time_t Now = time(
nullptr);
846 void WinCOFFObjectWriter::createFileSymbols(
MCAssembler &Asm) {
850 unsigned Count = (Name.
size() + SymbolSize - 1) / SymbolSize;
852 COFFSymbol *
File = createSymbol(
".file");
855 File->Aux.resize(Count);
858 unsigned Length = Name.
size();
859 for (
auto &Aux : File->Aux) {
860 Aux.AuxType = ATFile;
862 if (Length > SymbolSize) {
863 memcpy(&Aux.Aux, Name.c_str() +
Offset, SymbolSize);
864 Length = Length - SymbolSize;
866 memcpy(&Aux.Aux, Name.c_str() +
Offset, Length);
867 memset((
char *)&Aux.Aux + Length, 0, SymbolSize - Length);
871 Offset += SymbolSize;
877 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
881 void WinCOFFObjectWriter::assignSectionNumbers() {
883 auto Assign = [&](COFFSection &
Section) {
885 Section.Symbol->Data.SectionNumber =
I;
886 Section.Symbol->Aux[0].Aux.SectionDefinition.Number =
I;
893 for (
const std::unique_ptr<COFFSection> &
Section : Sections)
896 for (
const std::unique_ptr<COFFSection> &
Section : Sections)
902 void WinCOFFObjectWriter::assignFileOffsets(
MCAssembler &Asm,
904 unsigned Offset =
W.OS.tell();
909 for (
const auto &
Section : Asm) {
910 COFFSection *Sec = SectionMap[&
Section];
912 if (Sec->Number == -1)
917 if (IsPhysicalSection(Sec)) {
920 Sec->Header.PointerToRawData =
Offset;
922 Offset += Sec->Header.SizeOfRawData;
925 if (!Sec->Relocations.empty()) {
926 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
928 if (RelocationsOverflow) {
931 Sec->Header.NumberOfRelocations = 0xffff;
933 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
935 Sec->Header.PointerToRelocations =
Offset;
937 if (RelocationsOverflow) {
944 for (
auto &Relocation : Sec->Relocations) {
945 assert(Relocation.Symb->getIndex() != -1);
946 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
950 assert(Sec->Symbol->Aux.size() == 1 &&
951 "Section's symbol must have one aux!");
952 AuxSymbol &Aux = Sec->Symbol->Aux[0];
953 assert(Aux.AuxType == ATSectionDefinition &&
954 "Section's symbol's aux symbol must be a Section Definition!");
955 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
956 Aux.Aux.SectionDefinition.NumberOfRelocations =
957 Sec->Header.NumberOfRelocations;
958 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
959 Sec->Header.NumberOfLineNumbers;
965 uint64_t WinCOFFObjectWriter::writeObject(
MCAssembler &Asm,
967 uint64_t StartOffset =
W.OS.tell();
969 if (Sections.size() > INT32_MAX)
971 "PE COFF object files can't have more than 2147483647 sections");
977 assignSectionNumbers();
978 createFileSymbols(Asm);
980 for (
auto &Symbol : Symbols) {
983 Symbol->Data.SectionNumber = Symbol->Section->Number;
986 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
991 for (
const auto &S : Sections)
993 Strings.add(S->Name);
994 for (
const auto &S : Symbols)
996 Strings.add(S->Name);
1000 for (
const auto &S : Sections)
1002 for (
auto &S : Symbols)
1006 for (
auto &Symbol : Symbols) {
1007 if (Symbol->Other) {
1009 assert(Symbol->Aux.size() == 1 &&
"Symbol must contain one aux symbol!");
1010 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1011 "Symbol's aux symbol must be a Weak External!");
1012 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->
getIndex();
1017 for (
auto &
Section : Sections) {
1018 if (
Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1026 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
1028 COFFSection *Assoc = COMDATSymbol->Section;
1031 Twine(
"Missing associated COMDAT section for section ") +
1035 if (Assoc->Number == -1)
1038 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
1041 assignFileOffsets(Asm, Layout);
1053 WriteFileHeader(Header);
1054 writeSectionHeaders();
1057 sections::iterator
I = Sections.begin();
1058 sections::iterator
IE = Sections.end();
1061 for (; I != IE && J != JE; ++
I, ++J)
1062 writeSection(Asm, Layout, **I, *J);
1065 "Header::PointerToSymbolTable is insane!");
1068 for (
auto &Symbol : Symbols)
1070 WriteSymbol(*Symbol);
1073 Strings.write(
W.OS);
1075 return W.OS.tell() - StartOffset;
1082 void MCWinCOFFObjectTargetWriter::anchor() {}
1089 return llvm::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.
Compute iterated dominance frontiers using a linear time algorithm.
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 ...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
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)
std::map< SymbolStringPtr, JITEvaluatedSymbol > SymbolMap
A map from symbol names (as SymbolStringPtrs) to JITSymbols (address/flags pairs).
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
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[]
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...
Encapsulates the layout of an assembly file at a particular point in time.
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
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_)
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...
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)
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
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. ...
uint32_t PointerToRawData
Target - Wrapper for Target specific information.
MCSection * getParent() const
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.
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.
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.
void update(ArrayRef< char > Data)
uint32_t PointerToLineNumbers
StringRef - Represent a constant reference to a string, i.e.
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.