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/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCSectionCOFF.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/MC/StringTableBuilder.h"
31 #include "llvm/Support/COFF.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/TimeValue.h"
40 #define DEBUG_TYPE "WinCOFFObjectWriter"
43 typedef SmallString<COFF::NameSize> name;
54 AuxiliaryType AuxType;
65 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
76 COFFSymbol(StringRef name);
77 void set_name_offset(uint32_t Offset);
79 bool should_keep() const;
81 int64_t getIndex() const { return Index; }
82 void setIndex(int Value) {
85 MC->setIndex(static_cast<uint32_t>(Value));
89 // This class contains staging data for a COFF relocation entry.
90 struct COFFRelocation {
91 COFF::relocation Data;
94 COFFRelocation() : Symb(nullptr) {}
95 static size_t size() { return COFF::RelocationSize; }
98 typedef std::vector<COFFRelocation> relocations;
102 COFF::section Header;
106 MCSectionCOFF const *MCSection;
108 relocations Relocations;
110 COFFSection(StringRef name);
111 static size_t size();
114 class WinCOFFObjectWriter : public MCObjectWriter {
116 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
117 typedef std::vector<std::unique_ptr<COFFSection>> sections;
119 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
120 typedef DenseMap<MCSection const *, COFFSection *> section_map;
122 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
124 // Root level file contents.
128 StringTableBuilder Strings;
130 // Maps used during object file creation.
131 section_map SectionMap;
132 symbol_map SymbolMap;
136 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
138 void reset() override {
139 memset(&Header, 0, sizeof(Header));
140 Header.Machine = TargetObjectWriter->getMachine();
146 MCObjectWriter::reset();
149 COFFSymbol *createSymbol(StringRef Name);
150 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
151 COFFSection *createSection(StringRef Name);
153 template <typename object_t, typename list_t>
154 object_t *createCOFFEntity(StringRef Name, list_t &List);
156 void defineSection(MCSectionCOFF const &Sec);
157 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
158 const MCAsmLayout &Layout);
160 void SetSymbolName(COFFSymbol &S);
161 void SetSectionName(COFFSection &S);
163 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
165 bool IsPhysicalSection(COFFSection *S);
167 // Entity writing methods.
169 void WriteFileHeader(const COFF::header &Header);
170 void WriteSymbol(const COFFSymbol &S);
171 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
172 void WriteSectionHeader(const COFF::section &S);
173 void WriteRelocation(const COFF::relocation &R);
175 // MCObjectWriter interface implementation.
177 void ExecutePostLayoutBinding(MCAssembler &Asm,
178 const MCAsmLayout &Layout) override;
180 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
181 const MCSymbol &SymA,
182 const MCFragment &FB, bool InSet,
183 bool IsPCRel) const override;
185 bool isWeak(const MCSymbol &Sym) const override;
187 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
188 const MCFragment *Fragment, const MCFixup &Fixup,
189 MCValue Target, bool &IsPCRel,
190 uint64_t &FixedValue) override;
192 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
196 static inline void write_uint32_le(void *Data, uint32_t Value) {
197 support::endian::write<uint32_t, support::little, support::unaligned>(Data,
201 //------------------------------------------------------------------------------
202 // Symbol class implementation
204 COFFSymbol::COFFSymbol(StringRef name)
205 : Name(name.begin(), name.end()), Other(nullptr), Section(nullptr),
206 Relocations(0), MC(nullptr) {
207 memset(&Data, 0, sizeof(Data));
210 // In the case that the name does not fit within 8 bytes, the offset
211 // into the string table is stored in the last 4 bytes instead, leaving
212 // the first 4 bytes as 0.
213 void COFFSymbol::set_name_offset(uint32_t Offset) {
214 write_uint32_le(Data.Name + 0, 0);
215 write_uint32_le(Data.Name + 4, Offset);
218 /// logic to decide if the symbol should be reported in the symbol table
219 bool COFFSymbol::should_keep() const {
220 // no section means its external, keep it
224 // if it has relocations pointing at it, keep it
225 if (Relocations > 0) {
226 assert(Section->Number != -1 && "Sections with relocations must be real!");
230 // if this is a safeseh handler, keep it
231 if (MC && (MC->getFlags() & COFF::SF_SafeSEH))
234 // if the section its in is being droped, drop it
235 if (Section->Number == -1)
238 // if it is the section symbol, keep it
239 if (Section->Symbol == this)
242 // if its temporary, drop it
243 if (MC && MC->isTemporary())
246 // otherwise, keep it
250 //------------------------------------------------------------------------------
251 // Section class implementation
253 COFFSection::COFFSection(StringRef name)
254 : Name(name), MCSection(nullptr), Symbol(nullptr) {
255 memset(&Header, 0, sizeof(Header));
258 size_t COFFSection::size() { return COFF::SectionSize; }
260 //------------------------------------------------------------------------------
261 // WinCOFFObjectWriter class implementation
263 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
264 raw_pwrite_stream &OS)
265 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
266 memset(&Header, 0, sizeof(Header));
268 Header.Machine = TargetObjectWriter->getMachine();
271 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
272 return createCOFFEntity<COFFSymbol>(Name, Symbols);
275 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
276 symbol_map::iterator i = SymbolMap.find(Symbol);
277 if (i != SymbolMap.end())
279 COFFSymbol *RetSymbol =
280 createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
281 SymbolMap[Symbol] = RetSymbol;
285 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
286 return createCOFFEntity<COFFSection>(Name, Sections);
289 /// A template used to lookup or create a symbol/section, and initialize it if
291 template <typename object_t, typename list_t>
292 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, list_t &List) {
293 List.push_back(make_unique<object_t>(Name));
295 return List.back().get();
298 /// This function takes a section data object from the assembler
299 /// and creates the associated COFF section staging object.
300 void WinCOFFObjectWriter::defineSection(MCSectionCOFF const &Sec) {
301 COFFSection *coff_section = createSection(Sec.getSectionName());
302 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
303 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
304 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
305 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
306 if (COMDATSymbol->Section)
307 report_fatal_error("two sections have the same comdat");
308 COMDATSymbol->Section = coff_section;
312 coff_section->Symbol = coff_symbol;
313 coff_symbol->Section = coff_section;
314 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
316 // In this case the auxiliary symbol is a Section Definition.
317 coff_symbol->Aux.resize(1);
318 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
319 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
320 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
322 coff_section->Header.Characteristics = Sec.getCharacteristics();
324 uint32_t &Characteristics = coff_section->Header.Characteristics;
325 switch (Sec.getAlignment()) {
327 Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
330 Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
333 Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
336 Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
339 Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
342 Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
345 Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
348 Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
351 Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
354 Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
357 Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
360 Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
363 Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
366 Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
369 llvm_unreachable("unsupported section alignment");
372 // Bind internal COFF section to MC section.
373 coff_section->MCSection = &Sec;
374 SectionMap[&Sec] = coff_section;
377 static uint64_t getSymbolValue(const MCSymbol &Symbol,
378 const MCAsmLayout &Layout) {
379 if (Symbol.isCommon() && Symbol.isExternal())
380 return Symbol.getCommonSize();
383 if (!Layout.getSymbolOffset(Symbol, Res))
389 /// This function takes a symbol data object from the assembler
390 /// and creates the associated COFF symbol staging object.
391 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
392 MCAssembler &Assembler,
393 const MCAsmLayout &Layout) {
394 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
395 SymbolMap[&Symbol] = coff_symbol;
397 if (Symbol.getFlags() & COFF::SF_WeakExternal) {
398 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
400 if (Symbol.isVariable()) {
401 const MCSymbolRefExpr *SymRef =
402 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
405 report_fatal_error("Weak externals may only alias symbols");
407 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
409 std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
410 COFFSymbol *WeakDefault = createSymbol(WeakName);
411 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
412 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
413 WeakDefault->Data.Type = 0;
414 WeakDefault->Data.Value = 0;
415 coff_symbol->Other = WeakDefault;
418 // Setup the Weak External auxiliary symbol.
419 coff_symbol->Aux.resize(1);
420 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
421 coff_symbol->Aux[0].AuxType = ATWeakExternal;
422 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
423 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
424 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
426 coff_symbol->MC = &Symbol;
428 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
429 coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
431 coff_symbol->Data.Type =
432 (Symbol.getFlags() & COFF::SF_TypeMask) >> COFF::SF_TypeShift;
433 coff_symbol->Data.StorageClass =
434 (Symbol.getFlags() & COFF::SF_ClassMask) >> COFF::SF_ClassShift;
436 // If no storage class was specified in the streamer, define it here.
437 if (coff_symbol->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
438 bool IsExternal = Symbol.isExternal() ||
439 (!Symbol.getFragment() && !Symbol.isVariable());
441 coff_symbol->Data.StorageClass = IsExternal
442 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
443 : COFF::IMAGE_SYM_CLASS_STATIC;
447 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
449 if (Base->getFragment()) {
450 COFFSection *Sec = SectionMap[Base->getFragment()->getParent()];
452 if (coff_symbol->Section && coff_symbol->Section != Sec)
453 report_fatal_error("conflicting sections for symbol");
455 coff_symbol->Section = Sec;
459 coff_symbol->MC = &Symbol;
463 // Maximum offsets for different string table entry encodings.
464 static const unsigned Max6DecimalOffset = 999999;
465 static const unsigned Max7DecimalOffset = 9999999;
466 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
468 // Encode a string table entry offset in base 64, padded to 6 chars, and
469 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
470 // Buffer must be at least 8 bytes large. No terminating null appended.
471 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
472 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
473 "Illegal section name encoding for value");
475 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
476 "abcdefghijklmnopqrstuvwxyz"
482 char *Ptr = Buffer + 7;
483 for (unsigned i = 0; i < 6; ++i) {
484 unsigned Rem = Value % 64;
486 *(Ptr--) = Alphabet[Rem];
490 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
491 if (S.Name.size() > COFF::NameSize) {
492 uint64_t StringTableEntry = Strings.getOffset(S.Name);
494 if (StringTableEntry <= Max6DecimalOffset) {
495 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
496 } else if (StringTableEntry <= Max7DecimalOffset) {
497 // With seven digits, we have to skip the terminating null. Because
498 // sprintf always appends it, we use a larger temporary buffer.
500 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
501 std::memcpy(S.Header.Name, buffer, 8);
502 } else if (StringTableEntry <= MaxBase64Offset) {
503 // Starting with 10,000,000, offsets are encoded as base64.
504 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
506 report_fatal_error("COFF string table is greater than 64 GB.");
509 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
512 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
513 if (S.Name.size() > COFF::NameSize)
514 S.set_name_offset(Strings.getOffset(S.Name));
516 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
519 bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
521 // This doesn't seem to be right. Strings referred to from the .data section
522 // need symbols so they can be linked to code in the .text section right?
524 // return Asm.isSymbolLinkerVisible(Symbol);
526 // Non-temporary labels should always be visible to the linker.
527 if (!Symbol.isTemporary())
530 // Absolute temporary labels are never visible.
531 if (!Symbol.isInSection())
534 // For now, all non-variable symbols are exported,
535 // the linker will sort the rest out for us.
536 return !Symbol.isVariable();
539 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
540 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
544 //------------------------------------------------------------------------------
545 // entity writing methods
547 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
549 writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
551 writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
552 writeLE16(Header.Machine);
553 writeLE32(Header.TimeDateStamp);
554 writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
559 writeLE32(Header.NumberOfSections);
560 writeLE32(Header.PointerToSymbolTable);
561 writeLE32(Header.NumberOfSymbols);
563 writeLE16(Header.Machine);
564 writeLE16(static_cast<int16_t>(Header.NumberOfSections));
565 writeLE32(Header.TimeDateStamp);
566 writeLE32(Header.PointerToSymbolTable);
567 writeLE32(Header.NumberOfSymbols);
568 writeLE16(Header.SizeOfOptionalHeader);
569 writeLE16(Header.Characteristics);
573 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
574 writeBytes(StringRef(S.Data.Name, COFF::NameSize));
575 writeLE32(S.Data.Value);
577 writeLE32(S.Data.SectionNumber);
579 writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
580 writeLE16(S.Data.Type);
581 write8(S.Data.StorageClass);
582 write8(S.Data.NumberOfAuxSymbols);
583 WriteAuxiliarySymbols(S.Aux);
586 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
587 const COFFSymbol::AuxiliarySymbols &S) {
588 for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
590 switch (i->AuxType) {
591 case ATFunctionDefinition:
592 writeLE32(i->Aux.FunctionDefinition.TagIndex);
593 writeLE32(i->Aux.FunctionDefinition.TotalSize);
594 writeLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
595 writeLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
596 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
598 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
600 case ATbfAndefSymbol:
601 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
602 writeLE16(i->Aux.bfAndefSymbol.Linenumber);
603 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
604 writeLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
605 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
607 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
610 writeLE32(i->Aux.WeakExternal.TagIndex);
611 writeLE32(i->Aux.WeakExternal.Characteristics);
612 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
614 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
618 StringRef(reinterpret_cast<const char *>(&i->Aux),
619 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
621 case ATSectionDefinition:
622 writeLE32(i->Aux.SectionDefinition.Length);
623 writeLE16(i->Aux.SectionDefinition.NumberOfRelocations);
624 writeLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
625 writeLE32(i->Aux.SectionDefinition.CheckSum);
626 writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
627 write8(i->Aux.SectionDefinition.Selection);
628 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
629 writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
631 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
637 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
638 writeBytes(StringRef(S.Name, COFF::NameSize));
640 writeLE32(S.VirtualSize);
641 writeLE32(S.VirtualAddress);
642 writeLE32(S.SizeOfRawData);
643 writeLE32(S.PointerToRawData);
644 writeLE32(S.PointerToRelocations);
645 writeLE32(S.PointerToLineNumbers);
646 writeLE16(S.NumberOfRelocations);
647 writeLE16(S.NumberOfLineNumbers);
648 writeLE32(S.Characteristics);
651 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
652 writeLE32(R.VirtualAddress);
653 writeLE32(R.SymbolTableIndex);
657 ////////////////////////////////////////////////////////////////////////////////
658 // MCObjectWriter interface implementations
660 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
661 const MCAsmLayout &Layout) {
662 // "Define" each section & symbol. This creates section & symbol
663 // entries in the staging area.
664 for (const auto &Section : Asm)
665 defineSection(static_cast<const MCSectionCOFF &>(Section));
667 for (const MCSymbol &Symbol : Asm.symbols())
668 if (ExportSymbol(Symbol, Asm))
669 DefineSymbol(Symbol, Asm, Layout);
672 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
673 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
674 bool InSet, bool IsPCRel) const {
675 // MS LINK expects to be able to replace all references to a function with a
676 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
677 // away any relocations to functions.
678 if ((((SymA.getFlags() & COFF::SF_TypeMask) >> COFF::SF_TypeShift) >>
679 COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
681 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
685 bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
686 if (!Sym.isExternal())
689 if (!Sym.isInSection())
692 const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
693 if (!Sec.getCOMDATSymbol())
696 // It looks like for COFF it is invalid to replace a reference to a global
697 // in a comdat with a reference to a local.
698 // FIXME: Add a specification reference if available.
702 void WinCOFFObjectWriter::recordRelocation(
703 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
704 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
705 assert(Target.getSymA() && "Relocation must reference a symbol!");
707 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
708 const MCSymbol &A = Symbol;
709 if (!A.isRegistered())
710 Asm.getContext().reportFatalError(Fixup.getLoc(),
711 Twine("symbol '") + A.getName() +
712 "' can not be undefined");
714 MCSection *Section = Fragment->getParent();
716 // Mark this symbol as requiring an entry in the symbol table.
717 assert(SectionMap.find(Section) != SectionMap.end() &&
718 "Section must already have been defined in ExecutePostLayoutBinding!");
719 assert(SymbolMap.find(&A) != SymbolMap.end() &&
720 "Symbol must already have been defined in ExecutePostLayoutBinding!");
722 COFFSection *coff_section = SectionMap[Section];
723 COFFSymbol *coff_symbol = SymbolMap[&A];
724 const MCSymbolRefExpr *SymB = Target.getSymB();
725 bool CrossSection = false;
728 const MCSymbol *B = &SymB->getSymbol();
729 if (!B->getFragment())
730 Asm.getContext().reportFatalError(
732 Twine("symbol '") + B->getName() +
733 "' can not be undefined in a subtraction expression");
735 if (!A.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;
772 FixedValue += Layout.getFragmentOffset(coff_symbol->MC->getFragment()) +
773 coff_symbol->MC->getOffset();
775 Reloc.Symb = coff_symbol;
777 ++Reloc.Symb->Relocations;
779 Reloc.Data.VirtualAddress += Fixup.getOffset();
780 Reloc.Data.Type = TargetObjectWriter->getRelocType(
781 Target, Fixup, CrossSection, Asm.getBackend());
783 // FIXME: Can anyone explain what this does other than adjust for the size
785 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
786 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
787 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
788 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
791 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
792 switch (Reloc.Data.Type) {
793 case COFF::IMAGE_REL_ARM_ABSOLUTE:
794 case COFF::IMAGE_REL_ARM_ADDR32:
795 case COFF::IMAGE_REL_ARM_ADDR32NB:
796 case COFF::IMAGE_REL_ARM_TOKEN:
797 case COFF::IMAGE_REL_ARM_SECTION:
798 case COFF::IMAGE_REL_ARM_SECREL:
800 case COFF::IMAGE_REL_ARM_BRANCH11:
801 case COFF::IMAGE_REL_ARM_BLX11:
802 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
803 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
805 case COFF::IMAGE_REL_ARM_BRANCH24:
806 case COFF::IMAGE_REL_ARM_BLX24:
807 case COFF::IMAGE_REL_ARM_MOV32A:
808 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
809 // only used for ARM mode code, which is documented as being unsupported
810 // by Windows on ARM. Empirical proof indicates that masm is able to
811 // generate the relocations however the rest of the MSVC toolchain is
812 // unable to handle it.
813 llvm_unreachable("unsupported relocation");
815 case COFF::IMAGE_REL_ARM_MOV32T:
817 case COFF::IMAGE_REL_ARM_BRANCH20T:
818 case COFF::IMAGE_REL_ARM_BRANCH24T:
819 case COFF::IMAGE_REL_ARM_BLX23T:
820 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
821 // perform a 4 byte adjustment to the relocation. Relative branches are
822 // offset by 4 on ARM, however, because there is no RELA relocations, all
823 // branches are offset by 4.
824 FixedValue = FixedValue + 4;
829 if (TargetObjectWriter->recordRelocation(Fixup))
830 coff_section->Relocations.push_back(Reloc);
833 void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
834 const MCAsmLayout &Layout) {
835 size_t SectionsSize = Sections.size();
836 if (SectionsSize > static_cast<size_t>(INT32_MAX))
838 "PE COFF object files can't have more than 2147483647 sections");
840 // Assign symbol and section indexes and offsets.
841 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
843 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
845 // Assign section numbers.
847 for (const auto &Section : Sections) {
848 Section->Number = Number;
849 Section->Symbol->Data.SectionNumber = Number;
850 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
854 Header.NumberOfSections = NumberOfSections;
855 Header.NumberOfSymbols = 0;
857 for (const std::string &Name : Asm.getFileNames()) {
858 // round up to calculate the number of auxiliary symbols required
859 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
860 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
862 COFFSymbol *file = createSymbol(".file");
863 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
864 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
865 file->Aux.resize(Count);
868 unsigned Length = Name.size();
869 for (auto &Aux : file->Aux) {
870 Aux.AuxType = ATFile;
872 if (Length > SymbolSize) {
873 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
874 Length = Length - SymbolSize;
876 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
877 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
881 Offset += SymbolSize;
885 for (auto &Symbol : Symbols) {
886 // Update section number & offset for symbols that have them.
888 Symbol->Data.SectionNumber = Symbol->Section->Number;
889 if (Symbol->should_keep()) {
890 Symbol->setIndex(Header.NumberOfSymbols++);
891 // Update auxiliary symbol info.
892 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
893 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
895 Symbol->setIndex(-1);
899 // Build string table.
900 for (const auto &S : Sections)
901 if (S->Name.size() > COFF::NameSize)
902 Strings.add(S->Name);
903 for (const auto &S : Symbols)
904 if (S->should_keep() && S->Name.size() > COFF::NameSize)
905 Strings.add(S->Name);
906 Strings.finalize(StringTableBuilder::WinCOFF);
909 for (const auto &S : Sections)
911 for (auto &S : Symbols)
912 if (S->should_keep())
915 // Fixup weak external references.
916 for (auto &Symbol : Symbols) {
918 assert(Symbol->getIndex() != -1);
919 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
920 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
921 "Symbol's aux symbol must be a Weak External!");
922 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
926 // Fixup associative COMDAT sections.
927 for (auto &Section : Sections) {
928 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
929 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
932 const MCSectionCOFF &MCSec = *Section->MCSection;
934 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
936 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
937 assert(COMDATSymbol);
938 COFFSection *Assoc = COMDATSymbol->Section;
941 Twine("Missing associated COMDAT section for section ") +
942 MCSec.getSectionName());
944 // Skip this section if the associated section is unused.
945 if (Assoc->Number == -1)
948 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
951 // Assign file offsets to COFF object file structures.
956 offset += COFF::Header32Size;
958 offset += COFF::Header16Size;
959 offset += COFF::SectionSize * Header.NumberOfSections;
961 for (const auto &Section : Asm) {
962 COFFSection *Sec = SectionMap[&Section];
964 if (Sec->Number == -1)
967 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
969 if (IsPhysicalSection(Sec)) {
970 // Align the section data to a four byte boundary.
971 offset = RoundUpToAlignment(offset, 4);
972 Sec->Header.PointerToRawData = offset;
974 offset += Sec->Header.SizeOfRawData;
977 if (Sec->Relocations.size() > 0) {
978 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
980 if (RelocationsOverflow) {
981 // Signal overflow by setting NumberOfRelocations to max value. Actual
982 // size is found in reloc #0. Microsoft tools understand this.
983 Sec->Header.NumberOfRelocations = 0xffff;
985 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
987 Sec->Header.PointerToRelocations = offset;
989 if (RelocationsOverflow) {
990 // Reloc #0 will contain actual count, so make room for it.
991 offset += COFF::RelocationSize;
994 offset += COFF::RelocationSize * Sec->Relocations.size();
996 for (auto &Relocation : Sec->Relocations) {
997 assert(Relocation.Symb->getIndex() != -1);
998 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
1002 assert(Sec->Symbol->Aux.size() == 1 &&
1003 "Section's symbol must have one aux!");
1004 AuxSymbol &Aux = Sec->Symbol->Aux[0];
1005 assert(Aux.AuxType == ATSectionDefinition &&
1006 "Section's symbol's aux symbol must be a Section Definition!");
1007 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
1008 Aux.Aux.SectionDefinition.NumberOfRelocations =
1009 Sec->Header.NumberOfRelocations;
1010 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
1011 Sec->Header.NumberOfLineNumbers;
1014 Header.PointerToSymbolTable = offset;
1016 // We want a deterministic output. It looks like GNU as also writes 0 in here.
1017 Header.TimeDateStamp = 0;
1019 // Write it all to disk...
1020 WriteFileHeader(Header);
1023 sections::iterator i, ie;
1024 MCAssembler::iterator j, je;
1026 for (auto &Section : Sections) {
1027 if (Section->Number != -1) {
1028 if (Section->Relocations.size() >= 0xffff)
1029 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
1030 WriteSectionHeader(Section->Header);
1034 for (i = Sections.begin(), ie = Sections.end(), j = Asm.begin(),
1036 (i != ie) && (j != je); ++i, ++j) {
1038 if ((*i)->Number == -1)
1041 if ((*i)->Header.PointerToRawData != 0) {
1042 assert(OS.tell() <= (*i)->Header.PointerToRawData &&
1043 "Section::PointerToRawData is insane!");
1045 unsigned SectionDataPadding = (*i)->Header.PointerToRawData - OS.tell();
1046 assert(SectionDataPadding < 4 &&
1047 "Should only need at most three bytes of padding!");
1049 WriteZeros(SectionDataPadding);
1051 Asm.writeSectionData(&*j, Layout);
1054 if ((*i)->Relocations.size() > 0) {
1055 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1056 "Section::PointerToRelocations is insane!");
1058 if ((*i)->Relocations.size() >= 0xffff) {
1059 // In case of overflow, write actual relocation count as first
1060 // relocation. Including the synthetic reloc itself (+ 1).
1062 r.VirtualAddress = (*i)->Relocations.size() + 1;
1063 r.SymbolTableIndex = 0;
1068 for (const auto &Relocation : (*i)->Relocations)
1069 WriteRelocation(Relocation.Data);
1071 assert((*i)->Header.PointerToRelocations == 0 &&
1072 "Section::PointerToRelocations is insane!");
1076 assert(OS.tell() == Header.PointerToSymbolTable &&
1077 "Header::PointerToSymbolTable is insane!");
1079 for (auto &Symbol : Symbols)
1080 if (Symbol->getIndex() != -1)
1081 WriteSymbol(*Symbol);
1083 OS.write(Strings.data().data(), Strings.data().size());
1086 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1087 : Machine(Machine_) {}
1089 // Pin the vtable to this file.
1090 void MCWinCOFFObjectTargetWriter::anchor() {}
1092 //------------------------------------------------------------------------------
1093 // WinCOFFObjectWriter factory function
1096 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1097 raw_pwrite_stream &OS) {
1098 return new WinCOFFObjectWriter(MOTW, OS);