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;
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;
144 symbol_map SymbolMap;
150 void reset()
override {
151 memset(&Header, 0,
sizeof(Header));
152 Header.Machine = TargetObjectWriter->getMachine();
171 void SetSymbolName(COFFSymbol &S);
172 void SetSectionName(COFFSection &S);
174 bool IsPhysicalSection(COFFSection *S);
179 void WriteSymbol(
const COFFSymbol &S);
181 void writeSectionHeaders();
186 const COFFSection &Sec,
const MCSection &MCSec);
193 bool isSymbolRefDifferenceFullyResolvedImpl(
const MCAssembler &
Asm,
196 bool IsPCRel)
const override;
203 void assignSectionNumbers();
228 Header.Machine = TargetObjectWriter->getMachine();
231 COFFSymbol *WinCOFFObjectWriter::createSymbol(
StringRef Name) {
232 Symbols.push_back(make_unique<COFFSymbol>(Name));
236 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(
const MCSymbol *
Symbol) {
239 Ret = createSymbol(Symbol->
getName());
243 COFFSection *WinCOFFObjectWriter::createSection(
StringRef Name) {
244 Sections.emplace_back(make_unique<COFFSection>(Name));
245 return Sections.back().get();
284 void WinCOFFObjectWriter::defineSection(
const MCSectionCOFF &MCSec) {
294 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
295 if (COMDATSymbol->Section)
297 COMDATSymbol->Section =
Section;
302 Symbol->Aux.resize(1);
304 Symbol->Aux[0].AuxType = ATSectionDefinition;
305 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.
getSelection();
312 Section->MCSection = &MCSec;
328 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(
const MCSymbol &Symbol) {
340 return GetOrCreateCOFFSymbol(&Aliasee);
345 void WinCOFFObjectWriter::DefineSymbol(
const MCSymbol &MCSym,
348 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
350 COFFSection *Sec =
nullptr;
353 if (Sym->Section && Sym->Section != Sec)
357 COFFSymbol *
Local =
nullptr;
358 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
361 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
363 std::string WeakName = (
".weak." + MCSym.
getName() +
".default").str();
364 WeakDefault = createSymbol(WeakName);
368 WeakDefault->Section = Sec;
372 Sym->Other = WeakDefault;
376 memset(&Sym->Aux[0], 0,
sizeof(Sym->Aux[0]));
377 Sym->Aux[0].AuxType = ATWeakExternal;
378 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
379 Sym->Aux[0].Aux.WeakExternal.Characteristics =
392 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
393 Local->Data.Type = SymbolCOFF.
getType();
394 Local->Data.StorageClass = SymbolCOFF.
getClass();
418 "Illegal section name encoding for value");
420 static const char Alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
421 "abcdefghijklmnopqrstuvwxyz"
427 char *
Ptr = Buffer + 7;
428 for (
unsigned i = 0; i < 6; ++i) {
429 unsigned Rem = Value % 64;
431 *(Ptr--) = Alphabet[Rem];
435 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
437 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
441 uint64_t StringTableEntry = Strings.getOffset(S.Name);
446 std::memcpy(S.Header.Name, Buffer.
data(), Buffer.
size());
457 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
459 S.set_name_offset(Strings.getOffset(S.Name));
461 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
464 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
472 void WinCOFFObjectWriter::WriteFileHeader(
const COFF::header &Header) {
476 writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
498 void WinCOFFObjectWriter::WriteSymbol(
const COFFSymbol &S) {
500 writeLE32(S.Data.Value);
502 writeLE32(S.Data.SectionNumber);
504 writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
505 writeLE16(S.Data.Type);
506 write8(S.Data.StorageClass);
507 write8(S.Data.NumberOfAuxSymbols);
508 WriteAuxiliarySymbols(S.Aux);
511 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
513 for (
const AuxSymbol &i : S) {
515 case ATFunctionDefinition:
516 writeLE32(i.Aux.FunctionDefinition.TagIndex);
517 writeLE32(i.Aux.FunctionDefinition.TotalSize);
518 writeLE32(i.Aux.FunctionDefinition.PointerToLinenumber);
519 writeLE32(i.Aux.FunctionDefinition.PointerToNextFunction);
520 WriteZeros(
sizeof(i.Aux.FunctionDefinition.unused));
524 case ATbfAndefSymbol:
525 WriteZeros(
sizeof(i.Aux.bfAndefSymbol.unused1));
526 writeLE16(i.Aux.bfAndefSymbol.Linenumber);
527 WriteZeros(
sizeof(i.Aux.bfAndefSymbol.unused2));
528 writeLE32(i.Aux.bfAndefSymbol.PointerToNextFunction);
529 WriteZeros(
sizeof(i.Aux.bfAndefSymbol.unused3));
534 writeLE32(i.Aux.WeakExternal.TagIndex);
535 writeLE32(i.Aux.WeakExternal.Characteristics);
536 WriteZeros(
sizeof(i.Aux.WeakExternal.unused));
542 StringRef(reinterpret_cast<const char *>(&i.Aux),
545 case ATSectionDefinition:
546 writeLE32(i.Aux.SectionDefinition.Length);
547 writeLE16(i.Aux.SectionDefinition.NumberOfRelocations);
548 writeLE16(i.Aux.SectionDefinition.NumberOfLinenumbers);
549 writeLE32(i.Aux.SectionDefinition.CheckSum);
550 writeLE16(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
551 write8(i.Aux.SectionDefinition.Selection);
552 WriteZeros(
sizeof(i.Aux.SectionDefinition.unused));
553 writeLE16(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
562 void WinCOFFObjectWriter::writeSectionHeaders() {
566 std::vector<COFFSection *> Arr;
567 for (
auto &Section : Sections)
568 Arr.push_back(Section.get());
570 [](
const COFFSection *
A,
const COFFSection *
B) {
571 return A->Number <
B->Number;
574 for (
auto &Section : Arr) {
575 if (Section->Number == -1)
579 if (Section->Relocations.size() >= 0xffff)
618 setStream(OldStream);
630 void WinCOFFObjectWriter::writeSection(
MCAssembler &Asm,
632 const COFFSection &Sec,
634 if (Sec.Number == -1)
638 if (Sec.Header.PointerToRawData != 0) {
639 assert(getStream().tell() <= Sec.Header.PointerToRawData &&
640 "Section::PointerToRawData is insane!");
642 unsigned PaddingSize = Sec.Header.PointerToRawData - getStream().tell();
644 "Should only need at most three bytes of padding!");
645 WriteZeros(PaddingSize);
647 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
650 COFFSection *Sec = SectionMap[&MCSec];
652 assert(AuxSyms.
size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
653 AuxSymbol &SecDef = AuxSyms[0];
654 SecDef.Aux.SectionDefinition.CheckSum = CRC;
658 if (Sec.Relocations.empty()) {
659 assert(Sec.Header.PointerToRelocations == 0 &&
660 "Section::PointerToRelocations is insane!");
664 assert(getStream().tell() == Sec.Header.PointerToRelocations &&
665 "Section::PointerToRelocations is insane!");
667 if (Sec.Relocations.size() >= 0xffff) {
677 for (
const auto &Relocation : Sec.Relocations)
678 WriteRelocation(Relocation.Data);
684 void WinCOFFObjectWriter::executePostLayoutBinding(
MCAssembler &Asm,
688 for (
const auto &Section : Asm)
689 defineSection(static_cast<const MCSectionCOFF &>(Section));
691 for (
const MCSymbol &Symbol : Asm.symbols())
693 DefineSymbol(Symbol, Asm, Layout);
696 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
698 bool InSet,
bool IsPCRel)
const {
702 uint16_t
Type = cast<MCSymbolCOFF>(SymA).
getType();
706 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
710 void WinCOFFObjectWriter::recordRelocation(
MCAssembler &Asm,
714 uint64_t &FixedValue) {
715 assert(Target.
getSymA() &&
"Relocation must reference a symbol!");
718 if (!A.isRegistered()) {
720 Twine(
"symbol '") + A.getName() +
721 "' can not be undefined");
724 if (A.isTemporary() && A.isUndefined()) {
726 Twine(
"assembler label '") + A.getName() +
727 "' can not be undefined");
734 assert(SectionMap.find(MCSec) != SectionMap.end() &&
735 "Section must already have been defined in executePostLayoutBinding!");
737 COFFSection *Sec = SectionMap[MCSec];
746 "' can not be undefined in a subtraction expression");
754 int64_t OffsetOfRelocation =
757 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.
getConstant();
762 COFFRelocation Reloc;
764 Reloc.Data.SymbolTableIndex = 0;
768 if (A.isTemporary()) {
769 MCSection *TargetSection = &A.getSection();
771 SectionMap.find(TargetSection) != SectionMap.end() &&
772 "Section must already have been defined in executePostLayoutBinding!");
773 Reloc.Symb = SectionMap[TargetSection]->Symbol;
777 SymbolMap.find(&A) != SymbolMap.end() &&
778 "Symbol must already have been defined in executePostLayoutBinding!");
779 Reloc.Symb = SymbolMap[&
A];
782 ++Reloc.Symb->Relocations;
784 Reloc.Data.VirtualAddress += Fixup.
getOffset();
785 Reloc.Data.Type = TargetObjectWriter->getRelocType(
797 switch (Reloc.Data.Type) {
829 FixedValue = FixedValue + 4;
838 if (TargetObjectWriter->recordRelocation(Fixup))
839 Sec->Relocations.push_back(Reloc);
843 std::time_t Now = time(
nullptr);
850 void WinCOFFObjectWriter::createFileSymbols(
MCAssembler &Asm) {
854 unsigned Count = (Name.
size() + SymbolSize - 1) / SymbolSize;
856 COFFSymbol *
File = createSymbol(
".file");
859 File->Aux.resize(Count);
862 unsigned Length = Name.
size();
863 for (
auto &Aux : File->Aux) {
864 Aux.AuxType = ATFile;
866 if (Length > SymbolSize) {
867 memcpy(&Aux.Aux, Name.c_str() +
Offset, SymbolSize);
868 Length = Length - SymbolSize;
870 memcpy(&Aux.Aux, Name.c_str() +
Offset, Length);
871 memset((
char *)&Aux.Aux + Length, 0, SymbolSize - Length);
875 Offset += SymbolSize;
881 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
885 void WinCOFFObjectWriter::assignSectionNumbers() {
887 auto Assign = [&](COFFSection &
Section) {
889 Section.Symbol->Data.SectionNumber =
I;
890 Section.Symbol->Aux[0].Aux.SectionDefinition.Number =
I;
897 for (
const std::unique_ptr<COFFSection> &Section : Sections)
900 for (
const std::unique_ptr<COFFSection> &Section : Sections)
906 void WinCOFFObjectWriter::assignFileOffsets(
MCAssembler &Asm,
908 unsigned Offset = getInitialOffset();
913 for (
const auto &Section : Asm) {
914 COFFSection *Sec = SectionMap[&
Section];
916 if (Sec->Number == -1)
921 if (IsPhysicalSection(Sec)) {
924 Sec->Header.PointerToRawData =
Offset;
926 Offset += Sec->Header.SizeOfRawData;
929 if (!Sec->Relocations.empty()) {
930 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
932 if (RelocationsOverflow) {
935 Sec->Header.NumberOfRelocations = 0xffff;
937 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
939 Sec->Header.PointerToRelocations =
Offset;
941 if (RelocationsOverflow) {
948 for (
auto &Relocation : Sec->Relocations) {
949 assert(Relocation.Symb->getIndex() != -1);
950 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
954 assert(Sec->Symbol->Aux.size() == 1 &&
955 "Section's symbol must have one aux!");
956 AuxSymbol &Aux = Sec->Symbol->Aux[0];
957 assert(Aux.AuxType == ATSectionDefinition &&
958 "Section's symbol's aux symbol must be a Section Definition!");
959 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
960 Aux.Aux.SectionDefinition.NumberOfRelocations =
961 Sec->Header.NumberOfRelocations;
962 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
963 Sec->Header.NumberOfLineNumbers;
969 void WinCOFFObjectWriter::writeObject(
MCAssembler &Asm,
971 if (Sections.size() > INT32_MAX)
973 "PE COFF object files can't have more than 2147483647 sections");
979 assignSectionNumbers();
980 createFileSymbols(Asm);
982 for (
auto &Symbol : Symbols) {
985 Symbol->Data.SectionNumber = Symbol->Section->Number;
988 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
993 for (
const auto &S : Sections)
995 Strings.add(S->
Name);
996 for (
const auto &S : Symbols)
998 Strings.add(S->
Name);
1002 for (
const auto &S : Sections)
1004 for (
auto &S : Symbols)
1008 for (
auto &Symbol : Symbols) {
1009 if (Symbol->Other) {
1011 assert(Symbol->Aux.size() == 1 &&
"Symbol must contain one aux symbol!");
1012 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1013 "Symbol's aux symbol must be a Weak External!");
1014 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->
getIndex();
1019 for (
auto &Section : Sections) {
1020 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1028 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
1030 COFFSection *Assoc = COMDATSymbol->Section;
1033 Twine(
"Missing associated COMDAT section for section ") +
1037 if (Assoc->Number == -1)
1040 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
1043 assignFileOffsets(Asm, Layout);
1055 WriteFileHeader(Header);
1056 writeSectionHeaders();
1059 sections::iterator I = Sections.begin();
1060 sections::iterator
IE = Sections.end();
1063 for (; I != IE && J != JE; ++
I, ++J)
1064 writeSection(Asm, Layout, **I, *J);
1067 "Header::PointerToSymbolTable is insane!");
1070 for (
auto &Symbol : Symbols)
1072 WriteSymbol(*Symbol);
1075 Strings.write(getStream());
1078 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(
unsigned Machine_)
1082 void MCWinCOFFObjectTargetWriter::anchor() {}
1090 return new WinCOFFObjectWriter(MOTW, OS);
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
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)
const MCSymbol & getSymbol() const
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This represents an "assembler immediate".
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
static void encodeBase64StringEntry(char *Buffer, uint64_t Value)
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
static std::time_t getTime()
A raw_ostream that writes to an SmallVector or SmallString.
void write32le(void *P, uint32_t V)
unsigned getAlignment() const
MCContext & getContext() const
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)...
This represents a section on Windows.
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.
void setIndex(uint32_t Value) const
Set the (implementation defined) index.
const int32_t MaxNumberOfSections16
ArrayRef< std::string > getFileNames()
Utility for building string tables with deduplicated suffixes.
A two-byte section relative fixup.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
uint32_t getOffset() const
uint16_t getClass() const
uint32_t SymbolTableIndex
const MCSymbol * getBaseSymbol(const MCSymbol &Symbol) const
If this symbol is equivalent to A + Constant, return A.
void writeSectionData(const MCSection *Section, const MCAsmLayout &Layout) const
Emit the section contents using the given object writer.
The instances of the Type class are immutable: once they are created, they are never changed...
uint32_t getIndex() const
Get the (implementation defined) index.
MCSymbol * getCOMDATSymbol() const
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
virtual void reset()
lifetime management
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
void reportError(SMLoc L, const Twine &Msg)
A function that returns a base type.
const MCSymbolRefExpr * getSymB() const
unsigned getCharacteristics() const
static wasm::ValType getType(const TargetRegisterClass *RC)
uint16_t NumberOfLineNumbers
PowerPC TLS Dynamic Call Fixup
Twine concat(const Twine &Suffix) const
COFFYAML::AuxSymbolType AuxType
uint32_t PointerToRelocations
const MCSymbolRefExpr * getSymA() const
StringRef getSectionName() 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 const char * Target
MCSection * getParent() const
uint32_t PointerToRawData
static int alignTo(int Num, int PowOf2)
Target - Wrapper for Target specific information.
const MCExpr * getVariableValue(bool SetUsed=true) const
getVariableValue - Get the value for variable symbols.
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
uint64_t getCommonSize() const
Return the size of a 'common' symbol.
llvm_unreachable("Unknown RegBank!")
StringRef getName() const
getName - Get the symbol name.
pointer data()
Return a pointer to the vector's buffer, even if empty().
MCAsmBackend & getBackend() const
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool isCommon() const
Is this a 'common' symbol.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
bool isVariable() const
isVariable - Check if this is a variable symbol.
MCFragment * getFragment(bool SetUsed=true) const
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
int64_t getConstant() const
LLVM Value Representation.
MCObjectWriter * createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS)
Construct a new Win COFF writer instance.
uint32_t PointerToLineNumbers
StringRef - Represent a constant reference to a string, i.e.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
static bool isAssociative(const COFFSection &Section)
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).