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 (Data.isCommon() && Data.isExternal())
369 return Data.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.getData().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 = Assembler.getSymbolData(Symbol);
418 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
419 coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
421 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
422 coff_symbol->Data.StorageClass = (ResSymData.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 = Assembler.getSymbolData(*Base);
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.getData().getFlags() & COFF::SF_TypeMask) >>
668 COFF::SF_TypeShift) >>
669 COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
671 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
675 bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
676 const MCSymbolData &SD = Sym.getData();
677 if (!SD.isExternal())
680 if (!Sym.isInSection())
683 const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
684 if (!Sec.getCOMDATSymbol())
687 // It looks like for COFF it is invalid to replace a reference to a global
688 // in a comdat with a reference to a local.
689 // FIXME: Add a specification reference if available.
693 void WinCOFFObjectWriter::RecordRelocation(
694 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
695 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
696 assert(Target.getSymA() && "Relocation must reference a symbol!");
698 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
699 const MCSymbol &A = Symbol;
700 if (!Asm.hasSymbolData(A))
701 Asm.getContext().reportFatalError(Fixup.getLoc(),
702 Twine("symbol '") + A.getName() +
703 "' can not be undefined");
705 const MCSymbolData &A_SD = Asm.getSymbolData(A);
707 MCSection *Section = Fragment->getParent();
709 // Mark this symbol as requiring an entry in the symbol table.
710 assert(SectionMap.find(Section) != SectionMap.end() &&
711 "Section must already have been defined in ExecutePostLayoutBinding!");
712 assert(SymbolMap.find(&A) != SymbolMap.end() &&
713 "Symbol must already have been defined in ExecutePostLayoutBinding!");
715 COFFSection *coff_section = SectionMap[Section];
716 COFFSymbol *coff_symbol = SymbolMap[&A];
717 const MCSymbolRefExpr *SymB = Target.getSymB();
718 bool CrossSection = false;
721 const MCSymbol *B = &SymB->getSymbol();
722 const MCSymbolData &B_SD = Asm.getSymbolData(*B);
723 if (!B_SD.getFragment())
724 Asm.getContext().reportFatalError(
726 Twine("symbol '") + B->getName() +
727 "' can not be undefined in a subtraction expression");
729 if (!A_SD.getFragment())
730 Asm.getContext().reportFatalError(
732 Twine("symbol '") + Symbol.getName() +
733 "' can not be undefined in a subtraction expression");
735 CrossSection = &Symbol.getSection() != &B->getSection();
737 // Offset of the symbol in the section
738 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
740 // In the case where we have SymbA and SymB, we just need to store the delta
741 // between the two symbols. Update FixedValue to account for the delta, and
742 // skip recording the relocation.
744 int64_t OffsetOfA = Layout.getSymbolOffset(A);
745 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
749 // Offset of the relocation in the section
750 int64_t OffsetOfRelocation =
751 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
753 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
755 FixedValue = Target.getConstant();
758 COFFRelocation Reloc;
760 Reloc.Data.SymbolTableIndex = 0;
761 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
763 // Turn relocations for temporary symbols into section relocations.
764 if (coff_symbol->MC->isTemporary() || CrossSection) {
765 Reloc.Symb = coff_symbol->Section->Symbol;
767 Layout.getFragmentOffset(coff_symbol->MC->getData().getFragment()) +
768 coff_symbol->MC->getData().getOffset();
770 Reloc.Symb = coff_symbol;
772 ++Reloc.Symb->Relocations;
774 Reloc.Data.VirtualAddress += Fixup.getOffset();
775 Reloc.Data.Type = TargetObjectWriter->getRelocType(
776 Target, Fixup, CrossSection, Asm.getBackend());
778 // FIXME: Can anyone explain what this does other than adjust for the size
780 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
781 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
782 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
783 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
786 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
787 switch (Reloc.Data.Type) {
788 case COFF::IMAGE_REL_ARM_ABSOLUTE:
789 case COFF::IMAGE_REL_ARM_ADDR32:
790 case COFF::IMAGE_REL_ARM_ADDR32NB:
791 case COFF::IMAGE_REL_ARM_TOKEN:
792 case COFF::IMAGE_REL_ARM_SECTION:
793 case COFF::IMAGE_REL_ARM_SECREL:
795 case COFF::IMAGE_REL_ARM_BRANCH11:
796 case COFF::IMAGE_REL_ARM_BLX11:
797 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
798 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
800 case COFF::IMAGE_REL_ARM_BRANCH24:
801 case COFF::IMAGE_REL_ARM_BLX24:
802 case COFF::IMAGE_REL_ARM_MOV32A:
803 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
804 // only used for ARM mode code, which is documented as being unsupported
805 // by Windows on ARM. Empirical proof indicates that masm is able to
806 // generate the relocations however the rest of the MSVC toolchain is
807 // unable to handle it.
808 llvm_unreachable("unsupported relocation");
810 case COFF::IMAGE_REL_ARM_MOV32T:
812 case COFF::IMAGE_REL_ARM_BRANCH20T:
813 case COFF::IMAGE_REL_ARM_BRANCH24T:
814 case COFF::IMAGE_REL_ARM_BLX23T:
815 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
816 // perform a 4 byte adjustment to the relocation. Relative branches are
817 // offset by 4 on ARM, however, because there is no RELA relocations, all
818 // branches are offset by 4.
819 FixedValue = FixedValue + 4;
824 if (TargetObjectWriter->recordRelocation(Fixup))
825 coff_section->Relocations.push_back(Reloc);
828 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
829 const MCAsmLayout &Layout) {
830 size_t SectionsSize = Sections.size();
831 if (SectionsSize > static_cast<size_t>(INT32_MAX))
833 "PE COFF object files can't have more than 2147483647 sections");
835 // Assign symbol and section indexes and offsets.
836 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
838 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
840 DenseMap<COFFSection *, int32_t> SectionIndices(
841 NextPowerOf2(NumberOfSections));
843 // Assign section numbers.
845 for (const auto &Section : Sections) {
846 SectionIndices[Section.get()] = Number;
847 Section->Number = Number;
848 Section->Symbol->Data.SectionNumber = Number;
849 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
853 Header.NumberOfSections = NumberOfSections;
854 Header.NumberOfSymbols = 0;
856 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end(); FI != FE;
858 // round up to calculate the number of auxiliary symbols required
859 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
860 unsigned Count = (FI->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 = FI->size();
869 for (auto &Aux : file->Aux) {
870 Aux.AuxType = ATFile;
872 if (Length > SymbolSize) {
873 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
874 Length = Length - SymbolSize;
876 memcpy(&Aux.Aux, FI->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->Index = Header.NumberOfSymbols++;
891 // Update auxiliary symbol info.
892 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
893 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
898 // Build string table.
899 for (const auto &S : Sections)
900 if (S->Name.size() > COFF::NameSize)
901 Strings.add(S->Name);
902 for (const auto &S : Symbols)
903 if (S->should_keep() && S->Name.size() > COFF::NameSize)
904 Strings.add(S->Name);
905 Strings.finalize(StringTableBuilder::WinCOFF);
908 for (const auto &S : Sections)
910 for (auto &S : Symbols)
911 if (S->should_keep())
914 // Fixup weak external references.
915 for (auto &Symbol : Symbols) {
917 assert(Symbol->Index != -1);
918 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
919 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
920 "Symbol's aux symbol must be a Weak External!");
921 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
925 // Fixup associative COMDAT sections.
926 for (auto &Section : Sections) {
927 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
928 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
931 const MCSectionCOFF &MCSec = *Section->MCSection;
933 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
935 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
936 assert(COMDATSymbol);
937 COFFSection *Assoc = COMDATSymbol->Section;
940 Twine("Missing associated COMDAT section for section ") +
941 MCSec.getSectionName());
943 // Skip this section if the associated section is unused.
944 if (Assoc->Number == -1)
947 Section->Symbol->Aux[0].Aux.SectionDefinition.Number =
948 SectionIndices[Assoc];
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->Index != -1);
998 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
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::const_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->Index != -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);