1 //===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains an implementation of a Win32 COFF object file writer.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFragment.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCSymbolCOFF.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/MC/MCWinCOFFObjectWriter.h"
33 #include "llvm/MC/StringTableBuilder.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/COFF.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/JamCRC.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
51 using llvm::support::endian::write32le;
53 #define DEBUG_TYPE "WinCOFFObjectWriter"
57 typedef SmallString<COFF::NameSize> name;
68 AuxiliaryType AuxType;
76 COFF::symbol Data = {};
78 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
83 COFFSymbol *Other = nullptr;
84 COFFSection *Section = nullptr;
86 const MCSymbol *MC = nullptr;
88 COFFSymbol(StringRef Name) : Name(Name) {}
90 void set_name_offset(uint32_t Offset);
92 int64_t getIndex() const { return Index; }
93 void setIndex(int Value) {
96 MC->setIndex(static_cast<uint32_t>(Value));
100 // This class contains staging data for a COFF relocation entry.
101 struct COFFRelocation {
102 COFF::relocation Data;
103 COFFSymbol *Symb = nullptr;
105 COFFRelocation() = default;
107 static size_t size() { return COFF::RelocationSize; }
110 typedef std::vector<COFFRelocation> relocations;
114 COFF::section Header = {};
118 MCSectionCOFF const *MCSection = nullptr;
119 COFFSymbol *Symbol = nullptr;
120 relocations Relocations;
122 COFFSection(StringRef Name) : Name(Name) {}
125 class WinCOFFObjectWriter : public MCObjectWriter {
127 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
128 typedef std::vector<std::unique_ptr<COFFSection>> sections;
130 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
131 typedef DenseMap<MCSection const *, COFFSection *> section_map;
133 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
135 // Root level file contents.
136 COFF::header Header = {};
139 StringTableBuilder Strings{StringTableBuilder::WinCOFF};
141 // Maps used during object file creation.
142 section_map SectionMap;
143 symbol_map SymbolMap;
147 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
149 void reset() override {
150 memset(&Header, 0, sizeof(Header));
151 Header.Machine = TargetObjectWriter->getMachine();
157 MCObjectWriter::reset();
160 COFFSymbol *createSymbol(StringRef Name);
161 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
162 COFFSection *createSection(StringRef Name);
164 void defineSection(MCSectionCOFF const &Sec);
166 COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
167 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
168 const MCAsmLayout &Layout);
170 void SetSymbolName(COFFSymbol &S);
171 void SetSectionName(COFFSection &S);
173 bool IsPhysicalSection(COFFSection *S);
175 // Entity writing methods.
177 void WriteFileHeader(const COFF::header &Header);
178 void WriteSymbol(const COFFSymbol &S);
179 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
180 void writeSectionHeaders();
181 void WriteRelocation(const COFF::relocation &R);
182 uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
183 const MCSection &MCSec);
184 void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
185 const COFFSection &Sec, const MCSection &MCSec);
187 // MCObjectWriter interface implementation.
189 void executePostLayoutBinding(MCAssembler &Asm,
190 const MCAsmLayout &Layout) override;
192 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
193 const MCSymbol &SymA,
194 const MCFragment &FB, bool InSet,
195 bool IsPCRel) const override;
197 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
198 const MCFragment *Fragment, const MCFixup &Fixup,
199 MCValue Target, bool &IsPCRel,
200 uint64_t &FixedValue) override;
202 void createFileSymbols(MCAssembler &Asm);
203 void assignSectionNumbers();
204 void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
206 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
209 } // end anonymous namespace
211 //------------------------------------------------------------------------------
212 // Symbol class implementation
214 // In the case that the name does not fit within 8 bytes, the offset
215 // into the string table is stored in the last 4 bytes instead, leaving
216 // the first 4 bytes as 0.
217 void COFFSymbol::set_name_offset(uint32_t Offset) {
218 write32le(Data.Name + 0, 0);
219 write32le(Data.Name + 4, Offset);
222 //------------------------------------------------------------------------------
223 // WinCOFFObjectWriter class implementation
225 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
226 raw_pwrite_stream &OS)
227 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
228 Header.Machine = TargetObjectWriter->getMachine();
231 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
232 Symbols.push_back(make_unique<COFFSymbol>(Name));
233 return Symbols.back().get();
236 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
237 COFFSymbol *&Ret = SymbolMap[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();
248 static uint32_t getAlignment(const MCSectionCOFF &Sec) {
249 switch (Sec.getAlignment()) {
251 return COFF::IMAGE_SCN_ALIGN_1BYTES;
253 return COFF::IMAGE_SCN_ALIGN_2BYTES;
255 return COFF::IMAGE_SCN_ALIGN_4BYTES;
257 return COFF::IMAGE_SCN_ALIGN_8BYTES;
259 return COFF::IMAGE_SCN_ALIGN_16BYTES;
261 return COFF::IMAGE_SCN_ALIGN_32BYTES;
263 return COFF::IMAGE_SCN_ALIGN_64BYTES;
265 return COFF::IMAGE_SCN_ALIGN_128BYTES;
267 return COFF::IMAGE_SCN_ALIGN_256BYTES;
269 return COFF::IMAGE_SCN_ALIGN_512BYTES;
271 return COFF::IMAGE_SCN_ALIGN_1024BYTES;
273 return COFF::IMAGE_SCN_ALIGN_2048BYTES;
275 return COFF::IMAGE_SCN_ALIGN_4096BYTES;
277 return COFF::IMAGE_SCN_ALIGN_8192BYTES;
279 llvm_unreachable("unsupported section alignment");
282 /// This function takes a section data object from the assembler
283 /// and creates the associated COFF section staging object.
284 void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
285 COFFSection *Section = createSection(MCSec.getSectionName());
286 COFFSymbol *Symbol = createSymbol(MCSec.getSectionName());
287 Section->Symbol = Symbol;
288 Symbol->Section = Section;
289 Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
291 // Create a COMDAT symbol if needed.
292 if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
293 if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
294 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
295 if (COMDATSymbol->Section)
296 report_fatal_error("two sections have the same comdat");
297 COMDATSymbol->Section = Section;
301 // In this case the auxiliary symbol is a Section Definition.
302 Symbol->Aux.resize(1);
304 Symbol->Aux[0].AuxType = ATSectionDefinition;
305 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
307 // Set section alignment.
308 Section->Header.Characteristics = MCSec.getCharacteristics();
309 Section->Header.Characteristics |= getAlignment(MCSec);
311 // Bind internal COFF section to MC section.
312 Section->MCSection = &MCSec;
313 SectionMap[&MCSec] = Section;
316 static uint64_t getSymbolValue(const MCSymbol &Symbol,
317 const MCAsmLayout &Layout) {
318 if (Symbol.isCommon() && Symbol.isExternal())
319 return Symbol.getCommonSize();
322 if (!Layout.getSymbolOffset(Symbol, Res))
328 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
329 if (!Symbol.isVariable())
332 const MCSymbolRefExpr *SymRef =
333 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
337 const MCSymbol &Aliasee = SymRef->getSymbol();
338 if (!Aliasee.isUndefined())
340 return GetOrCreateCOFFSymbol(&Aliasee);
343 /// This function takes a symbol data object from the assembler
344 /// and creates the associated COFF symbol staging object.
345 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
346 MCAssembler &Assembler,
347 const MCAsmLayout &Layout) {
348 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
349 const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
350 COFFSection *Sec = nullptr;
351 if (Base && Base->getFragment()) {
352 Sec = SectionMap[Base->getFragment()->getParent()];
353 if (Sym->Section && Sym->Section != Sec)
354 report_fatal_error("conflicting sections for symbol");
357 COFFSymbol *Local = nullptr;
358 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
359 Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
361 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
363 std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
364 WeakDefault = createSymbol(WeakName);
366 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
368 WeakDefault->Section = Sec;
372 Sym->Other = WeakDefault;
374 // Setup the Weak External auxiliary symbol.
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 =
380 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
383 Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
390 Local->Data.Value = getSymbolValue(MCSym, Layout);
392 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
393 Local->Data.Type = SymbolCOFF.getType();
394 Local->Data.StorageClass = SymbolCOFF.getClass();
396 // If no storage class was specified in the streamer, define it here.
397 if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
398 bool IsExternal = MCSym.isExternal() ||
399 (!MCSym.getFragment() && !MCSym.isVariable());
401 Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
402 : COFF::IMAGE_SYM_CLASS_STATIC;
409 // Maximum offsets for different string table entry encodings.
410 enum : unsigned { Max7DecimalOffset = 9999999U };
411 enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
413 // Encode a string table entry offset in base 64, padded to 6 chars, and
414 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
415 // Buffer must be at least 8 bytes large. No terminating null appended.
416 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
417 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
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) {
436 if (S.Name.size() <= COFF::NameSize) {
437 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
441 uint64_t StringTableEntry = Strings.getOffset(S.Name);
442 if (StringTableEntry <= Max7DecimalOffset) {
443 SmallVector<char, COFF::NameSize> Buffer;
444 Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
445 assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
446 std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
449 if (StringTableEntry <= MaxBase64Offset) {
450 // Starting with 10,000,000, offsets are encoded as base64.
451 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
454 report_fatal_error("COFF string table is greater than 64 GB.");
457 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
458 if (S.Name.size() > COFF::NameSize)
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) {
465 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
469 //------------------------------------------------------------------------------
470 // entity writing methods
472 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
474 writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
476 writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
477 writeLE16(Header.Machine);
478 writeLE32(Header.TimeDateStamp);
479 writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
484 writeLE32(Header.NumberOfSections);
485 writeLE32(Header.PointerToSymbolTable);
486 writeLE32(Header.NumberOfSymbols);
488 writeLE16(Header.Machine);
489 writeLE16(static_cast<int16_t>(Header.NumberOfSections));
490 writeLE32(Header.TimeDateStamp);
491 writeLE32(Header.PointerToSymbolTable);
492 writeLE32(Header.NumberOfSymbols);
493 writeLE16(Header.SizeOfOptionalHeader);
494 writeLE16(Header.Characteristics);
498 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
499 writeBytes(StringRef(S.Data.Name, COFF::NameSize));
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(
512 const COFFSymbol::AuxiliarySymbols &S) {
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));
522 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
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));
531 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
534 writeLE32(i.Aux.WeakExternal.TagIndex);
535 writeLE32(i.Aux.WeakExternal.Characteristics);
536 WriteZeros(sizeof(i.Aux.WeakExternal.unused));
538 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
542 StringRef(reinterpret_cast<const char *>(&i.Aux),
543 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
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));
555 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
561 // Write the section header.
562 void WinCOFFObjectWriter::writeSectionHeaders() {
563 // Section numbers must be monotonically increasing in the section
564 // header, but our Sections array is not sorted by section number,
565 // so make a copy of Sections and sort it.
566 std::vector<COFFSection *> Arr;
567 for (auto &Section : Sections)
568 Arr.push_back(Section.get());
569 std::sort(Arr.begin(), Arr.end(),
570 [](const COFFSection *A, const COFFSection *B) {
571 return A->Number < B->Number;
574 for (auto &Section : Arr) {
575 if (Section->Number == -1)
578 COFF::section &S = Section->Header;
579 if (Section->Relocations.size() >= 0xffff)
580 S.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
581 writeBytes(StringRef(S.Name, COFF::NameSize));
582 writeLE32(S.VirtualSize);
583 writeLE32(S.VirtualAddress);
584 writeLE32(S.SizeOfRawData);
585 writeLE32(S.PointerToRawData);
586 writeLE32(S.PointerToRelocations);
587 writeLE32(S.PointerToLineNumbers);
588 writeLE16(S.NumberOfRelocations);
589 writeLE16(S.NumberOfLineNumbers);
590 writeLE32(S.Characteristics);
594 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
595 writeLE32(R.VirtualAddress);
596 writeLE32(R.SymbolTableIndex);
600 // Write MCSec's contents. What this function does is essentially
601 // "Asm.writeSectionData(&MCSec, Layout)", but it's a bit complicated
602 // because it needs to compute a CRC.
603 uint32_t WinCOFFObjectWriter::writeSectionContents(MCAssembler &Asm,
604 const MCAsmLayout &Layout,
605 const MCSection &MCSec) {
606 // Save the contents of the section to a temporary buffer, we need this
607 // to CRC the data before we dump it into the object file.
608 SmallVector<char, 128> Buf;
609 raw_svector_ostream VecOS(Buf);
610 raw_pwrite_stream &OldStream = getStream();
612 // Redirect the output stream to our buffer and fill our buffer with
615 Asm.writeSectionData(&MCSec, Layout);
617 // Reset the stream back to what it was before.
618 setStream(OldStream);
620 // Write the section contents to the object file.
623 // Calculate our CRC with an initial value of '0', this is not how
624 // JamCRC is specified but it aligns with the expected output.
625 JamCRC JC(/*Init=*/0);
630 void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
631 const MCAsmLayout &Layout,
632 const COFFSection &Sec,
633 const MCSection &MCSec) {
634 if (Sec.Number == -1)
637 // Write the section contents.
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();
643 assert(PaddingSize < 4 &&
644 "Should only need at most three bytes of padding!");
645 WriteZeros(PaddingSize);
647 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
649 // Update the section definition auxiliary symbol to record the CRC.
650 COFFSection *Sec = SectionMap[&MCSec];
651 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
652 assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
653 AuxSymbol &SecDef = AuxSyms[0];
654 SecDef.Aux.SectionDefinition.CheckSum = CRC;
657 // Write relocations for this section.
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) {
668 // In case of overflow, write actual relocation count as first
669 // relocation. Including the synthetic reloc itself (+ 1).
671 R.VirtualAddress = Sec.Relocations.size() + 1;
672 R.SymbolTableIndex = 0;
677 for (const auto &Relocation : Sec.Relocations)
678 WriteRelocation(Relocation.Data);
681 ////////////////////////////////////////////////////////////////////////////////
682 // MCObjectWriter interface implementations
684 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
685 const MCAsmLayout &Layout) {
686 // "Define" each section & symbol. This creates section & symbol
687 // entries in the staging area.
688 for (const auto &Section : Asm)
689 defineSection(static_cast<const MCSectionCOFF &>(Section));
691 for (const MCSymbol &Symbol : Asm.symbols())
692 if (!Symbol.isTemporary())
693 DefineSymbol(Symbol, Asm, Layout);
696 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
697 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
698 bool InSet, bool IsPCRel) const {
699 // MS LINK expects to be able to replace all references to a function with a
700 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
701 // away any relocations to functions.
702 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
703 if (Asm.isIncrementalLinkerCompatible() &&
704 (Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
706 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
710 void WinCOFFObjectWriter::recordRelocation(
711 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
712 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
713 assert(Target.getSymA() && "Relocation must reference a symbol!");
715 const MCSymbol &A = Target.getSymA()->getSymbol();
716 if (!A.isRegistered()) {
717 Asm.getContext().reportError(Fixup.getLoc(),
718 Twine("symbol '") + A.getName() +
719 "' can not be undefined");
722 if (A.isTemporary() && A.isUndefined()) {
723 Asm.getContext().reportError(Fixup.getLoc(),
724 Twine("assembler label '") + A.getName() +
725 "' can not be undefined");
729 MCSection *MCSec = Fragment->getParent();
731 // Mark this symbol as requiring an entry in the symbol table.
732 assert(SectionMap.find(MCSec) != SectionMap.end() &&
733 "Section must already have been defined in executePostLayoutBinding!");
735 COFFSection *Sec = SectionMap[MCSec];
736 const MCSymbolRefExpr *SymB = Target.getSymB();
737 bool CrossSection = false;
740 const MCSymbol *B = &SymB->getSymbol();
741 if (!B->getFragment()) {
742 Asm.getContext().reportError(
744 Twine("symbol '") + B->getName() +
745 "' can not be undefined in a subtraction expression");
749 if (!A.getFragment()) {
750 Asm.getContext().reportError(
752 Twine("symbol '") + A.getName() +
753 "' can not be undefined in a subtraction expression");
757 CrossSection = &A.getSection() != &B->getSection();
759 // Offset of the symbol in the section
760 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
762 // In the case where we have SymbA and SymB, we just need to store the delta
763 // between the two symbols. Update FixedValue to account for the delta, and
764 // skip recording the relocation.
766 int64_t OffsetOfA = Layout.getSymbolOffset(A);
767 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
771 // Offset of the relocation in the section
772 int64_t OffsetOfRelocation =
773 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
775 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
777 FixedValue = Target.getConstant();
780 COFFRelocation Reloc;
782 Reloc.Data.SymbolTableIndex = 0;
783 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
785 // Turn relocations for temporary symbols into section relocations.
786 if (A.isTemporary() || CrossSection) {
787 MCSection *TargetSection = &A.getSection();
789 SectionMap.find(TargetSection) != SectionMap.end() &&
790 "Section must already have been defined in executePostLayoutBinding!");
791 Reloc.Symb = SectionMap[TargetSection]->Symbol;
792 FixedValue += Layout.getSymbolOffset(A);
795 SymbolMap.find(&A) != SymbolMap.end() &&
796 "Symbol must already have been defined in executePostLayoutBinding!");
797 Reloc.Symb = SymbolMap[&A];
800 ++Reloc.Symb->Relocations;
802 Reloc.Data.VirtualAddress += Fixup.getOffset();
803 Reloc.Data.Type = TargetObjectWriter->getRelocType(
804 Target, Fixup, CrossSection, Asm.getBackend());
806 // FIXME: Can anyone explain what this does other than adjust for the size
808 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
809 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
810 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
811 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
814 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
815 switch (Reloc.Data.Type) {
816 case COFF::IMAGE_REL_ARM_ABSOLUTE:
817 case COFF::IMAGE_REL_ARM_ADDR32:
818 case COFF::IMAGE_REL_ARM_ADDR32NB:
819 case COFF::IMAGE_REL_ARM_TOKEN:
820 case COFF::IMAGE_REL_ARM_SECTION:
821 case COFF::IMAGE_REL_ARM_SECREL:
823 case COFF::IMAGE_REL_ARM_BRANCH11:
824 case COFF::IMAGE_REL_ARM_BLX11:
825 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
826 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
828 case COFF::IMAGE_REL_ARM_BRANCH24:
829 case COFF::IMAGE_REL_ARM_BLX24:
830 case COFF::IMAGE_REL_ARM_MOV32A:
831 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
832 // only used for ARM mode code, which is documented as being unsupported
833 // by Windows on ARM. Empirical proof indicates that masm is able to
834 // generate the relocations however the rest of the MSVC toolchain is
835 // unable to handle it.
836 llvm_unreachable("unsupported relocation");
838 case COFF::IMAGE_REL_ARM_MOV32T:
840 case COFF::IMAGE_REL_ARM_BRANCH20T:
841 case COFF::IMAGE_REL_ARM_BRANCH24T:
842 case COFF::IMAGE_REL_ARM_BLX23T:
843 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
844 // perform a 4 byte adjustment to the relocation. Relative branches are
845 // offset by 4 on ARM, however, because there is no RELA relocations, all
846 // branches are offset by 4.
847 FixedValue = FixedValue + 4;
852 // The fixed value never makes sense for section indices, ignore it.
853 if (Fixup.getKind() == FK_SecRel_2)
856 if (TargetObjectWriter->recordRelocation(Fixup))
857 Sec->Relocations.push_back(Reloc);
860 static std::time_t getTime() {
861 std::time_t Now = time(nullptr);
862 if (Now < 0 || !isUInt<32>(Now))
867 // Create .file symbols.
868 void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
869 for (const std::string &Name : Asm.getFileNames()) {
870 // round up to calculate the number of auxiliary symbols required
871 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
872 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
874 COFFSymbol *File = createSymbol(".file");
875 File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
876 File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
877 File->Aux.resize(Count);
880 unsigned Length = Name.size();
881 for (auto &Aux : File->Aux) {
882 Aux.AuxType = ATFile;
884 if (Length > SymbolSize) {
885 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
886 Length = Length - SymbolSize;
888 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
889 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
893 Offset += SymbolSize;
898 static bool isAssociative(const COFFSection &Section) {
899 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
900 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
903 void WinCOFFObjectWriter::assignSectionNumbers() {
905 auto Assign = [&](COFFSection &Section) {
907 Section.Symbol->Data.SectionNumber = I;
908 Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
912 // Although it is not explicitly requested by the Microsoft COFF spec,
913 // we should avoid emitting forward associative section references,
914 // because MSVC link.exe as of 2017 cannot handle that.
915 for (const std::unique_ptr<COFFSection> &Section : Sections)
916 if (!isAssociative(*Section))
918 for (const std::unique_ptr<COFFSection> &Section : Sections)
919 if (isAssociative(*Section))
923 // Assign file offsets to COFF object file structures.
924 void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
925 const MCAsmLayout &Layout) {
926 unsigned Offset = getInitialOffset();
928 Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
929 Offset += COFF::SectionSize * Header.NumberOfSections;
931 for (const auto &Section : Asm) {
932 COFFSection *Sec = SectionMap[&Section];
934 if (Sec->Number == -1)
937 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
939 if (IsPhysicalSection(Sec)) {
940 // Align the section data to a four byte boundary.
941 Offset = alignTo(Offset, 4);
942 Sec->Header.PointerToRawData = Offset;
944 Offset += Sec->Header.SizeOfRawData;
947 if (!Sec->Relocations.empty()) {
948 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
950 if (RelocationsOverflow) {
951 // Signal overflow by setting NumberOfRelocations to max value. Actual
952 // size is found in reloc #0. Microsoft tools understand this.
953 Sec->Header.NumberOfRelocations = 0xffff;
955 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
957 Sec->Header.PointerToRelocations = Offset;
959 if (RelocationsOverflow) {
960 // Reloc #0 will contain actual count, so make room for it.
961 Offset += COFF::RelocationSize;
964 Offset += COFF::RelocationSize * Sec->Relocations.size();
966 for (auto &Relocation : Sec->Relocations) {
967 assert(Relocation.Symb->getIndex() != -1);
968 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
972 assert(Sec->Symbol->Aux.size() == 1 &&
973 "Section's symbol must have one aux!");
974 AuxSymbol &Aux = Sec->Symbol->Aux[0];
975 assert(Aux.AuxType == ATSectionDefinition &&
976 "Section's symbol's aux symbol must be a Section Definition!");
977 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
978 Aux.Aux.SectionDefinition.NumberOfRelocations =
979 Sec->Header.NumberOfRelocations;
980 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
981 Sec->Header.NumberOfLineNumbers;
984 Header.PointerToSymbolTable = Offset;
987 void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
988 const MCAsmLayout &Layout) {
989 if (Sections.size() > INT32_MAX)
991 "PE COFF object files can't have more than 2147483647 sections");
993 UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
994 Header.NumberOfSections = Sections.size();
995 Header.NumberOfSymbols = 0;
997 assignSectionNumbers();
998 createFileSymbols(Asm);
1000 for (auto &Symbol : Symbols) {
1001 // Update section number & offset for symbols that have them.
1002 if (Symbol->Section)
1003 Symbol->Data.SectionNumber = Symbol->Section->Number;
1004 Symbol->setIndex(Header.NumberOfSymbols++);
1005 // Update auxiliary symbol info.
1006 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
1007 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
1010 // Build string table.
1011 for (const auto &S : Sections)
1012 if (S->Name.size() > COFF::NameSize)
1013 Strings.add(S->Name);
1014 for (const auto &S : Symbols)
1015 if (S->Name.size() > COFF::NameSize)
1016 Strings.add(S->Name);
1020 for (const auto &S : Sections)
1022 for (auto &S : Symbols)
1025 // Fixup weak external references.
1026 for (auto &Symbol : Symbols) {
1027 if (Symbol->Other) {
1028 assert(Symbol->getIndex() != -1);
1029 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1030 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1031 "Symbol's aux symbol must be a Weak External!");
1032 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1036 // Fixup associative COMDAT sections.
1037 for (auto &Section : Sections) {
1038 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1039 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1042 const MCSectionCOFF &MCSec = *Section->MCSection;
1044 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
1046 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
1047 assert(COMDATSymbol);
1048 COFFSection *Assoc = COMDATSymbol->Section;
1051 Twine("Missing associated COMDAT section for section ") +
1052 MCSec.getSectionName());
1054 // Skip this section if the associated section is unused.
1055 if (Assoc->Number == -1)
1058 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
1061 assignFileOffsets(Asm, Layout);
1063 // MS LINK expects to be able to use this timestamp to implement their
1064 // /INCREMENTAL feature.
1065 if (Asm.isIncrementalLinkerCompatible()) {
1066 Header.TimeDateStamp = getTime();
1068 // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1069 Header.TimeDateStamp = 0;
1072 // Write it all to disk...
1073 WriteFileHeader(Header);
1074 writeSectionHeaders();
1076 // Write section contents.
1077 sections::iterator I = Sections.begin();
1078 sections::iterator IE = Sections.end();
1079 MCAssembler::iterator J = Asm.begin();
1080 MCAssembler::iterator JE = Asm.end();
1081 for (; I != IE && J != JE; ++I, ++J)
1082 writeSection(Asm, Layout, **I, *J);
1084 assert(getStream().tell() == Header.PointerToSymbolTable &&
1085 "Header::PointerToSymbolTable is insane!");
1087 // Write a symbol table.
1088 for (auto &Symbol : Symbols)
1089 if (Symbol->getIndex() != -1)
1090 WriteSymbol(*Symbol);
1092 // Write a string table, which completes the entire COFF file.
1093 Strings.write(getStream());
1096 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1097 : Machine(Machine_) {}
1099 // Pin the vtable to this file.
1100 void MCWinCOFFObjectTargetWriter::anchor() {}
1102 //------------------------------------------------------------------------------
1103 // WinCOFFObjectWriter factory function
1106 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1107 raw_pwrite_stream &OS) {
1108 return new WinCOFFObjectWriter(MOTW, OS);