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