LLVM 20.0.0git
WinCOFFObjectWriter.cpp
Go to the documentation of this file.
1//===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains an implementation of a Win32 COFF object file writer.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/DenseSet.h"
15#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
21#include "llvm/MC/MCAssembler.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCFixup.h"
25#include "llvm/MC/MCFragment.h"
27#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCSymbol.h"
31#include "llvm/MC/MCValue.h"
34#include "llvm/Support/CRC.h"
38#include "llvm/Support/LEB128.h"
41#include <cassert>
42#include <cstdint>
43#include <cstring>
44#include <ctime>
45#include <memory>
46#include <string>
47#include <vector>
48
49using namespace llvm;
51
52#define DEBUG_TYPE "WinCOFFObjectWriter"
53
54namespace {
55
56constexpr int OffsetLabelIntervalBits = 20;
57
59
60enum AuxiliaryType { ATWeakExternal, ATFile, ATSectionDefinition };
61
62struct AuxSymbol {
63 AuxiliaryType AuxType;
65};
66
67class COFFSection;
68
69class COFFSymbol {
70public:
71 COFF::symbol Data = {};
72
73 using AuxiliarySymbols = SmallVector<AuxSymbol, 1>;
74
75 name Name;
76 int Index = 0;
77 AuxiliarySymbols Aux;
78 COFFSymbol *Other = nullptr;
79 COFFSection *Section = nullptr;
80 int Relocations = 0;
81 const MCSymbol *MC = nullptr;
82
83 COFFSymbol(StringRef Name) : Name(Name) {}
84
85 void set_name_offset(uint32_t Offset);
86
87 int64_t getIndex() const { return Index; }
88 void setIndex(int Value) {
89 Index = Value;
90 if (MC)
91 MC->setIndex(static_cast<uint32_t>(Value));
92 }
93};
94
95// This class contains staging data for a COFF relocation entry.
96struct COFFRelocation {
98 COFFSymbol *Symb = nullptr;
99
100 COFFRelocation() = default;
101
102 static size_t size() { return COFF::RelocationSize; }
103};
104
105using relocations = std::vector<COFFRelocation>;
106
107class COFFSection {
108public:
109 COFF::section Header = {};
110
111 std::string Name;
112 int Number = 0;
113 MCSectionCOFF const *MCSection = nullptr;
114 COFFSymbol *Symbol = nullptr;
115 relocations Relocations;
116
117 COFFSection(StringRef Name) : Name(std::string(Name)) {}
118
119 SmallVector<COFFSymbol *, 1> OffsetSymbols;
120};
121} // namespace
122
124 WinCOFFObjectWriter &OWriter;
126
127 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
128 using sections = std::vector<std::unique_ptr<COFFSection>>;
129
132
134
135 // Root level file contents.
136 COFF::header Header = {};
137 sections Sections;
138 symbols Symbols;
140
141 // Maps used during object file creation.
142 section_map SectionMap;
143 symbol_map SymbolMap;
144
145 symbol_list WeakDefaults;
146
147 bool UseBigObj;
148 bool UseOffsetLabels = false;
149
150public:
151 enum DwoMode {
156
158 DwoMode Mode);
159
160 void reset();
162 void recordRelocation(MCAssembler &Asm, const MCFragment *Fragment,
163 const MCFixup &Fixup, MCValue Target,
164 uint64_t &FixedValue);
166
167private:
168 COFFSymbol *createSymbol(StringRef Name);
169 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
170 COFFSection *createSection(StringRef Name);
171
172 void defineSection(const MCAssembler &Asm, MCSectionCOFF const &Sec);
173
174 COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
175 void defineSymbol(const MCAssembler &Asm, const MCSymbol &Symbol);
176
177 void SetSymbolName(COFFSymbol &S);
178 void SetSectionName(COFFSection &S);
179
180 bool IsPhysicalSection(COFFSection *S);
181
182 // Entity writing methods.
183 void WriteFileHeader(const COFF::header &Header);
184 void WriteSymbol(const COFFSymbol &S);
185 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
186 void writeSectionHeaders();
187 void WriteRelocation(const COFF::relocation &R);
188 uint32_t writeSectionContents(MCAssembler &Asm, const MCSection &MCSec);
189 void writeSection(MCAssembler &Asm, const COFFSection &Sec);
190
191 void createFileSymbols(MCAssembler &Asm);
192 void setWeakDefaultNames();
193 void assignSectionNumbers();
194 void assignFileOffsets(MCAssembler &Asm);
195};
196
198 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
199 : TargetObjectWriter(std::move(MOTW)),
200 ObjWriter(std::make_unique<WinCOFFWriter>(*this, OS,
201 WinCOFFWriter::AllSections)) {}
203 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS,
204 raw_pwrite_stream &DwoOS)
205 : TargetObjectWriter(std::move(MOTW)),
206 ObjWriter(std::make_unique<WinCOFFWriter>(*this, OS,
207 WinCOFFWriter::NonDwoOnly)),
208 DwoWriter(std::make_unique<WinCOFFWriter>(*this, DwoOS,
209 WinCOFFWriter::DwoOnly)) {}
210
211static bool isDwoSection(const MCSection &Sec) {
212 return Sec.getName().ends_with(".dwo");
213}
214
215//------------------------------------------------------------------------------
216// Symbol class implementation
217
218// In the case that the name does not fit within 8 bytes, the offset
219// into the string table is stored in the last 4 bytes instead, leaving
220// the first 4 bytes as 0.
221void COFFSymbol::set_name_offset(uint32_t Offset) {
222 write32le(Data.Name + 0, 0);
223 write32le(Data.Name + 4, Offset);
224}
225
226//------------------------------------------------------------------------------
227// WinCOFFWriter class implementation
228
231 : OWriter(OWriter), W(OS, llvm::endianness::little), Mode(Mode) {
232 Header.Machine = OWriter.TargetObjectWriter->getMachine();
233 // Some relocations on ARM64 (the 21 bit ADRP relocations) have a slightly
234 // limited range for the immediate offset (+/- 1 MB); create extra offset
235 // label symbols with regular intervals to allow referencing a
236 // non-temporary symbol that is close enough.
237 UseOffsetLabels = COFF::isAnyArm64(Header.Machine);
238}
239
240COFFSymbol *WinCOFFWriter::createSymbol(StringRef Name) {
241 Symbols.push_back(std::make_unique<COFFSymbol>(Name));
242 return Symbols.back().get();
243}
244
245COFFSymbol *WinCOFFWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
246 COFFSymbol *&Ret = SymbolMap[Symbol];
247 if (!Ret)
248 Ret = createSymbol(Symbol->getName());
249 return Ret;
250}
251
252COFFSection *WinCOFFWriter::createSection(StringRef Name) {
253 Sections.emplace_back(std::make_unique<COFFSection>(Name));
254 return Sections.back().get();
255}
256
258 switch (Sec.getAlign().value()) {
259 case 1:
261 case 2:
263 case 4:
265 case 8:
267 case 16:
269 case 32:
271 case 64:
273 case 128:
275 case 256:
277 case 512:
279 case 1024:
281 case 2048:
283 case 4096:
285 case 8192:
287 }
288 llvm_unreachable("unsupported section alignment");
289}
290
291/// This function takes a section data object from the assembler
292/// and creates the associated COFF section staging object.
293void WinCOFFWriter::defineSection(const MCAssembler &Asm,
294 const MCSectionCOFF &MCSec) {
295 COFFSection *Section = createSection(MCSec.getName());
296 COFFSymbol *Symbol = createSymbol(MCSec.getName());
297 Section->Symbol = Symbol;
298 SymbolMap[MCSec.getBeginSymbol()] = Symbol;
299 Symbol->Section = Section;
300 Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
301
302 // Create a COMDAT symbol if needed.
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;
309 }
310 }
311
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();
317
318 // Set section alignment.
319 Section->Header.Characteristics = MCSec.getCharacteristics();
320 Section->Header.Characteristics |= getAlignment(MCSec);
321
322 // Bind internal COFF section to MC section.
323 Section->MCSection = &MCSec;
324 SectionMap[&MCSec] = Section;
325
326 if (UseOffsetLabels) {
327 const uint32_t Interval = 1 << OffsetLabelIntervalBits;
328 uint32_t N = 1;
329 for (uint32_t Off = Interval, E = Asm.getSectionAddressSize(MCSec); Off < E;
330 Off += Interval) {
331 auto Name = ("$L" + MCSec.getName() + "_" + Twine(N++)).str();
332 COFFSymbol *Label = createSymbol(Name);
333 Label->Section = Section;
334 Label->Data.StorageClass = COFF::IMAGE_SYM_CLASS_LABEL;
335 Label->Data.Value = Off;
336 Section->OffsetSymbols.push_back(Label);
337 }
338 }
339}
340
341static uint64_t getSymbolValue(const MCSymbol &Symbol, const MCAssembler &Asm) {
342 if (Symbol.isCommon() && Symbol.isExternal())
343 return Symbol.getCommonSize();
344
345 uint64_t Res;
346 if (!Asm.getSymbolOffset(Symbol, Res))
347 return 0;
348
349 return Res;
350}
351
352COFFSymbol *WinCOFFWriter::getLinkedSymbol(const MCSymbol &Symbol) {
353 if (!Symbol.isVariable())
354 return nullptr;
355
356 const MCSymbolRefExpr *SymRef =
357 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
358 if (!SymRef)
359 return nullptr;
360
361 const MCSymbol &Aliasee = SymRef->getSymbol();
362 if (Aliasee.isUndefined() || Aliasee.isExternal())
363 return GetOrCreateCOFFSymbol(&Aliasee);
364 else
365 return nullptr;
366}
367
368/// This function takes a symbol data object from the assembler
369/// and creates the associated COFF symbol staging object.
370void WinCOFFWriter::defineSymbol(const MCAssembler &Asm,
371 const MCSymbol &MCSym) {
372 const MCSymbol *Base = Asm.getBaseSymbol(MCSym);
373 COFFSection *Sec = nullptr;
374 MCSectionCOFF *MCSec = nullptr;
375 if (Base && Base->getFragment()) {
376 MCSec = cast<MCSectionCOFF>(Base->getFragment()->getParent());
377 Sec = SectionMap[MCSec];
378 }
379
380 if (Mode == NonDwoOnly && MCSec && isDwoSection(*MCSec))
381 return;
382
383 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
384 COFFSymbol *Local = nullptr;
385 if (cast<MCSymbolCOFF>(MCSym).getWeakExternalCharacteristics()) {
386 Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
387 Sym->Section = nullptr;
388
389 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
390 if (!WeakDefault) {
391 std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
392 WeakDefault = createSymbol(WeakName);
393 if (!Sec)
394 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
395 else
396 WeakDefault->Section = Sec;
397 WeakDefaults.insert(WeakDefault);
398 Local = WeakDefault;
399 }
400
401 Sym->Other = WeakDefault;
402
403 // Setup the Weak External auxiliary symbol.
404 Sym->Aux.resize(1);
405 memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
406 Sym->Aux[0].AuxType = ATWeakExternal;
407 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0; // Filled in later
408 Sym->Aux[0].Aux.WeakExternal.Characteristics =
409 cast<MCSymbolCOFF>(MCSym).getWeakExternalCharacteristics();
410 } else {
411 if (!Base)
412 Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
413 else
414 Sym->Section = Sec;
415 Local = Sym;
416 }
417
418 if (Local) {
419 Local->Data.Value = getSymbolValue(MCSym, Asm);
420
421 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
422 Local->Data.Type = SymbolCOFF.getType();
423 Local->Data.StorageClass = SymbolCOFF.getClass();
424
425 // If no storage class was specified in the streamer, define it here.
426 if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
427 bool IsExternal =
428 MCSym.isExternal() || (!MCSym.getFragment() && !MCSym.isVariable());
429
430 Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
432 }
433 }
434
435 Sym->MC = &MCSym;
436}
437
438void WinCOFFWriter::SetSectionName(COFFSection &S) {
439 if (S.Name.size() <= COFF::NameSize) {
440 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
441 return;
442 }
443
444 uint64_t StringTableEntry = Strings.getOffset(S.Name);
445 if (!COFF::encodeSectionName(S.Header.Name, StringTableEntry))
446 report_fatal_error("COFF string table is greater than 64 GB.");
447}
448
449void WinCOFFWriter::SetSymbolName(COFFSymbol &S) {
450 if (S.Name.size() > COFF::NameSize)
451 S.set_name_offset(Strings.getOffset(S.Name));
452 else
453 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
454}
455
456bool WinCOFFWriter::IsPhysicalSection(COFFSection *S) {
457 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
458 0;
459}
460
461//------------------------------------------------------------------------------
462// entity writing methods
463
464void WinCOFFWriter::WriteFileHeader(const COFF::header &Header) {
465 if (UseBigObj) {
467 W.write<uint16_t>(0xFFFF);
469 W.write<uint16_t>(Header.Machine);
470 W.write<uint32_t>(Header.TimeDateStamp);
472 W.write<uint32_t>(0);
473 W.write<uint32_t>(0);
474 W.write<uint32_t>(0);
475 W.write<uint32_t>(0);
476 W.write<uint32_t>(Header.NumberOfSections);
477 W.write<uint32_t>(Header.PointerToSymbolTable);
478 W.write<uint32_t>(Header.NumberOfSymbols);
479 } else {
480 W.write<uint16_t>(Header.Machine);
481 W.write<uint16_t>(static_cast<int16_t>(Header.NumberOfSections));
482 W.write<uint32_t>(Header.TimeDateStamp);
483 W.write<uint32_t>(Header.PointerToSymbolTable);
484 W.write<uint32_t>(Header.NumberOfSymbols);
485 W.write<uint16_t>(Header.SizeOfOptionalHeader);
486 W.write<uint16_t>(Header.Characteristics);
487 }
488}
489
490void WinCOFFWriter::WriteSymbol(const COFFSymbol &S) {
491 W.OS.write(S.Data.Name, COFF::NameSize);
492 W.write<uint32_t>(S.Data.Value);
493 if (UseBigObj)
494 W.write<uint32_t>(S.Data.SectionNumber);
495 else
496 W.write<uint16_t>(static_cast<int16_t>(S.Data.SectionNumber));
497 W.write<uint16_t>(S.Data.Type);
498 W.OS << char(S.Data.StorageClass);
499 W.OS << char(S.Data.NumberOfAuxSymbols);
500 WriteAuxiliarySymbols(S.Aux);
501}
502
503void WinCOFFWriter::WriteAuxiliarySymbols(
505 for (const AuxSymbol &i : S) {
506 switch (i.AuxType) {
507 case ATWeakExternal:
508 W.write<uint32_t>(i.Aux.WeakExternal.TagIndex);
509 W.write<uint32_t>(i.Aux.WeakExternal.Characteristics);
510 W.OS.write_zeros(sizeof(i.Aux.WeakExternal.unused));
511 if (UseBigObj)
513 break;
514 case ATFile:
515 W.OS.write(reinterpret_cast<const char *>(&i.Aux),
517 break;
518 case ATSectionDefinition:
519 W.write<uint32_t>(i.Aux.SectionDefinition.Length);
520 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
521 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
522 W.write<uint32_t>(i.Aux.SectionDefinition.CheckSum);
523 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
524 W.OS << char(i.Aux.SectionDefinition.Selection);
525 W.OS.write_zeros(sizeof(i.Aux.SectionDefinition.unused));
526 W.write<uint16_t>(
527 static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
528 if (UseBigObj)
530 break;
531 }
532 }
533}
534
535// Write the section header.
536void WinCOFFWriter::writeSectionHeaders() {
537 // Section numbers must be monotonically increasing in the section
538 // header, but our Sections array is not sorted by section number,
539 // so make a copy of Sections and sort it.
540 std::vector<COFFSection *> Arr;
541 for (auto &Section : Sections)
542 Arr.push_back(Section.get());
543 llvm::sort(Arr, [](const COFFSection *A, const COFFSection *B) {
544 return A->Number < B->Number;
545 });
546
547 for (auto &Section : Arr) {
548 if (Section->Number == -1)
549 continue;
550
551 COFF::section &S = Section->Header;
552 if (Section->Relocations.size() >= 0xffff)
564 }
565}
566
567void WinCOFFWriter::WriteRelocation(const COFF::relocation &R) {
568 W.write<uint32_t>(R.VirtualAddress);
569 W.write<uint32_t>(R.SymbolTableIndex);
570 W.write<uint16_t>(R.Type);
571}
572
573// Write MCSec's contents. What this function does is essentially
574// "Asm.writeSectionData(&MCSec)", but it's a bit complicated
575// because it needs to compute a CRC.
576uint32_t WinCOFFWriter::writeSectionContents(MCAssembler &Asm,
577 const MCSection &MCSec) {
578 // Save the contents of the section to a temporary buffer, we need this
579 // to CRC the data before we dump it into the object file.
581 raw_svector_ostream VecOS(Buf);
582 Asm.writeSectionData(VecOS, &MCSec);
583
584 // Write the section contents to the object file.
585 W.OS << Buf;
586
587 // Calculate our CRC with an initial value of '0', this is not how
588 // JamCRC is specified but it aligns with the expected output.
589 JamCRC JC(/*Init=*/0);
590 JC.update(ArrayRef(reinterpret_cast<uint8_t *>(Buf.data()), Buf.size()));
591 return JC.getCRC();
592}
593
594void WinCOFFWriter::writeSection(MCAssembler &Asm, const COFFSection &Sec) {
595 if (Sec.Number == -1)
596 return;
597
598 // Write the section contents.
599 if (Sec.Header.PointerToRawData != 0) {
600 assert(W.OS.tell() == Sec.Header.PointerToRawData &&
601 "Section::PointerToRawData is insane!");
602
603 uint32_t CRC = writeSectionContents(Asm, *Sec.MCSection);
604
605 // Update the section definition auxiliary symbol to record the CRC.
606 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec.Symbol->Aux;
607 assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
608 AuxSymbol &SecDef = AuxSyms[0];
609 SecDef.Aux.SectionDefinition.CheckSum = CRC;
610 }
611
612 // Write relocations for this section.
613 if (Sec.Relocations.empty()) {
614 assert(Sec.Header.PointerToRelocations == 0 &&
615 "Section::PointerToRelocations is insane!");
616 return;
617 }
618
619 assert(W.OS.tell() == Sec.Header.PointerToRelocations &&
620 "Section::PointerToRelocations is insane!");
621
622 if (Sec.Relocations.size() >= 0xffff) {
623 // In case of overflow, write actual relocation count as first
624 // relocation. Including the synthetic reloc itself (+ 1).
626 R.VirtualAddress = Sec.Relocations.size() + 1;
627 R.SymbolTableIndex = 0;
628 R.Type = 0;
629 WriteRelocation(R);
630 }
631
632 for (const auto &Relocation : Sec.Relocations)
633 WriteRelocation(Relocation.Data);
634}
635
636// Create .file symbols.
637void WinCOFFWriter::createFileSymbols(MCAssembler &Asm) {
638 for (const std::pair<std::string, size_t> &It : OWriter.getFileNames()) {
639 // round up to calculate the number of auxiliary symbols required
640 const std::string &Name = It.first;
641 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
642 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
643
644 COFFSymbol *File = createSymbol(".file");
645 File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
646 File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
647 File->Aux.resize(Count);
648
649 unsigned Offset = 0;
650 unsigned Length = Name.size();
651 for (auto &Aux : File->Aux) {
652 Aux.AuxType = ATFile;
653
654 if (Length > SymbolSize) {
655 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
656 Length = Length - SymbolSize;
657 } else {
658 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
659 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
660 break;
661 }
662
663 Offset += SymbolSize;
664 }
665 }
666}
667
668void WinCOFFWriter::setWeakDefaultNames() {
669 if (WeakDefaults.empty())
670 return;
671
672 // If multiple object files use a weak symbol (either with a regular
673 // defined default, or an absolute zero symbol as default), the defaults
674 // cause duplicate definitions unless their names are made unique. Look
675 // for a defined extern symbol, that isn't comdat - that should be unique
676 // unless there are other duplicate definitions. And if none is found,
677 // allow picking a comdat symbol, as that's still better than nothing.
678
679 COFFSymbol *Unique = nullptr;
680 for (bool AllowComdat : {false, true}) {
681 for (auto &Sym : Symbols) {
682 // Don't include the names of the defaults themselves
683 if (WeakDefaults.count(Sym.get()))
684 continue;
685 // Only consider external symbols
686 if (Sym->Data.StorageClass != COFF::IMAGE_SYM_CLASS_EXTERNAL)
687 continue;
688 // Only consider symbols defined in a section or that are absolute
689 if (!Sym->Section && Sym->Data.SectionNumber != COFF::IMAGE_SYM_ABSOLUTE)
690 continue;
691 if (!AllowComdat && Sym->Section &&
692 Sym->Section->Header.Characteristics & COFF::IMAGE_SCN_LNK_COMDAT)
693 continue;
694 Unique = Sym.get();
695 break;
696 }
697 if (Unique)
698 break;
699 }
700 // If we didn't find any unique symbol to use for the names, just skip this.
701 if (!Unique)
702 return;
703 for (auto *Sym : WeakDefaults) {
704 Sym->Name.append(".");
705 Sym->Name.append(Unique->Name);
706 }
707}
708
709static bool isAssociative(const COFFSection &Section) {
710 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
712}
713
714void WinCOFFWriter::assignSectionNumbers() {
715 size_t I = 1;
716 auto Assign = [&](COFFSection &Section) {
717 Section.Number = I;
718 Section.Symbol->Data.SectionNumber = I;
719 Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
720 ++I;
721 };
722
723 // Although it is not explicitly requested by the Microsoft COFF spec,
724 // we should avoid emitting forward associative section references,
725 // because MSVC link.exe as of 2017 cannot handle that.
726 for (const std::unique_ptr<COFFSection> &Section : Sections)
727 if (!isAssociative(*Section))
728 Assign(*Section);
729 for (const std::unique_ptr<COFFSection> &Section : Sections)
730 if (isAssociative(*Section))
731 Assign(*Section);
732}
733
734// Assign file offsets to COFF object file structures.
735void WinCOFFWriter::assignFileOffsets(MCAssembler &Asm) {
736 unsigned Offset = W.OS.tell();
737
739 Offset += COFF::SectionSize * Header.NumberOfSections;
740
741 for (const auto &Section : Asm) {
742 COFFSection *Sec = SectionMap[&Section];
743
744 if (!Sec || Sec->Number == -1)
745 continue;
746
747 Sec->Header.SizeOfRawData = Asm.getSectionAddressSize(Section);
748
749 if (IsPhysicalSection(Sec)) {
750 Sec->Header.PointerToRawData = Offset;
751 Offset += Sec->Header.SizeOfRawData;
752 }
753
754 if (!Sec->Relocations.empty()) {
755 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
756
757 if (RelocationsOverflow) {
758 // Signal overflow by setting NumberOfRelocations to max value. Actual
759 // size is found in reloc #0. Microsoft tools understand this.
760 Sec->Header.NumberOfRelocations = 0xffff;
761 } else {
762 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
763 }
764 Sec->Header.PointerToRelocations = Offset;
765
766 if (RelocationsOverflow) {
767 // Reloc #0 will contain actual count, so make room for it.
769 }
770
771 Offset += COFF::RelocationSize * Sec->Relocations.size();
772
773 for (auto &Relocation : Sec->Relocations) {
774 assert(Relocation.Symb->getIndex() != -1);
775 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
776 }
777 }
778
779 assert(Sec->Symbol->Aux.size() == 1 &&
780 "Section's symbol must have one aux!");
781 AuxSymbol &Aux = Sec->Symbol->Aux[0];
782 assert(Aux.AuxType == ATSectionDefinition &&
783 "Section's symbol's aux symbol must be a Section Definition!");
784 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
785 Aux.Aux.SectionDefinition.NumberOfRelocations =
786 Sec->Header.NumberOfRelocations;
787 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
788 Sec->Header.NumberOfLineNumbers;
789 }
790
791 Header.PointerToSymbolTable = Offset;
792}
793
795 memset(&Header, 0, sizeof(Header));
796 Header.Machine = OWriter.TargetObjectWriter->getMachine();
797 Sections.clear();
798 Symbols.clear();
799 Strings.clear();
800 SectionMap.clear();
801 SymbolMap.clear();
802 WeakDefaults.clear();
803}
804
806 // "Define" each section & symbol. This creates section & symbol
807 // entries in the staging area.
808 for (const auto &Section : Asm) {
809 if ((Mode == NonDwoOnly && isDwoSection(Section)) ||
810 (Mode == DwoOnly && !isDwoSection(Section)))
811 continue;
812 defineSection(Asm, static_cast<const MCSectionCOFF &>(Section));
813 }
814
815 if (Mode != DwoOnly)
816 for (const MCSymbol &Symbol : Asm.symbols())
817 // Define non-temporary or temporary static (private-linkage) symbols
818 if (!Symbol.isTemporary() ||
819 cast<MCSymbolCOFF>(Symbol).getClass() == COFF::IMAGE_SYM_CLASS_STATIC)
820 defineSymbol(Asm, Symbol);
821}
822
824 const MCFragment *Fragment,
825 const MCFixup &Fixup, MCValue Target,
826 uint64_t &FixedValue) {
827 assert(Target.getSymA() && "Relocation must reference a symbol!");
828
829 const MCSymbol &A = Target.getSymA()->getSymbol();
830 if (!A.isRegistered()) {
831 Asm.getContext().reportError(Fixup.getLoc(), Twine("symbol '") +
832 A.getName() +
833 "' can not be undefined");
834 return;
835 }
836 if (A.isTemporary() && A.isUndefined()) {
837 Asm.getContext().reportError(Fixup.getLoc(), Twine("assembler label '") +
838 A.getName() +
839 "' can not be undefined");
840 return;
841 }
842
843 MCSection *MCSec = Fragment->getParent();
844
845 // Mark this symbol as requiring an entry in the symbol table.
846 assert(SectionMap.contains(MCSec) &&
847 "Section must already have been defined in executePostLayoutBinding!");
848
849 COFFSection *Sec = SectionMap[MCSec];
850 const MCSymbolRefExpr *SymB = Target.getSymB();
851
852 if (SymB) {
853 const MCSymbol *B = &SymB->getSymbol();
854 if (!B->getFragment()) {
855 Asm.getContext().reportError(
856 Fixup.getLoc(),
857 Twine("symbol '") + B->getName() +
858 "' can not be undefined in a subtraction expression");
859 return;
860 }
861
862 // Offset of the symbol in the section
863 int64_t OffsetOfB = Asm.getSymbolOffset(*B);
864
865 // Offset of the relocation in the section
866 int64_t OffsetOfRelocation =
867 Asm.getFragmentOffset(*Fragment) + Fixup.getOffset();
868
869 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
870 } else {
871 FixedValue = Target.getConstant();
872 }
873
874 COFFRelocation Reloc;
875
876 Reloc.Data.SymbolTableIndex = 0;
877 Reloc.Data.VirtualAddress = Asm.getFragmentOffset(*Fragment);
878
879 // Turn relocations for temporary symbols into section relocations.
880 if (A.isTemporary() && !SymbolMap[&A]) {
881 MCSection *TargetSection = &A.getSection();
882 assert(
883 SectionMap.contains(TargetSection) &&
884 "Section must already have been defined in executePostLayoutBinding!");
885 COFFSection *Section = SectionMap[TargetSection];
886 Reloc.Symb = Section->Symbol;
887 FixedValue += Asm.getSymbolOffset(A);
888 // Technically, we should do the final adjustments of FixedValue (below)
889 // before picking an offset symbol, otherwise we might choose one which
890 // is slightly too far away. The relocations where it really matters
891 // (arm64 adrp relocations) don't get any offset though.
892 if (UseOffsetLabels && !Section->OffsetSymbols.empty()) {
893 uint64_t LabelIndex = FixedValue >> OffsetLabelIntervalBits;
894 if (LabelIndex > 0) {
895 if (LabelIndex <= Section->OffsetSymbols.size())
896 Reloc.Symb = Section->OffsetSymbols[LabelIndex - 1];
897 else
898 Reloc.Symb = Section->OffsetSymbols.back();
899 FixedValue -= Reloc.Symb->Data.Value;
900 }
901 }
902 } else {
903 assert(
904 SymbolMap.contains(&A) &&
905 "Symbol must already have been defined in executePostLayoutBinding!");
906 Reloc.Symb = SymbolMap[&A];
907 }
908
909 ++Reloc.Symb->Relocations;
910
911 Reloc.Data.VirtualAddress += Fixup.getOffset();
912 Reloc.Data.Type = OWriter.TargetObjectWriter->getRelocType(
913 Asm.getContext(), Target, Fixup, SymB, Asm.getBackend());
914
915 // The *_REL32 relocations are relative to the end of the relocation,
916 // not to the start.
917 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
918 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
919 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
920 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32) ||
921 (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT &&
922 Reloc.Data.Type == COFF::IMAGE_REL_ARM_REL32) ||
923 (COFF::isAnyArm64(Header.Machine) &&
924 Reloc.Data.Type == COFF::IMAGE_REL_ARM64_REL32))
925 FixedValue += 4;
926
927 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
928 switch (Reloc.Data.Type) {
935 break;
938 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
939 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
940 // for Windows CE).
944 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
945 // only used for ARM mode code, which is documented as being unsupported
946 // by Windows on ARM. Empirical proof indicates that masm is able to
947 // generate the relocations however the rest of the MSVC toolchain is
948 // unable to handle it.
949 llvm_unreachable("unsupported relocation");
950 break;
952 break;
956 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
957 // perform a 4 byte adjustment to the relocation. Relative branches are
958 // offset by 4 on ARM, however, because there is no RELA relocations, all
959 // branches are offset by 4.
960 FixedValue = FixedValue + 4;
961 break;
962 }
963 }
964
965 // The fixed value never makes sense for section indices, ignore it.
966 if (Fixup.getKind() == FK_SecRel_2)
967 FixedValue = 0;
968
969 if (OWriter.TargetObjectWriter->recordRelocation(Fixup))
970 Sec->Relocations.push_back(Reloc);
971}
972
973static std::time_t getTime() {
974 std::time_t Now = time(nullptr);
975 if (Now < 0 || !isUInt<32>(Now))
976 return UINT32_MAX;
977 return Now;
978}
979
981 uint64_t StartOffset = W.OS.tell();
982
983 if (Sections.size() > INT32_MAX)
985 "PE COFF object files can't have more than 2147483647 sections");
986
987 UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
988 Header.NumberOfSections = Sections.size();
989 Header.NumberOfSymbols = 0;
990
991 setWeakDefaultNames();
992 assignSectionNumbers();
993 if (Mode != DwoOnly)
994 createFileSymbols(Asm);
995
996 for (auto &Symbol : Symbols) {
997 // Update section number & offset for symbols that have them.
998 if (Symbol->Section)
999 Symbol->Data.SectionNumber = Symbol->Section->Number;
1000 Symbol->setIndex(Header.NumberOfSymbols++);
1001 // Update auxiliary symbol info.
1002 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
1003 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
1004 }
1005
1006 // Build string table.
1007 for (const auto &S : Sections)
1008 if (S->Name.size() > COFF::NameSize)
1009 Strings.add(S->Name);
1010 for (const auto &S : Symbols)
1011 if (S->Name.size() > COFF::NameSize)
1012 Strings.add(S->Name);
1013 Strings.finalize();
1014
1015 // Set names.
1016 for (const auto &S : Sections)
1017 SetSectionName(*S);
1018 for (auto &S : Symbols)
1019 SetSymbolName(*S);
1020
1021 // Fixup weak external references.
1022 for (auto &Symbol : Symbols) {
1023 if (Symbol->Other) {
1024 assert(Symbol->getIndex() != -1);
1025 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1026 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1027 "Symbol's aux symbol must be a Weak External!");
1028 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1029 }
1030 }
1031
1032 // Fixup associative COMDAT sections.
1033 for (auto &Section : Sections) {
1034 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1036 continue;
1037
1038 const MCSectionCOFF &MCSec = *Section->MCSection;
1039 const MCSymbol *AssocMCSym = MCSec.getCOMDATSymbol();
1040 assert(AssocMCSym);
1041
1042 // It's an error to try to associate with an undefined symbol or a symbol
1043 // without a section.
1044 if (!AssocMCSym->isInSection()) {
1045 Asm.getContext().reportError(
1046 SMLoc(), Twine("cannot make section ") + MCSec.getName() +
1047 Twine(" associative with sectionless symbol ") +
1048 AssocMCSym->getName());
1049 continue;
1050 }
1051
1052 const auto *AssocMCSec = cast<MCSectionCOFF>(&AssocMCSym->getSection());
1053 assert(SectionMap.count(AssocMCSec));
1054 COFFSection *AssocSec = SectionMap[AssocMCSec];
1055
1056 // Skip this section if the associated section is unused.
1057 if (AssocSec->Number == -1)
1058 continue;
1059
1060 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = AssocSec->Number;
1061 }
1062
1063 // Create the contents of the .llvm_addrsig section.
1064 if (Mode != DwoOnly && OWriter.getEmitAddrsigSection()) {
1065 auto *Sec = Asm.getContext().getCOFFSection(
1066 ".llvm_addrsig", COFF::IMAGE_SCN_LNK_REMOVE);
1067 auto *Frag = cast<MCDataFragment>(Sec->curFragList()->Head);
1068 raw_svector_ostream OS(Frag->getContents());
1069 for (const MCSymbol *S : OWriter.AddrsigSyms) {
1070 if (!S->isRegistered())
1071 continue;
1072 if (!S->isTemporary()) {
1073 encodeULEB128(S->getIndex(), OS);
1074 continue;
1075 }
1076
1077 MCSection *TargetSection = &S->getSection();
1078 assert(SectionMap.contains(TargetSection) &&
1079 "Section must already have been defined in "
1080 "executePostLayoutBinding!");
1081 encodeULEB128(SectionMap[TargetSection]->Symbol->getIndex(), OS);
1082 }
1083 }
1084
1085 // Create the contents of the .llvm.call-graph-profile section.
1086 if (Mode != DwoOnly && !OWriter.getCGProfile().empty()) {
1087 auto *Sec = Asm.getContext().getCOFFSection(
1088 ".llvm.call-graph-profile", COFF::IMAGE_SCN_LNK_REMOVE);
1089 auto *Frag = cast<MCDataFragment>(Sec->curFragList()->Head);
1090 raw_svector_ostream OS(Frag->getContents());
1091 for (const auto &CGPE : OWriter.getCGProfile()) {
1092 uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
1093 uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
1094 support::endian::write(OS, FromIndex, W.Endian);
1095 support::endian::write(OS, ToIndex, W.Endian);
1096 support::endian::write(OS, CGPE.Count, W.Endian);
1097 }
1098 }
1099
1100 assignFileOffsets(Asm);
1101
1102 // MS LINK expects to be able to use this timestamp to implement their
1103 // /INCREMENTAL feature.
1104 if (OWriter.IncrementalLinkerCompatible) {
1105 Header.TimeDateStamp = getTime();
1106 } else {
1107 // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1108 Header.TimeDateStamp = 0;
1109 }
1110
1111 // Write it all to disk...
1112 WriteFileHeader(Header);
1113 writeSectionHeaders();
1114
1115#ifndef NDEBUG
1116 sections::iterator I = Sections.begin();
1117 sections::iterator IE = Sections.end();
1118 auto J = Asm.begin();
1119 auto JE = Asm.end();
1120 for (; I != IE && J != JE; ++I, ++J) {
1121 while (J != JE && ((Mode == NonDwoOnly && isDwoSection(*J)) ||
1122 (Mode == DwoOnly && !isDwoSection(*J))))
1123 ++J;
1124 assert(J != JE && (**I).MCSection == &*J && "Wrong bound MCSection");
1125 }
1126#endif
1127
1128 // Write section contents.
1129 for (std::unique_ptr<COFFSection> &Sec : Sections)
1130 writeSection(Asm, *Sec);
1131
1132 assert(W.OS.tell() == Header.PointerToSymbolTable &&
1133 "Header::PointerToSymbolTable is insane!");
1134
1135 // Write a symbol table.
1136 for (auto &Symbol : Symbols)
1137 if (Symbol->getIndex() != -1)
1138 WriteSymbol(*Symbol);
1139
1140 // Write a string table, which completes the entire COFF file.
1141 Strings.write(W.OS);
1142
1143 return W.OS.tell() - StartOffset;
1144}
1145
1146//------------------------------------------------------------------------------
1147// WinCOFFObjectWriter class implementation
1148
1149////////////////////////////////////////////////////////////////////////////////
1150// MCObjectWriter interface implementations
1151
1153 IncrementalLinkerCompatible = false;
1154 ObjWriter->reset();
1155 if (DwoWriter)
1156 DwoWriter->reset();
1158}
1159
1161 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1162 bool InSet, bool IsPCRel) const {
1163 // Don't drop relocations between functions, even if they are in the same text
1164 // section. Multiple Visual C++ linker features depend on having the
1165 // relocations present. The /INCREMENTAL flag will cause these relocations to
1166 // point to thunks, and the /GUARD:CF flag assumes that it can use relocations
1167 // to approximate the set of all address taken functions. LLD's implementation
1168 // of /GUARD:CF also relies on the existance of these relocations.
1169 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
1171 return false;
1172 return &SymA.getSection() == FB.getParent();
1173}
1174
1176 ObjWriter->executePostLayoutBinding(Asm);
1177 if (DwoWriter)
1178 DwoWriter->executePostLayoutBinding(Asm);
1179}
1180
1182 const MCFragment *Fragment,
1183 const MCFixup &Fixup, MCValue Target,
1184 uint64_t &FixedValue) {
1185 assert(!isDwoSection(*Fragment->getParent()) &&
1186 "No relocation in Dwo sections");
1187 ObjWriter->recordRelocation(Asm, Fragment, Fixup, Target, FixedValue);
1188}
1189
1191 uint64_t TotalSize = ObjWriter->writeObject(Asm);
1192 if (DwoWriter)
1193 TotalSize += DwoWriter->writeObject(Asm);
1194 return TotalSize;
1195}
1196
1198 : Machine(Machine_) {}
1199
1200// Pin the vtable to this file.
1201void MCWinCOFFObjectTargetWriter::anchor() {}
1202
1203//------------------------------------------------------------------------------
1204// WinCOFFObjectWriter factory function
1205
1206std::unique_ptr<MCObjectWriter> llvm::createWinCOFFObjectWriter(
1207 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS) {
1208 return std::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS);
1209}
1210
1211std::unique_ptr<MCObjectWriter> llvm::createWinCOFFDwoObjectWriter(
1212 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS,
1213 raw_pwrite_stream &DwoOS) {
1214 return std::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS, DwoOS);
1215}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
COFFYAML::AuxSymbolType AuxType
Definition: COFFYAML.cpp:372
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:390
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1315
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define I(x, y, z)
Definition: MD5.cpp:58
std::pair< uint64_t, uint64_t > Interval
PowerPC TLS Dynamic Call Fixup
uint32_t Number
Definition: Profile.cpp:47
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:46
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
static uint64_t getSymbolValue(const MCSymbol &Symbol, const MCAssembler &Asm)
static uint32_t getAlignment(const MCSectionCOFF &Sec)
static bool isAssociative(const COFFSection &Section)
static bool isDwoSection(const MCSection &Sec)
static std::time_t getTime()
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:147
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
MCSection * getParent() const
Definition: MCFragment.h:99
MutableArrayRef< std::pair< std::string, size_t > > getFileNames()
virtual void reset()
lifetime management
SmallVector< CGProfileEntry, 0 > & getCGProfile()
std::vector< const MCSymbol * > AddrsigSyms
This represents a section on Windows.
Definition: MCSectionCOFF.h:27
MCSymbol * getCOMDATSymbol() const
Definition: MCSectionCOFF.h:70
unsigned getCharacteristics() const
Definition: MCSectionCOFF.h:69
int getSelection() const
Definition: MCSectionCOFF.h:71
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
Align getAlign() const
Definition: MCSection.h:146
StringRef getName() const
Definition: MCSection.h:130
MCSymbol * getBeginSymbol()
Definition: MCSection.h:135
uint16_t getType() const
Definition: MCSymbolCOFF.h:36
uint16_t getClass() const
Definition: MCSymbolCOFF.h:43
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
const MCSymbol & getSymbol() const
Definition: MCExpr.h:411
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:254
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:300
bool isRegistered() const
Definition: MCSymbol.h:212
void setIndex(uint32_t Value) const
Set the (implementation defined) index.
Definition: MCSymbol.h:321
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:259
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:316
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:269
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
Definition: MCSymbol.h:222
bool isExternal() const
Definition: MCSymbol.h:407
MCFragment * getFragment(bool SetUsed=true) const
Definition: MCSymbol.h:397
This represents an "assembler immediate".
Definition: MCValue.h:36
Represents a location in source code.
Definition: SMLoc.h:23
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
size_t size() const
Definition: SmallVector.h:78
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:286
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:277
Utility for building string tables with deduplicated suffixes.
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
void finalize()
Analyze the strings and build the final table.
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
void reset() override
lifetime management
void recordRelocation(MCAssembler &Asm, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override
Record a relocation entry.
WinCOFFObjectWriter(std::unique_ptr< MCWinCOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS)
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB, bool InSet, bool IsPCRel) const override
void executePostLayoutBinding(MCAssembler &Asm) override
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
uint64_t writeObject(MCAssembler &Asm) override
Write the object file and returns the number of bytes written.
uint64_t writeObject(MCAssembler &Asm)
WinCOFFWriter(WinCOFFObjectWriter &OWriter, raw_pwrite_stream &OS, DwoMode Mode)
enum llvm::WinCOFFWriter::DwoMode Mode
void recordRelocation(MCAssembler &Asm, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue)
void executePostLayoutBinding(MCAssembler &Asm)
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:95
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
raw_ostream & write(unsigned char C)
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:434
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition: COFF.h:95
@ IMAGE_FILE_MACHINE_AMD64
Definition: COFF.h:97
@ IMAGE_FILE_MACHINE_I386
Definition: COFF.h:104
@ IMAGE_FILE_MACHINE_ARMNT
Definition: COFF.h:99
@ IMAGE_SCN_ALIGN_64BYTES
Definition: COFF.h:320
@ IMAGE_SCN_ALIGN_128BYTES
Definition: COFF.h:321
@ IMAGE_SCN_ALIGN_256BYTES
Definition: COFF.h:322
@ IMAGE_SCN_ALIGN_1024BYTES
Definition: COFF.h:324
@ IMAGE_SCN_ALIGN_1BYTES
Definition: COFF.h:314
@ IMAGE_SCN_LNK_REMOVE
Definition: COFF.h:307
@ IMAGE_SCN_ALIGN_512BYTES
Definition: COFF.h:323
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:304
@ IMAGE_SCN_ALIGN_4096BYTES
Definition: COFF.h:326
@ IMAGE_SCN_ALIGN_8192BYTES
Definition: COFF.h:327
@ IMAGE_SCN_LNK_NRELOC_OVFL
Definition: COFF.h:329
@ IMAGE_SCN_ALIGN_16BYTES
Definition: COFF.h:318
@ IMAGE_SCN_LNK_COMDAT
Definition: COFF.h:308
@ IMAGE_SCN_ALIGN_8BYTES
Definition: COFF.h:317
@ IMAGE_SCN_ALIGN_4BYTES
Definition: COFF.h:316
@ IMAGE_SCN_ALIGN_32BYTES
Definition: COFF.h:319
@ IMAGE_SCN_ALIGN_2BYTES
Definition: COFF.h:315
@ IMAGE_SCN_ALIGN_2048BYTES
Definition: COFF.h:325
bool isAnyArm64(T Machine)
Definition: COFF.h:129
@ IMAGE_REL_ARM64_REL32
Definition: COFF.h:417
@ NameSize
Definition: COFF.h:57
@ Header16Size
Definition: COFF.h:55
@ Symbol16Size
Definition: COFF.h:58
@ Header32Size
Definition: COFF.h:56
@ SectionSize
Definition: COFF.h:60
@ Symbol32Size
Definition: COFF.h:59
@ RelocationSize
Definition: COFF.h:61
@ IMAGE_REL_AMD64_REL32
Definition: COFF.h:364
@ IMAGE_SYM_CLASS_EXTERNAL
External symbol.
Definition: COFF.h:223
@ IMAGE_SYM_CLASS_LABEL
Label.
Definition: COFF.h:227
@ IMAGE_SYM_CLASS_FILE
File name.
Definition: COFF.h:245
@ IMAGE_SYM_CLASS_NULL
No symbol.
Definition: COFF.h:221
@ IMAGE_SYM_CLASS_WEAK_EXTERNAL
Duplicate tag.
Definition: COFF.h:248
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition: COFF.h:224
bool encodeSectionName(char *Out, uint64_t Offset)
Encode section name based on string table offset.
Definition: COFF.cpp:39
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition: COFF.h:458
@ IMAGE_REL_ARM_MOV32A
Definition: COFF.h:391
@ IMAGE_REL_ARM_BRANCH20T
Definition: COFF.h:393
@ IMAGE_REL_ARM_BRANCH24
Definition: COFF.h:383
@ IMAGE_REL_ARM_ADDR32NB
Definition: COFF.h:382
@ IMAGE_REL_ARM_BRANCH11
Definition: COFF.h:384
@ IMAGE_REL_ARM_BLX24
Definition: COFF.h:386
@ IMAGE_REL_ARM_ADDR32
Definition: COFF.h:381
@ IMAGE_REL_ARM_MOV32T
Definition: COFF.h:392
@ IMAGE_REL_ARM_BRANCH24T
Definition: COFF.h:394
@ IMAGE_REL_ARM_ABSOLUTE
Definition: COFF.h:380
@ IMAGE_REL_ARM_REL32
Definition: COFF.h:388
@ IMAGE_REL_ARM_BLX23T
Definition: COFF.h:395
@ IMAGE_REL_ARM_SECREL
Definition: COFF.h:390
@ IMAGE_REL_ARM_SECTION
Definition: COFF.h:389
@ IMAGE_REL_ARM_BLX11
Definition: COFF.h:387
@ IMAGE_REL_ARM_TOKEN
Definition: COFF.h:385
const int32_t MaxNumberOfSections16
Definition: COFF.h:32
@ IMAGE_REL_I386_REL32
Definition: COFF.h:356
static const char BigObjMagic[]
Definition: COFF.h:37
@ IMAGE_SYM_DEBUG
Definition: COFF.h:211
@ IMAGE_SYM_ABSOLUTE
Definition: COFF.h:212
@ IMAGE_SYM_DTYPE_FUNCTION
A function that returns a base type.
Definition: COFF.h:275
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition: COFF.h:279
void write32le(void *P, uint32_t V)
Definition: Endian.h:468
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:92
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
@ Length
Definition: DWP.cpp:480
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1697
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
std::unique_ptr< MCObjectWriter > createWinCOFFDwoObjectWriter(std::unique_ptr< MCWinCOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS)
@ FK_SecRel_2
A two-byte section relative fixup.
Definition: MCFixup.h:41
std::unique_ptr< MCObjectWriter > createWinCOFFObjectWriter(std::unique_ptr< MCWinCOFFObjectTargetWriter > MOTW, raw_pwrite_stream &OS)
Construct a new Win COFF writer instance.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
endianness
Definition: bit.h:70
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
uint16_t Machine
Definition: COFF.h:65
uint32_t VirtualSize
Definition: COFF.h:286
uint32_t PointerToRelocations
Definition: COFF.h:290
uint16_t NumberOfLineNumbers
Definition: COFF.h:293
uint32_t PointerToRawData
Definition: COFF.h:289
uint32_t SizeOfRawData
Definition: COFF.h:288
uint32_t Characteristics
Definition: COFF.h:294
uint16_t NumberOfRelocations
Definition: COFF.h:292
char Name[NameSize]
Definition: COFF.h:285
uint32_t VirtualAddress
Definition: COFF.h:287
uint32_t PointerToLineNumbers
Definition: COFF.h:291
Adapter to write values to a stream in a particular byte order.
Definition: EndianStream.h:67
void write(ArrayRef< value_type > Val)
Definition: EndianStream.h:71