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"
52 using llvm::support::endian::write32le;
54 #define DEBUG_TYPE "WinCOFFObjectWriter"
58 using name = SmallString<COFF::NameSize>;
69 AuxiliaryType AuxType;
77 COFF::symbol Data = {};
79 using AuxiliarySymbols = SmallVector<AuxSymbol, 1>;
84 COFFSymbol *Other = nullptr;
85 COFFSection *Section = nullptr;
87 const MCSymbol *MC = nullptr;
89 COFFSymbol(StringRef Name) : Name(Name) {}
91 void set_name_offset(uint32_t Offset);
93 int64_t getIndex() const { return Index; }
94 void setIndex(int Value) {
97 MC->setIndex(static_cast<uint32_t>(Value));
101 // This class contains staging data for a COFF relocation entry.
102 struct COFFRelocation {
103 COFF::relocation Data;
104 COFFSymbol *Symb = nullptr;
106 COFFRelocation() = default;
108 static size_t size() { return COFF::RelocationSize; }
111 using relocations = std::vector<COFFRelocation>;
115 COFF::section Header = {};
119 MCSectionCOFF const *MCSection = nullptr;
120 COFFSymbol *Symbol = nullptr;
121 relocations Relocations;
123 COFFSection(StringRef Name) : Name(Name) {}
126 class WinCOFFObjectWriter : public MCObjectWriter {
128 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
129 using sections = std::vector<std::unique_ptr<COFFSection>>;
131 using symbol_map = DenseMap<MCSymbol const *, COFFSymbol *>;
132 using section_map = DenseMap<MCSection const *, COFFSection *>;
134 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
136 // Root level file contents.
137 COFF::header Header = {};
140 StringTableBuilder Strings{StringTableBuilder::WinCOFF};
142 // Maps used during object file creation.
143 section_map SectionMap;
144 symbol_map SymbolMap;
148 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
150 void reset() override {
151 memset(&Header, 0, sizeof(Header));
152 Header.Machine = TargetObjectWriter->getMachine();
158 MCObjectWriter::reset();
161 COFFSymbol *createSymbol(StringRef Name);
162 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
163 COFFSection *createSection(StringRef Name);
165 void defineSection(MCSectionCOFF const &Sec);
167 COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
168 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
169 const MCAsmLayout &Layout);
171 void SetSymbolName(COFFSymbol &S);
172 void SetSectionName(COFFSection &S);
174 bool IsPhysicalSection(COFFSection *S);
176 // Entity writing methods.
178 void WriteFileHeader(const COFF::header &Header);
179 void WriteSymbol(const COFFSymbol &S);
180 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
181 void writeSectionHeaders();
182 void WriteRelocation(const COFF::relocation &R);
183 uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
184 const MCSection &MCSec);
185 void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
186 const COFFSection &Sec, const MCSection &MCSec);
188 // MCObjectWriter interface implementation.
190 void executePostLayoutBinding(MCAssembler &Asm,
191 const MCAsmLayout &Layout) override;
193 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
194 const MCSymbol &SymA,
195 const MCFragment &FB, bool InSet,
196 bool IsPCRel) const override;
198 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
199 const MCFragment *Fragment, const MCFixup &Fixup,
200 MCValue Target, bool &IsPCRel,
201 uint64_t &FixedValue) override;
203 void createFileSymbols(MCAssembler &Asm);
204 void assignSectionNumbers();
205 void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
207 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
210 } // end anonymous namespace
212 //------------------------------------------------------------------------------
213 // Symbol class implementation
215 // In the case that the name does not fit within 8 bytes, the offset
216 // into the string table is stored in the last 4 bytes instead, leaving
217 // the first 4 bytes as 0.
218 void COFFSymbol::set_name_offset(uint32_t Offset) {
219 write32le(Data.Name + 0, 0);
220 write32le(Data.Name + 4, Offset);
223 //------------------------------------------------------------------------------
224 // WinCOFFObjectWriter class implementation
226 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
227 raw_pwrite_stream &OS)
228 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
229 Header.Machine = TargetObjectWriter->getMachine();
232 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
233 Symbols.push_back(make_unique<COFFSymbol>(Name));
234 return Symbols.back().get();
237 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
238 COFFSymbol *&Ret = SymbolMap[Symbol];
240 Ret = createSymbol(Symbol->getName());
244 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
245 Sections.emplace_back(make_unique<COFFSection>(Name));
246 return Sections.back().get();
249 static uint32_t getAlignment(const MCSectionCOFF &Sec) {
250 switch (Sec.getAlignment()) {
252 return COFF::IMAGE_SCN_ALIGN_1BYTES;
254 return COFF::IMAGE_SCN_ALIGN_2BYTES;
256 return COFF::IMAGE_SCN_ALIGN_4BYTES;
258 return COFF::IMAGE_SCN_ALIGN_8BYTES;
260 return COFF::IMAGE_SCN_ALIGN_16BYTES;
262 return COFF::IMAGE_SCN_ALIGN_32BYTES;
264 return COFF::IMAGE_SCN_ALIGN_64BYTES;
266 return COFF::IMAGE_SCN_ALIGN_128BYTES;
268 return COFF::IMAGE_SCN_ALIGN_256BYTES;
270 return COFF::IMAGE_SCN_ALIGN_512BYTES;
272 return COFF::IMAGE_SCN_ALIGN_1024BYTES;
274 return COFF::IMAGE_SCN_ALIGN_2048BYTES;
276 return COFF::IMAGE_SCN_ALIGN_4096BYTES;
278 return COFF::IMAGE_SCN_ALIGN_8192BYTES;
280 llvm_unreachable("unsupported section alignment");
283 /// This function takes a section data object from the assembler
284 /// and creates the associated COFF section staging object.
285 void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
286 COFFSection *Section = createSection(MCSec.getSectionName());
287 COFFSymbol *Symbol = createSymbol(MCSec.getSectionName());
288 Section->Symbol = Symbol;
289 Symbol->Section = Section;
290 Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
292 // Create a COMDAT symbol if needed.
293 if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
294 if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
295 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
296 if (COMDATSymbol->Section)
297 report_fatal_error("two sections have the same comdat");
298 COMDATSymbol->Section = Section;
302 // In this case the auxiliary symbol is a Section Definition.
303 Symbol->Aux.resize(1);
305 Symbol->Aux[0].AuxType = ATSectionDefinition;
306 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
308 // Set section alignment.
309 Section->Header.Characteristics = MCSec.getCharacteristics();
310 Section->Header.Characteristics |= getAlignment(MCSec);
312 // Bind internal COFF section to MC section.
313 Section->MCSection = &MCSec;
314 SectionMap[&MCSec] = Section;
317 static uint64_t getSymbolValue(const MCSymbol &Symbol,
318 const MCAsmLayout &Layout) {
319 if (Symbol.isCommon() && Symbol.isExternal())
320 return Symbol.getCommonSize();
323 if (!Layout.getSymbolOffset(Symbol, Res))
329 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
330 if (!Symbol.isVariable())
333 const MCSymbolRefExpr *SymRef =
334 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
338 const MCSymbol &Aliasee = SymRef->getSymbol();
339 if (!Aliasee.isUndefined())
341 return GetOrCreateCOFFSymbol(&Aliasee);
344 /// This function takes a symbol data object from the assembler
345 /// and creates the associated COFF symbol staging object.
346 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
347 MCAssembler &Assembler,
348 const MCAsmLayout &Layout) {
349 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
350 const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
351 COFFSection *Sec = nullptr;
352 if (Base && Base->getFragment()) {
353 Sec = SectionMap[Base->getFragment()->getParent()];
354 if (Sym->Section && Sym->Section != Sec)
355 report_fatal_error("conflicting sections for symbol");
358 COFFSymbol *Local = nullptr;
359 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
360 Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
362 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
364 std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
365 WeakDefault = createSymbol(WeakName);
367 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
369 WeakDefault->Section = Sec;
373 Sym->Other = WeakDefault;
375 // Setup the Weak External auxiliary symbol.
377 memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
378 Sym->Aux[0].AuxType = ATWeakExternal;
379 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
380 Sym->Aux[0].Aux.WeakExternal.Characteristics =
381 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
384 Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
391 Local->Data.Value = getSymbolValue(MCSym, Layout);
393 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
394 Local->Data.Type = SymbolCOFF.getType();
395 Local->Data.StorageClass = SymbolCOFF.getClass();
397 // If no storage class was specified in the streamer, define it here.
398 if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
399 bool IsExternal = MCSym.isExternal() ||
400 (!MCSym.getFragment() && !MCSym.isVariable());
402 Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
403 : COFF::IMAGE_SYM_CLASS_STATIC;
410 // Maximum offsets for different string table entry encodings.
411 enum : unsigned { Max7DecimalOffset = 9999999U };
412 enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
414 // Encode a string table entry offset in base 64, padded to 6 chars, and
415 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
416 // Buffer must be at least 8 bytes large. No terminating null appended.
417 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
418 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
419 "Illegal section name encoding for value");
421 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
422 "abcdefghijklmnopqrstuvwxyz"
428 char *Ptr = Buffer + 7;
429 for (unsigned i = 0; i < 6; ++i) {
430 unsigned Rem = Value % 64;
432 *(Ptr--) = Alphabet[Rem];
436 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
437 if (S.Name.size() <= COFF::NameSize) {
438 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
442 uint64_t StringTableEntry = Strings.getOffset(S.Name);
443 if (StringTableEntry <= Max7DecimalOffset) {
444 SmallVector<char, COFF::NameSize> Buffer;
445 Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
446 assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
447 std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
450 if (StringTableEntry <= MaxBase64Offset) {
451 // Starting with 10,000,000, offsets are encoded as base64.
452 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
455 report_fatal_error("COFF string table is greater than 64 GB.");
458 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
459 if (S.Name.size() > COFF::NameSize)
460 S.set_name_offset(Strings.getOffset(S.Name));
462 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
465 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
466 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
470 //------------------------------------------------------------------------------
471 // entity writing methods
473 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
475 writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
477 writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
478 writeLE16(Header.Machine);
479 writeLE32(Header.TimeDateStamp);
480 writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
485 writeLE32(Header.NumberOfSections);
486 writeLE32(Header.PointerToSymbolTable);
487 writeLE32(Header.NumberOfSymbols);
489 writeLE16(Header.Machine);
490 writeLE16(static_cast<int16_t>(Header.NumberOfSections));
491 writeLE32(Header.TimeDateStamp);
492 writeLE32(Header.PointerToSymbolTable);
493 writeLE32(Header.NumberOfSymbols);
494 writeLE16(Header.SizeOfOptionalHeader);
495 writeLE16(Header.Characteristics);
499 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
500 writeBytes(StringRef(S.Data.Name, COFF::NameSize));
501 writeLE32(S.Data.Value);
503 writeLE32(S.Data.SectionNumber);
505 writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
506 writeLE16(S.Data.Type);
507 write8(S.Data.StorageClass);
508 write8(S.Data.NumberOfAuxSymbols);
509 WriteAuxiliarySymbols(S.Aux);
512 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
513 const COFFSymbol::AuxiliarySymbols &S) {
514 for (const AuxSymbol &i : S) {
516 case ATFunctionDefinition:
517 writeLE32(i.Aux.FunctionDefinition.TagIndex);
518 writeLE32(i.Aux.FunctionDefinition.TotalSize);
519 writeLE32(i.Aux.FunctionDefinition.PointerToLinenumber);
520 writeLE32(i.Aux.FunctionDefinition.PointerToNextFunction);
521 WriteZeros(sizeof(i.Aux.FunctionDefinition.unused));
523 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
525 case ATbfAndefSymbol:
526 WriteZeros(sizeof(i.Aux.bfAndefSymbol.unused1));
527 writeLE16(i.Aux.bfAndefSymbol.Linenumber);
528 WriteZeros(sizeof(i.Aux.bfAndefSymbol.unused2));
529 writeLE32(i.Aux.bfAndefSymbol.PointerToNextFunction);
530 WriteZeros(sizeof(i.Aux.bfAndefSymbol.unused3));
532 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
535 writeLE32(i.Aux.WeakExternal.TagIndex);
536 writeLE32(i.Aux.WeakExternal.Characteristics);
537 WriteZeros(sizeof(i.Aux.WeakExternal.unused));
539 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
543 StringRef(reinterpret_cast<const char *>(&i.Aux),
544 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
546 case ATSectionDefinition:
547 writeLE32(i.Aux.SectionDefinition.Length);
548 writeLE16(i.Aux.SectionDefinition.NumberOfRelocations);
549 writeLE16(i.Aux.SectionDefinition.NumberOfLinenumbers);
550 writeLE32(i.Aux.SectionDefinition.CheckSum);
551 writeLE16(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
552 write8(i.Aux.SectionDefinition.Selection);
553 WriteZeros(sizeof(i.Aux.SectionDefinition.unused));
554 writeLE16(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
556 WriteZeros(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 std::sort(Arr.begin(), Arr.end(),
571 [](const COFFSection *A, const COFFSection *B) {
572 return A->Number < B->Number;
575 for (auto &Section : Arr) {
576 if (Section->Number == -1)
579 COFF::section &S = Section->Header;
580 if (Section->Relocations.size() >= 0xffff)
581 S.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
582 writeBytes(StringRef(S.Name, COFF::NameSize));
583 writeLE32(S.VirtualSize);
584 writeLE32(S.VirtualAddress);
585 writeLE32(S.SizeOfRawData);
586 writeLE32(S.PointerToRawData);
587 writeLE32(S.PointerToRelocations);
588 writeLE32(S.PointerToLineNumbers);
589 writeLE16(S.NumberOfRelocations);
590 writeLE16(S.NumberOfLineNumbers);
591 writeLE32(S.Characteristics);
595 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
596 writeLE32(R.VirtualAddress);
597 writeLE32(R.SymbolTableIndex);
601 // Write MCSec's contents. What this function does is essentially
602 // "Asm.writeSectionData(&MCSec, Layout)", but it's a bit complicated
603 // because it needs to compute a CRC.
604 uint32_t WinCOFFObjectWriter::writeSectionContents(MCAssembler &Asm,
605 const MCAsmLayout &Layout,
606 const MCSection &MCSec) {
607 // Save the contents of the section to a temporary buffer, we need this
608 // to CRC the data before we dump it into the object file.
609 SmallVector<char, 128> Buf;
610 raw_svector_ostream VecOS(Buf);
611 raw_pwrite_stream &OldStream = getStream();
613 // Redirect the output stream to our buffer and fill our buffer with
616 Asm.writeSectionData(&MCSec, Layout);
618 // Reset the stream back to what it was before.
619 setStream(OldStream);
621 // Write the section contents to the object file.
624 // Calculate our CRC with an initial value of '0', this is not how
625 // JamCRC is specified but it aligns with the expected output.
626 JamCRC JC(/*Init=*/0);
631 void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
632 const MCAsmLayout &Layout,
633 const COFFSection &Sec,
634 const MCSection &MCSec) {
635 if (Sec.Number == -1)
638 // Write the section contents.
639 if (Sec.Header.PointerToRawData != 0) {
640 assert(getStream().tell() <= Sec.Header.PointerToRawData &&
641 "Section::PointerToRawData is insane!");
643 unsigned PaddingSize = Sec.Header.PointerToRawData - getStream().tell();
644 assert(PaddingSize < 4 &&
645 "Should only need at most three bytes of padding!");
646 WriteZeros(PaddingSize);
648 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
650 // Update the section definition auxiliary symbol to record the CRC.
651 COFFSection *Sec = SectionMap[&MCSec];
652 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
653 assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
654 AuxSymbol &SecDef = AuxSyms[0];
655 SecDef.Aux.SectionDefinition.CheckSum = CRC;
658 // Write relocations for this section.
659 if (Sec.Relocations.empty()) {
660 assert(Sec.Header.PointerToRelocations == 0 &&
661 "Section::PointerToRelocations is insane!");
665 assert(getStream().tell() == Sec.Header.PointerToRelocations &&
666 "Section::PointerToRelocations is insane!");
668 if (Sec.Relocations.size() >= 0xffff) {
669 // In case of overflow, write actual relocation count as first
670 // relocation. Including the synthetic reloc itself (+ 1).
672 R.VirtualAddress = Sec.Relocations.size() + 1;
673 R.SymbolTableIndex = 0;
678 for (const auto &Relocation : Sec.Relocations)
679 WriteRelocation(Relocation.Data);
682 ////////////////////////////////////////////////////////////////////////////////
683 // MCObjectWriter interface implementations
685 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
686 const MCAsmLayout &Layout) {
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 // MS LINK expects to be able to replace all references to a function with a
701 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
702 // away any relocations to functions.
703 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
704 if (Asm.isIncrementalLinkerCompatible() &&
705 (Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
707 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
711 void WinCOFFObjectWriter::recordRelocation(
712 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
713 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
714 assert(Target.getSymA() && "Relocation must reference a symbol!");
716 const MCSymbol &A = Target.getSymA()->getSymbol();
717 if (!A.isRegistered()) {
718 Asm.getContext().reportError(Fixup.getLoc(),
719 Twine("symbol '") + A.getName() +
720 "' can not be undefined");
723 if (A.isTemporary() && A.isUndefined()) {
724 Asm.getContext().reportError(Fixup.getLoc(),
725 Twine("assembler label '") + A.getName() +
726 "' can not be undefined");
730 MCSection *MCSec = Fragment->getParent();
732 // Mark this symbol as requiring an entry in the symbol table.
733 assert(SectionMap.find(MCSec) != SectionMap.end() &&
734 "Section must already have been defined in executePostLayoutBinding!");
736 COFFSection *Sec = SectionMap[MCSec];
737 const MCSymbolRefExpr *SymB = Target.getSymB();
738 bool CrossSection = false;
741 const MCSymbol *B = &SymB->getSymbol();
742 if (!B->getFragment()) {
743 Asm.getContext().reportError(
745 Twine("symbol '") + B->getName() +
746 "' can not be undefined in a subtraction expression");
750 if (!A.getFragment()) {
751 Asm.getContext().reportError(
753 Twine("symbol '") + A.getName() +
754 "' can not be undefined in a subtraction expression");
758 CrossSection = &A.getSection() != &B->getSection();
760 // Offset of the symbol in the section
761 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
763 // In the case where we have SymbA and SymB, we just need to store the delta
764 // between the two symbols. Update FixedValue to account for the delta, and
765 // skip recording the relocation.
767 int64_t OffsetOfA = Layout.getSymbolOffset(A);
768 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
772 // Offset of the relocation in the section
773 int64_t OffsetOfRelocation =
774 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
776 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
778 FixedValue = Target.getConstant();
781 COFFRelocation Reloc;
783 Reloc.Data.SymbolTableIndex = 0;
784 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
786 // Turn relocations for temporary symbols into section relocations.
787 if (A.isTemporary() || CrossSection) {
788 MCSection *TargetSection = &A.getSection();
790 SectionMap.find(TargetSection) != SectionMap.end() &&
791 "Section must already have been defined in executePostLayoutBinding!");
792 Reloc.Symb = SectionMap[TargetSection]->Symbol;
793 FixedValue += Layout.getSymbolOffset(A);
796 SymbolMap.find(&A) != SymbolMap.end() &&
797 "Symbol must already have been defined in executePostLayoutBinding!");
798 Reloc.Symb = SymbolMap[&A];
801 ++Reloc.Symb->Relocations;
803 Reloc.Data.VirtualAddress += Fixup.getOffset();
804 Reloc.Data.Type = TargetObjectWriter->getRelocType(
805 Target, Fixup, CrossSection, Asm.getBackend());
807 // FIXME: Can anyone explain what this does other than adjust for the size
809 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
810 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
811 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
812 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
815 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
816 switch (Reloc.Data.Type) {
817 case COFF::IMAGE_REL_ARM_ABSOLUTE:
818 case COFF::IMAGE_REL_ARM_ADDR32:
819 case COFF::IMAGE_REL_ARM_ADDR32NB:
820 case COFF::IMAGE_REL_ARM_TOKEN:
821 case COFF::IMAGE_REL_ARM_SECTION:
822 case COFF::IMAGE_REL_ARM_SECREL:
824 case COFF::IMAGE_REL_ARM_BRANCH11:
825 case COFF::IMAGE_REL_ARM_BLX11:
826 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
827 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
829 case COFF::IMAGE_REL_ARM_BRANCH24:
830 case COFF::IMAGE_REL_ARM_BLX24:
831 case COFF::IMAGE_REL_ARM_MOV32A:
832 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
833 // only used for ARM mode code, which is documented as being unsupported
834 // by Windows on ARM. Empirical proof indicates that masm is able to
835 // generate the relocations however the rest of the MSVC toolchain is
836 // unable to handle it.
837 llvm_unreachable("unsupported relocation");
839 case COFF::IMAGE_REL_ARM_MOV32T:
841 case COFF::IMAGE_REL_ARM_BRANCH20T:
842 case COFF::IMAGE_REL_ARM_BRANCH24T:
843 case COFF::IMAGE_REL_ARM_BLX23T:
844 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
845 // perform a 4 byte adjustment to the relocation. Relative branches are
846 // offset by 4 on ARM, however, because there is no RELA relocations, all
847 // branches are offset by 4.
848 FixedValue = FixedValue + 4;
853 // The fixed value never makes sense for section indices, ignore it.
854 if (Fixup.getKind() == FK_SecRel_2)
857 if (TargetObjectWriter->recordRelocation(Fixup))
858 Sec->Relocations.push_back(Reloc);
861 static std::time_t getTime() {
862 std::time_t Now = time(nullptr);
863 if (Now < 0 || !isUInt<32>(Now))
868 // Create .file symbols.
869 void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
870 for (const std::string &Name : Asm.getFileNames()) {
871 // round up to calculate the number of auxiliary symbols required
872 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
873 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
875 COFFSymbol *File = createSymbol(".file");
876 File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
877 File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
878 File->Aux.resize(Count);
881 unsigned Length = Name.size();
882 for (auto &Aux : File->Aux) {
883 Aux.AuxType = ATFile;
885 if (Length > SymbolSize) {
886 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
887 Length = Length - SymbolSize;
889 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
890 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
894 Offset += SymbolSize;
899 static bool isAssociative(const COFFSection &Section) {
900 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
901 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
904 void WinCOFFObjectWriter::assignSectionNumbers() {
906 auto Assign = [&](COFFSection &Section) {
908 Section.Symbol->Data.SectionNumber = I;
909 Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
913 // Although it is not explicitly requested by the Microsoft COFF spec,
914 // we should avoid emitting forward associative section references,
915 // because MSVC link.exe as of 2017 cannot handle that.
916 for (const std::unique_ptr<COFFSection> &Section : Sections)
917 if (!isAssociative(*Section))
919 for (const std::unique_ptr<COFFSection> &Section : Sections)
920 if (isAssociative(*Section))
924 // Assign file offsets to COFF object file structures.
925 void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
926 const MCAsmLayout &Layout) {
927 unsigned Offset = getInitialOffset();
929 Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
930 Offset += COFF::SectionSize * Header.NumberOfSections;
932 for (const auto &Section : Asm) {
933 COFFSection *Sec = SectionMap[&Section];
935 if (Sec->Number == -1)
938 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
940 if (IsPhysicalSection(Sec)) {
941 // Align the section data to a four byte boundary.
942 Offset = alignTo(Offset, 4);
943 Sec->Header.PointerToRawData = Offset;
945 Offset += Sec->Header.SizeOfRawData;
948 if (!Sec->Relocations.empty()) {
949 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
951 if (RelocationsOverflow) {
952 // Signal overflow by setting NumberOfRelocations to max value. Actual
953 // size is found in reloc #0. Microsoft tools understand this.
954 Sec->Header.NumberOfRelocations = 0xffff;
956 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
958 Sec->Header.PointerToRelocations = Offset;
960 if (RelocationsOverflow) {
961 // Reloc #0 will contain actual count, so make room for it.
962 Offset += COFF::RelocationSize;
965 Offset += COFF::RelocationSize * Sec->Relocations.size();
967 for (auto &Relocation : Sec->Relocations) {
968 assert(Relocation.Symb->getIndex() != -1);
969 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
973 assert(Sec->Symbol->Aux.size() == 1 &&
974 "Section's symbol must have one aux!");
975 AuxSymbol &Aux = Sec->Symbol->Aux[0];
976 assert(Aux.AuxType == ATSectionDefinition &&
977 "Section's symbol's aux symbol must be a Section Definition!");
978 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
979 Aux.Aux.SectionDefinition.NumberOfRelocations =
980 Sec->Header.NumberOfRelocations;
981 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
982 Sec->Header.NumberOfLineNumbers;
985 Header.PointerToSymbolTable = Offset;
988 void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
989 const MCAsmLayout &Layout) {
990 if (Sections.size() > INT32_MAX)
992 "PE COFF object files can't have more than 2147483647 sections");
994 UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
995 Header.NumberOfSections = Sections.size();
996 Header.NumberOfSymbols = 0;
998 assignSectionNumbers();
999 createFileSymbols(Asm);
1001 for (auto &Symbol : Symbols) {
1002 // Update section number & offset for symbols that have them.
1003 if (Symbol->Section)
1004 Symbol->Data.SectionNumber = Symbol->Section->Number;
1005 Symbol->setIndex(Header.NumberOfSymbols++);
1006 // Update auxiliary symbol info.
1007 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
1008 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
1011 // Build string table.
1012 for (const auto &S : Sections)
1013 if (S->Name.size() > COFF::NameSize)
1014 Strings.add(S->Name);
1015 for (const auto &S : Symbols)
1016 if (S->Name.size() > COFF::NameSize)
1017 Strings.add(S->Name);
1021 for (const auto &S : Sections)
1023 for (auto &S : Symbols)
1026 // Fixup weak external references.
1027 for (auto &Symbol : Symbols) {
1028 if (Symbol->Other) {
1029 assert(Symbol->getIndex() != -1);
1030 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1031 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1032 "Symbol's aux symbol must be a Weak External!");
1033 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1037 // Fixup associative COMDAT sections.
1038 for (auto &Section : Sections) {
1039 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1040 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1043 const MCSectionCOFF &MCSec = *Section->MCSection;
1045 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
1047 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
1048 assert(COMDATSymbol);
1049 COFFSection *Assoc = COMDATSymbol->Section;
1052 Twine("Missing associated COMDAT section for section ") +
1053 MCSec.getSectionName());
1055 // Skip this section if the associated section is unused.
1056 if (Assoc->Number == -1)
1059 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
1062 assignFileOffsets(Asm, Layout);
1064 // MS LINK expects to be able to use this timestamp to implement their
1065 // /INCREMENTAL feature.
1066 if (Asm.isIncrementalLinkerCompatible()) {
1067 Header.TimeDateStamp = getTime();
1069 // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1070 Header.TimeDateStamp = 0;
1073 // Write it all to disk...
1074 WriteFileHeader(Header);
1075 writeSectionHeaders();
1077 // Write section contents.
1078 sections::iterator I = Sections.begin();
1079 sections::iterator IE = Sections.end();
1080 MCAssembler::iterator J = Asm.begin();
1081 MCAssembler::iterator JE = Asm.end();
1082 for (; I != IE && J != JE; ++I, ++J)
1083 writeSection(Asm, Layout, **I, *J);
1085 assert(getStream().tell() == Header.PointerToSymbolTable &&
1086 "Header::PointerToSymbolTable is insane!");
1088 // Write a symbol table.
1089 for (auto &Symbol : Symbols)
1090 if (Symbol->getIndex() != -1)
1091 WriteSymbol(*Symbol);
1093 // Write a string table, which completes the entire COFF file.
1094 Strings.write(getStream());
1097 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1098 : Machine(Machine_) {}
1100 // Pin the vtable to this file.
1101 void MCWinCOFFObjectTargetWriter::anchor() {}
1103 //------------------------------------------------------------------------------
1104 // WinCOFFObjectWriter factory function
1107 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1108 raw_pwrite_stream &OS) {
1109 return new WinCOFFObjectWriter(MOTW, OS);