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 MCSectionCOFF const *MCSection;
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(MCSectionCOFF const &Sec);
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), MCSection(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(MCSectionCOFF const &Sec) {
289 COFFSection *coff_section = createSection(Sec.getSectionName());
290 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
291 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
292 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
293 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
294 if (COMDATSymbol->Section)
295 report_fatal_error("two sections have the same comdat");
296 COMDATSymbol->Section = coff_section;
300 coff_section->Symbol = coff_symbol;
301 coff_symbol->Section = coff_section;
302 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
304 // In this case the auxiliary symbol is a Section Definition.
305 coff_symbol->Aux.resize(1);
306 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
307 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
308 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
310 coff_section->Header.Characteristics = Sec.getCharacteristics();
312 uint32_t &Characteristics = coff_section->Header.Characteristics;
313 switch (Sec.getAlignment()) {
315 Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
318 Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
321 Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
324 Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
327 Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
330 Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
333 Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
336 Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
339 Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
342 Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
345 Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
348 Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
351 Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
354 Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
357 llvm_unreachable("unsupported section alignment");
360 // Bind internal COFF section to MC section.
361 coff_section->MCSection = &Sec;
362 SectionMap[&Sec] = coff_section;
365 static uint64_t getSymbolValue(const MCSymbol &Symbol,
366 const MCAsmLayout &Layout) {
367 const MCSymbolData &Data = Symbol.getData();
368 if (Symbol.isCommon() && Data.isExternal())
369 return Symbol.getCommonSize();
372 if (!Layout.getSymbolOffset(Symbol, Res))
378 /// This function takes a symbol data object from the assembler
379 /// and creates the associated COFF symbol staging object.
380 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
381 MCAssembler &Assembler,
382 const MCAsmLayout &Layout) {
383 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
384 SymbolMap[&Symbol] = coff_symbol;
386 if (Symbol.getFlags() & COFF::SF_WeakExternal) {
387 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
389 if (Symbol.isVariable()) {
390 const MCSymbolRefExpr *SymRef =
391 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
394 report_fatal_error("Weak externals may only alias symbols");
396 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
398 std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
399 COFFSymbol *WeakDefault = createSymbol(WeakName);
400 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
401 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
402 WeakDefault->Data.Type = 0;
403 WeakDefault->Data.Value = 0;
404 coff_symbol->Other = WeakDefault;
407 // Setup the Weak External auxiliary symbol.
408 coff_symbol->Aux.resize(1);
409 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
410 coff_symbol->Aux[0].AuxType = ATWeakExternal;
411 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
412 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
413 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
415 coff_symbol->MC = &Symbol;
417 const MCSymbolData &ResSymData = Symbol.getData();
418 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
419 coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
421 coff_symbol->Data.Type = (Symbol.getFlags() & 0x0000FFFF) >> 0;
422 coff_symbol->Data.StorageClass = (Symbol.getFlags() & 0x00FF0000) >> 16;
424 // If no storage class was specified in the streamer, define it here.
425 if (coff_symbol->Data.StorageClass == 0) {
426 bool IsExternal = ResSymData.isExternal() ||
427 (!ResSymData.getFragment() && !Symbol.isVariable());
429 coff_symbol->Data.StorageClass = IsExternal
430 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
431 : COFF::IMAGE_SYM_CLASS_STATIC;
435 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
437 const MCSymbolData &BaseData = Base->getData();
438 if (BaseData.getFragment()) {
439 COFFSection *Sec = SectionMap[BaseData.getFragment()->getParent()];
441 if (coff_symbol->Section && coff_symbol->Section != Sec)
442 report_fatal_error("conflicting sections for symbol");
444 coff_symbol->Section = Sec;
448 coff_symbol->MC = &Symbol;
452 // Maximum offsets for different string table entry encodings.
453 static const unsigned Max6DecimalOffset = 999999;
454 static const unsigned Max7DecimalOffset = 9999999;
455 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
457 // Encode a string table entry offset in base 64, padded to 6 chars, and
458 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
459 // Buffer must be at least 8 bytes large. No terminating null appended.
460 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
461 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
462 "Illegal section name encoding for value");
464 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
465 "abcdefghijklmnopqrstuvwxyz"
471 char *Ptr = Buffer + 7;
472 for (unsigned i = 0; i < 6; ++i) {
473 unsigned Rem = Value % 64;
475 *(Ptr--) = Alphabet[Rem];
479 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
480 if (S.Name.size() > COFF::NameSize) {
481 uint64_t StringTableEntry = Strings.getOffset(S.Name);
483 if (StringTableEntry <= Max6DecimalOffset) {
484 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
485 } else if (StringTableEntry <= Max7DecimalOffset) {
486 // With seven digits, we have to skip the terminating null. Because
487 // sprintf always appends it, we use a larger temporary buffer.
489 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
490 std::memcpy(S.Header.Name, buffer, 8);
491 } else if (StringTableEntry <= MaxBase64Offset) {
492 // Starting with 10,000,000, offsets are encoded as base64.
493 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
495 report_fatal_error("COFF string table is greater than 64 GB.");
498 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
501 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
502 if (S.Name.size() > COFF::NameSize)
503 S.set_name_offset(Strings.getOffset(S.Name));
505 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
508 bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
510 // This doesn't seem to be right. Strings referred to from the .data section
511 // need symbols so they can be linked to code in the .text section right?
513 // return Asm.isSymbolLinkerVisible(Symbol);
515 // Non-temporary labels should always be visible to the linker.
516 if (!Symbol.isTemporary())
519 // Absolute temporary labels are never visible.
520 if (!Symbol.isInSection())
523 // For now, all non-variable symbols are exported,
524 // the linker will sort the rest out for us.
525 return !Symbol.isVariable();
528 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
529 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
533 //------------------------------------------------------------------------------
534 // entity writing methods
536 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
538 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
540 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
541 WriteLE16(Header.Machine);
542 WriteLE32(Header.TimeDateStamp);
543 WriteBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
548 WriteLE32(Header.NumberOfSections);
549 WriteLE32(Header.PointerToSymbolTable);
550 WriteLE32(Header.NumberOfSymbols);
552 WriteLE16(Header.Machine);
553 WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
554 WriteLE32(Header.TimeDateStamp);
555 WriteLE32(Header.PointerToSymbolTable);
556 WriteLE32(Header.NumberOfSymbols);
557 WriteLE16(Header.SizeOfOptionalHeader);
558 WriteLE16(Header.Characteristics);
562 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
563 WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
564 WriteLE32(S.Data.Value);
566 WriteLE32(S.Data.SectionNumber);
568 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
569 WriteLE16(S.Data.Type);
570 Write8(S.Data.StorageClass);
571 Write8(S.Data.NumberOfAuxSymbols);
572 WriteAuxiliarySymbols(S.Aux);
575 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
576 const COFFSymbol::AuxiliarySymbols &S) {
577 for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
579 switch (i->AuxType) {
580 case ATFunctionDefinition:
581 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
582 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
583 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
584 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
585 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
587 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
589 case ATbfAndefSymbol:
590 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
591 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
592 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
593 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
594 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
596 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
599 WriteLE32(i->Aux.WeakExternal.TagIndex);
600 WriteLE32(i->Aux.WeakExternal.Characteristics);
601 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
603 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
607 StringRef(reinterpret_cast<const char *>(&i->Aux),
608 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
610 case ATSectionDefinition:
611 WriteLE32(i->Aux.SectionDefinition.Length);
612 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
613 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
614 WriteLE32(i->Aux.SectionDefinition.CheckSum);
615 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
616 Write8(i->Aux.SectionDefinition.Selection);
617 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
618 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
620 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
626 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
627 WriteBytes(StringRef(S.Name, COFF::NameSize));
629 WriteLE32(S.VirtualSize);
630 WriteLE32(S.VirtualAddress);
631 WriteLE32(S.SizeOfRawData);
632 WriteLE32(S.PointerToRawData);
633 WriteLE32(S.PointerToRelocations);
634 WriteLE32(S.PointerToLineNumbers);
635 WriteLE16(S.NumberOfRelocations);
636 WriteLE16(S.NumberOfLineNumbers);
637 WriteLE32(S.Characteristics);
640 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
641 WriteLE32(R.VirtualAddress);
642 WriteLE32(R.SymbolTableIndex);
646 ////////////////////////////////////////////////////////////////////////////////
647 // MCObjectWriter interface implementations
649 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
650 const MCAsmLayout &Layout) {
651 // "Define" each section & symbol. This creates section & symbol
652 // entries in the staging area.
653 for (const auto &Section : Asm)
654 defineSection(static_cast<const MCSectionCOFF &>(Section));
656 for (const MCSymbol &Symbol : Asm.symbols())
657 if (ExportSymbol(Symbol, Asm))
658 DefineSymbol(Symbol, Asm, Layout);
661 bool WinCOFFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
662 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
663 bool InSet, bool IsPCRel) const {
664 // MS LINK expects to be able to replace all references to a function with a
665 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
666 // away any relocations to functions.
667 if ((((SymA.getFlags() & COFF::SF_TypeMask) >> COFF::SF_TypeShift) >>
668 COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
670 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
674 bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
675 const MCSymbolData &SD = Sym.getData();
676 if (!SD.isExternal())
679 if (!Sym.isInSection())
682 const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
683 if (!Sec.getCOMDATSymbol())
686 // It looks like for COFF it is invalid to replace a reference to a global
687 // in a comdat with a reference to a local.
688 // FIXME: Add a specification reference if available.
692 void WinCOFFObjectWriter::RecordRelocation(
693 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
694 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
695 assert(Target.getSymA() && "Relocation must reference a symbol!");
697 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
698 const MCSymbol &A = Symbol;
699 if (!Asm.hasSymbolData(A))
700 Asm.getContext().reportFatalError(Fixup.getLoc(),
701 Twine("symbol '") + A.getName() +
702 "' can not be undefined");
704 const MCSymbolData &A_SD = A.getData();
706 MCSection *Section = Fragment->getParent();
708 // Mark this symbol as requiring an entry in the symbol table.
709 assert(SectionMap.find(Section) != SectionMap.end() &&
710 "Section must already have been defined in ExecutePostLayoutBinding!");
711 assert(SymbolMap.find(&A) != SymbolMap.end() &&
712 "Symbol must already have been defined in ExecutePostLayoutBinding!");
714 COFFSection *coff_section = SectionMap[Section];
715 COFFSymbol *coff_symbol = SymbolMap[&A];
716 const MCSymbolRefExpr *SymB = Target.getSymB();
717 bool CrossSection = false;
720 const MCSymbol *B = &SymB->getSymbol();
721 const MCSymbolData &B_SD = B->getData();
722 if (!B_SD.getFragment())
723 Asm.getContext().reportFatalError(
725 Twine("symbol '") + B->getName() +
726 "' can not be undefined in a subtraction expression");
728 if (!A_SD.getFragment())
729 Asm.getContext().reportFatalError(
731 Twine("symbol '") + Symbol.getName() +
732 "' can not be undefined in a subtraction expression");
734 CrossSection = &Symbol.getSection() != &B->getSection();
736 // Offset of the symbol in the section
737 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
739 // In the case where we have SymbA and SymB, we just need to store the delta
740 // between the two symbols. Update FixedValue to account for the delta, and
741 // skip recording the relocation.
743 int64_t OffsetOfA = Layout.getSymbolOffset(A);
744 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
748 // Offset of the relocation in the section
749 int64_t OffsetOfRelocation =
750 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
752 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
754 FixedValue = Target.getConstant();
757 COFFRelocation Reloc;
759 Reloc.Data.SymbolTableIndex = 0;
760 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
762 // Turn relocations for temporary symbols into section relocations.
763 if (coff_symbol->MC->isTemporary() || CrossSection) {
764 Reloc.Symb = coff_symbol->Section->Symbol;
766 Layout.getFragmentOffset(coff_symbol->MC->getData().getFragment()) +
767 coff_symbol->MC->getOffset();
769 Reloc.Symb = coff_symbol;
771 ++Reloc.Symb->Relocations;
773 Reloc.Data.VirtualAddress += Fixup.getOffset();
774 Reloc.Data.Type = TargetObjectWriter->getRelocType(
775 Target, Fixup, CrossSection, Asm.getBackend());
777 // FIXME: Can anyone explain what this does other than adjust for the size
779 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
780 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
781 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
782 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
785 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
786 switch (Reloc.Data.Type) {
787 case COFF::IMAGE_REL_ARM_ABSOLUTE:
788 case COFF::IMAGE_REL_ARM_ADDR32:
789 case COFF::IMAGE_REL_ARM_ADDR32NB:
790 case COFF::IMAGE_REL_ARM_TOKEN:
791 case COFF::IMAGE_REL_ARM_SECTION:
792 case COFF::IMAGE_REL_ARM_SECREL:
794 case COFF::IMAGE_REL_ARM_BRANCH11:
795 case COFF::IMAGE_REL_ARM_BLX11:
796 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
797 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
799 case COFF::IMAGE_REL_ARM_BRANCH24:
800 case COFF::IMAGE_REL_ARM_BLX24:
801 case COFF::IMAGE_REL_ARM_MOV32A:
802 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
803 // only used for ARM mode code, which is documented as being unsupported
804 // by Windows on ARM. Empirical proof indicates that masm is able to
805 // generate the relocations however the rest of the MSVC toolchain is
806 // unable to handle it.
807 llvm_unreachable("unsupported relocation");
809 case COFF::IMAGE_REL_ARM_MOV32T:
811 case COFF::IMAGE_REL_ARM_BRANCH20T:
812 case COFF::IMAGE_REL_ARM_BRANCH24T:
813 case COFF::IMAGE_REL_ARM_BLX23T:
814 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
815 // perform a 4 byte adjustment to the relocation. Relative branches are
816 // offset by 4 on ARM, however, because there is no RELA relocations, all
817 // branches are offset by 4.
818 FixedValue = FixedValue + 4;
823 if (TargetObjectWriter->recordRelocation(Fixup))
824 coff_section->Relocations.push_back(Reloc);
827 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
828 const MCAsmLayout &Layout) {
829 size_t SectionsSize = Sections.size();
830 if (SectionsSize > static_cast<size_t>(INT32_MAX))
832 "PE COFF object files can't have more than 2147483647 sections");
834 // Assign symbol and section indexes and offsets.
835 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
837 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
839 DenseMap<COFFSection *, int32_t> SectionIndices(
840 NextPowerOf2(NumberOfSections));
842 // Assign section numbers.
844 for (const auto &Section : Sections) {
845 SectionIndices[Section.get()] = Number;
846 Section->Number = Number;
847 Section->Symbol->Data.SectionNumber = Number;
848 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
852 Header.NumberOfSections = NumberOfSections;
853 Header.NumberOfSymbols = 0;
855 for (const std::string &Name : Asm.getFileNames()) {
856 // round up to calculate the number of auxiliary symbols required
857 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
858 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
860 COFFSymbol *file = createSymbol(".file");
861 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
862 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
863 file->Aux.resize(Count);
866 unsigned Length = Name.size();
867 for (auto &Aux : file->Aux) {
868 Aux.AuxType = ATFile;
870 if (Length > SymbolSize) {
871 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
872 Length = Length - SymbolSize;
874 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
875 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
879 Offset += SymbolSize;
883 for (auto &Symbol : Symbols) {
884 // Update section number & offset for symbols that have them.
886 Symbol->Data.SectionNumber = Symbol->Section->Number;
887 if (Symbol->should_keep()) {
888 Symbol->Index = Header.NumberOfSymbols++;
889 // Update auxiliary symbol info.
890 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
891 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
896 // Build string table.
897 for (const auto &S : Sections)
898 if (S->Name.size() > COFF::NameSize)
899 Strings.add(S->Name);
900 for (const auto &S : Symbols)
901 if (S->should_keep() && S->Name.size() > COFF::NameSize)
902 Strings.add(S->Name);
903 Strings.finalize(StringTableBuilder::WinCOFF);
906 for (const auto &S : Sections)
908 for (auto &S : Symbols)
909 if (S->should_keep())
912 // Fixup weak external references.
913 for (auto &Symbol : Symbols) {
915 assert(Symbol->Index != -1);
916 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
917 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
918 "Symbol's aux symbol must be a Weak External!");
919 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
923 // Fixup associative COMDAT sections.
924 for (auto &Section : Sections) {
925 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
926 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
929 const MCSectionCOFF &MCSec = *Section->MCSection;
931 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
933 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
934 assert(COMDATSymbol);
935 COFFSection *Assoc = COMDATSymbol->Section;
938 Twine("Missing associated COMDAT section for section ") +
939 MCSec.getSectionName());
941 // Skip this section if the associated section is unused.
942 if (Assoc->Number == -1)
945 Section->Symbol->Aux[0].Aux.SectionDefinition.Number =
946 SectionIndices[Assoc];
949 // Assign file offsets to COFF object file structures.
954 offset += COFF::Header32Size;
956 offset += COFF::Header16Size;
957 offset += COFF::SectionSize * Header.NumberOfSections;
959 for (const auto &Section : Asm) {
960 COFFSection *Sec = SectionMap[&Section];
962 if (Sec->Number == -1)
965 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
967 if (IsPhysicalSection(Sec)) {
968 // Align the section data to a four byte boundary.
969 offset = RoundUpToAlignment(offset, 4);
970 Sec->Header.PointerToRawData = offset;
972 offset += Sec->Header.SizeOfRawData;
975 if (Sec->Relocations.size() > 0) {
976 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
978 if (RelocationsOverflow) {
979 // Signal overflow by setting NumberOfRelocations to max value. Actual
980 // size is found in reloc #0. Microsoft tools understand this.
981 Sec->Header.NumberOfRelocations = 0xffff;
983 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
985 Sec->Header.PointerToRelocations = offset;
987 if (RelocationsOverflow) {
988 // Reloc #0 will contain actual count, so make room for it.
989 offset += COFF::RelocationSize;
992 offset += COFF::RelocationSize * Sec->Relocations.size();
994 for (auto &Relocation : Sec->Relocations) {
995 assert(Relocation.Symb->Index != -1);
996 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
1000 assert(Sec->Symbol->Aux.size() == 1 &&
1001 "Section's symbol must have one aux!");
1002 AuxSymbol &Aux = Sec->Symbol->Aux[0];
1003 assert(Aux.AuxType == ATSectionDefinition &&
1004 "Section's symbol's aux symbol must be a Section Definition!");
1005 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1006 Aux.Aux.SectionDefinition.NumberOfRelocations =
1007 Sec->Header.NumberOfRelocations;
1008 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1009 Sec->Header.NumberOfLineNumbers;
1012 Header.PointerToSymbolTable = offset;
1014 // We want a deterministic output. It looks like GNU as also writes 0 in here.
1015 Header.TimeDateStamp = 0;
1017 // Write it all to disk...
1018 WriteFileHeader(Header);
1021 sections::iterator i, ie;
1022 MCAssembler::const_iterator j, je;
1024 for (auto &Section : Sections) {
1025 if (Section->Number != -1) {
1026 if (Section->Relocations.size() >= 0xffff)
1027 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
1028 WriteSectionHeader(Section->Header);
1032 for (i = Sections.begin(), ie = Sections.end(), j = Asm.begin(),
1034 (i != ie) && (j != je); ++i, ++j) {
1036 if ((*i)->Number == -1)
1039 if ((*i)->Header.PointerToRawData != 0) {
1040 assert(OS.tell() <= (*i)->Header.PointerToRawData &&
1041 "Section::PointerToRawData is insane!");
1043 unsigned SectionDataPadding = (*i)->Header.PointerToRawData - OS.tell();
1044 assert(SectionDataPadding < 4 &&
1045 "Should only need at most three bytes of padding!");
1047 WriteZeros(SectionDataPadding);
1049 Asm.writeSectionData(&*j, Layout);
1052 if ((*i)->Relocations.size() > 0) {
1053 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1054 "Section::PointerToRelocations is insane!");
1056 if ((*i)->Relocations.size() >= 0xffff) {
1057 // In case of overflow, write actual relocation count as first
1058 // relocation. Including the synthetic reloc itself (+ 1).
1060 r.VirtualAddress = (*i)->Relocations.size() + 1;
1061 r.SymbolTableIndex = 0;
1066 for (const auto &Relocation : (*i)->Relocations)
1067 WriteRelocation(Relocation.Data);
1069 assert((*i)->Header.PointerToRelocations == 0 &&
1070 "Section::PointerToRelocations is insane!");
1074 assert(OS.tell() == Header.PointerToSymbolTable &&
1075 "Header::PointerToSymbolTable is insane!");
1077 for (auto &Symbol : Symbols)
1078 if (Symbol->Index != -1)
1079 WriteSymbol(*Symbol);
1081 OS.write(Strings.data().data(), Strings.data().size());
1084 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1085 : Machine(Machine_) {}
1087 // Pin the vtable to this file.
1088 void MCWinCOFFObjectTargetWriter::anchor() {}
1090 //------------------------------------------------------------------------------
1091 // WinCOFFObjectWriter factory function
1094 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1095 raw_pwrite_stream &OS) {
1096 return new WinCOFFObjectWriter(MOTW, OS);