1 //===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- C++ -*-===//
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/MC/MCWinCOFFObjectWriter.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.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/MCObjectWriter.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCSectionCOFF.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/MC/StringTableBuilder.h"
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Endian.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/TimeValue.h"
39 #define DEBUG_TYPE "WinCOFFObjectWriter"
42 typedef SmallString<COFF::NameSize> name;
53 AuxiliaryType AuxType;
64 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
75 COFFSymbol(StringRef name);
76 void set_name_offset(uint32_t Offset);
78 bool should_keep() const;
81 // This class contains staging data for a COFF relocation entry.
82 struct COFFRelocation {
83 COFF::relocation Data;
86 COFFRelocation() : Symb(nullptr) {}
87 static size_t size() { return COFF::RelocationSize; }
90 typedef std::vector<COFFRelocation> relocations;
98 MCSectionData const *MCData;
100 relocations Relocations;
102 COFFSection(StringRef name);
103 static size_t size();
106 class WinCOFFObjectWriter : public MCObjectWriter {
108 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
109 typedef std::vector<std::unique_ptr<COFFSection>> sections;
111 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
112 typedef DenseMap<MCSection const *, COFFSection *> section_map;
114 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
116 // Root level file contents.
120 StringTableBuilder Strings;
122 // Maps used during object file creation.
123 section_map SectionMap;
124 symbol_map SymbolMap;
128 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
130 void reset() override {
131 memset(&Header, 0, sizeof(Header));
132 Header.Machine = TargetObjectWriter->getMachine();
138 MCObjectWriter::reset();
141 COFFSymbol *createSymbol(StringRef Name);
142 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
143 COFFSection *createSection(StringRef Name);
145 template <typename object_t, typename list_t>
146 object_t *createCOFFEntity(StringRef Name, list_t &List);
148 void DefineSection(MCSectionData const &SectionData);
149 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
150 const MCAsmLayout &Layout);
152 void SetSymbolName(COFFSymbol &S);
153 void SetSectionName(COFFSection &S);
155 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
157 bool IsPhysicalSection(COFFSection *S);
159 // Entity writing methods.
161 void WriteFileHeader(const COFF::header &Header);
162 void WriteSymbol(const COFFSymbol &S);
163 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
164 void WriteSectionHeader(const COFF::section &S);
165 void WriteRelocation(const COFF::relocation &R);
167 // MCObjectWriter interface implementation.
169 void ExecutePostLayoutBinding(MCAssembler &Asm,
170 const MCAsmLayout &Layout) override;
172 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
173 const MCSymbol &SymA,
174 const MCFragment &FB, bool InSet,
175 bool IsPCRel) const override;
177 bool isWeak(const MCSymbol &Sym) const override;
179 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
180 const MCFragment *Fragment, const MCFixup &Fixup,
181 MCValue Target, bool &IsPCRel,
182 uint64_t &FixedValue) override;
184 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
188 static inline void write_uint32_le(void *Data, uint32_t Value) {
189 support::endian::write<uint32_t, support::little, support::unaligned>(Data,
193 //------------------------------------------------------------------------------
194 // Symbol class implementation
196 COFFSymbol::COFFSymbol(StringRef name)
197 : Name(name.begin(), name.end()), Other(nullptr), Section(nullptr),
198 Relocations(0), MC(nullptr) {
199 memset(&Data, 0, sizeof(Data));
202 // In the case that the name does not fit within 8 bytes, the offset
203 // into the string table is stored in the last 4 bytes instead, leaving
204 // the first 4 bytes as 0.
205 void COFFSymbol::set_name_offset(uint32_t Offset) {
206 write_uint32_le(Data.Name + 0, 0);
207 write_uint32_le(Data.Name + 4, Offset);
210 /// logic to decide if the symbol should be reported in the symbol table
211 bool COFFSymbol::should_keep() const {
212 // no section means its external, keep it
216 // if it has relocations pointing at it, keep it
217 if (Relocations > 0) {
218 assert(Section->Number != -1 && "Sections with relocations must be real!");
222 // if the section its in is being droped, drop it
223 if (Section->Number == -1)
226 // if it is the section symbol, keep it
227 if (Section->Symbol == this)
230 // if its temporary, drop it
231 if (MC && MC->isTemporary())
234 // otherwise, keep it
238 //------------------------------------------------------------------------------
239 // Section class implementation
241 COFFSection::COFFSection(StringRef name)
242 : Name(name), MCData(nullptr), Symbol(nullptr) {
243 memset(&Header, 0, sizeof(Header));
246 size_t COFFSection::size() { return COFF::SectionSize; }
248 //------------------------------------------------------------------------------
249 // WinCOFFObjectWriter class implementation
251 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
252 raw_pwrite_stream &OS)
253 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
254 memset(&Header, 0, sizeof(Header));
256 Header.Machine = TargetObjectWriter->getMachine();
259 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
260 return createCOFFEntity<COFFSymbol>(Name, Symbols);
263 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
264 symbol_map::iterator i = SymbolMap.find(Symbol);
265 if (i != SymbolMap.end())
267 COFFSymbol *RetSymbol =
268 createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
269 SymbolMap[Symbol] = RetSymbol;
273 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
274 return createCOFFEntity<COFFSection>(Name, Sections);
277 /// A template used to lookup or create a symbol/section, and initialize it if
279 template <typename object_t, typename list_t>
280 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, list_t &List) {
281 List.push_back(make_unique<object_t>(Name));
283 return List.back().get();
286 /// This function takes a section data object from the assembler
287 /// and creates the associated COFF section staging object.
288 void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
289 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF &&
290 "Got non-COFF section in the COFF backend!");
291 // FIXME: Not sure how to verify this (at least in a debug build).
292 MCSectionCOFF const &Sec =
293 static_cast<MCSectionCOFF const &>(SectionData.getSection());
295 COFFSection *coff_section = createSection(Sec.getSectionName());
296 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
297 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
298 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
299 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
300 if (COMDATSymbol->Section)
301 report_fatal_error("two sections have the same comdat");
302 COMDATSymbol->Section = coff_section;
306 coff_section->Symbol = coff_symbol;
307 coff_symbol->Section = coff_section;
308 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
310 // In this case the auxiliary symbol is a Section Definition.
311 coff_symbol->Aux.resize(1);
312 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
313 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
314 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
316 coff_section->Header.Characteristics = Sec.getCharacteristics();
318 uint32_t &Characteristics = coff_section->Header.Characteristics;
319 switch (Sec.getAlignment()) {
321 Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
324 Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
327 Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
330 Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
333 Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
336 Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
339 Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
342 Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
345 Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
348 Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
351 Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
354 Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
357 Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
360 Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
363 llvm_unreachable("unsupported section alignment");
366 // Bind internal COFF section to MC section.
367 coff_section->MCData = &SectionData;
368 SectionMap[&SectionData.getSection()] = coff_section;
371 static uint64_t getSymbolValue(const MCSymbol &Symbol,
372 const MCAsmLayout &Layout) {
373 const MCSymbolData &Data = Symbol.getData();
374 if (Data.isCommon() && Data.isExternal())
375 return Data.getCommonSize();
378 if (!Layout.getSymbolOffset(Symbol, Res))
384 /// This function takes a symbol data object from the assembler
385 /// and creates the associated COFF symbol staging object.
386 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
387 MCAssembler &Assembler,
388 const MCAsmLayout &Layout) {
389 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
390 SymbolMap[&Symbol] = coff_symbol;
392 if (Symbol.getData().getFlags() & COFF::SF_WeakExternal) {
393 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
395 if (Symbol.isVariable()) {
396 const MCSymbolRefExpr *SymRef =
397 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
400 report_fatal_error("Weak externals may only alias symbols");
402 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
404 std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
405 COFFSymbol *WeakDefault = createSymbol(WeakName);
406 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
407 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
408 WeakDefault->Data.Type = 0;
409 WeakDefault->Data.Value = 0;
410 coff_symbol->Other = WeakDefault;
413 // Setup the Weak External auxiliary symbol.
414 coff_symbol->Aux.resize(1);
415 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
416 coff_symbol->Aux[0].AuxType = ATWeakExternal;
417 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
418 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
419 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
421 coff_symbol->MC = &Symbol;
423 const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol);
424 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
425 coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
427 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
428 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
430 // If no storage class was specified in the streamer, define it here.
431 if (coff_symbol->Data.StorageClass == 0) {
432 bool IsExternal = ResSymData.isExternal() ||
433 (!ResSymData.getFragment() && !Symbol.isVariable());
435 coff_symbol->Data.StorageClass = IsExternal
436 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
437 : COFF::IMAGE_SYM_CLASS_STATIC;
441 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
443 const MCSymbolData &BaseData = Assembler.getSymbolData(*Base);
444 if (BaseData.getFragment()) {
445 COFFSection *Sec = SectionMap[BaseData.getFragment()->getParent()];
447 if (coff_symbol->Section && coff_symbol->Section != Sec)
448 report_fatal_error("conflicting sections for symbol");
450 coff_symbol->Section = Sec;
454 coff_symbol->MC = &Symbol;
458 // Maximum offsets for different string table entry encodings.
459 static const unsigned Max6DecimalOffset = 999999;
460 static const unsigned Max7DecimalOffset = 9999999;
461 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
463 // Encode a string table entry offset in base 64, padded to 6 chars, and
464 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
465 // Buffer must be at least 8 bytes large. No terminating null appended.
466 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
467 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
468 "Illegal section name encoding for value");
470 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
471 "abcdefghijklmnopqrstuvwxyz"
477 char *Ptr = Buffer + 7;
478 for (unsigned i = 0; i < 6; ++i) {
479 unsigned Rem = Value % 64;
481 *(Ptr--) = Alphabet[Rem];
485 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
486 if (S.Name.size() > COFF::NameSize) {
487 uint64_t StringTableEntry = Strings.getOffset(S.Name);
489 if (StringTableEntry <= Max6DecimalOffset) {
490 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
491 } else if (StringTableEntry <= Max7DecimalOffset) {
492 // With seven digits, we have to skip the terminating null. Because
493 // sprintf always appends it, we use a larger temporary buffer.
495 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
496 std::memcpy(S.Header.Name, buffer, 8);
497 } else if (StringTableEntry <= MaxBase64Offset) {
498 // Starting with 10,000,000, offsets are encoded as base64.
499 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
501 report_fatal_error("COFF string table is greater than 64 GB.");
504 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
507 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
508 if (S.Name.size() > COFF::NameSize)
509 S.set_name_offset(Strings.getOffset(S.Name));
511 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
514 bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
516 // This doesn't seem to be right. Strings referred to from the .data section
517 // need symbols so they can be linked to code in the .text section right?
519 // return Asm.isSymbolLinkerVisible(Symbol);
521 // Non-temporary labels should always be visible to the linker.
522 if (!Symbol.isTemporary())
525 // Absolute temporary labels are never visible.
526 if (!Symbol.isInSection())
529 // For now, all non-variable symbols are exported,
530 // the linker will sort the rest out for us.
531 return !Symbol.isVariable();
534 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
535 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
539 //------------------------------------------------------------------------------
540 // entity writing methods
542 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
544 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
546 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
547 WriteLE16(Header.Machine);
548 WriteLE32(Header.TimeDateStamp);
549 WriteBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
554 WriteLE32(Header.NumberOfSections);
555 WriteLE32(Header.PointerToSymbolTable);
556 WriteLE32(Header.NumberOfSymbols);
558 WriteLE16(Header.Machine);
559 WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
560 WriteLE32(Header.TimeDateStamp);
561 WriteLE32(Header.PointerToSymbolTable);
562 WriteLE32(Header.NumberOfSymbols);
563 WriteLE16(Header.SizeOfOptionalHeader);
564 WriteLE16(Header.Characteristics);
568 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
569 WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
570 WriteLE32(S.Data.Value);
572 WriteLE32(S.Data.SectionNumber);
574 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
575 WriteLE16(S.Data.Type);
576 Write8(S.Data.StorageClass);
577 Write8(S.Data.NumberOfAuxSymbols);
578 WriteAuxiliarySymbols(S.Aux);
581 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
582 const COFFSymbol::AuxiliarySymbols &S) {
583 for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
585 switch (i->AuxType) {
586 case ATFunctionDefinition:
587 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
588 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
589 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
590 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
591 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
593 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
595 case ATbfAndefSymbol:
596 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
597 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
598 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
599 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
600 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
602 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
605 WriteLE32(i->Aux.WeakExternal.TagIndex);
606 WriteLE32(i->Aux.WeakExternal.Characteristics);
607 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
609 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
613 StringRef(reinterpret_cast<const char *>(&i->Aux),
614 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
616 case ATSectionDefinition:
617 WriteLE32(i->Aux.SectionDefinition.Length);
618 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
619 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
620 WriteLE32(i->Aux.SectionDefinition.CheckSum);
621 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
622 Write8(i->Aux.SectionDefinition.Selection);
623 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
624 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
626 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
632 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
633 WriteBytes(StringRef(S.Name, COFF::NameSize));
635 WriteLE32(S.VirtualSize);
636 WriteLE32(S.VirtualAddress);
637 WriteLE32(S.SizeOfRawData);
638 WriteLE32(S.PointerToRawData);
639 WriteLE32(S.PointerToRelocations);
640 WriteLE32(S.PointerToLineNumbers);
641 WriteLE16(S.NumberOfRelocations);
642 WriteLE16(S.NumberOfLineNumbers);
643 WriteLE32(S.Characteristics);
646 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
647 WriteLE32(R.VirtualAddress);
648 WriteLE32(R.SymbolTableIndex);
652 ////////////////////////////////////////////////////////////////////////////////
653 // MCObjectWriter interface implementations
655 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
656 const MCAsmLayout &Layout) {
657 // "Define" each section & symbol. This creates section & symbol
658 // entries in the staging area.
659 for (const auto &Section : Asm)
660 DefineSection(Section.getSectionData());
662 for (const MCSymbol &Symbol : Asm.symbols())
663 if (ExportSymbol(Symbol, Asm))
664 DefineSymbol(Symbol, Asm, Layout);
667 bool WinCOFFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
668 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
669 bool InSet, bool IsPCRel) const {
670 // MS LINK expects to be able to replace all references to a function with a
671 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
672 // away any relocations to functions.
673 if ((((SymA.getData().getFlags() & COFF::SF_TypeMask) >>
674 COFF::SF_TypeShift) >>
675 COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
677 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
681 bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
682 const MCSymbolData &SD = Sym.getData();
683 if (!SD.isExternal())
686 if (!Sym.isInSection())
689 const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
690 if (!Sec.getCOMDATSymbol())
693 // It looks like for COFF it is invalid to replace a reference to a global
694 // in a comdat with a reference to a local.
695 // FIXME: Add a specification reference if available.
699 void WinCOFFObjectWriter::RecordRelocation(
700 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
701 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
702 assert(Target.getSymA() && "Relocation must reference a symbol!");
704 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
705 const MCSymbol &A = Symbol;
706 if (!Asm.hasSymbolData(A))
707 Asm.getContext().reportFatalError(Fixup.getLoc(),
708 Twine("symbol '") + A.getName() +
709 "' can not be undefined");
711 const MCSymbolData &A_SD = Asm.getSymbolData(A);
713 MCSection *Section = Fragment->getParent();
715 // Mark this symbol as requiring an entry in the symbol table.
716 assert(SectionMap.find(Section) != SectionMap.end() &&
717 "Section must already have been defined in ExecutePostLayoutBinding!");
718 assert(SymbolMap.find(&A) != SymbolMap.end() &&
719 "Symbol must already have been defined in ExecutePostLayoutBinding!");
721 COFFSection *coff_section = SectionMap[Section];
722 COFFSymbol *coff_symbol = SymbolMap[&A];
723 const MCSymbolRefExpr *SymB = Target.getSymB();
724 bool CrossSection = false;
727 const MCSymbol *B = &SymB->getSymbol();
728 const MCSymbolData &B_SD = Asm.getSymbolData(*B);
729 if (!B_SD.getFragment())
730 Asm.getContext().reportFatalError(
732 Twine("symbol '") + B->getName() +
733 "' can not be undefined in a subtraction expression");
735 if (!A_SD.getFragment())
736 Asm.getContext().reportFatalError(
738 Twine("symbol '") + Symbol.getName() +
739 "' can not be undefined in a subtraction expression");
741 CrossSection = &Symbol.getSection() != &B->getSection();
743 // Offset of the symbol in the section
744 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
746 // In the case where we have SymbA and SymB, we just need to store the delta
747 // between the two symbols. Update FixedValue to account for the delta, and
748 // skip recording the relocation.
750 int64_t OffsetOfA = Layout.getSymbolOffset(A);
751 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
755 // Offset of the relocation in the section
756 int64_t OffsetOfRelocation =
757 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
759 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
761 FixedValue = Target.getConstant();
764 COFFRelocation Reloc;
766 Reloc.Data.SymbolTableIndex = 0;
767 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
769 // Turn relocations for temporary symbols into section relocations.
770 if (coff_symbol->MC->isTemporary() || CrossSection) {
771 Reloc.Symb = coff_symbol->Section->Symbol;
773 Layout.getFragmentOffset(coff_symbol->MC->getData().getFragment()) +
774 coff_symbol->MC->getData().getOffset();
776 Reloc.Symb = coff_symbol;
778 ++Reloc.Symb->Relocations;
780 Reloc.Data.VirtualAddress += Fixup.getOffset();
781 Reloc.Data.Type = TargetObjectWriter->getRelocType(
782 Target, Fixup, CrossSection, Asm.getBackend());
784 // FIXME: Can anyone explain what this does other than adjust for the size
786 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
787 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
788 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
789 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
792 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
793 switch (Reloc.Data.Type) {
794 case COFF::IMAGE_REL_ARM_ABSOLUTE:
795 case COFF::IMAGE_REL_ARM_ADDR32:
796 case COFF::IMAGE_REL_ARM_ADDR32NB:
797 case COFF::IMAGE_REL_ARM_TOKEN:
798 case COFF::IMAGE_REL_ARM_SECTION:
799 case COFF::IMAGE_REL_ARM_SECREL:
801 case COFF::IMAGE_REL_ARM_BRANCH11:
802 case COFF::IMAGE_REL_ARM_BLX11:
803 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
804 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
806 case COFF::IMAGE_REL_ARM_BRANCH24:
807 case COFF::IMAGE_REL_ARM_BLX24:
808 case COFF::IMAGE_REL_ARM_MOV32A:
809 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
810 // only used for ARM mode code, which is documented as being unsupported
811 // by Windows on ARM. Empirical proof indicates that masm is able to
812 // generate the relocations however the rest of the MSVC toolchain is
813 // unable to handle it.
814 llvm_unreachable("unsupported relocation");
816 case COFF::IMAGE_REL_ARM_MOV32T:
818 case COFF::IMAGE_REL_ARM_BRANCH20T:
819 case COFF::IMAGE_REL_ARM_BRANCH24T:
820 case COFF::IMAGE_REL_ARM_BLX23T:
821 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
822 // perform a 4 byte adjustment to the relocation. Relative branches are
823 // offset by 4 on ARM, however, because there is no RELA relocations, all
824 // branches are offset by 4.
825 FixedValue = FixedValue + 4;
830 if (TargetObjectWriter->recordRelocation(Fixup))
831 coff_section->Relocations.push_back(Reloc);
834 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
835 const MCAsmLayout &Layout) {
836 size_t SectionsSize = Sections.size();
837 if (SectionsSize > static_cast<size_t>(INT32_MAX))
839 "PE COFF object files can't have more than 2147483647 sections");
841 // Assign symbol and section indexes and offsets.
842 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
844 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
846 DenseMap<COFFSection *, int32_t> SectionIndices(
847 NextPowerOf2(NumberOfSections));
849 // Assign section numbers.
851 for (const auto &Section : Sections) {
852 SectionIndices[Section.get()] = Number;
853 Section->Number = Number;
854 Section->Symbol->Data.SectionNumber = Number;
855 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
859 Header.NumberOfSections = NumberOfSections;
860 Header.NumberOfSymbols = 0;
862 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end(); FI != FE;
864 // round up to calculate the number of auxiliary symbols required
865 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
866 unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize;
868 COFFSymbol *file = createSymbol(".file");
869 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
870 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
871 file->Aux.resize(Count);
874 unsigned Length = FI->size();
875 for (auto &Aux : file->Aux) {
876 Aux.AuxType = ATFile;
878 if (Length > SymbolSize) {
879 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
880 Length = Length - SymbolSize;
882 memcpy(&Aux.Aux, FI->c_str() + Offset, Length);
883 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
887 Offset += SymbolSize;
891 for (auto &Symbol : Symbols) {
892 // Update section number & offset for symbols that have them.
894 Symbol->Data.SectionNumber = Symbol->Section->Number;
895 if (Symbol->should_keep()) {
896 Symbol->Index = Header.NumberOfSymbols++;
897 // Update auxiliary symbol info.
898 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
899 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
904 // Build string table.
905 for (const auto &S : Sections)
906 if (S->Name.size() > COFF::NameSize)
907 Strings.add(S->Name);
908 for (const auto &S : Symbols)
909 if (S->should_keep() && S->Name.size() > COFF::NameSize)
910 Strings.add(S->Name);
911 Strings.finalize(StringTableBuilder::WinCOFF);
914 for (const auto &S : Sections)
916 for (auto &S : Symbols)
917 if (S->should_keep())
920 // Fixup weak external references.
921 for (auto &Symbol : Symbols) {
923 assert(Symbol->Index != -1);
924 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
925 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
926 "Symbol's aux symbol must be a Weak External!");
927 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
931 // Fixup associative COMDAT sections.
932 for (auto &Section : Sections) {
933 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
934 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
937 const MCSectionCOFF &MCSec =
938 static_cast<const MCSectionCOFF &>(Section->MCData->getSection());
940 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
942 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
943 assert(COMDATSymbol);
944 COFFSection *Assoc = COMDATSymbol->Section;
947 Twine("Missing associated COMDAT section for section ") +
948 MCSec.getSectionName());
950 // Skip this section if the associated section is unused.
951 if (Assoc->Number == -1)
954 Section->Symbol->Aux[0].Aux.SectionDefinition.Number =
955 SectionIndices[Assoc];
958 // Assign file offsets to COFF object file structures.
963 offset += COFF::Header32Size;
965 offset += COFF::Header16Size;
966 offset += COFF::SectionSize * Header.NumberOfSections;
968 for (const auto &Section : Asm) {
969 COFFSection *Sec = SectionMap[&Section];
971 if (Sec->Number == -1)
974 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
976 if (IsPhysicalSection(Sec)) {
977 // Align the section data to a four byte boundary.
978 offset = RoundUpToAlignment(offset, 4);
979 Sec->Header.PointerToRawData = offset;
981 offset += Sec->Header.SizeOfRawData;
984 if (Sec->Relocations.size() > 0) {
985 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
987 if (RelocationsOverflow) {
988 // Signal overflow by setting NumberOfRelocations to max value. Actual
989 // size is found in reloc #0. Microsoft tools understand this.
990 Sec->Header.NumberOfRelocations = 0xffff;
992 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
994 Sec->Header.PointerToRelocations = offset;
996 if (RelocationsOverflow) {
997 // Reloc #0 will contain actual count, so make room for it.
998 offset += COFF::RelocationSize;
1001 offset += COFF::RelocationSize * Sec->Relocations.size();
1003 for (auto &Relocation : Sec->Relocations) {
1004 assert(Relocation.Symb->Index != -1);
1005 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
1009 assert(Sec->Symbol->Aux.size() == 1 &&
1010 "Section's symbol must have one aux!");
1011 AuxSymbol &Aux = Sec->Symbol->Aux[0];
1012 assert(Aux.AuxType == ATSectionDefinition &&
1013 "Section's symbol's aux symbol must be a Section Definition!");
1014 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1015 Aux.Aux.SectionDefinition.NumberOfRelocations =
1016 Sec->Header.NumberOfRelocations;
1017 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1018 Sec->Header.NumberOfLineNumbers;
1021 Header.PointerToSymbolTable = offset;
1023 // We want a deterministic output. It looks like GNU as also writes 0 in here.
1024 Header.TimeDateStamp = 0;
1026 // Write it all to disk...
1027 WriteFileHeader(Header);
1030 sections::iterator i, ie;
1031 MCAssembler::const_iterator j, je;
1033 for (auto &Section : Sections) {
1034 if (Section->Number != -1) {
1035 if (Section->Relocations.size() >= 0xffff)
1036 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
1037 WriteSectionHeader(Section->Header);
1041 for (i = Sections.begin(), ie = Sections.end(), j = Asm.begin(),
1043 (i != ie) && (j != je); ++i, ++j) {
1045 if ((*i)->Number == -1)
1048 if ((*i)->Header.PointerToRawData != 0) {
1049 assert(OS.tell() <= (*i)->Header.PointerToRawData &&
1050 "Section::PointerToRawData is insane!");
1052 unsigned SectionDataPadding = (*i)->Header.PointerToRawData - OS.tell();
1053 assert(SectionDataPadding < 4 &&
1054 "Should only need at most three bytes of padding!");
1056 WriteZeros(SectionDataPadding);
1058 Asm.writeSectionData(&*j, Layout);
1061 if ((*i)->Relocations.size() > 0) {
1062 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1063 "Section::PointerToRelocations is insane!");
1065 if ((*i)->Relocations.size() >= 0xffff) {
1066 // In case of overflow, write actual relocation count as first
1067 // relocation. Including the synthetic reloc itself (+ 1).
1069 r.VirtualAddress = (*i)->Relocations.size() + 1;
1070 r.SymbolTableIndex = 0;
1075 for (const auto &Relocation : (*i)->Relocations)
1076 WriteRelocation(Relocation.Data);
1078 assert((*i)->Header.PointerToRelocations == 0 &&
1079 "Section::PointerToRelocations is insane!");
1083 assert(OS.tell() == Header.PointerToSymbolTable &&
1084 "Header::PointerToSymbolTable is insane!");
1086 for (auto &Symbol : Symbols)
1087 if (Symbol->Index != -1)
1088 WriteSymbol(*Symbol);
1090 OS.write(Strings.data().data(), Strings.data().size());
1093 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1094 : Machine(Machine_) {}
1096 // Pin the vtable to this file.
1097 void MCWinCOFFObjectTargetWriter::anchor() {}
1099 //------------------------------------------------------------------------------
1100 // WinCOFFObjectWriter factory function
1103 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1104 raw_pwrite_stream &OS) {
1105 return new WinCOFFObjectWriter(MOTW, OS);