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/MCSymbolCOFF.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/JamCRC.h"
36 #include "llvm/Support/TimeValue.h"
42 #define DEBUG_TYPE "WinCOFFObjectWriter"
45 typedef SmallString<COFF::NameSize> name;
56 AuxiliaryType AuxType;
67 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
78 COFFSymbol(StringRef name);
79 void set_name_offset(uint32_t Offset);
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{StringTableBuilder::WinCOFF};
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 IsPhysicalSection(COFFSection *S);
165 // Entity writing methods.
167 void WriteFileHeader(const COFF::header &Header);
168 void WriteSymbol(const COFFSymbol &S);
169 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
170 void writeSectionHeader(const COFF::section &S);
171 void WriteRelocation(const COFF::relocation &R);
173 // MCObjectWriter interface implementation.
175 void executePostLayoutBinding(MCAssembler &Asm,
176 const MCAsmLayout &Layout) override;
178 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
179 const MCSymbol &SymA,
180 const MCFragment &FB, bool InSet,
181 bool IsPCRel) const override;
183 bool isWeak(const MCSymbol &Sym) const override;
185 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
186 const MCFragment *Fragment, const MCFixup &Fixup,
187 MCValue Target, bool &IsPCRel,
188 uint64_t &FixedValue) override;
190 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
194 static inline void write_uint32_le(void *Data, uint32_t Value) {
195 support::endian::write<uint32_t, support::little, support::unaligned>(Data,
199 //------------------------------------------------------------------------------
200 // Symbol class implementation
202 COFFSymbol::COFFSymbol(StringRef name)
203 : Name(name.begin(), name.end()), Other(nullptr), Section(nullptr),
204 Relocations(0), MC(nullptr) {
205 memset(&Data, 0, sizeof(Data));
208 // In the case that the name does not fit within 8 bytes, the offset
209 // into the string table is stored in the last 4 bytes instead, leaving
210 // the first 4 bytes as 0.
211 void COFFSymbol::set_name_offset(uint32_t Offset) {
212 write_uint32_le(Data.Name + 0, 0);
213 write_uint32_le(Data.Name + 4, Offset);
216 //------------------------------------------------------------------------------
217 // Section class implementation
219 COFFSection::COFFSection(StringRef name)
220 : Name(name), MCSection(nullptr), Symbol(nullptr) {
221 memset(&Header, 0, sizeof(Header));
224 size_t COFFSection::size() { return COFF::SectionSize; }
226 //------------------------------------------------------------------------------
227 // WinCOFFObjectWriter class implementation
229 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
230 raw_pwrite_stream &OS)
231 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
232 memset(&Header, 0, sizeof(Header));
234 Header.Machine = TargetObjectWriter->getMachine();
237 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
238 return createCOFFEntity<COFFSymbol>(Name, Symbols);
241 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
242 symbol_map::iterator i = SymbolMap.find(Symbol);
243 if (i != SymbolMap.end())
245 COFFSymbol *RetSymbol =
246 createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
247 SymbolMap[Symbol] = RetSymbol;
251 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
252 return createCOFFEntity<COFFSection>(Name, Sections);
255 /// A template used to lookup or create a symbol/section, and initialize it if
257 template <typename object_t, typename list_t>
258 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, list_t &List) {
259 List.push_back(make_unique<object_t>(Name));
261 return List.back().get();
264 /// This function takes a section data object from the assembler
265 /// and creates the associated COFF section staging object.
266 void WinCOFFObjectWriter::defineSection(MCSectionCOFF const &Sec) {
267 COFFSection *coff_section = createSection(Sec.getSectionName());
268 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
269 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
270 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
271 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
272 if (COMDATSymbol->Section)
273 report_fatal_error("two sections have the same comdat");
274 COMDATSymbol->Section = coff_section;
278 coff_section->Symbol = coff_symbol;
279 coff_symbol->Section = coff_section;
280 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
282 // In this case the auxiliary symbol is a Section Definition.
283 coff_symbol->Aux.resize(1);
284 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
285 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
286 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
288 coff_section->Header.Characteristics = Sec.getCharacteristics();
290 uint32_t &Characteristics = coff_section->Header.Characteristics;
291 switch (Sec.getAlignment()) {
293 Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
296 Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
299 Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
302 Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
305 Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
308 Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
311 Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
314 Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
317 Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
320 Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
323 Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
326 Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
329 Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
332 Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
335 llvm_unreachable("unsupported section alignment");
338 // Bind internal COFF section to MC section.
339 coff_section->MCSection = &Sec;
340 SectionMap[&Sec] = coff_section;
343 static uint64_t getSymbolValue(const MCSymbol &Symbol,
344 const MCAsmLayout &Layout) {
345 if (Symbol.isCommon() && Symbol.isExternal())
346 return Symbol.getCommonSize();
349 if (!Layout.getSymbolOffset(Symbol, Res))
355 /// This function takes a symbol data object from the assembler
356 /// and creates the associated COFF symbol staging object.
357 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
358 MCAssembler &Assembler,
359 const MCAsmLayout &Layout) {
360 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
362 if (cast<MCSymbolCOFF>(Symbol).isWeakExternal()) {
363 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
365 if (Symbol.isVariable()) {
366 const MCSymbolRefExpr *SymRef =
367 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
370 report_fatal_error("Weak externals may only alias symbols");
372 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
374 std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
375 COFFSymbol *WeakDefault = createSymbol(WeakName);
376 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
377 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
378 WeakDefault->Data.Type = 0;
379 WeakDefault->Data.Value = 0;
380 coff_symbol->Other = WeakDefault;
383 // Setup the Weak External auxiliary symbol.
384 coff_symbol->Aux.resize(1);
385 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
386 coff_symbol->Aux[0].AuxType = ATWeakExternal;
387 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
388 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
389 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
391 coff_symbol->MC = &Symbol;
393 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
394 coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
396 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(Symbol);
397 coff_symbol->Data.Type = SymbolCOFF.getType();
398 coff_symbol->Data.StorageClass = SymbolCOFF.getClass();
400 // If no storage class was specified in the streamer, define it here.
401 if (coff_symbol->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
402 bool IsExternal = Symbol.isExternal() ||
403 (!Symbol.getFragment() && !Symbol.isVariable());
405 coff_symbol->Data.StorageClass = IsExternal
406 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
407 : COFF::IMAGE_SYM_CLASS_STATIC;
411 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
413 if (Base->getFragment()) {
414 COFFSection *Sec = SectionMap[Base->getFragment()->getParent()];
416 if (coff_symbol->Section && coff_symbol->Section != Sec)
417 report_fatal_error("conflicting sections for symbol");
419 coff_symbol->Section = Sec;
423 coff_symbol->MC = &Symbol;
427 // Maximum offsets for different string table entry encodings.
428 static const unsigned Max6DecimalOffset = 999999;
429 static const unsigned Max7DecimalOffset = 9999999;
430 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
432 // Encode a string table entry offset in base 64, padded to 6 chars, and
433 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
434 // Buffer must be at least 8 bytes large. No terminating null appended.
435 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
436 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
437 "Illegal section name encoding for value");
439 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
440 "abcdefghijklmnopqrstuvwxyz"
446 char *Ptr = Buffer + 7;
447 for (unsigned i = 0; i < 6; ++i) {
448 unsigned Rem = Value % 64;
450 *(Ptr--) = Alphabet[Rem];
454 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
455 if (S.Name.size() > COFF::NameSize) {
456 uint64_t StringTableEntry = Strings.getOffset(S.Name);
458 if (StringTableEntry <= Max6DecimalOffset) {
459 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
460 } else if (StringTableEntry <= Max7DecimalOffset) {
461 // With seven digits, we have to skip the terminating null. Because
462 // sprintf always appends it, we use a larger temporary buffer.
464 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
465 std::memcpy(S.Header.Name, buffer, 8);
466 } else if (StringTableEntry <= MaxBase64Offset) {
467 // Starting with 10,000,000, offsets are encoded as base64.
468 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
470 report_fatal_error("COFF string table is greater than 64 GB.");
473 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
476 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
477 if (S.Name.size() > COFF::NameSize)
478 S.set_name_offset(Strings.getOffset(S.Name));
480 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
483 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
484 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
488 //------------------------------------------------------------------------------
489 // entity writing methods
491 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
493 writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
495 writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
496 writeLE16(Header.Machine);
497 writeLE32(Header.TimeDateStamp);
498 writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
503 writeLE32(Header.NumberOfSections);
504 writeLE32(Header.PointerToSymbolTable);
505 writeLE32(Header.NumberOfSymbols);
507 writeLE16(Header.Machine);
508 writeLE16(static_cast<int16_t>(Header.NumberOfSections));
509 writeLE32(Header.TimeDateStamp);
510 writeLE32(Header.PointerToSymbolTable);
511 writeLE32(Header.NumberOfSymbols);
512 writeLE16(Header.SizeOfOptionalHeader);
513 writeLE16(Header.Characteristics);
517 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
518 writeBytes(StringRef(S.Data.Name, COFF::NameSize));
519 writeLE32(S.Data.Value);
521 writeLE32(S.Data.SectionNumber);
523 writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
524 writeLE16(S.Data.Type);
525 write8(S.Data.StorageClass);
526 write8(S.Data.NumberOfAuxSymbols);
527 WriteAuxiliarySymbols(S.Aux);
530 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
531 const COFFSymbol::AuxiliarySymbols &S) {
532 for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
534 switch (i->AuxType) {
535 case ATFunctionDefinition:
536 writeLE32(i->Aux.FunctionDefinition.TagIndex);
537 writeLE32(i->Aux.FunctionDefinition.TotalSize);
538 writeLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
539 writeLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
540 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
542 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
544 case ATbfAndefSymbol:
545 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
546 writeLE16(i->Aux.bfAndefSymbol.Linenumber);
547 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
548 writeLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
549 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
551 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
554 writeLE32(i->Aux.WeakExternal.TagIndex);
555 writeLE32(i->Aux.WeakExternal.Characteristics);
556 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
558 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
562 StringRef(reinterpret_cast<const char *>(&i->Aux),
563 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
565 case ATSectionDefinition:
566 writeLE32(i->Aux.SectionDefinition.Length);
567 writeLE16(i->Aux.SectionDefinition.NumberOfRelocations);
568 writeLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
569 writeLE32(i->Aux.SectionDefinition.CheckSum);
570 writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
571 write8(i->Aux.SectionDefinition.Selection);
572 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
573 writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
575 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
581 void WinCOFFObjectWriter::writeSectionHeader(const COFF::section &S) {
582 writeBytes(StringRef(S.Name, COFF::NameSize));
584 writeLE32(S.VirtualSize);
585 writeLE32(S.VirtualAddress);
586 writeLE32(S.SizeOfRawData);
587 writeLE32(S.PointerToRawData);
588 writeLE32(S.PointerToRelocations);
589 writeLE32(S.PointerToLineNumbers);
590 writeLE16(S.NumberOfRelocations);
591 writeLE16(S.NumberOfLineNumbers);
592 writeLE32(S.Characteristics);
595 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
596 writeLE32(R.VirtualAddress);
597 writeLE32(R.SymbolTableIndex);
601 ////////////////////////////////////////////////////////////////////////////////
602 // MCObjectWriter interface implementations
604 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
605 const MCAsmLayout &Layout) {
606 // "Define" each section & symbol. This creates section & symbol
607 // entries in the staging area.
608 for (const auto &Section : Asm)
609 defineSection(static_cast<const MCSectionCOFF &>(Section));
611 for (const MCSymbol &Symbol : Asm.symbols())
612 if (!Symbol.isTemporary())
613 DefineSymbol(Symbol, Asm, Layout);
616 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
617 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
618 bool InSet, bool IsPCRel) const {
619 // MS LINK expects to be able to replace all references to a function with a
620 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
621 // away any relocations to functions.
622 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
623 if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
625 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
629 bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
630 if (!Sym.isExternal())
633 if (!Sym.isInSection())
636 const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
637 if (!Sec.getCOMDATSymbol())
640 // It looks like for COFF it is invalid to replace a reference to a global
641 // in a comdat with a reference to a local.
642 // FIXME: Add a specification reference if available.
646 void WinCOFFObjectWriter::recordRelocation(
647 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
648 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
649 assert(Target.getSymA() && "Relocation must reference a symbol!");
651 const MCSymbol &A = Target.getSymA()->getSymbol();
652 if (!A.isRegistered()) {
653 Asm.getContext().reportError(Fixup.getLoc(),
654 Twine("symbol '") + A.getName() +
655 "' can not be undefined");
658 if (A.isTemporary() && A.isUndefined()) {
659 Asm.getContext().reportError(Fixup.getLoc(),
660 Twine("assembler label '") + A.getName() +
661 "' can not be undefined");
665 MCSection *Section = Fragment->getParent();
667 // Mark this symbol as requiring an entry in the symbol table.
668 assert(SectionMap.find(Section) != SectionMap.end() &&
669 "Section must already have been defined in executePostLayoutBinding!");
671 COFFSection *coff_section = SectionMap[Section];
672 const MCSymbolRefExpr *SymB = Target.getSymB();
673 bool CrossSection = false;
676 const MCSymbol *B = &SymB->getSymbol();
677 if (!B->getFragment()) {
678 Asm.getContext().reportError(
680 Twine("symbol '") + B->getName() +
681 "' can not be undefined in a subtraction expression");
685 if (!A.getFragment()) {
686 Asm.getContext().reportError(
688 Twine("symbol '") + A.getName() +
689 "' can not be undefined in a subtraction expression");
693 CrossSection = &A.getSection() != &B->getSection();
695 // Offset of the symbol in the section
696 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
698 // In the case where we have SymbA and SymB, we just need to store the delta
699 // between the two symbols. Update FixedValue to account for the delta, and
700 // skip recording the relocation.
702 int64_t OffsetOfA = Layout.getSymbolOffset(A);
703 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
707 // Offset of the relocation in the section
708 int64_t OffsetOfRelocation =
709 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
711 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
713 FixedValue = Target.getConstant();
716 COFFRelocation Reloc;
718 Reloc.Data.SymbolTableIndex = 0;
719 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
721 // Turn relocations for temporary symbols into section relocations.
722 if (A.isTemporary() || CrossSection) {
723 MCSection *TargetSection = &A.getSection();
725 SectionMap.find(TargetSection) != SectionMap.end() &&
726 "Section must already have been defined in executePostLayoutBinding!");
727 Reloc.Symb = SectionMap[TargetSection]->Symbol;
728 FixedValue += Layout.getSymbolOffset(A);
731 SymbolMap.find(&A) != SymbolMap.end() &&
732 "Symbol must already have been defined in executePostLayoutBinding!");
733 Reloc.Symb = SymbolMap[&A];
736 ++Reloc.Symb->Relocations;
738 Reloc.Data.VirtualAddress += Fixup.getOffset();
739 Reloc.Data.Type = TargetObjectWriter->getRelocType(
740 Target, Fixup, CrossSection, Asm.getBackend());
742 // FIXME: Can anyone explain what this does other than adjust for the size
744 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
745 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
746 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
747 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
750 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
751 switch (Reloc.Data.Type) {
752 case COFF::IMAGE_REL_ARM_ABSOLUTE:
753 case COFF::IMAGE_REL_ARM_ADDR32:
754 case COFF::IMAGE_REL_ARM_ADDR32NB:
755 case COFF::IMAGE_REL_ARM_TOKEN:
756 case COFF::IMAGE_REL_ARM_SECTION:
757 case COFF::IMAGE_REL_ARM_SECREL:
759 case COFF::IMAGE_REL_ARM_BRANCH11:
760 case COFF::IMAGE_REL_ARM_BLX11:
761 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
762 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
764 case COFF::IMAGE_REL_ARM_BRANCH24:
765 case COFF::IMAGE_REL_ARM_BLX24:
766 case COFF::IMAGE_REL_ARM_MOV32A:
767 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
768 // only used for ARM mode code, which is documented as being unsupported
769 // by Windows on ARM. Empirical proof indicates that masm is able to
770 // generate the relocations however the rest of the MSVC toolchain is
771 // unable to handle it.
772 llvm_unreachable("unsupported relocation");
774 case COFF::IMAGE_REL_ARM_MOV32T:
776 case COFF::IMAGE_REL_ARM_BRANCH20T:
777 case COFF::IMAGE_REL_ARM_BRANCH24T:
778 case COFF::IMAGE_REL_ARM_BLX23T:
779 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
780 // perform a 4 byte adjustment to the relocation. Relative branches are
781 // offset by 4 on ARM, however, because there is no RELA relocations, all
782 // branches are offset by 4.
783 FixedValue = FixedValue + 4;
788 if (TargetObjectWriter->recordRelocation(Fixup))
789 coff_section->Relocations.push_back(Reloc);
792 void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
793 const MCAsmLayout &Layout) {
794 size_t SectionsSize = Sections.size();
795 if (SectionsSize > static_cast<size_t>(INT32_MAX))
797 "PE COFF object files can't have more than 2147483647 sections");
799 // Assign symbol and section indexes and offsets.
800 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
802 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
804 // Assign section numbers.
806 for (const auto &Section : Sections) {
807 Section->Number = Number;
808 Section->Symbol->Data.SectionNumber = Number;
809 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
813 Header.NumberOfSections = NumberOfSections;
814 Header.NumberOfSymbols = 0;
816 for (const std::string &Name : Asm.getFileNames()) {
817 // round up to calculate the number of auxiliary symbols required
818 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
819 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
821 COFFSymbol *file = createSymbol(".file");
822 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
823 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
824 file->Aux.resize(Count);
827 unsigned Length = Name.size();
828 for (auto &Aux : file->Aux) {
829 Aux.AuxType = ATFile;
831 if (Length > SymbolSize) {
832 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
833 Length = Length - SymbolSize;
835 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
836 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
840 Offset += SymbolSize;
844 for (auto &Symbol : Symbols) {
845 // Update section number & offset for symbols that have them.
847 Symbol->Data.SectionNumber = Symbol->Section->Number;
848 Symbol->setIndex(Header.NumberOfSymbols++);
849 // Update auxiliary symbol info.
850 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
851 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
854 // Build string table.
855 for (const auto &S : Sections)
856 if (S->Name.size() > COFF::NameSize)
857 Strings.add(S->Name);
858 for (const auto &S : Symbols)
859 if (S->Name.size() > COFF::NameSize)
860 Strings.add(S->Name);
864 for (const auto &S : Sections)
866 for (auto &S : Symbols)
869 // Fixup weak external references.
870 for (auto &Symbol : Symbols) {
872 assert(Symbol->getIndex() != -1);
873 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
874 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
875 "Symbol's aux symbol must be a Weak External!");
876 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
880 // Fixup associative COMDAT sections.
881 for (auto &Section : Sections) {
882 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
883 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
886 const MCSectionCOFF &MCSec = *Section->MCSection;
888 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
890 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
891 assert(COMDATSymbol);
892 COFFSection *Assoc = COMDATSymbol->Section;
895 Twine("Missing associated COMDAT section for section ") +
896 MCSec.getSectionName());
898 // Skip this section if the associated section is unused.
899 if (Assoc->Number == -1)
902 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
905 // Assign file offsets to COFF object file structures.
907 unsigned offset = getInitialOffset();
910 offset += COFF::Header32Size;
912 offset += COFF::Header16Size;
913 offset += COFF::SectionSize * Header.NumberOfSections;
915 for (const auto &Section : Asm) {
916 COFFSection *Sec = SectionMap[&Section];
918 if (Sec->Number == -1)
921 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
923 if (IsPhysicalSection(Sec)) {
924 // Align the section data to a four byte boundary.
925 offset = RoundUpToAlignment(offset, 4);
926 Sec->Header.PointerToRawData = offset;
928 offset += Sec->Header.SizeOfRawData;
931 if (Sec->Relocations.size() > 0) {
932 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
934 if (RelocationsOverflow) {
935 // Signal overflow by setting NumberOfRelocations to max value. Actual
936 // size is found in reloc #0. Microsoft tools understand this.
937 Sec->Header.NumberOfRelocations = 0xffff;
939 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
941 Sec->Header.PointerToRelocations = offset;
943 if (RelocationsOverflow) {
944 // Reloc #0 will contain actual count, so make room for it.
945 offset += COFF::RelocationSize;
948 offset += COFF::RelocationSize * Sec->Relocations.size();
950 for (auto &Relocation : Sec->Relocations) {
951 assert(Relocation.Symb->getIndex() != -1);
952 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
956 assert(Sec->Symbol->Aux.size() == 1 &&
957 "Section's symbol must have one aux!");
958 AuxSymbol &Aux = Sec->Symbol->Aux[0];
959 assert(Aux.AuxType == ATSectionDefinition &&
960 "Section's symbol's aux symbol must be a Section Definition!");
961 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
962 Aux.Aux.SectionDefinition.NumberOfRelocations =
963 Sec->Header.NumberOfRelocations;
964 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
965 Sec->Header.NumberOfLineNumbers;
968 Header.PointerToSymbolTable = offset;
970 #if (ENABLE_TIMESTAMPS == 1)
971 // MS LINK expects to be able to use this timestamp to implement their
972 // /INCREMENTAL feature.
973 std::time_t Now = time(nullptr);
974 if (Now < 0 || !isUInt<32>(Now))
976 Header.TimeDateStamp = Now;
978 // We want a deterministic output. It looks like GNU as also writes 0 in here.
979 Header.TimeDateStamp = 0;
982 // Write it all to disk...
983 WriteFileHeader(Header);
986 sections::iterator i, ie;
987 MCAssembler::iterator j, je;
989 for (auto &Section : Sections) {
990 if (Section->Number != -1) {
991 if (Section->Relocations.size() >= 0xffff)
992 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
993 writeSectionHeader(Section->Header);
997 SmallVector<char, 128> SectionContents;
998 for (i = Sections.begin(), ie = Sections.end(), j = Asm.begin(),
1000 (i != ie) && (j != je); ++i, ++j) {
1002 if ((*i)->Number == -1)
1005 if ((*i)->Header.PointerToRawData != 0) {
1006 assert(getStream().tell() <= (*i)->Header.PointerToRawData &&
1007 "Section::PointerToRawData is insane!");
1009 unsigned SectionDataPadding =
1010 (*i)->Header.PointerToRawData - getStream().tell();
1011 assert(SectionDataPadding < 4 &&
1012 "Should only need at most three bytes of padding!");
1014 WriteZeros(SectionDataPadding);
1016 // Save the contents of the section to a temporary buffer, we need this
1017 // to CRC the data before we dump it into the object file.
1018 SectionContents.clear();
1019 raw_svector_ostream VecOS(SectionContents);
1020 raw_pwrite_stream &OldStream = getStream();
1021 // Redirect the output stream to our buffer.
1023 // Fill our buffer with the section data.
1024 Asm.writeSectionData(&*j, Layout);
1025 // Reset the stream back to what it was before.
1026 setStream(OldStream);
1028 // Calculate our CRC with an initial value of '0', this is not how
1029 // JamCRC is specified but it aligns with the expected output.
1030 JamCRC JC(/*Init=*/0x00000000U);
1031 JC.update(SectionContents);
1033 // Write the section contents to the object file.
1034 getStream() << SectionContents;
1036 // Update the section definition auxiliary symbol to record the CRC.
1037 COFFSection *Sec = SectionMap[&*j];
1038 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
1039 assert(AuxSyms.size() == 1 &&
1040 AuxSyms[0].AuxType == ATSectionDefinition);
1041 AuxSymbol &SecDef = AuxSyms[0];
1042 SecDef.Aux.SectionDefinition.CheckSum = JC.getCRC();
1045 if ((*i)->Relocations.size() > 0) {
1046 assert(getStream().tell() == (*i)->Header.PointerToRelocations &&
1047 "Section::PointerToRelocations is insane!");
1049 if ((*i)->Relocations.size() >= 0xffff) {
1050 // In case of overflow, write actual relocation count as first
1051 // relocation. Including the synthetic reloc itself (+ 1).
1053 r.VirtualAddress = (*i)->Relocations.size() + 1;
1054 r.SymbolTableIndex = 0;
1059 for (const auto &Relocation : (*i)->Relocations)
1060 WriteRelocation(Relocation.Data);
1062 assert((*i)->Header.PointerToRelocations == 0 &&
1063 "Section::PointerToRelocations is insane!");
1067 assert(getStream().tell() == Header.PointerToSymbolTable &&
1068 "Header::PointerToSymbolTable is insane!");
1070 for (auto &Symbol : Symbols)
1071 if (Symbol->getIndex() != -1)
1072 WriteSymbol(*Symbol);
1074 getStream().write(Strings.data().data(), Strings.data().size());
1077 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1078 : Machine(Machine_) {}
1080 // Pin the vtable to this file.
1081 void MCWinCOFFObjectTargetWriter::anchor() {}
1083 //------------------------------------------------------------------------------
1084 // WinCOFFObjectWriter factory function
1087 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1088 raw_pwrite_stream &OS) {
1089 return new WinCOFFObjectWriter(MOTW, OS);