[PowerPC] Do not emit record-form rotates when record-form andi/andis suffices
[llvm-core.git] / lib / MC / WinCOFFObjectWriter.cpp
blob3ec1c09260053ec664b7670cf04ccde9e72c25e1
1 //===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains an implementation of a Win32 COFF object file writer.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/COFF.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/MCFixup.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSection.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/MC/MCSymbolCOFF.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/MC/MCWinCOFFObjectWriter.h"
34 #include "llvm/MC/StringTableBuilder.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/JamCRC.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <algorithm>
43 #include <cassert>
44 #include <cstddef>
45 #include <cstdint>
46 #include <cstring>
47 #include <ctime>
48 #include <memory>
49 #include <string>
50 #include <vector>
52 using namespace llvm;
53 using llvm::support::endian::write32le;
55 #define DEBUG_TYPE "WinCOFFObjectWriter"
57 namespace {
59 using name = SmallString<COFF::NameSize>;
61 enum AuxiliaryType {
62 ATWeakExternal,
63 ATFile,
64 ATSectionDefinition
67 struct AuxSymbol {
68 AuxiliaryType AuxType;
69 COFF::Auxiliary Aux;
72 class COFFSection;
74 class COFFSymbol {
75 public:
76 COFF::symbol Data = {};
78 using AuxiliarySymbols = SmallVector<AuxSymbol, 1>;
80 name Name;
81 int Index;
82 AuxiliarySymbols Aux;
83 COFFSymbol *Other = nullptr;
84 COFFSection *Section = nullptr;
85 int Relocations = 0;
86 const MCSymbol *MC = nullptr;
88 COFFSymbol(StringRef Name) : Name(Name) {}
90 void set_name_offset(uint32_t Offset);
92 int64_t getIndex() const { return Index; }
93 void setIndex(int Value) {
94 Index = Value;
95 if (MC)
96 MC->setIndex(static_cast<uint32_t>(Value));
100 // This class contains staging data for a COFF relocation entry.
101 struct COFFRelocation {
102 COFF::relocation Data;
103 COFFSymbol *Symb = nullptr;
105 COFFRelocation() = default;
107 static size_t size() { return COFF::RelocationSize; }
110 using relocations = std::vector<COFFRelocation>;
112 class COFFSection {
113 public:
114 COFF::section Header = {};
116 std::string Name;
117 int Number;
118 MCSectionCOFF const *MCSection = nullptr;
119 COFFSymbol *Symbol = nullptr;
120 relocations Relocations;
122 COFFSection(StringRef Name) : Name(Name) {}
125 class WinCOFFObjectWriter : public MCObjectWriter {
126 public:
127 support::endian::Writer W;
129 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
130 using sections = std::vector<std::unique_ptr<COFFSection>>;
132 using symbol_map = DenseMap<MCSymbol const *, COFFSymbol *>;
133 using section_map = DenseMap<MCSection const *, COFFSection *>;
135 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
137 // Root level file contents.
138 COFF::header Header = {};
139 sections Sections;
140 symbols Symbols;
141 StringTableBuilder Strings{StringTableBuilder::WinCOFF};
143 // Maps used during object file creation.
144 section_map SectionMap;
145 symbol_map SymbolMap;
147 bool UseBigObj;
149 bool EmitAddrsigSection = false;
150 MCSectionCOFF *AddrsigSection;
151 std::vector<const MCSymbol *> AddrsigSyms;
153 WinCOFFObjectWriter(std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW,
154 raw_pwrite_stream &OS);
156 void reset() override {
157 memset(&Header, 0, sizeof(Header));
158 Header.Machine = TargetObjectWriter->getMachine();
159 Sections.clear();
160 Symbols.clear();
161 Strings.clear();
162 SectionMap.clear();
163 SymbolMap.clear();
164 MCObjectWriter::reset();
167 COFFSymbol *createSymbol(StringRef Name);
168 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
169 COFFSection *createSection(StringRef Name);
171 void defineSection(MCSectionCOFF const &Sec);
173 COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
174 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
175 const MCAsmLayout &Layout);
177 void SetSymbolName(COFFSymbol &S);
178 void SetSectionName(COFFSection &S);
180 bool IsPhysicalSection(COFFSection *S);
182 // Entity writing methods.
184 void WriteFileHeader(const COFF::header &Header);
185 void WriteSymbol(const COFFSymbol &S);
186 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
187 void writeSectionHeaders();
188 void WriteRelocation(const COFF::relocation &R);
189 uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
190 const MCSection &MCSec);
191 void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
192 const COFFSection &Sec, const MCSection &MCSec);
194 // MCObjectWriter interface implementation.
196 void executePostLayoutBinding(MCAssembler &Asm,
197 const MCAsmLayout &Layout) override;
199 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
200 const MCSymbol &SymA,
201 const MCFragment &FB, bool InSet,
202 bool IsPCRel) const override;
204 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
205 const MCFragment *Fragment, const MCFixup &Fixup,
206 MCValue Target, uint64_t &FixedValue) override;
208 void createFileSymbols(MCAssembler &Asm);
209 void assignSectionNumbers();
210 void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
212 void emitAddrsigSection() override { EmitAddrsigSection = true; }
213 void addAddrsigSymbol(const MCSymbol *Sym) override {
214 AddrsigSyms.push_back(Sym);
217 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
220 } // end anonymous namespace
222 //------------------------------------------------------------------------------
223 // Symbol class implementation
225 // In the case that the name does not fit within 8 bytes, the offset
226 // into the string table is stored in the last 4 bytes instead, leaving
227 // the first 4 bytes as 0.
228 void COFFSymbol::set_name_offset(uint32_t Offset) {
229 write32le(Data.Name + 0, 0);
230 write32le(Data.Name + 4, Offset);
233 //------------------------------------------------------------------------------
234 // WinCOFFObjectWriter class implementation
236 WinCOFFObjectWriter::WinCOFFObjectWriter(
237 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
238 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {
239 Header.Machine = TargetObjectWriter->getMachine();
242 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
243 Symbols.push_back(make_unique<COFFSymbol>(Name));
244 return Symbols.back().get();
247 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
248 COFFSymbol *&Ret = SymbolMap[Symbol];
249 if (!Ret)
250 Ret = createSymbol(Symbol->getName());
251 return Ret;
254 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
255 Sections.emplace_back(make_unique<COFFSection>(Name));
256 return Sections.back().get();
259 static uint32_t getAlignment(const MCSectionCOFF &Sec) {
260 switch (Sec.getAlignment()) {
261 case 1:
262 return COFF::IMAGE_SCN_ALIGN_1BYTES;
263 case 2:
264 return COFF::IMAGE_SCN_ALIGN_2BYTES;
265 case 4:
266 return COFF::IMAGE_SCN_ALIGN_4BYTES;
267 case 8:
268 return COFF::IMAGE_SCN_ALIGN_8BYTES;
269 case 16:
270 return COFF::IMAGE_SCN_ALIGN_16BYTES;
271 case 32:
272 return COFF::IMAGE_SCN_ALIGN_32BYTES;
273 case 64:
274 return COFF::IMAGE_SCN_ALIGN_64BYTES;
275 case 128:
276 return COFF::IMAGE_SCN_ALIGN_128BYTES;
277 case 256:
278 return COFF::IMAGE_SCN_ALIGN_256BYTES;
279 case 512:
280 return COFF::IMAGE_SCN_ALIGN_512BYTES;
281 case 1024:
282 return COFF::IMAGE_SCN_ALIGN_1024BYTES;
283 case 2048:
284 return COFF::IMAGE_SCN_ALIGN_2048BYTES;
285 case 4096:
286 return COFF::IMAGE_SCN_ALIGN_4096BYTES;
287 case 8192:
288 return COFF::IMAGE_SCN_ALIGN_8192BYTES;
290 llvm_unreachable("unsupported section alignment");
293 /// This function takes a section data object from the assembler
294 /// and creates the associated COFF section staging object.
295 void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
296 COFFSection *Section = createSection(MCSec.getSectionName());
297 COFFSymbol *Symbol = createSymbol(MCSec.getSectionName());
298 Section->Symbol = Symbol;
299 Symbol->Section = Section;
300 Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
302 // Create a COMDAT symbol if needed.
303 if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
304 if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
305 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
306 if (COMDATSymbol->Section)
307 report_fatal_error("two sections have the same comdat");
308 COMDATSymbol->Section = Section;
312 // In this case the auxiliary symbol is a Section Definition.
313 Symbol->Aux.resize(1);
314 Symbol->Aux[0] = {};
315 Symbol->Aux[0].AuxType = ATSectionDefinition;
316 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
318 // Set section alignment.
319 Section->Header.Characteristics = MCSec.getCharacteristics();
320 Section->Header.Characteristics |= getAlignment(MCSec);
322 // Bind internal COFF section to MC section.
323 Section->MCSection = &MCSec;
324 SectionMap[&MCSec] = Section;
327 static uint64_t getSymbolValue(const MCSymbol &Symbol,
328 const MCAsmLayout &Layout) {
329 if (Symbol.isCommon() && Symbol.isExternal())
330 return Symbol.getCommonSize();
332 uint64_t Res;
333 if (!Layout.getSymbolOffset(Symbol, Res))
334 return 0;
336 return Res;
339 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
340 if (!Symbol.isVariable())
341 return nullptr;
343 const MCSymbolRefExpr *SymRef =
344 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
345 if (!SymRef)
346 return nullptr;
348 const MCSymbol &Aliasee = SymRef->getSymbol();
349 if (!Aliasee.isUndefined())
350 return nullptr;
351 return GetOrCreateCOFFSymbol(&Aliasee);
354 /// This function takes a symbol data object from the assembler
355 /// and creates the associated COFF symbol staging object.
356 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
357 MCAssembler &Assembler,
358 const MCAsmLayout &Layout) {
359 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
360 const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
361 COFFSection *Sec = nullptr;
362 if (Base && Base->getFragment()) {
363 Sec = SectionMap[Base->getFragment()->getParent()];
364 if (Sym->Section && Sym->Section != Sec)
365 report_fatal_error("conflicting sections for symbol");
368 COFFSymbol *Local = nullptr;
369 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
370 Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
372 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
373 if (!WeakDefault) {
374 std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
375 WeakDefault = createSymbol(WeakName);
376 if (!Sec)
377 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
378 else
379 WeakDefault->Section = Sec;
380 Local = WeakDefault;
383 Sym->Other = WeakDefault;
385 // Setup the Weak External auxiliary symbol.
386 Sym->Aux.resize(1);
387 memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
388 Sym->Aux[0].AuxType = ATWeakExternal;
389 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
390 Sym->Aux[0].Aux.WeakExternal.Characteristics =
391 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
392 } else {
393 if (!Base)
394 Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
395 else
396 Sym->Section = Sec;
397 Local = Sym;
400 if (Local) {
401 Local->Data.Value = getSymbolValue(MCSym, Layout);
403 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
404 Local->Data.Type = SymbolCOFF.getType();
405 Local->Data.StorageClass = SymbolCOFF.getClass();
407 // If no storage class was specified in the streamer, define it here.
408 if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
409 bool IsExternal = MCSym.isExternal() ||
410 (!MCSym.getFragment() && !MCSym.isVariable());
412 Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
413 : COFF::IMAGE_SYM_CLASS_STATIC;
417 Sym->MC = &MCSym;
420 // Maximum offsets for different string table entry encodings.
421 enum : unsigned { Max7DecimalOffset = 9999999U };
422 enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
424 // Encode a string table entry offset in base 64, padded to 6 chars, and
425 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
426 // Buffer must be at least 8 bytes large. No terminating null appended.
427 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
428 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
429 "Illegal section name encoding for value");
431 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
432 "abcdefghijklmnopqrstuvwxyz"
433 "0123456789+/";
435 Buffer[0] = '/';
436 Buffer[1] = '/';
438 char *Ptr = Buffer + 7;
439 for (unsigned i = 0; i < 6; ++i) {
440 unsigned Rem = Value % 64;
441 Value /= 64;
442 *(Ptr--) = Alphabet[Rem];
446 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
447 if (S.Name.size() <= COFF::NameSize) {
448 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
449 return;
452 uint64_t StringTableEntry = Strings.getOffset(S.Name);
453 if (StringTableEntry <= Max7DecimalOffset) {
454 SmallVector<char, COFF::NameSize> Buffer;
455 Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
456 assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
457 std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
458 return;
460 if (StringTableEntry <= MaxBase64Offset) {
461 // Starting with 10,000,000, offsets are encoded as base64.
462 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
463 return;
465 report_fatal_error("COFF string table is greater than 64 GB.");
468 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
469 if (S.Name.size() > COFF::NameSize)
470 S.set_name_offset(Strings.getOffset(S.Name));
471 else
472 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
475 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
476 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
480 //------------------------------------------------------------------------------
481 // entity writing methods
483 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
484 if (UseBigObj) {
485 W.write<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
486 W.write<uint16_t>(0xFFFF);
487 W.write<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion);
488 W.write<uint16_t>(Header.Machine);
489 W.write<uint32_t>(Header.TimeDateStamp);
490 W.OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
491 W.write<uint32_t>(0);
492 W.write<uint32_t>(0);
493 W.write<uint32_t>(0);
494 W.write<uint32_t>(0);
495 W.write<uint32_t>(Header.NumberOfSections);
496 W.write<uint32_t>(Header.PointerToSymbolTable);
497 W.write<uint32_t>(Header.NumberOfSymbols);
498 } else {
499 W.write<uint16_t>(Header.Machine);
500 W.write<uint16_t>(static_cast<int16_t>(Header.NumberOfSections));
501 W.write<uint32_t>(Header.TimeDateStamp);
502 W.write<uint32_t>(Header.PointerToSymbolTable);
503 W.write<uint32_t>(Header.NumberOfSymbols);
504 W.write<uint16_t>(Header.SizeOfOptionalHeader);
505 W.write<uint16_t>(Header.Characteristics);
509 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
510 W.OS.write(S.Data.Name, COFF::NameSize);
511 W.write<uint32_t>(S.Data.Value);
512 if (UseBigObj)
513 W.write<uint32_t>(S.Data.SectionNumber);
514 else
515 W.write<uint16_t>(static_cast<int16_t>(S.Data.SectionNumber));
516 W.write<uint16_t>(S.Data.Type);
517 W.OS << char(S.Data.StorageClass);
518 W.OS << char(S.Data.NumberOfAuxSymbols);
519 WriteAuxiliarySymbols(S.Aux);
522 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
523 const COFFSymbol::AuxiliarySymbols &S) {
524 for (const AuxSymbol &i : S) {
525 switch (i.AuxType) {
526 case ATWeakExternal:
527 W.write<uint32_t>(i.Aux.WeakExternal.TagIndex);
528 W.write<uint32_t>(i.Aux.WeakExternal.Characteristics);
529 W.OS.write_zeros(sizeof(i.Aux.WeakExternal.unused));
530 if (UseBigObj)
531 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
532 break;
533 case ATFile:
534 W.OS.write(reinterpret_cast<const char *>(&i.Aux),
535 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size);
536 break;
537 case ATSectionDefinition:
538 W.write<uint32_t>(i.Aux.SectionDefinition.Length);
539 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
540 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
541 W.write<uint32_t>(i.Aux.SectionDefinition.CheckSum);
542 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
543 W.OS << char(i.Aux.SectionDefinition.Selection);
544 W.OS.write_zeros(sizeof(i.Aux.SectionDefinition.unused));
545 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
546 if (UseBigObj)
547 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
548 break;
553 // Write the section header.
554 void WinCOFFObjectWriter::writeSectionHeaders() {
555 // Section numbers must be monotonically increasing in the section
556 // header, but our Sections array is not sorted by section number,
557 // so make a copy of Sections and sort it.
558 std::vector<COFFSection *> Arr;
559 for (auto &Section : Sections)
560 Arr.push_back(Section.get());
561 llvm::sort(Arr.begin(), Arr.end(),
562 [](const COFFSection *A, const COFFSection *B) {
563 return A->Number < B->Number;
566 for (auto &Section : Arr) {
567 if (Section->Number == -1)
568 continue;
570 COFF::section &S = Section->Header;
571 if (Section->Relocations.size() >= 0xffff)
572 S.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
573 W.OS.write(S.Name, COFF::NameSize);
574 W.write<uint32_t>(S.VirtualSize);
575 W.write<uint32_t>(S.VirtualAddress);
576 W.write<uint32_t>(S.SizeOfRawData);
577 W.write<uint32_t>(S.PointerToRawData);
578 W.write<uint32_t>(S.PointerToRelocations);
579 W.write<uint32_t>(S.PointerToLineNumbers);
580 W.write<uint16_t>(S.NumberOfRelocations);
581 W.write<uint16_t>(S.NumberOfLineNumbers);
582 W.write<uint32_t>(S.Characteristics);
586 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
587 W.write<uint32_t>(R.VirtualAddress);
588 W.write<uint32_t>(R.SymbolTableIndex);
589 W.write<uint16_t>(R.Type);
592 // Write MCSec's contents. What this function does is essentially
593 // "Asm.writeSectionData(&MCSec, Layout)", but it's a bit complicated
594 // because it needs to compute a CRC.
595 uint32_t WinCOFFObjectWriter::writeSectionContents(MCAssembler &Asm,
596 const MCAsmLayout &Layout,
597 const MCSection &MCSec) {
598 // Save the contents of the section to a temporary buffer, we need this
599 // to CRC the data before we dump it into the object file.
600 SmallVector<char, 128> Buf;
601 raw_svector_ostream VecOS(Buf);
602 Asm.writeSectionData(VecOS, &MCSec, Layout);
604 // Write the section contents to the object file.
605 W.OS << Buf;
607 // Calculate our CRC with an initial value of '0', this is not how
608 // JamCRC is specified but it aligns with the expected output.
609 JamCRC JC(/*Init=*/0);
610 JC.update(Buf);
611 return JC.getCRC();
614 void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
615 const MCAsmLayout &Layout,
616 const COFFSection &Sec,
617 const MCSection &MCSec) {
618 if (Sec.Number == -1)
619 return;
621 // Write the section contents.
622 if (Sec.Header.PointerToRawData != 0) {
623 assert(W.OS.tell() == Sec.Header.PointerToRawData &&
624 "Section::PointerToRawData is insane!");
626 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
628 // Update the section definition auxiliary symbol to record the CRC.
629 COFFSection *Sec = SectionMap[&MCSec];
630 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
631 assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
632 AuxSymbol &SecDef = AuxSyms[0];
633 SecDef.Aux.SectionDefinition.CheckSum = CRC;
636 // Write relocations for this section.
637 if (Sec.Relocations.empty()) {
638 assert(Sec.Header.PointerToRelocations == 0 &&
639 "Section::PointerToRelocations is insane!");
640 return;
643 assert(W.OS.tell() == Sec.Header.PointerToRelocations &&
644 "Section::PointerToRelocations is insane!");
646 if (Sec.Relocations.size() >= 0xffff) {
647 // In case of overflow, write actual relocation count as first
648 // relocation. Including the synthetic reloc itself (+ 1).
649 COFF::relocation R;
650 R.VirtualAddress = Sec.Relocations.size() + 1;
651 R.SymbolTableIndex = 0;
652 R.Type = 0;
653 WriteRelocation(R);
656 for (const auto &Relocation : Sec.Relocations)
657 WriteRelocation(Relocation.Data);
660 ////////////////////////////////////////////////////////////////////////////////
661 // MCObjectWriter interface implementations
663 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
664 const MCAsmLayout &Layout) {
665 if (EmitAddrsigSection) {
666 AddrsigSection = Asm.getContext().getCOFFSection(
667 ".llvm_addrsig", COFF::IMAGE_SCN_LNK_REMOVE,
668 SectionKind::getMetadata());
669 Asm.registerSection(*AddrsigSection);
672 // "Define" each section & symbol. This creates section & symbol
673 // entries in the staging area.
674 for (const auto &Section : Asm)
675 defineSection(static_cast<const MCSectionCOFF &>(Section));
677 for (const MCSymbol &Symbol : Asm.symbols())
678 if (!Symbol.isTemporary())
679 DefineSymbol(Symbol, Asm, Layout);
682 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
683 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
684 bool InSet, bool IsPCRel) const {
685 // Don't drop relocations between functions, even if they are in the same text
686 // section. Multiple Visual C++ linker features depend on having the
687 // relocations present. The /INCREMENTAL flag will cause these relocations to
688 // point to thunks, and the /GUARD:CF flag assumes that it can use relocations
689 // to approximate the set of all address taken functions. LLD's implementation
690 // of /GUARD:CF also relies on the existance of these relocations.
691 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
692 if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
693 return false;
694 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
695 InSet, IsPCRel);
698 void WinCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
699 const MCAsmLayout &Layout,
700 const MCFragment *Fragment,
701 const MCFixup &Fixup, MCValue Target,
702 uint64_t &FixedValue) {
703 assert(Target.getSymA() && "Relocation must reference a symbol!");
705 const MCSymbol &A = Target.getSymA()->getSymbol();
706 if (!A.isRegistered()) {
707 Asm.getContext().reportError(Fixup.getLoc(),
708 Twine("symbol '") + A.getName() +
709 "' can not be undefined");
710 return;
712 if (A.isTemporary() && A.isUndefined()) {
713 Asm.getContext().reportError(Fixup.getLoc(),
714 Twine("assembler label '") + A.getName() +
715 "' can not be undefined");
716 return;
719 MCSection *MCSec = Fragment->getParent();
721 // Mark this symbol as requiring an entry in the symbol table.
722 assert(SectionMap.find(MCSec) != SectionMap.end() &&
723 "Section must already have been defined in executePostLayoutBinding!");
725 COFFSection *Sec = SectionMap[MCSec];
726 const MCSymbolRefExpr *SymB = Target.getSymB();
728 if (SymB) {
729 const MCSymbol *B = &SymB->getSymbol();
730 if (!B->getFragment()) {
731 Asm.getContext().reportError(
732 Fixup.getLoc(),
733 Twine("symbol '") + B->getName() +
734 "' can not be undefined in a subtraction expression");
735 return;
738 // Offset of the symbol in the section
739 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
741 // Offset of the relocation in the section
742 int64_t OffsetOfRelocation =
743 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
745 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
746 } else {
747 FixedValue = Target.getConstant();
750 COFFRelocation Reloc;
752 Reloc.Data.SymbolTableIndex = 0;
753 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
755 // Turn relocations for temporary symbols into section relocations.
756 if (A.isTemporary()) {
757 MCSection *TargetSection = &A.getSection();
758 assert(
759 SectionMap.find(TargetSection) != SectionMap.end() &&
760 "Section must already have been defined in executePostLayoutBinding!");
761 Reloc.Symb = SectionMap[TargetSection]->Symbol;
762 FixedValue += Layout.getSymbolOffset(A);
763 } else {
764 assert(
765 SymbolMap.find(&A) != SymbolMap.end() &&
766 "Symbol must already have been defined in executePostLayoutBinding!");
767 Reloc.Symb = SymbolMap[&A];
770 ++Reloc.Symb->Relocations;
772 Reloc.Data.VirtualAddress += Fixup.getOffset();
773 Reloc.Data.Type = TargetObjectWriter->getRelocType(
774 Asm.getContext(), Target, Fixup, SymB, Asm.getBackend());
776 // FIXME: Can anyone explain what this does other than adjust for the size
777 // of the offset?
778 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
779 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
780 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
781 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
782 FixedValue += 4;
784 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
785 switch (Reloc.Data.Type) {
786 case COFF::IMAGE_REL_ARM_ABSOLUTE:
787 case COFF::IMAGE_REL_ARM_ADDR32:
788 case COFF::IMAGE_REL_ARM_ADDR32NB:
789 case COFF::IMAGE_REL_ARM_TOKEN:
790 case COFF::IMAGE_REL_ARM_SECTION:
791 case COFF::IMAGE_REL_ARM_SECREL:
792 break;
793 case COFF::IMAGE_REL_ARM_BRANCH11:
794 case COFF::IMAGE_REL_ARM_BLX11:
795 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
796 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
797 // for Windows CE).
798 case COFF::IMAGE_REL_ARM_BRANCH24:
799 case COFF::IMAGE_REL_ARM_BLX24:
800 case COFF::IMAGE_REL_ARM_MOV32A:
801 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
802 // only used for ARM mode code, which is documented as being unsupported
803 // by Windows on ARM. Empirical proof indicates that masm is able to
804 // generate the relocations however the rest of the MSVC toolchain is
805 // unable to handle it.
806 llvm_unreachable("unsupported relocation");
807 break;
808 case COFF::IMAGE_REL_ARM_MOV32T:
809 break;
810 case COFF::IMAGE_REL_ARM_BRANCH20T:
811 case COFF::IMAGE_REL_ARM_BRANCH24T:
812 case COFF::IMAGE_REL_ARM_BLX23T:
813 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
814 // perform a 4 byte adjustment to the relocation. Relative branches are
815 // offset by 4 on ARM, however, because there is no RELA relocations, all
816 // branches are offset by 4.
817 FixedValue = FixedValue + 4;
818 break;
822 // The fixed value never makes sense for section indices, ignore it.
823 if (Fixup.getKind() == FK_SecRel_2)
824 FixedValue = 0;
826 if (TargetObjectWriter->recordRelocation(Fixup))
827 Sec->Relocations.push_back(Reloc);
830 static std::time_t getTime() {
831 std::time_t Now = time(nullptr);
832 if (Now < 0 || !isUInt<32>(Now))
833 return UINT32_MAX;
834 return Now;
837 // Create .file symbols.
838 void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
839 for (const std::string &Name : Asm.getFileNames()) {
840 // round up to calculate the number of auxiliary symbols required
841 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
842 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
844 COFFSymbol *File = createSymbol(".file");
845 File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
846 File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
847 File->Aux.resize(Count);
849 unsigned Offset = 0;
850 unsigned Length = Name.size();
851 for (auto &Aux : File->Aux) {
852 Aux.AuxType = ATFile;
854 if (Length > SymbolSize) {
855 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
856 Length = Length - SymbolSize;
857 } else {
858 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
859 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
860 break;
863 Offset += SymbolSize;
868 static bool isAssociative(const COFFSection &Section) {
869 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
870 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
873 void WinCOFFObjectWriter::assignSectionNumbers() {
874 size_t I = 1;
875 auto Assign = [&](COFFSection &Section) {
876 Section.Number = I;
877 Section.Symbol->Data.SectionNumber = I;
878 Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
879 ++I;
882 // Although it is not explicitly requested by the Microsoft COFF spec,
883 // we should avoid emitting forward associative section references,
884 // because MSVC link.exe as of 2017 cannot handle that.
885 for (const std::unique_ptr<COFFSection> &Section : Sections)
886 if (!isAssociative(*Section))
887 Assign(*Section);
888 for (const std::unique_ptr<COFFSection> &Section : Sections)
889 if (isAssociative(*Section))
890 Assign(*Section);
893 // Assign file offsets to COFF object file structures.
894 void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
895 const MCAsmLayout &Layout) {
896 unsigned Offset = W.OS.tell();
898 Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
899 Offset += COFF::SectionSize * Header.NumberOfSections;
901 for (const auto &Section : Asm) {
902 COFFSection *Sec = SectionMap[&Section];
904 if (Sec->Number == -1)
905 continue;
907 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
909 if (IsPhysicalSection(Sec)) {
910 Sec->Header.PointerToRawData = Offset;
911 Offset += Sec->Header.SizeOfRawData;
914 if (!Sec->Relocations.empty()) {
915 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
917 if (RelocationsOverflow) {
918 // Signal overflow by setting NumberOfRelocations to max value. Actual
919 // size is found in reloc #0. Microsoft tools understand this.
920 Sec->Header.NumberOfRelocations = 0xffff;
921 } else {
922 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
924 Sec->Header.PointerToRelocations = Offset;
926 if (RelocationsOverflow) {
927 // Reloc #0 will contain actual count, so make room for it.
928 Offset += COFF::RelocationSize;
931 Offset += COFF::RelocationSize * Sec->Relocations.size();
933 for (auto &Relocation : Sec->Relocations) {
934 assert(Relocation.Symb->getIndex() != -1);
935 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
939 assert(Sec->Symbol->Aux.size() == 1 &&
940 "Section's symbol must have one aux!");
941 AuxSymbol &Aux = Sec->Symbol->Aux[0];
942 assert(Aux.AuxType == ATSectionDefinition &&
943 "Section's symbol's aux symbol must be a Section Definition!");
944 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
945 Aux.Aux.SectionDefinition.NumberOfRelocations =
946 Sec->Header.NumberOfRelocations;
947 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
948 Sec->Header.NumberOfLineNumbers;
951 Header.PointerToSymbolTable = Offset;
954 uint64_t WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
955 const MCAsmLayout &Layout) {
956 uint64_t StartOffset = W.OS.tell();
958 if (Sections.size() > INT32_MAX)
959 report_fatal_error(
960 "PE COFF object files can't have more than 2147483647 sections");
962 UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
963 Header.NumberOfSections = Sections.size();
964 Header.NumberOfSymbols = 0;
966 assignSectionNumbers();
967 createFileSymbols(Asm);
969 for (auto &Symbol : Symbols) {
970 // Update section number & offset for symbols that have them.
971 if (Symbol->Section)
972 Symbol->Data.SectionNumber = Symbol->Section->Number;
973 Symbol->setIndex(Header.NumberOfSymbols++);
974 // Update auxiliary symbol info.
975 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
976 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
979 // Build string table.
980 for (const auto &S : Sections)
981 if (S->Name.size() > COFF::NameSize)
982 Strings.add(S->Name);
983 for (const auto &S : Symbols)
984 if (S->Name.size() > COFF::NameSize)
985 Strings.add(S->Name);
986 Strings.finalize();
988 // Set names.
989 for (const auto &S : Sections)
990 SetSectionName(*S);
991 for (auto &S : Symbols)
992 SetSymbolName(*S);
994 // Fixup weak external references.
995 for (auto &Symbol : Symbols) {
996 if (Symbol->Other) {
997 assert(Symbol->getIndex() != -1);
998 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
999 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1000 "Symbol's aux symbol must be a Weak External!");
1001 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1005 // Fixup associative COMDAT sections.
1006 for (auto &Section : Sections) {
1007 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1008 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1009 continue;
1011 const MCSectionCOFF &MCSec = *Section->MCSection;
1012 const MCSymbol *AssocMCSym = MCSec.getCOMDATSymbol();
1013 assert(AssocMCSym);
1015 // It's an error to try to associate with an undefined symbol or a symbol
1016 // without a section.
1017 if (!AssocMCSym->isInSection()) {
1018 Asm.getContext().reportError(
1019 SMLoc(), Twine("cannot make section ") + MCSec.getSectionName() +
1020 Twine(" associative with sectionless symbol ") +
1021 AssocMCSym->getName());
1022 continue;
1025 const auto *AssocMCSec = cast<MCSectionCOFF>(&AssocMCSym->getSection());
1026 assert(SectionMap.count(AssocMCSec));
1027 COFFSection *AssocSec = SectionMap[AssocMCSec];
1029 // Skip this section if the associated section is unused.
1030 if (AssocSec->Number == -1)
1031 continue;
1033 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = AssocSec->Number;
1036 // Create the contents of the .llvm_addrsig section.
1037 if (EmitAddrsigSection) {
1038 auto Frag = new MCDataFragment(AddrsigSection);
1039 Frag->setLayoutOrder(0);
1040 raw_svector_ostream OS(Frag->getContents());
1041 for (const MCSymbol *S : AddrsigSyms) {
1042 if (!S->isTemporary()) {
1043 encodeULEB128(S->getIndex(), OS);
1044 continue;
1047 MCSection *TargetSection = &S->getSection();
1048 assert(SectionMap.find(TargetSection) != SectionMap.end() &&
1049 "Section must already have been defined in "
1050 "executePostLayoutBinding!");
1051 encodeULEB128(SectionMap[TargetSection]->Symbol->getIndex(), OS);
1055 assignFileOffsets(Asm, Layout);
1057 // MS LINK expects to be able to use this timestamp to implement their
1058 // /INCREMENTAL feature.
1059 if (Asm.isIncrementalLinkerCompatible()) {
1060 Header.TimeDateStamp = getTime();
1061 } else {
1062 // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1063 Header.TimeDateStamp = 0;
1066 // Write it all to disk...
1067 WriteFileHeader(Header);
1068 writeSectionHeaders();
1070 // Write section contents.
1071 sections::iterator I = Sections.begin();
1072 sections::iterator IE = Sections.end();
1073 MCAssembler::iterator J = Asm.begin();
1074 MCAssembler::iterator JE = Asm.end();
1075 for (; I != IE && J != JE; ++I, ++J)
1076 writeSection(Asm, Layout, **I, *J);
1078 assert(W.OS.tell() == Header.PointerToSymbolTable &&
1079 "Header::PointerToSymbolTable is insane!");
1081 // Write a symbol table.
1082 for (auto &Symbol : Symbols)
1083 if (Symbol->getIndex() != -1)
1084 WriteSymbol(*Symbol);
1086 // Write a string table, which completes the entire COFF file.
1087 Strings.write(W.OS);
1089 return W.OS.tell() - StartOffset;
1092 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1093 : Machine(Machine_) {}
1095 // Pin the vtable to this file.
1096 void MCWinCOFFObjectTargetWriter::anchor() {}
1098 //------------------------------------------------------------------------------
1099 // WinCOFFObjectWriter factory function
1101 std::unique_ptr<MCObjectWriter> llvm::createWinCOFFObjectWriter(
1102 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS) {
1103 return llvm::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS);