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/Config/config.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSymbolCOFF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/COFF.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Endian.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/JamCRC.h"
37 #include "llvm/Support/TimeValue.h"
43 #define DEBUG_TYPE "WinCOFFObjectWriter"
46 typedef SmallString<COFF::NameSize> name;
57 AuxiliaryType AuxType;
68 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
79 COFFSymbol(StringRef name);
80 void set_name_offset(uint32_t Offset);
82 int64_t getIndex() const { return Index; }
83 void setIndex(int Value) {
86 MC->setIndex(static_cast<uint32_t>(Value));
90 // This class contains staging data for a COFF relocation entry.
91 struct COFFRelocation {
92 COFF::relocation Data;
95 COFFRelocation() : Symb(nullptr) {}
96 static size_t size() { return COFF::RelocationSize; }
99 typedef std::vector<COFFRelocation> relocations;
103 COFF::section Header;
107 MCSectionCOFF const *MCSection;
109 relocations Relocations;
111 COFFSection(StringRef name);
112 static size_t size();
115 class WinCOFFObjectWriter : public MCObjectWriter {
117 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
118 typedef std::vector<std::unique_ptr<COFFSection>> sections;
120 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
121 typedef DenseMap<MCSection const *, COFFSection *> section_map;
123 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
125 // Root level file contents.
129 StringTableBuilder Strings{StringTableBuilder::WinCOFF};
131 // Maps used during object file creation.
132 section_map SectionMap;
133 symbol_map SymbolMap;
137 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
139 void reset() override {
140 memset(&Header, 0, sizeof(Header));
141 Header.Machine = TargetObjectWriter->getMachine();
147 MCObjectWriter::reset();
150 COFFSymbol *createSymbol(StringRef Name);
151 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
152 COFFSection *createSection(StringRef Name);
154 template <typename object_t, typename list_t>
155 object_t *createCOFFEntity(StringRef Name, list_t &List);
157 void defineSection(MCSectionCOFF const &Sec);
158 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
159 const MCAsmLayout &Layout);
161 void SetSymbolName(COFFSymbol &S);
162 void SetSectionName(COFFSection &S);
164 bool IsPhysicalSection(COFFSection *S);
166 // Entity writing methods.
168 void WriteFileHeader(const COFF::header &Header);
169 void WriteSymbol(const COFFSymbol &S);
170 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
171 void writeSectionHeader(const COFF::section &S);
172 void WriteRelocation(const COFF::relocation &R);
174 // MCObjectWriter interface implementation.
176 void executePostLayoutBinding(MCAssembler &Asm,
177 const MCAsmLayout &Layout) override;
179 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
180 const MCSymbol &SymA,
181 const MCFragment &FB, bool InSet,
182 bool IsPCRel) const override;
184 bool isWeak(const MCSymbol &Sym) const override;
186 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
187 const MCFragment *Fragment, const MCFixup &Fixup,
188 MCValue Target, bool &IsPCRel,
189 uint64_t &FixedValue) override;
191 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
195 static inline void write_uint32_le(void *Data, uint32_t Value) {
196 support::endian::write<uint32_t, support::little, support::unaligned>(Data,
200 //------------------------------------------------------------------------------
201 // Symbol class implementation
203 COFFSymbol::COFFSymbol(StringRef name)
204 : Name(name.begin(), name.end()), Other(nullptr), Section(nullptr),
205 Relocations(0), MC(nullptr) {
206 memset(&Data, 0, sizeof(Data));
209 // In the case that the name does not fit within 8 bytes, the offset
210 // into the string table is stored in the last 4 bytes instead, leaving
211 // the first 4 bytes as 0.
212 void COFFSymbol::set_name_offset(uint32_t Offset) {
213 write_uint32_le(Data.Name + 0, 0);
214 write_uint32_le(Data.Name + 4, Offset);
217 //------------------------------------------------------------------------------
218 // Section class implementation
220 COFFSection::COFFSection(StringRef name)
221 : Name(name), MCSection(nullptr), Symbol(nullptr) {
222 memset(&Header, 0, sizeof(Header));
225 size_t COFFSection::size() { return COFF::SectionSize; }
227 //------------------------------------------------------------------------------
228 // WinCOFFObjectWriter class implementation
230 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
231 raw_pwrite_stream &OS)
232 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
233 memset(&Header, 0, sizeof(Header));
235 Header.Machine = TargetObjectWriter->getMachine();
238 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
239 return createCOFFEntity<COFFSymbol>(Name, Symbols);
242 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
243 symbol_map::iterator i = SymbolMap.find(Symbol);
244 if (i != SymbolMap.end())
246 COFFSymbol *RetSymbol =
247 createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
248 SymbolMap[Symbol] = RetSymbol;
252 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
253 return createCOFFEntity<COFFSection>(Name, Sections);
256 /// A template used to lookup or create a symbol/section, and initialize it if
258 template <typename object_t, typename list_t>
259 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, list_t &List) {
260 List.push_back(make_unique<object_t>(Name));
262 return List.back().get();
265 /// This function takes a section data object from the assembler
266 /// and creates the associated COFF section staging object.
267 void WinCOFFObjectWriter::defineSection(MCSectionCOFF const &Sec) {
268 COFFSection *coff_section = createSection(Sec.getSectionName());
269 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
270 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
271 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
272 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
273 if (COMDATSymbol->Section)
274 report_fatal_error("two sections have the same comdat");
275 COMDATSymbol->Section = coff_section;
279 coff_section->Symbol = coff_symbol;
280 coff_symbol->Section = coff_section;
281 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
283 // In this case the auxiliary symbol is a Section Definition.
284 coff_symbol->Aux.resize(1);
285 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
286 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
287 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
289 coff_section->Header.Characteristics = Sec.getCharacteristics();
291 uint32_t &Characteristics = coff_section->Header.Characteristics;
292 switch (Sec.getAlignment()) {
294 Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
297 Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
300 Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
303 Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
306 Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
309 Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
312 Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
315 Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
318 Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
321 Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
324 Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
327 Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
330 Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
333 Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
336 llvm_unreachable("unsupported section alignment");
339 // Bind internal COFF section to MC section.
340 coff_section->MCSection = &Sec;
341 SectionMap[&Sec] = coff_section;
344 static uint64_t getSymbolValue(const MCSymbol &Symbol,
345 const MCAsmLayout &Layout) {
346 if (Symbol.isCommon() && Symbol.isExternal())
347 return Symbol.getCommonSize();
350 if (!Layout.getSymbolOffset(Symbol, Res))
356 /// This function takes a symbol data object from the assembler
357 /// and creates the associated COFF symbol staging object.
358 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
359 MCAssembler &Assembler,
360 const MCAsmLayout &Layout) {
361 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
363 if (cast<MCSymbolCOFF>(Symbol).isWeakExternal()) {
364 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
366 if (Symbol.isVariable()) {
367 const MCSymbolRefExpr *SymRef =
368 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
371 report_fatal_error("Weak externals may only alias symbols");
373 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
375 std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
376 COFFSymbol *WeakDefault = createSymbol(WeakName);
377 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
378 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
379 WeakDefault->Data.Type = 0;
380 WeakDefault->Data.Value = 0;
381 coff_symbol->Other = WeakDefault;
384 // Setup the Weak External auxiliary symbol.
385 coff_symbol->Aux.resize(1);
386 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
387 coff_symbol->Aux[0].AuxType = ATWeakExternal;
388 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
389 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
390 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
392 coff_symbol->MC = &Symbol;
394 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
395 coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
397 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(Symbol);
398 coff_symbol->Data.Type = SymbolCOFF.getType();
399 coff_symbol->Data.StorageClass = SymbolCOFF.getClass();
401 // If no storage class was specified in the streamer, define it here.
402 if (coff_symbol->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
403 bool IsExternal = Symbol.isExternal() ||
404 (!Symbol.getFragment() && !Symbol.isVariable());
406 coff_symbol->Data.StorageClass = IsExternal
407 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
408 : COFF::IMAGE_SYM_CLASS_STATIC;
412 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
414 if (Base->getFragment()) {
415 COFFSection *Sec = SectionMap[Base->getFragment()->getParent()];
417 if (coff_symbol->Section && coff_symbol->Section != Sec)
418 report_fatal_error("conflicting sections for symbol");
420 coff_symbol->Section = Sec;
424 coff_symbol->MC = &Symbol;
428 // Maximum offsets for different string table entry encodings.
429 static const unsigned Max6DecimalOffset = 999999;
430 static const unsigned Max7DecimalOffset = 9999999;
431 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
433 // Encode a string table entry offset in base 64, padded to 6 chars, and
434 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
435 // Buffer must be at least 8 bytes large. No terminating null appended.
436 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
437 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
438 "Illegal section name encoding for value");
440 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
441 "abcdefghijklmnopqrstuvwxyz"
447 char *Ptr = Buffer + 7;
448 for (unsigned i = 0; i < 6; ++i) {
449 unsigned Rem = Value % 64;
451 *(Ptr--) = Alphabet[Rem];
455 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
456 if (S.Name.size() > COFF::NameSize) {
457 uint64_t StringTableEntry = Strings.getOffset(S.Name);
459 if (StringTableEntry <= Max6DecimalOffset) {
460 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
461 } else if (StringTableEntry <= Max7DecimalOffset) {
462 // With seven digits, we have to skip the terminating null. Because
463 // sprintf always appends it, we use a larger temporary buffer.
465 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
466 std::memcpy(S.Header.Name, buffer, 8);
467 } else if (StringTableEntry <= MaxBase64Offset) {
468 // Starting with 10,000,000, offsets are encoded as base64.
469 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
471 report_fatal_error("COFF string table is greater than 64 GB.");
474 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
477 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
478 if (S.Name.size() > COFF::NameSize)
479 S.set_name_offset(Strings.getOffset(S.Name));
481 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
484 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
485 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
489 //------------------------------------------------------------------------------
490 // entity writing methods
492 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
494 writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
496 writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
497 writeLE16(Header.Machine);
498 writeLE32(Header.TimeDateStamp);
499 writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
504 writeLE32(Header.NumberOfSections);
505 writeLE32(Header.PointerToSymbolTable);
506 writeLE32(Header.NumberOfSymbols);
508 writeLE16(Header.Machine);
509 writeLE16(static_cast<int16_t>(Header.NumberOfSections));
510 writeLE32(Header.TimeDateStamp);
511 writeLE32(Header.PointerToSymbolTable);
512 writeLE32(Header.NumberOfSymbols);
513 writeLE16(Header.SizeOfOptionalHeader);
514 writeLE16(Header.Characteristics);
518 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
519 writeBytes(StringRef(S.Data.Name, COFF::NameSize));
520 writeLE32(S.Data.Value);
522 writeLE32(S.Data.SectionNumber);
524 writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
525 writeLE16(S.Data.Type);
526 write8(S.Data.StorageClass);
527 write8(S.Data.NumberOfAuxSymbols);
528 WriteAuxiliarySymbols(S.Aux);
531 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
532 const COFFSymbol::AuxiliarySymbols &S) {
533 for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
535 switch (i->AuxType) {
536 case ATFunctionDefinition:
537 writeLE32(i->Aux.FunctionDefinition.TagIndex);
538 writeLE32(i->Aux.FunctionDefinition.TotalSize);
539 writeLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
540 writeLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
541 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
543 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
545 case ATbfAndefSymbol:
546 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
547 writeLE16(i->Aux.bfAndefSymbol.Linenumber);
548 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
549 writeLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
550 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
552 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
555 writeLE32(i->Aux.WeakExternal.TagIndex);
556 writeLE32(i->Aux.WeakExternal.Characteristics);
557 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
559 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
563 StringRef(reinterpret_cast<const char *>(&i->Aux),
564 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
566 case ATSectionDefinition:
567 writeLE32(i->Aux.SectionDefinition.Length);
568 writeLE16(i->Aux.SectionDefinition.NumberOfRelocations);
569 writeLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
570 writeLE32(i->Aux.SectionDefinition.CheckSum);
571 writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
572 write8(i->Aux.SectionDefinition.Selection);
573 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
574 writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
576 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
582 void WinCOFFObjectWriter::writeSectionHeader(const COFF::section &S) {
583 writeBytes(StringRef(S.Name, COFF::NameSize));
585 writeLE32(S.VirtualSize);
586 writeLE32(S.VirtualAddress);
587 writeLE32(S.SizeOfRawData);
588 writeLE32(S.PointerToRawData);
589 writeLE32(S.PointerToRelocations);
590 writeLE32(S.PointerToLineNumbers);
591 writeLE16(S.NumberOfRelocations);
592 writeLE16(S.NumberOfLineNumbers);
593 writeLE32(S.Characteristics);
596 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
597 writeLE32(R.VirtualAddress);
598 writeLE32(R.SymbolTableIndex);
602 ////////////////////////////////////////////////////////////////////////////////
603 // MCObjectWriter interface implementations
605 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
606 const MCAsmLayout &Layout) {
607 // "Define" each section & symbol. This creates section & symbol
608 // entries in the staging area.
609 for (const auto &Section : Asm)
610 defineSection(static_cast<const MCSectionCOFF &>(Section));
612 for (const MCSymbol &Symbol : Asm.symbols())
613 if (!Symbol.isTemporary())
614 DefineSymbol(Symbol, Asm, Layout);
617 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
618 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
619 bool InSet, bool IsPCRel) const {
620 // MS LINK expects to be able to replace all references to a function with a
621 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
622 // away any relocations to functions.
623 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
624 if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
626 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
630 bool WinCOFFObjectWriter::isWeak(const MCSymbol &Sym) const {
631 if (!Sym.isExternal())
634 if (!Sym.isInSection())
637 const auto &Sec = cast<MCSectionCOFF>(Sym.getSection());
638 if (!Sec.getCOMDATSymbol())
641 // It looks like for COFF it is invalid to replace a reference to a global
642 // in a comdat with a reference to a local.
643 // FIXME: Add a specification reference if available.
647 void WinCOFFObjectWriter::recordRelocation(
648 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
649 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
650 assert(Target.getSymA() && "Relocation must reference a symbol!");
652 const MCSymbol &A = Target.getSymA()->getSymbol();
653 if (!A.isRegistered()) {
654 Asm.getContext().reportError(Fixup.getLoc(),
655 Twine("symbol '") + A.getName() +
656 "' can not be undefined");
659 if (A.isTemporary() && A.isUndefined()) {
660 Asm.getContext().reportError(Fixup.getLoc(),
661 Twine("assembler label '") + A.getName() +
662 "' can not be undefined");
666 MCSection *Section = Fragment->getParent();
668 // Mark this symbol as requiring an entry in the symbol table.
669 assert(SectionMap.find(Section) != SectionMap.end() &&
670 "Section must already have been defined in executePostLayoutBinding!");
672 COFFSection *coff_section = SectionMap[Section];
673 const MCSymbolRefExpr *SymB = Target.getSymB();
674 bool CrossSection = false;
677 const MCSymbol *B = &SymB->getSymbol();
678 if (!B->getFragment()) {
679 Asm.getContext().reportError(
681 Twine("symbol '") + B->getName() +
682 "' can not be undefined in a subtraction expression");
686 if (!A.getFragment()) {
687 Asm.getContext().reportError(
689 Twine("symbol '") + A.getName() +
690 "' can not be undefined in a subtraction expression");
694 CrossSection = &A.getSection() != &B->getSection();
696 // Offset of the symbol in the section
697 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
699 // In the case where we have SymbA and SymB, we just need to store the delta
700 // between the two symbols. Update FixedValue to account for the delta, and
701 // skip recording the relocation.
703 int64_t OffsetOfA = Layout.getSymbolOffset(A);
704 FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
708 // Offset of the relocation in the section
709 int64_t OffsetOfRelocation =
710 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
712 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
714 FixedValue = Target.getConstant();
717 COFFRelocation Reloc;
719 Reloc.Data.SymbolTableIndex = 0;
720 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
722 // Turn relocations for temporary symbols into section relocations.
723 if (A.isTemporary() || CrossSection) {
724 MCSection *TargetSection = &A.getSection();
726 SectionMap.find(TargetSection) != SectionMap.end() &&
727 "Section must already have been defined in executePostLayoutBinding!");
728 Reloc.Symb = SectionMap[TargetSection]->Symbol;
729 FixedValue += Layout.getSymbolOffset(A);
732 SymbolMap.find(&A) != SymbolMap.end() &&
733 "Symbol must already have been defined in executePostLayoutBinding!");
734 Reloc.Symb = SymbolMap[&A];
737 ++Reloc.Symb->Relocations;
739 Reloc.Data.VirtualAddress += Fixup.getOffset();
740 Reloc.Data.Type = TargetObjectWriter->getRelocType(
741 Target, Fixup, CrossSection, Asm.getBackend());
743 // FIXME: Can anyone explain what this does other than adjust for the size
745 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
746 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
747 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
748 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
751 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
752 switch (Reloc.Data.Type) {
753 case COFF::IMAGE_REL_ARM_ABSOLUTE:
754 case COFF::IMAGE_REL_ARM_ADDR32:
755 case COFF::IMAGE_REL_ARM_ADDR32NB:
756 case COFF::IMAGE_REL_ARM_TOKEN:
757 case COFF::IMAGE_REL_ARM_SECTION:
758 case COFF::IMAGE_REL_ARM_SECREL:
760 case COFF::IMAGE_REL_ARM_BRANCH11:
761 case COFF::IMAGE_REL_ARM_BLX11:
762 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
763 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
765 case COFF::IMAGE_REL_ARM_BRANCH24:
766 case COFF::IMAGE_REL_ARM_BLX24:
767 case COFF::IMAGE_REL_ARM_MOV32A:
768 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
769 // only used for ARM mode code, which is documented as being unsupported
770 // by Windows on ARM. Empirical proof indicates that masm is able to
771 // generate the relocations however the rest of the MSVC toolchain is
772 // unable to handle it.
773 llvm_unreachable("unsupported relocation");
775 case COFF::IMAGE_REL_ARM_MOV32T:
777 case COFF::IMAGE_REL_ARM_BRANCH20T:
778 case COFF::IMAGE_REL_ARM_BRANCH24T:
779 case COFF::IMAGE_REL_ARM_BLX23T:
780 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
781 // perform a 4 byte adjustment to the relocation. Relative branches are
782 // offset by 4 on ARM, however, because there is no RELA relocations, all
783 // branches are offset by 4.
784 FixedValue = FixedValue + 4;
789 if (TargetObjectWriter->recordRelocation(Fixup))
790 coff_section->Relocations.push_back(Reloc);
793 void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
794 const MCAsmLayout &Layout) {
795 size_t SectionsSize = Sections.size();
796 if (SectionsSize > static_cast<size_t>(INT32_MAX))
798 "PE COFF object files can't have more than 2147483647 sections");
800 // Assign symbol and section indexes and offsets.
801 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
803 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
805 // Assign section numbers.
807 for (const auto &Section : Sections) {
808 Section->Number = Number;
809 Section->Symbol->Data.SectionNumber = Number;
810 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
814 Header.NumberOfSections = NumberOfSections;
815 Header.NumberOfSymbols = 0;
817 for (const std::string &Name : Asm.getFileNames()) {
818 // round up to calculate the number of auxiliary symbols required
819 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
820 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
822 COFFSymbol *file = createSymbol(".file");
823 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
824 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
825 file->Aux.resize(Count);
828 unsigned Length = Name.size();
829 for (auto &Aux : file->Aux) {
830 Aux.AuxType = ATFile;
832 if (Length > SymbolSize) {
833 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
834 Length = Length - SymbolSize;
836 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
837 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
841 Offset += SymbolSize;
845 for (auto &Symbol : Symbols) {
846 // Update section number & offset for symbols that have them.
848 Symbol->Data.SectionNumber = Symbol->Section->Number;
849 Symbol->setIndex(Header.NumberOfSymbols++);
850 // Update auxiliary symbol info.
851 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
852 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
855 // Build string table.
856 for (const auto &S : Sections)
857 if (S->Name.size() > COFF::NameSize)
858 Strings.add(S->Name);
859 for (const auto &S : Symbols)
860 if (S->Name.size() > COFF::NameSize)
861 Strings.add(S->Name);
865 for (const auto &S : Sections)
867 for (auto &S : Symbols)
870 // Fixup weak external references.
871 for (auto &Symbol : Symbols) {
873 assert(Symbol->getIndex() != -1);
874 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
875 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
876 "Symbol's aux symbol must be a Weak External!");
877 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
881 // Fixup associative COMDAT sections.
882 for (auto &Section : Sections) {
883 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
884 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
887 const MCSectionCOFF &MCSec = *Section->MCSection;
889 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
891 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
892 assert(COMDATSymbol);
893 COFFSection *Assoc = COMDATSymbol->Section;
896 Twine("Missing associated COMDAT section for section ") +
897 MCSec.getSectionName());
899 // Skip this section if the associated section is unused.
900 if (Assoc->Number == -1)
903 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
906 // Assign file offsets to COFF object file structures.
908 unsigned offset = getInitialOffset();
911 offset += COFF::Header32Size;
913 offset += COFF::Header16Size;
914 offset += COFF::SectionSize * Header.NumberOfSections;
916 for (const auto &Section : Asm) {
917 COFFSection *Sec = SectionMap[&Section];
919 if (Sec->Number == -1)
922 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
924 if (IsPhysicalSection(Sec)) {
925 // Align the section data to a four byte boundary.
926 offset = RoundUpToAlignment(offset, 4);
927 Sec->Header.PointerToRawData = offset;
929 offset += Sec->Header.SizeOfRawData;
932 if (Sec->Relocations.size() > 0) {
933 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
935 if (RelocationsOverflow) {
936 // Signal overflow by setting NumberOfRelocations to max value. Actual
937 // size is found in reloc #0. Microsoft tools understand this.
938 Sec->Header.NumberOfRelocations = 0xffff;
940 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
942 Sec->Header.PointerToRelocations = offset;
944 if (RelocationsOverflow) {
945 // Reloc #0 will contain actual count, so make room for it.
946 offset += COFF::RelocationSize;
949 offset += COFF::RelocationSize * Sec->Relocations.size();
951 for (auto &Relocation : Sec->Relocations) {
952 assert(Relocation.Symb->getIndex() != -1);
953 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
957 assert(Sec->Symbol->Aux.size() == 1 &&
958 "Section's symbol must have one aux!");
959 AuxSymbol &Aux = Sec->Symbol->Aux[0];
960 assert(Aux.AuxType == ATSectionDefinition &&
961 "Section's symbol's aux symbol must be a Section Definition!");
962 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
963 Aux.Aux.SectionDefinition.NumberOfRelocations =
964 Sec->Header.NumberOfRelocations;
965 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
966 Sec->Header.NumberOfLineNumbers;
969 Header.PointerToSymbolTable = offset;
971 #if (ENABLE_TIMESTAMPS == 1)
972 // MS LINK expects to be able to use this timestamp to implement their
973 // /INCREMENTAL feature.
974 std::time_t Now = time(nullptr);
975 if (Now < 0 || !isUInt<32>(Now))
977 Header.TimeDateStamp = Now;
979 // We want a deterministic output. It looks like GNU as also writes 0 in here.
980 Header.TimeDateStamp = 0;
983 // Write it all to disk...
984 WriteFileHeader(Header);
987 sections::iterator i, ie;
988 MCAssembler::iterator j, je;
990 for (auto &Section : Sections) {
991 if (Section->Number != -1) {
992 if (Section->Relocations.size() >= 0xffff)
993 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
994 writeSectionHeader(Section->Header);
998 SmallVector<char, 128> SectionContents;
999 for (i = Sections.begin(), ie = Sections.end(), j = Asm.begin(),
1001 (i != ie) && (j != je); ++i, ++j) {
1003 if ((*i)->Number == -1)
1006 if ((*i)->Header.PointerToRawData != 0) {
1007 assert(getStream().tell() <= (*i)->Header.PointerToRawData &&
1008 "Section::PointerToRawData is insane!");
1010 unsigned SectionDataPadding =
1011 (*i)->Header.PointerToRawData - getStream().tell();
1012 assert(SectionDataPadding < 4 &&
1013 "Should only need at most three bytes of padding!");
1015 WriteZeros(SectionDataPadding);
1017 // Save the contents of the section to a temporary buffer, we need this
1018 // to CRC the data before we dump it into the object file.
1019 SectionContents.clear();
1020 raw_svector_ostream VecOS(SectionContents);
1021 raw_pwrite_stream &OldStream = getStream();
1022 // Redirect the output stream to our buffer.
1024 // Fill our buffer with the section data.
1025 Asm.writeSectionData(&*j, Layout);
1026 // Reset the stream back to what it was before.
1027 setStream(OldStream);
1029 // Calculate our CRC with an initial value of '0', this is not how
1030 // JamCRC is specified but it aligns with the expected output.
1031 JamCRC JC(/*Init=*/0x00000000U);
1032 JC.update(SectionContents);
1034 // Write the section contents to the object file.
1035 getStream() << SectionContents;
1037 // Update the section definition auxiliary symbol to record the CRC.
1038 COFFSection *Sec = SectionMap[&*j];
1039 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
1040 assert(AuxSyms.size() == 1 &&
1041 AuxSyms[0].AuxType == ATSectionDefinition);
1042 AuxSymbol &SecDef = AuxSyms[0];
1043 SecDef.Aux.SectionDefinition.CheckSum = JC.getCRC();
1046 if ((*i)->Relocations.size() > 0) {
1047 assert(getStream().tell() == (*i)->Header.PointerToRelocations &&
1048 "Section::PointerToRelocations is insane!");
1050 if ((*i)->Relocations.size() >= 0xffff) {
1051 // In case of overflow, write actual relocation count as first
1052 // relocation. Including the synthetic reloc itself (+ 1).
1054 r.VirtualAddress = (*i)->Relocations.size() + 1;
1055 r.SymbolTableIndex = 0;
1060 for (const auto &Relocation : (*i)->Relocations)
1061 WriteRelocation(Relocation.Data);
1063 assert((*i)->Header.PointerToRelocations == 0 &&
1064 "Section::PointerToRelocations is insane!");
1068 assert(getStream().tell() == Header.PointerToSymbolTable &&
1069 "Header::PointerToSymbolTable is insane!");
1071 for (auto &Symbol : Symbols)
1072 if (Symbol->getIndex() != -1)
1073 WriteSymbol(*Symbol);
1075 getStream().write(Strings.data().data(), Strings.data().size());
1078 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1079 : Machine(Machine_) {}
1081 // Pin the vtable to this file.
1082 void MCWinCOFFObjectTargetWriter::anchor() {}
1084 //------------------------------------------------------------------------------
1085 // WinCOFFObjectWriter factory function
1088 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1089 raw_pwrite_stream &OS) {
1090 return new WinCOFFObjectWriter(MOTW, OS);