1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements ELF object file writer information.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCELFObjectWriter.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCFixup.h"
29 #include "llvm/MC/MCFixupKindInfo.h"
30 #include "llvm/MC/MCFragment.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCObjectWriter.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCSectionELF.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/MC/MCSymbolELF.h"
37 #include "llvm/MC/MCValue.h"
38 #include "llvm/MC/StringTableBuilder.h"
39 #include "llvm/Support/Alignment.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/Compression.h"
43 #include "llvm/Support/EndianStream.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/LEB128.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/SMLoc.h"
50 #include "llvm/Support/StringSaver.h"
51 #include "llvm/Support/SwapByteOrder.h"
52 #include "llvm/Support/raw_ostream.h"
66 #define DEBUG_TYPE "reloc-info"
70 using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
72 class ELFObjectWriter;
75 bool isDwoSection(const MCSectionELF &Sec) {
76 return Sec.getName().endswith(".dwo");
79 class SymbolTableWriter {
83 // indexes we are going to write to .symtab_shndx.
84 std::vector<uint32_t> ShndxIndexes;
86 // The numbel of symbols written so far.
89 void createSymtabShndx();
91 template <typename T> void write(T Value);
94 SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit);
96 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
97 uint8_t other, uint32_t shndx, bool Reserved);
99 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
103 ELFObjectWriter &OWriter;
104 support::endian::Writer W;
112 static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
113 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
114 bool Used, bool Renamed);
116 /// Helper struct for containing some precomputed information on symbols.
117 struct ELFSymbolData {
118 const MCSymbolELF *Symbol;
119 uint32_t SectionIndex;
122 // Support lexicographic sorting.
123 bool operator<(const ELFSymbolData &RHS) const {
124 unsigned LHSType = Symbol->getType();
125 unsigned RHSType = RHS.Symbol->getType();
126 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
128 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
130 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
131 return SectionIndex < RHS.SectionIndex;
132 return Name < RHS.Name;
137 /// @name Symbol Table Data
140 StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
144 // This holds the symbol table index of the last local symbol.
145 unsigned LastLocalSymbolIndex;
146 // This holds the .strtab section index.
147 unsigned StringTableIndex;
148 // This holds the .symtab section index.
149 unsigned SymbolTableIndex;
151 // Sections in the order they are to be output in the section table.
152 std::vector<const MCSectionELF *> SectionTable;
153 unsigned addToSectionTable(const MCSectionELF *Sec);
155 // TargetObjectWriter wrappers.
156 bool is64Bit() const;
157 bool hasRelocationAddend() const;
159 void align(unsigned Alignment);
161 bool maybeWriteCompression(uint64_t Size,
162 SmallVectorImpl<char> &CompressedContents,
163 bool ZLibStyle, unsigned Alignment);
166 ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
167 bool IsLittleEndian, DwoMode Mode)
169 W(OS, IsLittleEndian ? support::little : support::big), Mode(Mode) {}
171 void WriteWord(uint64_t Word) {
173 W.write<uint64_t>(Word);
175 W.write<uint32_t>(Word);
178 template <typename T> void write(T Val) {
182 void writeHeader(const MCAssembler &Asm);
184 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
185 ELFSymbolData &MSD, const MCAsmLayout &Layout);
187 // Start and end offset of each section
188 using SectionOffsetsTy =
189 std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>;
191 // Map from a signature symbol to the group section index
192 using RevGroupMapTy = DenseMap<const MCSymbol *, unsigned>;
194 /// Compute the symbol table data
196 /// \param Asm - The assembler.
197 /// \param SectionIndexMap - Maps a section to its index.
198 /// \param RevGroupMap - Maps a signature symbol to the group section.
199 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
200 const SectionIndexMapTy &SectionIndexMap,
201 const RevGroupMapTy &RevGroupMap,
202 SectionOffsetsTy &SectionOffsets);
204 void writeAddrsigSection();
206 MCSectionELF *createRelocationSection(MCContext &Ctx,
207 const MCSectionELF &Sec);
209 const MCSectionELF *createStringTable(MCContext &Ctx);
211 void writeSectionHeader(const MCAsmLayout &Layout,
212 const SectionIndexMapTy &SectionIndexMap,
213 const SectionOffsetsTy &SectionOffsets);
215 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
216 const MCAsmLayout &Layout);
218 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
219 uint64_t Address, uint64_t Offset, uint64_t Size,
220 uint32_t Link, uint32_t Info, uint64_t Alignment,
223 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
225 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout);
226 void writeSection(const SectionIndexMapTy &SectionIndexMap,
227 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
228 const MCSectionELF &Section);
231 class ELFObjectWriter : public MCObjectWriter {
232 /// The target specific ELF writer instance.
233 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
235 DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> Relocations;
237 DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
239 bool EmitAddrsigSection = false;
240 std::vector<const MCSymbol *> AddrsigSyms;
242 bool hasRelocationAddend() const;
244 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
245 const MCSymbolRefExpr *RefA,
246 const MCSymbolELF *Sym, uint64_t C,
247 unsigned Type) const;
250 ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
251 : TargetObjectWriter(std::move(MOTW)) {}
253 void reset() override {
256 MCObjectWriter::reset();
259 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
260 const MCSymbol &SymA,
261 const MCFragment &FB, bool InSet,
262 bool IsPCRel) const override;
264 virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
265 const MCSectionELF *From,
266 const MCSectionELF *To) {
270 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
271 const MCFragment *Fragment, const MCFixup &Fixup,
272 MCValue Target, uint64_t &FixedValue) override;
274 void executePostLayoutBinding(MCAssembler &Asm,
275 const MCAsmLayout &Layout) override;
277 void emitAddrsigSection() override { EmitAddrsigSection = true; }
278 void addAddrsigSymbol(const MCSymbol *Sym) override {
279 AddrsigSyms.push_back(Sym);
282 friend struct ELFWriter;
285 class ELFSingleObjectWriter : public ELFObjectWriter {
286 raw_pwrite_stream &OS;
290 ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
291 raw_pwrite_stream &OS, bool IsLittleEndian)
292 : ELFObjectWriter(std::move(MOTW)), OS(OS),
293 IsLittleEndian(IsLittleEndian) {}
295 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
296 return ELFWriter(*this, OS, IsLittleEndian, ELFWriter::AllSections)
297 .writeObject(Asm, Layout);
300 friend struct ELFWriter;
303 class ELFDwoObjectWriter : public ELFObjectWriter {
304 raw_pwrite_stream &OS, &DwoOS;
308 ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
309 raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
311 : ELFObjectWriter(std::move(MOTW)), OS(OS), DwoOS(DwoOS),
312 IsLittleEndian(IsLittleEndian) {}
314 virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
315 const MCSectionELF *From,
316 const MCSectionELF *To) override {
317 if (isDwoSection(*From)) {
318 Ctx.reportError(Loc, "A dwo section may not contain relocations");
321 if (To && isDwoSection(*To)) {
322 Ctx.reportError(Loc, "A relocation may not refer to a dwo section");
328 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
329 uint64_t Size = ELFWriter(*this, OS, IsLittleEndian, ELFWriter::NonDwoOnly)
330 .writeObject(Asm, Layout);
331 Size += ELFWriter(*this, DwoOS, IsLittleEndian, ELFWriter::DwoOnly)
332 .writeObject(Asm, Layout);
337 } // end anonymous namespace
339 void ELFWriter::align(unsigned Alignment) {
340 uint64_t Padding = offsetToAlignment(W.OS.tell(), Align(Alignment));
341 W.OS.write_zeros(Padding);
344 unsigned ELFWriter::addToSectionTable(const MCSectionELF *Sec) {
345 SectionTable.push_back(Sec);
346 StrTabBuilder.add(Sec->getName());
347 return SectionTable.size();
350 void SymbolTableWriter::createSymtabShndx() {
351 if (!ShndxIndexes.empty())
354 ShndxIndexes.resize(NumWritten);
357 template <typename T> void SymbolTableWriter::write(T Value) {
358 EWriter.write(Value);
361 SymbolTableWriter::SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit)
362 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
364 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
365 uint64_t size, uint8_t other,
366 uint32_t shndx, bool Reserved) {
367 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
372 if (!ShndxIndexes.empty()) {
374 ShndxIndexes.push_back(shndx);
376 ShndxIndexes.push_back(0);
379 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
382 write(name); // st_name
383 write(info); // st_info
384 write(other); // st_other
385 write(Index); // st_shndx
386 write(value); // st_value
387 write(size); // st_size
389 write(name); // st_name
390 write(uint32_t(value)); // st_value
391 write(uint32_t(size)); // st_size
392 write(info); // st_info
393 write(other); // st_other
394 write(Index); // st_shndx
400 bool ELFWriter::is64Bit() const {
401 return OWriter.TargetObjectWriter->is64Bit();
404 bool ELFWriter::hasRelocationAddend() const {
405 return OWriter.hasRelocationAddend();
408 // Emit the ELF header.
409 void ELFWriter::writeHeader(const MCAssembler &Asm) {
415 // emitWord method behaves differently for ELF32 and ELF64, writing
416 // 4 bytes in the former and 8 in the latter.
418 W.OS << ELF::ElfMagic; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
420 W.OS << char(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
423 W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
426 W.OS << char(ELF::EV_CURRENT); // e_ident[EI_VERSION]
428 W.OS << char(OWriter.TargetObjectWriter->getOSABI());
429 // e_ident[EI_ABIVERSION]
430 W.OS << char(OWriter.TargetObjectWriter->getABIVersion());
432 W.OS.write_zeros(ELF::EI_NIDENT - ELF::EI_PAD);
434 W.write<uint16_t>(ELF::ET_REL); // e_type
436 W.write<uint16_t>(OWriter.TargetObjectWriter->getEMachine()); // e_machine = target
438 W.write<uint32_t>(ELF::EV_CURRENT); // e_version
439 WriteWord(0); // e_entry, no entry point in .o file
440 WriteWord(0); // e_phoff, no program header for .o
441 WriteWord(0); // e_shoff = sec hdr table off in bytes
443 // e_flags = whatever the target wants
444 W.write<uint32_t>(Asm.getELFHeaderEFlags());
446 // e_ehsize = ELF header size
447 W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr)
448 : sizeof(ELF::Elf32_Ehdr));
450 W.write<uint16_t>(0); // e_phentsize = prog header entry size
451 W.write<uint16_t>(0); // e_phnum = # prog header entries = 0
453 // e_shentsize = Section header entry size
454 W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr)
455 : sizeof(ELF::Elf32_Shdr));
457 // e_shnum = # of section header ents
458 W.write<uint16_t>(0);
460 // e_shstrndx = Section # of '.shstrtab'
461 assert(StringTableIndex < ELF::SHN_LORESERVE);
462 W.write<uint16_t>(StringTableIndex);
465 uint64_t ELFWriter::SymbolValue(const MCSymbol &Sym,
466 const MCAsmLayout &Layout) {
467 if (Sym.isCommon() && (Sym.isTargetCommon() || Sym.isExternal()))
468 return Sym.getCommonAlignment();
471 if (!Layout.getSymbolOffset(Sym, Res))
474 if (Layout.getAssembler().isThumbFunc(&Sym))
480 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
481 uint8_t Type = newType;
483 // Propagation rules:
484 // IFUNC > FUNC > OBJECT > NOTYPE
485 // TLS_OBJECT > OBJECT > NOTYPE
487 // dont let the new type degrade the old type
491 case ELF::STT_GNU_IFUNC:
492 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
493 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
494 Type = ELF::STT_GNU_IFUNC;
497 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
498 Type == ELF::STT_TLS)
499 Type = ELF::STT_FUNC;
501 case ELF::STT_OBJECT:
502 if (Type == ELF::STT_NOTYPE)
503 Type = ELF::STT_OBJECT;
506 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
507 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
515 static bool isIFunc(const MCSymbolELF *Symbol) {
516 while (Symbol->getType() != ELF::STT_GNU_IFUNC) {
517 const MCSymbolRefExpr *Value;
518 if (!Symbol->isVariable() ||
519 !(Value = dyn_cast<MCSymbolRefExpr>(Symbol->getVariableValue())) ||
520 Value->getKind() != MCSymbolRefExpr::VK_None ||
521 mergeTypeForSet(Symbol->getType(), ELF::STT_GNU_IFUNC) != ELF::STT_GNU_IFUNC)
523 Symbol = &cast<MCSymbolELF>(Value->getSymbol());
528 void ELFWriter::writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
529 ELFSymbolData &MSD, const MCAsmLayout &Layout) {
530 const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
531 const MCSymbolELF *Base =
532 cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
534 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
536 bool IsReserved = !Base || Symbol.isCommon();
538 // Binding and Type share the same byte as upper and lower nibbles
539 uint8_t Binding = Symbol.getBinding();
540 uint8_t Type = Symbol.getType();
541 if (isIFunc(&Symbol))
542 Type = ELF::STT_GNU_IFUNC;
544 Type = mergeTypeForSet(Type, Base->getType());
546 uint8_t Info = (Binding << 4) | Type;
548 // Other and Visibility share the same byte with Visibility using the lower
550 uint8_t Visibility = Symbol.getVisibility();
551 uint8_t Other = Symbol.getOther() | Visibility;
553 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
556 const MCExpr *ESize = MSD.Symbol->getSize();
558 ESize = Base->getSize();
562 if (!ESize->evaluateKnownAbsolute(Res, Layout))
563 report_fatal_error("Size expression must be absolute.");
567 // Write out the symbol table entry
568 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
572 bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
573 bool Used, bool Renamed) {
574 if (Symbol.isVariable()) {
575 const MCExpr *Expr = Symbol.getVariableValue();
576 // Target Expressions that are always inlined do not appear in the symtab
577 if (const auto *T = dyn_cast<MCTargetExpr>(Expr))
578 if (T->inlineAssignedExpr())
580 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
581 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
592 if (Symbol.isVariable() && Symbol.isUndefined()) {
593 // FIXME: this is here just to diagnose the case of a var = commmon_sym.
594 Layout.getBaseSymbol(Symbol);
598 if (Symbol.isTemporary())
601 if (Symbol.getType() == ELF::STT_SECTION)
607 void ELFWriter::computeSymbolTable(
608 MCAssembler &Asm, const MCAsmLayout &Layout,
609 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
610 SectionOffsetsTy &SectionOffsets) {
611 MCContext &Ctx = Asm.getContext();
612 SymbolTableWriter Writer(*this, is64Bit());
615 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
616 MCSectionELF *SymtabSection =
617 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
618 SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
619 SymbolTableIndex = addToSectionTable(SymtabSection);
621 align(SymtabSection->getAlignment());
622 uint64_t SecStart = W.OS.tell();
624 // The first entry is the undefined symbol entry.
625 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
627 std::vector<ELFSymbolData> LocalSymbolData;
628 std::vector<ELFSymbolData> ExternalSymbolData;
630 // Add the data for the symbols.
631 bool HasLargeSectionIndex = false;
632 for (const MCSymbol &S : Asm.symbols()) {
633 const auto &Symbol = cast<MCSymbolELF>(S);
634 bool Used = Symbol.isUsedInReloc();
635 bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
636 bool isSignature = Symbol.isSignature();
638 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
639 OWriter.Renames.count(&Symbol)))
642 if (Symbol.isTemporary() && Symbol.isUndefined()) {
643 Ctx.reportError(SMLoc(), "Undefined temporary symbol " + Symbol.getName());
648 MSD.Symbol = cast<MCSymbolELF>(&Symbol);
650 bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
651 assert(Local || !Symbol.isTemporary());
653 if (Symbol.isAbsolute()) {
654 MSD.SectionIndex = ELF::SHN_ABS;
655 } else if (Symbol.isCommon()) {
656 if (Symbol.isTargetCommon()) {
657 MSD.SectionIndex = Symbol.getIndex();
660 MSD.SectionIndex = ELF::SHN_COMMON;
662 } else if (Symbol.isUndefined()) {
663 if (isSignature && !Used) {
664 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
665 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
666 HasLargeSectionIndex = true;
668 MSD.SectionIndex = ELF::SHN_UNDEF;
671 const MCSectionELF &Section =
672 static_cast<const MCSectionELF &>(Symbol.getSection());
674 // We may end up with a situation when section symbol is technically
675 // defined, but should not be. That happens because we explicitly
676 // pre-create few .debug_* sections to have accessors.
677 // And if these sections were not really defined in the code, but were
678 // referenced, we simply error out.
679 if (!Section.isRegistered()) {
680 assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
682 Ctx.reportError(SMLoc(),
683 "Undefined section reference: " + Symbol.getName());
687 if (Mode == NonDwoOnly && isDwoSection(Section))
689 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
690 assert(MSD.SectionIndex && "Invalid section index!");
691 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
692 HasLargeSectionIndex = true;
695 StringRef Name = Symbol.getName();
697 // Sections have their own string table
698 if (Symbol.getType() != ELF::STT_SECTION) {
700 StrTabBuilder.add(Name);
704 LocalSymbolData.push_back(MSD);
706 ExternalSymbolData.push_back(MSD);
709 // This holds the .symtab_shndx section index.
710 unsigned SymtabShndxSectionIndex = 0;
712 if (HasLargeSectionIndex) {
713 MCSectionELF *SymtabShndxSection =
714 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
715 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
716 SymtabShndxSection->setAlignment(Align(4));
719 ArrayRef<std::string> FileNames = Asm.getFileNames();
720 for (const std::string &Name : FileNames)
721 StrTabBuilder.add(Name);
723 StrTabBuilder.finalize();
725 // File symbols are emitted first and handled separately from normal symbols,
726 // i.e. a non-STT_FILE symbol with the same name may appear.
727 for (const std::string &Name : FileNames)
728 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
729 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
732 // Symbols are required to be in lexicographic order.
733 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
734 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
736 // Set the symbol indices. Local symbols must come before all other
737 // symbols with non-local bindings.
738 unsigned Index = FileNames.size() + 1;
740 for (ELFSymbolData &MSD : LocalSymbolData) {
741 unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
743 : StrTabBuilder.getOffset(MSD.Name);
744 MSD.Symbol->setIndex(Index++);
745 writeSymbol(Writer, StringIndex, MSD, Layout);
748 // Write the symbol table entries.
749 LastLocalSymbolIndex = Index;
751 for (ELFSymbolData &MSD : ExternalSymbolData) {
752 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
753 MSD.Symbol->setIndex(Index++);
754 writeSymbol(Writer, StringIndex, MSD, Layout);
755 assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
758 uint64_t SecEnd = W.OS.tell();
759 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
761 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
762 if (ShndxIndexes.empty()) {
763 assert(SymtabShndxSectionIndex == 0);
766 assert(SymtabShndxSectionIndex != 0);
768 SecStart = W.OS.tell();
769 const MCSectionELF *SymtabShndxSection =
770 SectionTable[SymtabShndxSectionIndex - 1];
771 for (uint32_t Index : ShndxIndexes)
773 SecEnd = W.OS.tell();
774 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
777 void ELFWriter::writeAddrsigSection() {
778 for (const MCSymbol *Sym : OWriter.AddrsigSyms)
779 encodeULEB128(Sym->getIndex(), W.OS);
782 MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
783 const MCSectionELF &Sec) {
784 if (OWriter.Relocations[&Sec].empty())
787 const StringRef SectionName = Sec.getName();
788 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
789 RelaSectionName += SectionName;
792 if (hasRelocationAddend())
793 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
795 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
798 if (Sec.getFlags() & ELF::SHF_GROUP)
799 Flags = ELF::SHF_GROUP;
801 MCSectionELF *RelaSection = Ctx.createELFRelSection(
802 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
803 Flags, EntrySize, Sec.getGroup(), &Sec);
804 RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
808 // Include the debug info compression header.
809 bool ELFWriter::maybeWriteCompression(
810 uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
811 unsigned Alignment) {
814 is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
815 if (Size <= HdrSize + CompressedContents.size())
817 // Platform specific header is followed by compressed data.
819 // Write Elf64_Chdr header.
820 write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
821 write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
822 write(static_cast<ELF::Elf64_Xword>(Size));
823 write(static_cast<ELF::Elf64_Xword>(Alignment));
825 // Write Elf32_Chdr header otherwise.
826 write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
827 write(static_cast<ELF::Elf32_Word>(Size));
828 write(static_cast<ELF::Elf32_Word>(Alignment));
833 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
834 // useful for consumers to preallocate a buffer to decompress into.
835 const StringRef Magic = "ZLIB";
836 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
839 support::endian::write(W.OS, Size, support::big);
843 void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
844 const MCAsmLayout &Layout) {
845 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
846 StringRef SectionName = Section.getName();
848 auto &MC = Asm.getContext();
849 const auto &MAI = MC.getAsmInfo();
851 // Compressing debug_frame requires handling alignment fragments which is
852 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
853 // for writing to arbitrary buffers) for little benefit.
854 bool CompressionEnabled =
855 MAI->compressDebugSections() != DebugCompressionType::None;
856 if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
857 SectionName == ".debug_frame") {
858 Asm.writeSectionData(W.OS, &Section, Layout);
862 assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
863 MAI->compressDebugSections() == DebugCompressionType::GNU) &&
864 "expected zlib or zlib-gnu style compression");
866 SmallVector<char, 128> UncompressedData;
867 raw_svector_ostream VecOS(UncompressedData);
868 Asm.writeSectionData(VecOS, &Section, Layout);
870 SmallVector<char, 128> CompressedContents;
871 if (Error E = zlib::compress(
872 StringRef(UncompressedData.data(), UncompressedData.size()),
873 CompressedContents)) {
874 consumeError(std::move(E));
875 W.OS << UncompressedData;
879 bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
880 if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
881 ZlibStyle, Sec.getAlignment())) {
882 W.OS << UncompressedData;
887 // Set the compressed flag. That is zlib style.
888 Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
889 // Alignment field should reflect the requirements of
890 // the compressed section header.
891 Section.setAlignment(is64Bit() ? Align(8) : Align(4));
893 // Add "z" prefix to section name. This is zlib-gnu style.
894 MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
896 W.OS << CompressedContents;
899 void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
900 uint64_t Address, uint64_t Offset,
901 uint64_t Size, uint32_t Link, uint32_t Info,
902 uint64_t Alignment, uint64_t EntrySize) {
903 W.write<uint32_t>(Name); // sh_name: index into string table
904 W.write<uint32_t>(Type); // sh_type
905 WriteWord(Flags); // sh_flags
906 WriteWord(Address); // sh_addr
907 WriteWord(Offset); // sh_offset
908 WriteWord(Size); // sh_size
909 W.write<uint32_t>(Link); // sh_link
910 W.write<uint32_t>(Info); // sh_info
911 WriteWord(Alignment); // sh_addralign
912 WriteWord(EntrySize); // sh_entsize
915 void ELFWriter::writeRelocations(const MCAssembler &Asm,
916 const MCSectionELF &Sec) {
917 std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
919 // We record relocations by pushing to the end of a vector. Reverse the vector
920 // to get the relocations in the order they were created.
921 // In most cases that is not important, but it can be for special sections
922 // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
923 std::reverse(Relocs.begin(), Relocs.end());
925 // Sort the relocation entries. MIPS needs this.
926 OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
928 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
929 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
930 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
934 if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
935 write(uint32_t(Index));
937 write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
938 write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
939 write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
940 write(OWriter.TargetObjectWriter->getRType(Entry.Type));
942 struct ELF::Elf64_Rela ERE64;
943 ERE64.setSymbolAndType(Index, Entry.Type);
946 if (hasRelocationAddend())
949 write(uint32_t(Entry.Offset));
951 struct ELF::Elf32_Rela ERE32;
952 ERE32.setSymbolAndType(Index, Entry.Type);
955 if (hasRelocationAddend())
956 write(uint32_t(Entry.Addend));
958 if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
960 OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
961 write(uint32_t(Entry.Offset));
963 ERE32.setSymbolAndType(0, RType);
968 OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
969 write(uint32_t(Entry.Offset));
971 ERE32.setSymbolAndType(0, RType);
980 const MCSectionELF *ELFWriter::createStringTable(MCContext &Ctx) {
981 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
982 StrTabBuilder.write(W.OS);
983 return StrtabSection;
986 void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
987 uint32_t GroupSymbolIndex, uint64_t Offset,
988 uint64_t Size, const MCSectionELF &Section) {
989 uint64_t sh_link = 0;
990 uint64_t sh_info = 0;
992 switch(Section.getType()) {
997 case ELF::SHT_DYNAMIC:
998 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1001 case ELF::SHT_RELA: {
1002 sh_link = SymbolTableIndex;
1003 assert(sh_link && ".symtab not found");
1004 const MCSection *InfoSection = Section.getLinkedToSection();
1005 sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
1009 case ELF::SHT_SYMTAB:
1010 sh_link = StringTableIndex;
1011 sh_info = LastLocalSymbolIndex;
1014 case ELF::SHT_SYMTAB_SHNDX:
1015 case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
1016 case ELF::SHT_LLVM_ADDRSIG:
1017 sh_link = SymbolTableIndex;
1020 case ELF::SHT_GROUP:
1021 sh_link = SymbolTableIndex;
1022 sh_info = GroupSymbolIndex;
1026 if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
1027 const MCSymbol *Sym = Section.getLinkedToSymbol();
1028 const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
1029 sh_link = SectionIndexMap.lookup(Sec);
1032 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getName()),
1033 Section.getType(), Section.getFlags(), 0, Offset, Size,
1034 sh_link, sh_info, Section.getAlignment(),
1035 Section.getEntrySize());
1038 void ELFWriter::writeSectionHeader(
1039 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1040 const SectionOffsetsTy &SectionOffsets) {
1041 const unsigned NumSections = SectionTable.size();
1043 // Null section first.
1044 uint64_t FirstSectionSize =
1045 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1046 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1048 for (const MCSectionELF *Section : SectionTable) {
1049 uint32_t GroupSymbolIndex;
1050 unsigned Type = Section->getType();
1051 if (Type != ELF::SHT_GROUP)
1052 GroupSymbolIndex = 0;
1054 GroupSymbolIndex = Section->getGroup()->getIndex();
1056 const std::pair<uint64_t, uint64_t> &Offsets =
1057 SectionOffsets.find(Section)->second;
1059 if (Type == ELF::SHT_NOBITS)
1060 Size = Layout.getSectionAddressSize(Section);
1062 Size = Offsets.second - Offsets.first;
1064 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1069 uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1070 uint64_t StartOffset = W.OS.tell();
1072 MCContext &Ctx = Asm.getContext();
1073 MCSectionELF *StrtabSection =
1074 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1075 StringTableIndex = addToSectionTable(StrtabSection);
1077 RevGroupMapTy RevGroupMap;
1078 SectionIndexMapTy SectionIndexMap;
1080 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1082 // Write out the ELF header ...
1085 // ... then the sections ...
1086 SectionOffsetsTy SectionOffsets;
1087 std::vector<MCSectionELF *> Groups;
1088 std::vector<MCSectionELF *> Relocations;
1089 for (MCSection &Sec : Asm) {
1090 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1091 if (Mode == NonDwoOnly && isDwoSection(Section))
1093 if (Mode == DwoOnly && !isDwoSection(Section))
1096 align(Section.getAlignment());
1098 // Remember the offset into the file for this section.
1099 uint64_t SecStart = W.OS.tell();
1101 const MCSymbolELF *SignatureSymbol = Section.getGroup();
1102 writeSectionData(Asm, Section, Layout);
1104 uint64_t SecEnd = W.OS.tell();
1105 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1107 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1109 if (SignatureSymbol) {
1110 Asm.registerSymbol(*SignatureSymbol);
1111 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1113 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1114 GroupIdx = addToSectionTable(Group);
1115 Group->setAlignment(Align(4));
1116 Groups.push_back(Group);
1118 std::vector<const MCSectionELF *> &Members =
1119 GroupMembers[SignatureSymbol];
1120 Members.push_back(&Section);
1122 Members.push_back(RelSection);
1125 SectionIndexMap[&Section] = addToSectionTable(&Section);
1127 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1128 Relocations.push_back(RelSection);
1131 OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
1134 MCSectionELF *CGProfileSection = nullptr;
1135 if (!Asm.CGProfile.empty()) {
1136 CGProfileSection = Ctx.getELFSection(".llvm.call-graph-profile",
1137 ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
1138 ELF::SHF_EXCLUDE, 16, "");
1139 SectionIndexMap[CGProfileSection] = addToSectionTable(CGProfileSection);
1142 for (MCSectionELF *Group : Groups) {
1143 align(Group->getAlignment());
1145 // Remember the offset into the file for this section.
1146 uint64_t SecStart = W.OS.tell();
1148 const MCSymbol *SignatureSymbol = Group->getGroup();
1149 assert(SignatureSymbol);
1150 write(uint32_t(ELF::GRP_COMDAT));
1151 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1152 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1156 uint64_t SecEnd = W.OS.tell();
1157 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1160 if (Mode == DwoOnly) {
1161 // dwo files don't have symbol tables or relocations, but they do have
1163 StrTabBuilder.finalize();
1165 MCSectionELF *AddrsigSection;
1166 if (OWriter.EmitAddrsigSection) {
1167 AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
1169 addToSectionTable(AddrsigSection);
1172 // Compute symbol table information.
1173 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1176 for (MCSectionELF *RelSection : Relocations) {
1177 align(RelSection->getAlignment());
1179 // Remember the offset into the file for this section.
1180 uint64_t SecStart = W.OS.tell();
1182 writeRelocations(Asm,
1183 cast<MCSectionELF>(*RelSection->getLinkedToSection()));
1185 uint64_t SecEnd = W.OS.tell();
1186 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1189 if (OWriter.EmitAddrsigSection) {
1190 uint64_t SecStart = W.OS.tell();
1191 writeAddrsigSection();
1192 uint64_t SecEnd = W.OS.tell();
1193 SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
1197 if (CGProfileSection) {
1198 uint64_t SecStart = W.OS.tell();
1199 for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
1200 W.write<uint32_t>(CGPE.From->getSymbol().getIndex());
1201 W.write<uint32_t>(CGPE.To->getSymbol().getIndex());
1202 W.write<uint64_t>(CGPE.Count);
1204 uint64_t SecEnd = W.OS.tell();
1205 SectionOffsets[CGProfileSection] = std::make_pair(SecStart, SecEnd);
1209 uint64_t SecStart = W.OS.tell();
1210 const MCSectionELF *Sec = createStringTable(Ctx);
1211 uint64_t SecEnd = W.OS.tell();
1212 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1215 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1216 align(NaturalAlignment);
1218 const uint64_t SectionHeaderOffset = W.OS.tell();
1220 // ... then the section header table ...
1221 writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1223 uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1224 (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1225 : SectionTable.size() + 1,
1227 unsigned NumSectionsOffset;
1229 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1232 support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1233 Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1234 offsetof(ELF::Elf64_Ehdr, e_shoff));
1235 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1238 support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1239 Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1240 offsetof(ELF::Elf32_Ehdr, e_shoff));
1241 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1243 Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1246 return W.OS.tell() - StartOffset;
1249 bool ELFObjectWriter::hasRelocationAddend() const {
1250 return TargetObjectWriter->hasRelocationAddend();
1253 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1254 const MCAsmLayout &Layout) {
1255 // The presence of symbol versions causes undefined symbols and
1256 // versions declared with @@@ to be renamed.
1257 for (const std::pair<StringRef, const MCSymbol *> &P : Asm.Symvers) {
1258 StringRef AliasName = P.first;
1259 const auto &Symbol = cast<MCSymbolELF>(*P.second);
1260 size_t Pos = AliasName.find('@');
1261 assert(Pos != StringRef::npos);
1263 StringRef Prefix = AliasName.substr(0, Pos);
1264 StringRef Rest = AliasName.substr(Pos);
1265 StringRef Tail = Rest;
1266 if (Rest.startswith("@@@"))
1267 Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1270 cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1271 Asm.registerSymbol(*Alias);
1272 const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1273 Alias->setVariableValue(Value);
1275 // Aliases defined with .symvar copy the binding from the symbol they alias.
1276 // This is the first place we are able to copy this information.
1277 Alias->setExternal(Symbol.isExternal());
1278 Alias->setBinding(Symbol.getBinding());
1279 Alias->setOther(Symbol.getOther());
1281 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
1284 // FIXME: Get source locations for these errors or diagnose them earlier.
1285 if (Symbol.isUndefined() && Rest.startswith("@@") &&
1286 !Rest.startswith("@@@")) {
1287 Asm.getContext().reportError(SMLoc(), "versioned symbol " + AliasName +
1288 " must be defined");
1292 if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
1293 Asm.getContext().reportError(
1294 SMLoc(), llvm::Twine("multiple symbol versions defined for ") +
1299 Renames.insert(std::make_pair(&Symbol, Alias));
1302 for (const MCSymbol *&Sym : AddrsigSyms) {
1303 if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
1305 if (Sym->isInSection() && Sym->getName().startswith(".L"))
1306 Sym = Sym->getSection().getBeginSymbol();
1307 Sym->setUsedInReloc();
1311 // It is always valid to create a relocation with a symbol. It is preferable
1312 // to use a relocation with a section if that is possible. Using the section
1313 // allows us to omit some local symbols from the symbol table.
1314 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1315 const MCSymbolRefExpr *RefA,
1316 const MCSymbolELF *Sym,
1318 unsigned Type) const {
1319 // A PCRel relocation to an absolute value has no symbol (or section). We
1320 // represent that with a relocation to a null section.
1324 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1328 // The .odp creation emits a relocation against the symbol ".TOC." which
1329 // create a R_PPC64_TOC relocation. However the relocation symbol name
1330 // in final object creation should be NULL, since the symbol does not
1331 // really exist, it is just the reference to TOC base for the current
1332 // object file. Since the symbol is undefined, returning false results
1333 // in a relocation with a null section which is the desired result.
1334 case MCSymbolRefExpr::VK_PPC_TOCBASE:
1337 // These VariantKind cause the relocation to refer to something other than
1338 // the symbol itself, like a linker generated table. Since the address of
1339 // symbol is not relevant, we cannot replace the symbol with the
1340 // section and patch the difference in the addend.
1341 case MCSymbolRefExpr::VK_GOT:
1342 case MCSymbolRefExpr::VK_PLT:
1343 case MCSymbolRefExpr::VK_GOTPCREL:
1344 case MCSymbolRefExpr::VK_PPC_GOT_LO:
1345 case MCSymbolRefExpr::VK_PPC_GOT_HI:
1346 case MCSymbolRefExpr::VK_PPC_GOT_HA:
1350 // An undefined symbol is not in any section, so the relocation has to point
1351 // to the symbol itself.
1352 assert(Sym && "Expected a symbol");
1353 if (Sym->isUndefined())
1356 unsigned Binding = Sym->getBinding();
1359 llvm_unreachable("Invalid Binding");
1360 case ELF::STB_LOCAL:
1363 // If the symbol is weak, it might be overridden by a symbol in another
1364 // file. The relocation has to point to the symbol so that the linker
1367 case ELF::STB_GLOBAL:
1368 // Global ELF symbols can be preempted by the dynamic linker. The relocation
1369 // has to point to the symbol for a reason analogous to the STB_WEAK case.
1373 // Keep symbol type for a local ifunc because it may result in an IRELATIVE
1374 // reloc that the dynamic loader will use to resolve the address at startup
1376 if (Sym->getType() == ELF::STT_GNU_IFUNC)
1379 // If a relocation points to a mergeable section, we have to be careful.
1380 // If the offset is zero, a relocation with the section will encode the
1381 // same information. With a non-zero offset, the situation is different.
1382 // For example, a relocation can point 42 bytes past the end of a string.
1383 // If we change such a relocation to use the section, the linker would think
1384 // that it pointed to another string and subtracting 42 at runtime will
1385 // produce the wrong value.
1386 if (Sym->isInSection()) {
1387 auto &Sec = cast<MCSectionELF>(Sym->getSection());
1388 unsigned Flags = Sec.getFlags();
1389 if (Flags & ELF::SHF_MERGE) {
1393 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
1394 // only handle section relocations to mergeable sections if using RELA.
1395 if (!hasRelocationAddend())
1399 // Most TLS relocations use a got, so they need the symbol. Even those that
1400 // are just an offset (@tpoff), require a symbol in gold versions before
1401 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1402 // http://sourceware.org/PR16773.
1403 if (Flags & ELF::SHF_TLS)
1407 // If the symbol is a thumb function the final relocation must set the lowest
1408 // bit. With a symbol that is done by just having the symbol have that bit
1409 // set, so we would lose the bit if we relocated with the section.
1410 // FIXME: We could use the section but add the bit to the relocation value.
1411 if (Asm.isThumbFunc(Sym))
1414 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1419 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1420 const MCAsmLayout &Layout,
1421 const MCFragment *Fragment,
1422 const MCFixup &Fixup, MCValue Target,
1423 uint64_t &FixedValue) {
1424 MCAsmBackend &Backend = Asm.getBackend();
1425 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1426 MCFixupKindInfo::FKF_IsPCRel;
1427 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1428 uint64_t C = Target.getConstant();
1429 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1430 MCContext &Ctx = Asm.getContext();
1432 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1433 const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1434 if (SymB.isUndefined()) {
1435 Ctx.reportError(Fixup.getLoc(),
1436 Twine("symbol '") + SymB.getName() +
1437 "' can not be undefined in a subtraction expression");
1441 assert(!SymB.isAbsolute() && "Should have been folded");
1442 const MCSection &SecB = SymB.getSection();
1443 if (&SecB != &FixupSection) {
1444 Ctx.reportError(Fixup.getLoc(),
1445 "Cannot represent a difference across sections");
1449 assert(!IsPCRel && "should have been folded");
1451 C += FixupOffset - Layout.getSymbolOffset(SymB);
1454 // We either rejected the fixup or folded B into C at this point.
1455 const MCSymbolRefExpr *RefA = Target.getSymA();
1456 const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1458 bool ViaWeakRef = false;
1459 if (SymA && SymA->isVariable()) {
1460 const MCExpr *Expr = SymA->getVariableValue();
1461 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1462 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1463 SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1469 const MCSectionELF *SecA = (SymA && SymA->isInSection())
1470 ? cast<MCSectionELF>(&SymA->getSection())
1472 if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
1475 unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1476 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
1477 uint64_t Addend = 0;
1479 FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
1480 ? C + Layout.getSymbolOffset(*SymA)
1482 if (hasRelocationAddend()) {
1483 Addend = FixedValue;
1487 if (!RelocateWithSymbol) {
1488 const auto *SectionSymbol =
1489 SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1491 SectionSymbol->setUsedInReloc();
1492 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
1493 Relocations[&FixupSection].push_back(Rec);
1497 const MCSymbolELF *RenamedSymA = SymA;
1499 if (const MCSymbolELF *R = Renames.lookup(SymA))
1503 RenamedSymA->setIsWeakrefUsedInReloc();
1505 RenamedSymA->setUsedInReloc();
1507 ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
1508 Relocations[&FixupSection].push_back(Rec);
1511 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1512 const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1513 bool InSet, bool IsPCRel) const {
1514 const auto &SymA = cast<MCSymbolELF>(SA);
1517 if (SymA.getBinding() != ELF::STB_LOCAL ||
1518 SymA.getType() == ELF::STT_GNU_IFUNC)
1521 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1525 std::unique_ptr<MCObjectWriter>
1526 llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1527 raw_pwrite_stream &OS, bool IsLittleEndian) {
1528 return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1532 std::unique_ptr<MCObjectWriter>
1533 llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1534 raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
1535 bool IsLittleEndian) {
1536 return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,