1 //===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains an implementation of a Win32 COFF object file writer.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixup.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolCOFF.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/MC/MCWinCOFFObjectWriter.h"
34 #include "llvm/MC/StringTableBuilder.h"
35 #include "llvm/Support/CRC.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/EndianStream.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
53 using llvm::support::endian::write32le;
55 #define DEBUG_TYPE "WinCOFFObjectWriter"
59 using name = SmallString<COFF::NameSize>;
68 AuxiliaryType AuxType;
76 COFF::symbol Data = {};
78 using AuxiliarySymbols = SmallVector<AuxSymbol, 1>;
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 using relocations = std::vector<COFFRelocation>;
114 COFF::section Header = {};
118 MCSectionCOFF const *MCSection = nullptr;
119 COFFSymbol *Symbol = nullptr;
120 relocations Relocations;
122 COFFSection(StringRef Name) : Name(std::string(Name)) {}
125 class WinCOFFObjectWriter : public MCObjectWriter {
127 support::endian::Writer W;
129 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
130 using sections = std::vector<std::unique_ptr<COFFSection>>;
132 using symbol_map = DenseMap<MCSymbol const *, COFFSymbol *>;
133 using section_map = DenseMap<MCSection const *, COFFSection *>;
135 using symbol_list = DenseSet<COFFSymbol *>;
137 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
139 // Root level file contents.
140 COFF::header Header = {};
143 StringTableBuilder Strings{StringTableBuilder::WinCOFF};
145 // Maps used during object file creation.
146 section_map SectionMap;
147 symbol_map SymbolMap;
149 symbol_list WeakDefaults;
153 bool EmitAddrsigSection = false;
154 MCSectionCOFF *AddrsigSection;
155 std::vector<const MCSymbol *> AddrsigSyms;
157 MCSectionCOFF *CGProfileSection = nullptr;
159 WinCOFFObjectWriter(std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW,
160 raw_pwrite_stream &OS);
162 void reset() override {
163 memset(&Header, 0, sizeof(Header));
164 Header.Machine = TargetObjectWriter->getMachine();
170 MCObjectWriter::reset();
173 COFFSymbol *createSymbol(StringRef Name);
174 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
175 COFFSection *createSection(StringRef Name);
177 void defineSection(MCSectionCOFF const &Sec);
179 COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
180 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
181 const MCAsmLayout &Layout);
183 void SetSymbolName(COFFSymbol &S);
184 void SetSectionName(COFFSection &S);
186 bool IsPhysicalSection(COFFSection *S);
188 // Entity writing methods.
190 void WriteFileHeader(const COFF::header &Header);
191 void WriteSymbol(const COFFSymbol &S);
192 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
193 void writeSectionHeaders();
194 void WriteRelocation(const COFF::relocation &R);
195 uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
196 const MCSection &MCSec);
197 void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
198 const COFFSection &Sec, const MCSection &MCSec);
200 // MCObjectWriter interface implementation.
202 void executePostLayoutBinding(MCAssembler &Asm,
203 const MCAsmLayout &Layout) override;
205 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
206 const MCSymbol &SymA,
207 const MCFragment &FB, bool InSet,
208 bool IsPCRel) const override;
210 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
211 const MCFragment *Fragment, const MCFixup &Fixup,
212 MCValue Target, uint64_t &FixedValue) override;
214 void createFileSymbols(MCAssembler &Asm);
215 void setWeakDefaultNames();
216 void assignSectionNumbers();
217 void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
219 void emitAddrsigSection() override { EmitAddrsigSection = true; }
220 void addAddrsigSymbol(const MCSymbol *Sym) override {
221 AddrsigSyms.push_back(Sym);
224 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
227 } // end anonymous namespace
229 //------------------------------------------------------------------------------
230 // Symbol class implementation
232 // In the case that the name does not fit within 8 bytes, the offset
233 // into the string table is stored in the last 4 bytes instead, leaving
234 // the first 4 bytes as 0.
235 void COFFSymbol::set_name_offset(uint32_t Offset) {
236 write32le(Data.Name + 0, 0);
237 write32le(Data.Name + 4, Offset);
240 //------------------------------------------------------------------------------
241 // WinCOFFObjectWriter class implementation
243 WinCOFFObjectWriter::WinCOFFObjectWriter(
244 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
245 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {
246 Header.Machine = TargetObjectWriter->getMachine();
249 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
250 Symbols.push_back(std::make_unique<COFFSymbol>(Name));
251 return Symbols.back().get();
254 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
255 COFFSymbol *&Ret = SymbolMap[Symbol];
257 Ret = createSymbol(Symbol->getName());
261 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
262 Sections.emplace_back(std::make_unique<COFFSection>(Name));
263 return Sections.back().get();
266 static uint32_t getAlignment(const MCSectionCOFF &Sec) {
267 switch (Sec.getAlignment()) {
269 return COFF::IMAGE_SCN_ALIGN_1BYTES;
271 return COFF::IMAGE_SCN_ALIGN_2BYTES;
273 return COFF::IMAGE_SCN_ALIGN_4BYTES;
275 return COFF::IMAGE_SCN_ALIGN_8BYTES;
277 return COFF::IMAGE_SCN_ALIGN_16BYTES;
279 return COFF::IMAGE_SCN_ALIGN_32BYTES;
281 return COFF::IMAGE_SCN_ALIGN_64BYTES;
283 return COFF::IMAGE_SCN_ALIGN_128BYTES;
285 return COFF::IMAGE_SCN_ALIGN_256BYTES;
287 return COFF::IMAGE_SCN_ALIGN_512BYTES;
289 return COFF::IMAGE_SCN_ALIGN_1024BYTES;
291 return COFF::IMAGE_SCN_ALIGN_2048BYTES;
293 return COFF::IMAGE_SCN_ALIGN_4096BYTES;
295 return COFF::IMAGE_SCN_ALIGN_8192BYTES;
297 llvm_unreachable("unsupported section alignment");
300 /// This function takes a section data object from the assembler
301 /// and creates the associated COFF section staging object.
302 void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
303 COFFSection *Section = createSection(MCSec.getName());
304 COFFSymbol *Symbol = createSymbol(MCSec.getName());
305 Section->Symbol = Symbol;
306 Symbol->Section = Section;
307 Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
309 // Create a COMDAT symbol if needed.
310 if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
311 if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
312 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
313 if (COMDATSymbol->Section)
314 report_fatal_error("two sections have the same comdat");
315 COMDATSymbol->Section = Section;
319 // In this case the auxiliary symbol is a Section Definition.
320 Symbol->Aux.resize(1);
322 Symbol->Aux[0].AuxType = ATSectionDefinition;
323 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
325 // Set section alignment.
326 Section->Header.Characteristics = MCSec.getCharacteristics();
327 Section->Header.Characteristics |= getAlignment(MCSec);
329 // Bind internal COFF section to MC section.
330 Section->MCSection = &MCSec;
331 SectionMap[&MCSec] = Section;
334 static uint64_t getSymbolValue(const MCSymbol &Symbol,
335 const MCAsmLayout &Layout) {
336 if (Symbol.isCommon() && Symbol.isExternal())
337 return Symbol.getCommonSize();
340 if (!Layout.getSymbolOffset(Symbol, Res))
346 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
347 if (!Symbol.isVariable())
350 const MCSymbolRefExpr *SymRef =
351 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
355 const MCSymbol &Aliasee = SymRef->getSymbol();
356 if (!Aliasee.isUndefined())
358 return GetOrCreateCOFFSymbol(&Aliasee);
361 /// This function takes a symbol data object from the assembler
362 /// and creates the associated COFF symbol staging object.
363 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
364 MCAssembler &Assembler,
365 const MCAsmLayout &Layout) {
366 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
367 const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
368 COFFSection *Sec = nullptr;
369 if (Base && Base->getFragment()) {
370 Sec = SectionMap[Base->getFragment()->getParent()];
371 if (Sym->Section && Sym->Section != Sec)
372 report_fatal_error("conflicting sections for symbol");
375 COFFSymbol *Local = nullptr;
376 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
377 Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
378 Sym->Section = nullptr;
380 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
382 std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
383 WeakDefault = createSymbol(WeakName);
385 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
387 WeakDefault->Section = Sec;
388 WeakDefaults.insert(WeakDefault);
392 Sym->Other = WeakDefault;
394 // Setup the Weak External auxiliary symbol.
396 memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
397 Sym->Aux[0].AuxType = ATWeakExternal;
398 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
399 Sym->Aux[0].Aux.WeakExternal.Characteristics =
400 COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS;
403 Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
410 Local->Data.Value = getSymbolValue(MCSym, Layout);
412 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
413 Local->Data.Type = SymbolCOFF.getType();
414 Local->Data.StorageClass = SymbolCOFF.getClass();
416 // If no storage class was specified in the streamer, define it here.
417 if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
418 bool IsExternal = MCSym.isExternal() ||
419 (!MCSym.getFragment() && !MCSym.isVariable());
421 Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
422 : COFF::IMAGE_SYM_CLASS_STATIC;
429 // Maximum offsets for different string table entry encodings.
430 enum : unsigned { Max7DecimalOffset = 9999999U };
431 enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
433 // Encode a string table entry offset in base 64, padded to 6 chars, and
434 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
435 // Buffer must be at least 8 bytes large. No terminating null appended.
436 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
437 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
438 "Illegal section name encoding for value");
440 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
441 "abcdefghijklmnopqrstuvwxyz"
447 char *Ptr = Buffer + 7;
448 for (unsigned i = 0; i < 6; ++i) {
449 unsigned Rem = Value % 64;
451 *(Ptr--) = Alphabet[Rem];
455 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
456 if (S.Name.size() <= COFF::NameSize) {
457 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
461 uint64_t StringTableEntry = Strings.getOffset(S.Name);
462 if (StringTableEntry <= Max7DecimalOffset) {
463 SmallVector<char, COFF::NameSize> Buffer;
464 Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
465 assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
466 std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
469 if (StringTableEntry <= MaxBase64Offset) {
470 // Starting with 10,000,000, offsets are encoded as base64.
471 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
474 report_fatal_error("COFF string table is greater than 64 GB.");
477 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
478 if (S.Name.size() > COFF::NameSize)
479 S.set_name_offset(Strings.getOffset(S.Name));
481 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
484 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
485 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
489 //------------------------------------------------------------------------------
490 // entity writing methods
492 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
494 W.write<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
495 W.write<uint16_t>(0xFFFF);
496 W.write<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion);
497 W.write<uint16_t>(Header.Machine);
498 W.write<uint32_t>(Header.TimeDateStamp);
499 W.OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
500 W.write<uint32_t>(0);
501 W.write<uint32_t>(0);
502 W.write<uint32_t>(0);
503 W.write<uint32_t>(0);
504 W.write<uint32_t>(Header.NumberOfSections);
505 W.write<uint32_t>(Header.PointerToSymbolTable);
506 W.write<uint32_t>(Header.NumberOfSymbols);
508 W.write<uint16_t>(Header.Machine);
509 W.write<uint16_t>(static_cast<int16_t>(Header.NumberOfSections));
510 W.write<uint32_t>(Header.TimeDateStamp);
511 W.write<uint32_t>(Header.PointerToSymbolTable);
512 W.write<uint32_t>(Header.NumberOfSymbols);
513 W.write<uint16_t>(Header.SizeOfOptionalHeader);
514 W.write<uint16_t>(Header.Characteristics);
518 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
519 W.OS.write(S.Data.Name, COFF::NameSize);
520 W.write<uint32_t>(S.Data.Value);
522 W.write<uint32_t>(S.Data.SectionNumber);
524 W.write<uint16_t>(static_cast<int16_t>(S.Data.SectionNumber));
525 W.write<uint16_t>(S.Data.Type);
526 W.OS << char(S.Data.StorageClass);
527 W.OS << char(S.Data.NumberOfAuxSymbols);
528 WriteAuxiliarySymbols(S.Aux);
531 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
532 const COFFSymbol::AuxiliarySymbols &S) {
533 for (const AuxSymbol &i : S) {
536 W.write<uint32_t>(i.Aux.WeakExternal.TagIndex);
537 W.write<uint32_t>(i.Aux.WeakExternal.Characteristics);
538 W.OS.write_zeros(sizeof(i.Aux.WeakExternal.unused));
540 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
543 W.OS.write(reinterpret_cast<const char *>(&i.Aux),
544 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size);
546 case ATSectionDefinition:
547 W.write<uint32_t>(i.Aux.SectionDefinition.Length);
548 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
549 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
550 W.write<uint32_t>(i.Aux.SectionDefinition.CheckSum);
551 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
552 W.OS << char(i.Aux.SectionDefinition.Selection);
553 W.OS.write_zeros(sizeof(i.Aux.SectionDefinition.unused));
554 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
556 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
562 // Write the section header.
563 void WinCOFFObjectWriter::writeSectionHeaders() {
564 // Section numbers must be monotonically increasing in the section
565 // header, but our Sections array is not sorted by section number,
566 // so make a copy of Sections and sort it.
567 std::vector<COFFSection *> Arr;
568 for (auto &Section : Sections)
569 Arr.push_back(Section.get());
570 llvm::sort(Arr, [](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 W.OS.write(S.Name, COFF::NameSize);
582 W.write<uint32_t>(S.VirtualSize);
583 W.write<uint32_t>(S.VirtualAddress);
584 W.write<uint32_t>(S.SizeOfRawData);
585 W.write<uint32_t>(S.PointerToRawData);
586 W.write<uint32_t>(S.PointerToRelocations);
587 W.write<uint32_t>(S.PointerToLineNumbers);
588 W.write<uint16_t>(S.NumberOfRelocations);
589 W.write<uint16_t>(S.NumberOfLineNumbers);
590 W.write<uint32_t>(S.Characteristics);
594 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
595 W.write<uint32_t>(R.VirtualAddress);
596 W.write<uint32_t>(R.SymbolTableIndex);
597 W.write<uint16_t>(R.Type);
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 Asm.writeSectionData(VecOS, &MCSec, Layout);
612 // Write the section contents to the object file.
615 // Calculate our CRC with an initial value of '0', this is not how
616 // JamCRC is specified but it aligns with the expected output.
617 JamCRC JC(/*Init=*/0);
618 JC.update(makeArrayRef(reinterpret_cast<uint8_t*>(Buf.data()), Buf.size()));
622 void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
623 const MCAsmLayout &Layout,
624 const COFFSection &Sec,
625 const MCSection &MCSec) {
626 if (Sec.Number == -1)
629 // Write the section contents.
630 if (Sec.Header.PointerToRawData != 0) {
631 assert(W.OS.tell() == Sec.Header.PointerToRawData &&
632 "Section::PointerToRawData is insane!");
634 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
636 // Update the section definition auxiliary symbol to record the CRC.
637 COFFSection *Sec = SectionMap[&MCSec];
638 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
639 assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
640 AuxSymbol &SecDef = AuxSyms[0];
641 SecDef.Aux.SectionDefinition.CheckSum = CRC;
644 // Write relocations for this section.
645 if (Sec.Relocations.empty()) {
646 assert(Sec.Header.PointerToRelocations == 0 &&
647 "Section::PointerToRelocations is insane!");
651 assert(W.OS.tell() == Sec.Header.PointerToRelocations &&
652 "Section::PointerToRelocations is insane!");
654 if (Sec.Relocations.size() >= 0xffff) {
655 // In case of overflow, write actual relocation count as first
656 // relocation. Including the synthetic reloc itself (+ 1).
658 R.VirtualAddress = Sec.Relocations.size() + 1;
659 R.SymbolTableIndex = 0;
664 for (const auto &Relocation : Sec.Relocations)
665 WriteRelocation(Relocation.Data);
668 ////////////////////////////////////////////////////////////////////////////////
669 // MCObjectWriter interface implementations
671 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
672 const MCAsmLayout &Layout) {
673 if (EmitAddrsigSection) {
674 AddrsigSection = Asm.getContext().getCOFFSection(
675 ".llvm_addrsig", COFF::IMAGE_SCN_LNK_REMOVE,
676 SectionKind::getMetadata());
677 Asm.registerSection(*AddrsigSection);
680 if (!Asm.CGProfile.empty()) {
681 CGProfileSection = Asm.getContext().getCOFFSection(
682 ".llvm.call-graph-profile", COFF::IMAGE_SCN_LNK_REMOVE,
683 SectionKind::getMetadata());
684 Asm.registerSection(*CGProfileSection);
687 // "Define" each section & symbol. This creates section & symbol
688 // entries in the staging area.
689 for (const auto &Section : Asm)
690 defineSection(static_cast<const MCSectionCOFF &>(Section));
692 for (const MCSymbol &Symbol : Asm.symbols())
693 if (!Symbol.isTemporary())
694 DefineSymbol(Symbol, Asm, Layout);
697 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
698 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
699 bool InSet, bool IsPCRel) const {
700 // Don't drop relocations between functions, even if they are in the same text
701 // section. Multiple Visual C++ linker features depend on having the
702 // relocations present. The /INCREMENTAL flag will cause these relocations to
703 // point to thunks, and the /GUARD:CF flag assumes that it can use relocations
704 // to approximate the set of all address taken functions. LLD's implementation
705 // of /GUARD:CF also relies on the existance of these relocations.
706 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
707 if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
709 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
713 void WinCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
714 const MCAsmLayout &Layout,
715 const MCFragment *Fragment,
716 const MCFixup &Fixup, MCValue Target,
717 uint64_t &FixedValue) {
718 assert(Target.getSymA() && "Relocation must reference a symbol!");
720 const MCSymbol &A = Target.getSymA()->getSymbol();
721 if (!A.isRegistered()) {
722 Asm.getContext().reportError(Fixup.getLoc(),
723 Twine("symbol '") + A.getName() +
724 "' can not be undefined");
727 if (A.isTemporary() && A.isUndefined()) {
728 Asm.getContext().reportError(Fixup.getLoc(),
729 Twine("assembler label '") + A.getName() +
730 "' can not be undefined");
734 MCSection *MCSec = Fragment->getParent();
736 // Mark this symbol as requiring an entry in the symbol table.
737 assert(SectionMap.find(MCSec) != SectionMap.end() &&
738 "Section must already have been defined in executePostLayoutBinding!");
740 COFFSection *Sec = SectionMap[MCSec];
741 const MCSymbolRefExpr *SymB = Target.getSymB();
744 const MCSymbol *B = &SymB->getSymbol();
745 if (!B->getFragment()) {
746 Asm.getContext().reportError(
748 Twine("symbol '") + B->getName() +
749 "' can not be undefined in a subtraction expression");
753 // Offset of the symbol in the section
754 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
756 // Offset of the relocation in the section
757 int64_t OffsetOfRelocation =
758 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
760 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
762 FixedValue = Target.getConstant();
765 COFFRelocation Reloc;
767 Reloc.Data.SymbolTableIndex = 0;
768 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
770 // Turn relocations for temporary symbols into section relocations.
771 if (A.isTemporary()) {
772 MCSection *TargetSection = &A.getSection();
774 SectionMap.find(TargetSection) != SectionMap.end() &&
775 "Section must already have been defined in executePostLayoutBinding!");
776 Reloc.Symb = SectionMap[TargetSection]->Symbol;
777 FixedValue += Layout.getSymbolOffset(A);
780 SymbolMap.find(&A) != SymbolMap.end() &&
781 "Symbol must already have been defined in executePostLayoutBinding!");
782 Reloc.Symb = SymbolMap[&A];
785 ++Reloc.Symb->Relocations;
787 Reloc.Data.VirtualAddress += Fixup.getOffset();
788 Reloc.Data.Type = TargetObjectWriter->getRelocType(
789 Asm.getContext(), Target, Fixup, SymB, Asm.getBackend());
791 // FIXME: Can anyone explain what this does other than adjust for the size
793 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
794 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
795 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
796 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
799 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
800 switch (Reloc.Data.Type) {
801 case COFF::IMAGE_REL_ARM_ABSOLUTE:
802 case COFF::IMAGE_REL_ARM_ADDR32:
803 case COFF::IMAGE_REL_ARM_ADDR32NB:
804 case COFF::IMAGE_REL_ARM_TOKEN:
805 case COFF::IMAGE_REL_ARM_SECTION:
806 case COFF::IMAGE_REL_ARM_SECREL:
808 case COFF::IMAGE_REL_ARM_BRANCH11:
809 case COFF::IMAGE_REL_ARM_BLX11:
810 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
811 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
813 case COFF::IMAGE_REL_ARM_BRANCH24:
814 case COFF::IMAGE_REL_ARM_BLX24:
815 case COFF::IMAGE_REL_ARM_MOV32A:
816 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
817 // only used for ARM mode code, which is documented as being unsupported
818 // by Windows on ARM. Empirical proof indicates that masm is able to
819 // generate the relocations however the rest of the MSVC toolchain is
820 // unable to handle it.
821 llvm_unreachable("unsupported relocation");
823 case COFF::IMAGE_REL_ARM_MOV32T:
825 case COFF::IMAGE_REL_ARM_BRANCH20T:
826 case COFF::IMAGE_REL_ARM_BRANCH24T:
827 case COFF::IMAGE_REL_ARM_BLX23T:
828 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
829 // perform a 4 byte adjustment to the relocation. Relative branches are
830 // offset by 4 on ARM, however, because there is no RELA relocations, all
831 // branches are offset by 4.
832 FixedValue = FixedValue + 4;
837 // The fixed value never makes sense for section indices, ignore it.
838 if (Fixup.getKind() == FK_SecRel_2)
841 if (TargetObjectWriter->recordRelocation(Fixup))
842 Sec->Relocations.push_back(Reloc);
845 static std::time_t getTime() {
846 std::time_t Now = time(nullptr);
847 if (Now < 0 || !isUInt<32>(Now))
852 // Create .file symbols.
853 void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
854 for (const std::string &Name : Asm.getFileNames()) {
855 // round up to calculate the number of auxiliary symbols required
856 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
857 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
859 COFFSymbol *File = createSymbol(".file");
860 File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
861 File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
862 File->Aux.resize(Count);
865 unsigned Length = Name.size();
866 for (auto &Aux : File->Aux) {
867 Aux.AuxType = ATFile;
869 if (Length > SymbolSize) {
870 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
871 Length = Length - SymbolSize;
873 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
874 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
878 Offset += SymbolSize;
883 void WinCOFFObjectWriter::setWeakDefaultNames() {
884 if (WeakDefaults.empty())
887 // If multiple object files use a weak symbol (either with a regular
888 // defined default, or an absolute zero symbol as default), the defaults
889 // cause duplicate definitions unless their names are made unique. Look
890 // for a defined extern symbol, that isn't comdat - that should be unique
891 // unless there are other duplicate definitions. And if none is found,
892 // allow picking a comdat symbol, as that's still better than nothing.
894 COFFSymbol *Unique = nullptr;
895 for (bool AllowComdat : {false, true}) {
896 for (auto &Sym : Symbols) {
897 // Don't include the names of the defaults themselves
898 if (WeakDefaults.count(Sym.get()))
900 // Only consider external symbols
901 if (Sym->Data.StorageClass != COFF::IMAGE_SYM_CLASS_EXTERNAL)
903 // Only consider symbols defined in a section or that are absolute
904 if (!Sym->Section && Sym->Data.SectionNumber != COFF::IMAGE_SYM_ABSOLUTE)
906 if (!AllowComdat && Sym->Section &&
907 Sym->Section->Header.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
915 // If we didn't find any unique symbol to use for the names, just skip this.
918 for (auto *Sym : WeakDefaults) {
919 Sym->Name.append(".");
920 Sym->Name.append(Unique->Name);
924 static bool isAssociative(const COFFSection &Section) {
925 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
926 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
929 void WinCOFFObjectWriter::assignSectionNumbers() {
931 auto Assign = [&](COFFSection &Section) {
933 Section.Symbol->Data.SectionNumber = I;
934 Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
938 // Although it is not explicitly requested by the Microsoft COFF spec,
939 // we should avoid emitting forward associative section references,
940 // because MSVC link.exe as of 2017 cannot handle that.
941 for (const std::unique_ptr<COFFSection> &Section : Sections)
942 if (!isAssociative(*Section))
944 for (const std::unique_ptr<COFFSection> &Section : Sections)
945 if (isAssociative(*Section))
949 // Assign file offsets to COFF object file structures.
950 void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
951 const MCAsmLayout &Layout) {
952 unsigned Offset = W.OS.tell();
954 Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
955 Offset += COFF::SectionSize * Header.NumberOfSections;
957 for (const auto &Section : Asm) {
958 COFFSection *Sec = SectionMap[&Section];
960 if (Sec->Number == -1)
963 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
965 if (IsPhysicalSection(Sec)) {
966 Sec->Header.PointerToRawData = Offset;
967 Offset += Sec->Header.SizeOfRawData;
970 if (!Sec->Relocations.empty()) {
971 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
973 if (RelocationsOverflow) {
974 // Signal overflow by setting NumberOfRelocations to max value. Actual
975 // size is found in reloc #0. Microsoft tools understand this.
976 Sec->Header.NumberOfRelocations = 0xffff;
978 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
980 Sec->Header.PointerToRelocations = Offset;
982 if (RelocationsOverflow) {
983 // Reloc #0 will contain actual count, so make room for it.
984 Offset += COFF::RelocationSize;
987 Offset += COFF::RelocationSize * Sec->Relocations.size();
989 for (auto &Relocation : Sec->Relocations) {
990 assert(Relocation.Symb->getIndex() != -1);
991 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
995 assert(Sec->Symbol->Aux.size() == 1 &&
996 "Section's symbol must have one aux!");
997 AuxSymbol &Aux = Sec->Symbol->Aux[0];
998 assert(Aux.AuxType == ATSectionDefinition &&
999 "Section's symbol's aux symbol must be a Section Definition!");
1000 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1001 Aux.Aux.SectionDefinition.NumberOfRelocations =
1002 Sec->Header.NumberOfRelocations;
1003 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1004 Sec->Header.NumberOfLineNumbers;
1007 Header.PointerToSymbolTable = Offset;
1010 uint64_t WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
1011 const MCAsmLayout &Layout) {
1012 uint64_t StartOffset = W.OS.tell();
1014 if (Sections.size() > INT32_MAX)
1016 "PE COFF object files can't have more than 2147483647 sections");
1018 UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
1019 Header.NumberOfSections = Sections.size();
1020 Header.NumberOfSymbols = 0;
1022 setWeakDefaultNames();
1023 assignSectionNumbers();
1024 createFileSymbols(Asm);
1026 for (auto &Symbol : Symbols) {
1027 // Update section number & offset for symbols that have them.
1028 if (Symbol->Section)
1029 Symbol->Data.SectionNumber = Symbol->Section->Number;
1030 Symbol->setIndex(Header.NumberOfSymbols++);
1031 // Update auxiliary symbol info.
1032 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
1033 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
1036 // Build string table.
1037 for (const auto &S : Sections)
1038 if (S->Name.size() > COFF::NameSize)
1039 Strings.add(S->Name);
1040 for (const auto &S : Symbols)
1041 if (S->Name.size() > COFF::NameSize)
1042 Strings.add(S->Name);
1046 for (const auto &S : Sections)
1048 for (auto &S : Symbols)
1051 // Fixup weak external references.
1052 for (auto &Symbol : Symbols) {
1053 if (Symbol->Other) {
1054 assert(Symbol->getIndex() != -1);
1055 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1056 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1057 "Symbol's aux symbol must be a Weak External!");
1058 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1062 // Fixup associative COMDAT sections.
1063 for (auto &Section : Sections) {
1064 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1065 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1068 const MCSectionCOFF &MCSec = *Section->MCSection;
1069 const MCSymbol *AssocMCSym = MCSec.getCOMDATSymbol();
1072 // It's an error to try to associate with an undefined symbol or a symbol
1073 // without a section.
1074 if (!AssocMCSym->isInSection()) {
1075 Asm.getContext().reportError(
1076 SMLoc(), Twine("cannot make section ") + MCSec.getName() +
1077 Twine(" associative with sectionless symbol ") +
1078 AssocMCSym->getName());
1082 const auto *AssocMCSec = cast<MCSectionCOFF>(&AssocMCSym->getSection());
1083 assert(SectionMap.count(AssocMCSec));
1084 COFFSection *AssocSec = SectionMap[AssocMCSec];
1086 // Skip this section if the associated section is unused.
1087 if (AssocSec->Number == -1)
1090 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = AssocSec->Number;
1093 // Create the contents of the .llvm_addrsig section.
1094 if (EmitAddrsigSection) {
1095 auto Frag = new MCDataFragment(AddrsigSection);
1096 Frag->setLayoutOrder(0);
1097 raw_svector_ostream OS(Frag->getContents());
1098 for (const MCSymbol *S : AddrsigSyms) {
1099 if (!S->isTemporary()) {
1100 encodeULEB128(S->getIndex(), OS);
1104 MCSection *TargetSection = &S->getSection();
1105 assert(SectionMap.find(TargetSection) != SectionMap.end() &&
1106 "Section must already have been defined in "
1107 "executePostLayoutBinding!");
1108 encodeULEB128(SectionMap[TargetSection]->Symbol->getIndex(), OS);
1112 // Create the contents of the .llvm.call-graph-profile section.
1113 if (CGProfileSection) {
1114 auto *Frag = new MCDataFragment(CGProfileSection);
1115 Frag->setLayoutOrder(0);
1116 raw_svector_ostream OS(Frag->getContents());
1117 for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
1118 uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
1119 uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
1120 support::endian::write(OS, FromIndex, W.Endian);
1121 support::endian::write(OS, ToIndex, W.Endian);
1122 support::endian::write(OS, CGPE.Count, W.Endian);
1126 assignFileOffsets(Asm, Layout);
1128 // MS LINK expects to be able to use this timestamp to implement their
1129 // /INCREMENTAL feature.
1130 if (Asm.isIncrementalLinkerCompatible()) {
1131 Header.TimeDateStamp = getTime();
1133 // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1134 Header.TimeDateStamp = 0;
1137 // Write it all to disk...
1138 WriteFileHeader(Header);
1139 writeSectionHeaders();
1141 // Write section contents.
1142 sections::iterator I = Sections.begin();
1143 sections::iterator IE = Sections.end();
1144 MCAssembler::iterator J = Asm.begin();
1145 MCAssembler::iterator JE = Asm.end();
1146 for (; I != IE && J != JE; ++I, ++J)
1147 writeSection(Asm, Layout, **I, *J);
1149 assert(W.OS.tell() == Header.PointerToSymbolTable &&
1150 "Header::PointerToSymbolTable is insane!");
1152 // Write a symbol table.
1153 for (auto &Symbol : Symbols)
1154 if (Symbol->getIndex() != -1)
1155 WriteSymbol(*Symbol);
1157 // Write a string table, which completes the entire COFF file.
1158 Strings.write(W.OS);
1160 return W.OS.tell() - StartOffset;
1163 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1164 : Machine(Machine_) {}
1166 // Pin the vtable to this file.
1167 void MCWinCOFFObjectTargetWriter::anchor() {}
1169 //------------------------------------------------------------------------------
1170 // WinCOFFObjectWriter factory function
1172 std::unique_ptr<MCObjectWriter> llvm::createWinCOFFObjectWriter(
1173 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS) {
1174 return std::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS);