[InstCombine] Signed saturation patterns
[llvm-core.git] / lib / MC / ELFObjectWriter.cpp
blob6f160e491cea565473cdf6204e0ec0a6e7fab7a5
1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
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 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/Endian.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"
53 #include <algorithm>
54 #include <cassert>
55 #include <cstddef>
56 #include <cstdint>
57 #include <map>
58 #include <memory>
59 #include <string>
60 #include <utility>
61 #include <vector>
63 using namespace llvm;
65 #undef DEBUG_TYPE
66 #define DEBUG_TYPE "reloc-info"
68 namespace {
70 using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
72 class ELFObjectWriter;
73 struct ELFWriter;
75 bool isDwoSection(const MCSectionELF &Sec) {
76 return Sec.getSectionName().endswith(".dwo");
79 class SymbolTableWriter {
80 ELFWriter &EWriter;
81 bool Is64Bit;
83 // indexes we are going to write to .symtab_shndx.
84 std::vector<uint32_t> ShndxIndexes;
86 // The numbel of symbols written so far.
87 unsigned NumWritten;
89 void createSymtabShndx();
91 template <typename T> void write(T Value);
93 public:
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; }
102 struct ELFWriter {
103 ELFObjectWriter &OWriter;
104 support::endian::Writer W;
106 enum DwoMode {
107 AllSections,
108 NonDwoOnly,
109 DwoOnly,
110 } Mode;
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;
120 StringRef Name;
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)
127 return false;
128 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
129 return true;
130 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
131 return SectionIndex < RHS.SectionIndex;
132 return Name < RHS.Name;
136 /// @}
137 /// @name Symbol Table Data
138 /// @{
140 StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
142 /// @}
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);
165 public:
166 ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
167 bool IsLittleEndian, DwoMode Mode)
168 : OWriter(OWriter),
169 W(OS, IsLittleEndian ? support::little : support::big), Mode(Mode) {}
171 void WriteWord(uint64_t Word) {
172 if (is64Bit())
173 W.write<uint64_t>(Word);
174 else
175 W.write<uint32_t>(Word);
178 template <typename T> void write(T Val) {
179 W.write(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,
221 uint64_t EntrySize);
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;
249 public:
250 ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
251 : TargetObjectWriter(std::move(MOTW)) {}
253 void reset() override {
254 Relocations.clear();
255 Renames.clear();
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) {
267 return true;
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;
287 bool IsLittleEndian;
289 public:
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;
305 bool IsLittleEndian;
307 public:
308 ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
309 raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
310 bool IsLittleEndian)
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");
319 return false;
321 if (To && isDwoSection(*To)) {
322 Ctx.reportError(Loc, "A relocation may not refer to a dwo section");
323 return false;
325 return true;
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);
333 return Size;
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->getSectionName());
347 return SectionTable.size();
350 void SymbolTableWriter::createSymtabShndx() {
351 if (!ShndxIndexes.empty())
352 return;
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;
369 if (LargeIndex)
370 createSymtabShndx();
372 if (!ShndxIndexes.empty()) {
373 if (LargeIndex)
374 ShndxIndexes.push_back(shndx);
375 else
376 ShndxIndexes.push_back(0);
379 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
381 if (Is64Bit) {
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
388 } else {
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
397 ++NumWritten;
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) {
410 // ELF Header
411 // ----------
413 // Note
414 // ----
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]
422 // e_ident[EI_DATA]
423 W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
424 : ELF::ELFDATA2MSB);
426 W.OS << char(ELF::EV_CURRENT); // e_ident[EI_VERSION]
427 // e_ident[EI_OSABI]
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();
470 uint64_t Res;
471 if (!Layout.getSymbolOffset(Sym, Res))
472 return 0;
474 if (Layout.getAssembler().isThumbFunc(&Sym))
475 Res |= 1;
477 return Res;
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
488 switch (origType) {
489 default:
490 break;
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;
495 break;
496 case ELF::STT_FUNC:
497 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
498 Type == ELF::STT_TLS)
499 Type = ELF::STT_FUNC;
500 break;
501 case ELF::STT_OBJECT:
502 if (Type == ELF::STT_NOTYPE)
503 Type = ELF::STT_OBJECT;
504 break;
505 case ELF::STT_TLS:
506 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
507 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
508 Type = ELF::STT_TLS;
509 break;
512 return Type;
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)
522 return false;
523 Symbol = &cast<MCSymbolELF>(Value->getSymbol());
525 return true;
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
535 // SHN_COMMON.
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;
543 if (Base) {
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
549 // 2 bits
550 uint8_t Visibility = Symbol.getVisibility();
551 uint8_t Other = Symbol.getOther() | Visibility;
553 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
554 uint64_t Size = 0;
556 const MCExpr *ESize = MSD.Symbol->getSize();
557 if (!ESize && Base)
558 ESize = Base->getSize();
560 if (ESize) {
561 int64_t Res;
562 if (!ESize->evaluateKnownAbsolute(Res, Layout))
563 report_fatal_error("Size expression must be absolute.");
564 Size = Res;
567 // Write out the symbol table entry
568 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
569 IsReserved);
572 // True if the assembler knows nothing about the final value of the symbol.
573 // This doesn't cover the comdat issues, since in those cases the assembler
574 // can at least know that all symbols in the section will move together.
575 static bool isWeak(const MCSymbolELF &Sym) {
576 if (Sym.getType() == ELF::STT_GNU_IFUNC)
577 return true;
579 switch (Sym.getBinding()) {
580 default:
581 llvm_unreachable("Unknown binding");
582 case ELF::STB_LOCAL:
583 return false;
584 case ELF::STB_GLOBAL:
585 return false;
586 case ELF::STB_WEAK:
587 case ELF::STB_GNU_UNIQUE:
588 return true;
592 bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
593 bool Used, bool Renamed) {
594 if (Symbol.isVariable()) {
595 const MCExpr *Expr = Symbol.getVariableValue();
596 // Target Expressions that are always inlined do not appear in the symtab
597 if (const auto *T = dyn_cast<MCTargetExpr>(Expr))
598 if (T->inlineAssignedExpr())
599 return false;
600 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
601 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
602 return false;
606 if (Used)
607 return true;
609 if (Renamed)
610 return false;
612 if (Symbol.isVariable() && Symbol.isUndefined()) {
613 // FIXME: this is here just to diagnose the case of a var = commmon_sym.
614 Layout.getBaseSymbol(Symbol);
615 return false;
618 if (Symbol.isUndefined() && !Symbol.isBindingSet())
619 return false;
621 if (Symbol.isTemporary())
622 return false;
624 if (Symbol.getType() == ELF::STT_SECTION)
625 return false;
627 return true;
630 void ELFWriter::computeSymbolTable(
631 MCAssembler &Asm, const MCAsmLayout &Layout,
632 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
633 SectionOffsetsTy &SectionOffsets) {
634 MCContext &Ctx = Asm.getContext();
635 SymbolTableWriter Writer(*this, is64Bit());
637 // Symbol table
638 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
639 MCSectionELF *SymtabSection =
640 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
641 SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
642 SymbolTableIndex = addToSectionTable(SymtabSection);
644 align(SymtabSection->getAlignment());
645 uint64_t SecStart = W.OS.tell();
647 // The first entry is the undefined symbol entry.
648 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
650 std::vector<ELFSymbolData> LocalSymbolData;
651 std::vector<ELFSymbolData> ExternalSymbolData;
653 // Add the data for the symbols.
654 bool HasLargeSectionIndex = false;
655 for (const MCSymbol &S : Asm.symbols()) {
656 const auto &Symbol = cast<MCSymbolELF>(S);
657 bool Used = Symbol.isUsedInReloc();
658 bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
659 bool isSignature = Symbol.isSignature();
661 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
662 OWriter.Renames.count(&Symbol)))
663 continue;
665 if (Symbol.isTemporary() && Symbol.isUndefined()) {
666 Ctx.reportError(SMLoc(), "Undefined temporary symbol");
667 continue;
670 ELFSymbolData MSD;
671 MSD.Symbol = cast<MCSymbolELF>(&Symbol);
673 bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
674 assert(Local || !Symbol.isTemporary());
676 if (Symbol.isAbsolute()) {
677 MSD.SectionIndex = ELF::SHN_ABS;
678 } else if (Symbol.isCommon()) {
679 if (Symbol.isTargetCommon()) {
680 MSD.SectionIndex = Symbol.getIndex();
681 } else {
682 assert(!Local);
683 MSD.SectionIndex = ELF::SHN_COMMON;
685 } else if (Symbol.isUndefined()) {
686 if (isSignature && !Used) {
687 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
688 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
689 HasLargeSectionIndex = true;
690 } else {
691 MSD.SectionIndex = ELF::SHN_UNDEF;
693 } else {
694 const MCSectionELF &Section =
695 static_cast<const MCSectionELF &>(Symbol.getSection());
697 // We may end up with a situation when section symbol is technically
698 // defined, but should not be. That happens because we explicitly
699 // pre-create few .debug_* sections to have accessors.
700 // And if these sections were not really defined in the code, but were
701 // referenced, we simply error out.
702 if (!Section.isRegistered()) {
703 assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
704 ELF::STT_SECTION);
705 Ctx.reportError(SMLoc(),
706 "Undefined section reference: " + Symbol.getName());
707 continue;
710 if (Mode == NonDwoOnly && isDwoSection(Section))
711 continue;
712 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
713 assert(MSD.SectionIndex && "Invalid section index!");
714 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
715 HasLargeSectionIndex = true;
718 StringRef Name = Symbol.getName();
720 // Sections have their own string table
721 if (Symbol.getType() != ELF::STT_SECTION) {
722 MSD.Name = Name;
723 StrTabBuilder.add(Name);
726 if (Local)
727 LocalSymbolData.push_back(MSD);
728 else
729 ExternalSymbolData.push_back(MSD);
732 // This holds the .symtab_shndx section index.
733 unsigned SymtabShndxSectionIndex = 0;
735 if (HasLargeSectionIndex) {
736 MCSectionELF *SymtabShndxSection =
737 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
738 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
739 SymtabShndxSection->setAlignment(Align(4));
742 ArrayRef<std::string> FileNames = Asm.getFileNames();
743 for (const std::string &Name : FileNames)
744 StrTabBuilder.add(Name);
746 StrTabBuilder.finalize();
748 // File symbols are emitted first and handled separately from normal symbols,
749 // i.e. a non-STT_FILE symbol with the same name may appear.
750 for (const std::string &Name : FileNames)
751 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
752 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
753 ELF::SHN_ABS, true);
755 // Symbols are required to be in lexicographic order.
756 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
757 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
759 // Set the symbol indices. Local symbols must come before all other
760 // symbols with non-local bindings.
761 unsigned Index = FileNames.size() + 1;
763 for (ELFSymbolData &MSD : LocalSymbolData) {
764 unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
766 : StrTabBuilder.getOffset(MSD.Name);
767 MSD.Symbol->setIndex(Index++);
768 writeSymbol(Writer, StringIndex, MSD, Layout);
771 // Write the symbol table entries.
772 LastLocalSymbolIndex = Index;
774 for (ELFSymbolData &MSD : ExternalSymbolData) {
775 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
776 MSD.Symbol->setIndex(Index++);
777 writeSymbol(Writer, StringIndex, MSD, Layout);
778 assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
781 uint64_t SecEnd = W.OS.tell();
782 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
784 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
785 if (ShndxIndexes.empty()) {
786 assert(SymtabShndxSectionIndex == 0);
787 return;
789 assert(SymtabShndxSectionIndex != 0);
791 SecStart = W.OS.tell();
792 const MCSectionELF *SymtabShndxSection =
793 SectionTable[SymtabShndxSectionIndex - 1];
794 for (uint32_t Index : ShndxIndexes)
795 write(Index);
796 SecEnd = W.OS.tell();
797 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
800 void ELFWriter::writeAddrsigSection() {
801 for (const MCSymbol *Sym : OWriter.AddrsigSyms)
802 encodeULEB128(Sym->getIndex(), W.OS);
805 MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
806 const MCSectionELF &Sec) {
807 if (OWriter.Relocations[&Sec].empty())
808 return nullptr;
810 const StringRef SectionName = Sec.getSectionName();
811 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
812 RelaSectionName += SectionName;
814 unsigned EntrySize;
815 if (hasRelocationAddend())
816 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
817 else
818 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
820 unsigned Flags = 0;
821 if (Sec.getFlags() & ELF::SHF_GROUP)
822 Flags = ELF::SHF_GROUP;
824 MCSectionELF *RelaSection = Ctx.createELFRelSection(
825 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
826 Flags, EntrySize, Sec.getGroup(), &Sec);
827 RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
828 return RelaSection;
831 // Include the debug info compression header.
832 bool ELFWriter::maybeWriteCompression(
833 uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
834 unsigned Alignment) {
835 if (ZLibStyle) {
836 uint64_t HdrSize =
837 is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
838 if (Size <= HdrSize + CompressedContents.size())
839 return false;
840 // Platform specific header is followed by compressed data.
841 if (is64Bit()) {
842 // Write Elf64_Chdr header.
843 write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
844 write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
845 write(static_cast<ELF::Elf64_Xword>(Size));
846 write(static_cast<ELF::Elf64_Xword>(Alignment));
847 } else {
848 // Write Elf32_Chdr header otherwise.
849 write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
850 write(static_cast<ELF::Elf32_Word>(Size));
851 write(static_cast<ELF::Elf32_Word>(Alignment));
853 return true;
856 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
857 // useful for consumers to preallocate a buffer to decompress into.
858 const StringRef Magic = "ZLIB";
859 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
860 return false;
861 W.OS << Magic;
862 support::endian::write(W.OS, Size, support::big);
863 return true;
866 void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
867 const MCAsmLayout &Layout) {
868 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
869 StringRef SectionName = Section.getSectionName();
871 auto &MC = Asm.getContext();
872 const auto &MAI = MC.getAsmInfo();
874 // Compressing debug_frame requires handling alignment fragments which is
875 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
876 // for writing to arbitrary buffers) for little benefit.
877 bool CompressionEnabled =
878 MAI->compressDebugSections() != DebugCompressionType::None;
879 if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
880 SectionName == ".debug_frame") {
881 Asm.writeSectionData(W.OS, &Section, Layout);
882 return;
885 assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
886 MAI->compressDebugSections() == DebugCompressionType::GNU) &&
887 "expected zlib or zlib-gnu style compression");
889 SmallVector<char, 128> UncompressedData;
890 raw_svector_ostream VecOS(UncompressedData);
891 Asm.writeSectionData(VecOS, &Section, Layout);
893 SmallVector<char, 128> CompressedContents;
894 if (Error E = zlib::compress(
895 StringRef(UncompressedData.data(), UncompressedData.size()),
896 CompressedContents)) {
897 consumeError(std::move(E));
898 W.OS << UncompressedData;
899 return;
902 bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
903 if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
904 ZlibStyle, Sec.getAlignment())) {
905 W.OS << UncompressedData;
906 return;
909 if (ZlibStyle) {
910 // Set the compressed flag. That is zlib style.
911 Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
912 // Alignment field should reflect the requirements of
913 // the compressed section header.
914 Section.setAlignment(is64Bit() ? Align(8) : Align(4));
915 } else {
916 // Add "z" prefix to section name. This is zlib-gnu style.
917 MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
919 W.OS << CompressedContents;
922 void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
923 uint64_t Address, uint64_t Offset,
924 uint64_t Size, uint32_t Link, uint32_t Info,
925 uint64_t Alignment, uint64_t EntrySize) {
926 W.write<uint32_t>(Name); // sh_name: index into string table
927 W.write<uint32_t>(Type); // sh_type
928 WriteWord(Flags); // sh_flags
929 WriteWord(Address); // sh_addr
930 WriteWord(Offset); // sh_offset
931 WriteWord(Size); // sh_size
932 W.write<uint32_t>(Link); // sh_link
933 W.write<uint32_t>(Info); // sh_info
934 WriteWord(Alignment); // sh_addralign
935 WriteWord(EntrySize); // sh_entsize
938 void ELFWriter::writeRelocations(const MCAssembler &Asm,
939 const MCSectionELF &Sec) {
940 std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
942 // We record relocations by pushing to the end of a vector. Reverse the vector
943 // to get the relocations in the order they were created.
944 // In most cases that is not important, but it can be for special sections
945 // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
946 std::reverse(Relocs.begin(), Relocs.end());
948 // Sort the relocation entries. MIPS needs this.
949 OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
951 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
952 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
953 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
955 if (is64Bit()) {
956 write(Entry.Offset);
957 if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
958 write(uint32_t(Index));
960 write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
961 write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
962 write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
963 write(OWriter.TargetObjectWriter->getRType(Entry.Type));
964 } else {
965 struct ELF::Elf64_Rela ERE64;
966 ERE64.setSymbolAndType(Index, Entry.Type);
967 write(ERE64.r_info);
969 if (hasRelocationAddend())
970 write(Entry.Addend);
971 } else {
972 write(uint32_t(Entry.Offset));
974 struct ELF::Elf32_Rela ERE32;
975 ERE32.setSymbolAndType(Index, Entry.Type);
976 write(ERE32.r_info);
978 if (hasRelocationAddend())
979 write(uint32_t(Entry.Addend));
981 if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
982 if (uint32_t RType =
983 OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
984 write(uint32_t(Entry.Offset));
986 ERE32.setSymbolAndType(0, RType);
987 write(ERE32.r_info);
988 write(uint32_t(0));
990 if (uint32_t RType =
991 OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
992 write(uint32_t(Entry.Offset));
994 ERE32.setSymbolAndType(0, RType);
995 write(ERE32.r_info);
996 write(uint32_t(0));
1003 const MCSectionELF *ELFWriter::createStringTable(MCContext &Ctx) {
1004 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1005 StrTabBuilder.write(W.OS);
1006 return StrtabSection;
1009 void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1010 uint32_t GroupSymbolIndex, uint64_t Offset,
1011 uint64_t Size, const MCSectionELF &Section) {
1012 uint64_t sh_link = 0;
1013 uint64_t sh_info = 0;
1015 switch(Section.getType()) {
1016 default:
1017 // Nothing to do.
1018 break;
1020 case ELF::SHT_DYNAMIC:
1021 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1023 case ELF::SHT_REL:
1024 case ELF::SHT_RELA: {
1025 sh_link = SymbolTableIndex;
1026 assert(sh_link && ".symtab not found");
1027 const MCSection *InfoSection = Section.getAssociatedSection();
1028 sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
1029 break;
1032 case ELF::SHT_SYMTAB:
1033 sh_link = StringTableIndex;
1034 sh_info = LastLocalSymbolIndex;
1035 break;
1037 case ELF::SHT_SYMTAB_SHNDX:
1038 case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
1039 case ELF::SHT_LLVM_ADDRSIG:
1040 sh_link = SymbolTableIndex;
1041 break;
1043 case ELF::SHT_GROUP:
1044 sh_link = SymbolTableIndex;
1045 sh_info = GroupSymbolIndex;
1046 break;
1049 if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
1050 const MCSymbol *Sym = Section.getAssociatedSymbol();
1051 const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
1052 sh_link = SectionIndexMap.lookup(Sec);
1055 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1056 Section.getType(), Section.getFlags(), 0, Offset, Size,
1057 sh_link, sh_info, Section.getAlignment(),
1058 Section.getEntrySize());
1061 void ELFWriter::writeSectionHeader(
1062 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1063 const SectionOffsetsTy &SectionOffsets) {
1064 const unsigned NumSections = SectionTable.size();
1066 // Null section first.
1067 uint64_t FirstSectionSize =
1068 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1069 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1071 for (const MCSectionELF *Section : SectionTable) {
1072 uint32_t GroupSymbolIndex;
1073 unsigned Type = Section->getType();
1074 if (Type != ELF::SHT_GROUP)
1075 GroupSymbolIndex = 0;
1076 else
1077 GroupSymbolIndex = Section->getGroup()->getIndex();
1079 const std::pair<uint64_t, uint64_t> &Offsets =
1080 SectionOffsets.find(Section)->second;
1081 uint64_t Size;
1082 if (Type == ELF::SHT_NOBITS)
1083 Size = Layout.getSectionAddressSize(Section);
1084 else
1085 Size = Offsets.second - Offsets.first;
1087 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1088 *Section);
1092 uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1093 uint64_t StartOffset = W.OS.tell();
1095 MCContext &Ctx = Asm.getContext();
1096 MCSectionELF *StrtabSection =
1097 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1098 StringTableIndex = addToSectionTable(StrtabSection);
1100 RevGroupMapTy RevGroupMap;
1101 SectionIndexMapTy SectionIndexMap;
1103 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1105 // Write out the ELF header ...
1106 writeHeader(Asm);
1108 // ... then the sections ...
1109 SectionOffsetsTy SectionOffsets;
1110 std::vector<MCSectionELF *> Groups;
1111 std::vector<MCSectionELF *> Relocations;
1112 for (MCSection &Sec : Asm) {
1113 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1114 if (Mode == NonDwoOnly && isDwoSection(Section))
1115 continue;
1116 if (Mode == DwoOnly && !isDwoSection(Section))
1117 continue;
1119 align(Section.getAlignment());
1121 // Remember the offset into the file for this section.
1122 uint64_t SecStart = W.OS.tell();
1124 const MCSymbolELF *SignatureSymbol = Section.getGroup();
1125 writeSectionData(Asm, Section, Layout);
1127 uint64_t SecEnd = W.OS.tell();
1128 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1130 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1132 if (SignatureSymbol) {
1133 Asm.registerSymbol(*SignatureSymbol);
1134 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1135 if (!GroupIdx) {
1136 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1137 GroupIdx = addToSectionTable(Group);
1138 Group->setAlignment(Align(4));
1139 Groups.push_back(Group);
1141 std::vector<const MCSectionELF *> &Members =
1142 GroupMembers[SignatureSymbol];
1143 Members.push_back(&Section);
1144 if (RelSection)
1145 Members.push_back(RelSection);
1148 SectionIndexMap[&Section] = addToSectionTable(&Section);
1149 if (RelSection) {
1150 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1151 Relocations.push_back(RelSection);
1154 OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
1157 MCSectionELF *CGProfileSection = nullptr;
1158 if (!Asm.CGProfile.empty()) {
1159 CGProfileSection = Ctx.getELFSection(".llvm.call-graph-profile",
1160 ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
1161 ELF::SHF_EXCLUDE, 16, "");
1162 SectionIndexMap[CGProfileSection] = addToSectionTable(CGProfileSection);
1165 for (MCSectionELF *Group : Groups) {
1166 align(Group->getAlignment());
1168 // Remember the offset into the file for this section.
1169 uint64_t SecStart = W.OS.tell();
1171 const MCSymbol *SignatureSymbol = Group->getGroup();
1172 assert(SignatureSymbol);
1173 write(uint32_t(ELF::GRP_COMDAT));
1174 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1175 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1176 write(SecIndex);
1179 uint64_t SecEnd = W.OS.tell();
1180 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1183 if (Mode == DwoOnly) {
1184 // dwo files don't have symbol tables or relocations, but they do have
1185 // string tables.
1186 StrTabBuilder.finalize();
1187 } else {
1188 MCSectionELF *AddrsigSection;
1189 if (OWriter.EmitAddrsigSection) {
1190 AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
1191 ELF::SHF_EXCLUDE);
1192 addToSectionTable(AddrsigSection);
1195 // Compute symbol table information.
1196 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1197 SectionOffsets);
1199 for (MCSectionELF *RelSection : Relocations) {
1200 align(RelSection->getAlignment());
1202 // Remember the offset into the file for this section.
1203 uint64_t SecStart = W.OS.tell();
1205 writeRelocations(Asm,
1206 cast<MCSectionELF>(*RelSection->getAssociatedSection()));
1208 uint64_t SecEnd = W.OS.tell();
1209 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1212 if (OWriter.EmitAddrsigSection) {
1213 uint64_t SecStart = W.OS.tell();
1214 writeAddrsigSection();
1215 uint64_t SecEnd = W.OS.tell();
1216 SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
1220 if (CGProfileSection) {
1221 uint64_t SecStart = W.OS.tell();
1222 for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
1223 W.write<uint32_t>(CGPE.From->getSymbol().getIndex());
1224 W.write<uint32_t>(CGPE.To->getSymbol().getIndex());
1225 W.write<uint64_t>(CGPE.Count);
1227 uint64_t SecEnd = W.OS.tell();
1228 SectionOffsets[CGProfileSection] = std::make_pair(SecStart, SecEnd);
1232 uint64_t SecStart = W.OS.tell();
1233 const MCSectionELF *Sec = createStringTable(Ctx);
1234 uint64_t SecEnd = W.OS.tell();
1235 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1238 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1239 align(NaturalAlignment);
1241 const uint64_t SectionHeaderOffset = W.OS.tell();
1243 // ... then the section header table ...
1244 writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1246 uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1247 (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1248 : SectionTable.size() + 1,
1249 W.Endian);
1250 unsigned NumSectionsOffset;
1252 auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1253 if (is64Bit()) {
1254 uint64_t Val =
1255 support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1256 Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1257 offsetof(ELF::Elf64_Ehdr, e_shoff));
1258 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1259 } else {
1260 uint32_t Val =
1261 support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1262 Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1263 offsetof(ELF::Elf32_Ehdr, e_shoff));
1264 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1266 Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1267 NumSectionsOffset);
1269 return W.OS.tell() - StartOffset;
1272 bool ELFObjectWriter::hasRelocationAddend() const {
1273 return TargetObjectWriter->hasRelocationAddend();
1276 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1277 const MCAsmLayout &Layout) {
1278 // The presence of symbol versions causes undefined symbols and
1279 // versions declared with @@@ to be renamed.
1280 for (const std::pair<StringRef, const MCSymbol *> &P : Asm.Symvers) {
1281 StringRef AliasName = P.first;
1282 const auto &Symbol = cast<MCSymbolELF>(*P.second);
1283 size_t Pos = AliasName.find('@');
1284 assert(Pos != StringRef::npos);
1286 StringRef Prefix = AliasName.substr(0, Pos);
1287 StringRef Rest = AliasName.substr(Pos);
1288 StringRef Tail = Rest;
1289 if (Rest.startswith("@@@"))
1290 Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1292 auto *Alias =
1293 cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1294 Asm.registerSymbol(*Alias);
1295 const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1296 Alias->setVariableValue(Value);
1298 // Aliases defined with .symvar copy the binding from the symbol they alias.
1299 // This is the first place we are able to copy this information.
1300 Alias->setExternal(Symbol.isExternal());
1301 Alias->setBinding(Symbol.getBinding());
1302 Alias->setOther(Symbol.getOther());
1304 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
1305 continue;
1307 // FIXME: Get source locations for these errors or diagnose them earlier.
1308 if (Symbol.isUndefined() && Rest.startswith("@@") &&
1309 !Rest.startswith("@@@")) {
1310 Asm.getContext().reportError(SMLoc(), "versioned symbol " + AliasName +
1311 " must be defined");
1312 continue;
1315 if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
1316 Asm.getContext().reportError(
1317 SMLoc(), llvm::Twine("multiple symbol versions defined for ") +
1318 Symbol.getName());
1319 continue;
1322 Renames.insert(std::make_pair(&Symbol, Alias));
1325 for (const MCSymbol *&Sym : AddrsigSyms) {
1326 if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
1327 Sym = R;
1328 if (Sym->isInSection() && Sym->getName().startswith(".L"))
1329 Sym = Sym->getSection().getBeginSymbol();
1330 Sym->setUsedInReloc();
1334 // It is always valid to create a relocation with a symbol. It is preferable
1335 // to use a relocation with a section if that is possible. Using the section
1336 // allows us to omit some local symbols from the symbol table.
1337 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1338 const MCSymbolRefExpr *RefA,
1339 const MCSymbolELF *Sym,
1340 uint64_t C,
1341 unsigned Type) const {
1342 // A PCRel relocation to an absolute value has no symbol (or section). We
1343 // represent that with a relocation to a null section.
1344 if (!RefA)
1345 return false;
1347 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1348 switch (Kind) {
1349 default:
1350 break;
1351 // The .odp creation emits a relocation against the symbol ".TOC." which
1352 // create a R_PPC64_TOC relocation. However the relocation symbol name
1353 // in final object creation should be NULL, since the symbol does not
1354 // really exist, it is just the reference to TOC base for the current
1355 // object file. Since the symbol is undefined, returning false results
1356 // in a relocation with a null section which is the desired result.
1357 case MCSymbolRefExpr::VK_PPC_TOCBASE:
1358 return false;
1360 // These VariantKind cause the relocation to refer to something other than
1361 // the symbol itself, like a linker generated table. Since the address of
1362 // symbol is not relevant, we cannot replace the symbol with the
1363 // section and patch the difference in the addend.
1364 case MCSymbolRefExpr::VK_GOT:
1365 case MCSymbolRefExpr::VK_PLT:
1366 case MCSymbolRefExpr::VK_GOTPCREL:
1367 case MCSymbolRefExpr::VK_PPC_GOT_LO:
1368 case MCSymbolRefExpr::VK_PPC_GOT_HI:
1369 case MCSymbolRefExpr::VK_PPC_GOT_HA:
1370 return true;
1373 // An undefined symbol is not in any section, so the relocation has to point
1374 // to the symbol itself.
1375 assert(Sym && "Expected a symbol");
1376 if (Sym->isUndefined())
1377 return true;
1379 unsigned Binding = Sym->getBinding();
1380 switch(Binding) {
1381 default:
1382 llvm_unreachable("Invalid Binding");
1383 case ELF::STB_LOCAL:
1384 break;
1385 case ELF::STB_WEAK:
1386 // If the symbol is weak, it might be overridden by a symbol in another
1387 // file. The relocation has to point to the symbol so that the linker
1388 // can update it.
1389 return true;
1390 case ELF::STB_GLOBAL:
1391 // Global ELF symbols can be preempted by the dynamic linker. The relocation
1392 // has to point to the symbol for a reason analogous to the STB_WEAK case.
1393 return true;
1396 // Keep symbol type for a local ifunc because it may result in an IRELATIVE
1397 // reloc that the dynamic loader will use to resolve the address at startup
1398 // time.
1399 if (Sym->getType() == ELF::STT_GNU_IFUNC)
1400 return true;
1402 // If a relocation points to a mergeable section, we have to be careful.
1403 // If the offset is zero, a relocation with the section will encode the
1404 // same information. With a non-zero offset, the situation is different.
1405 // For example, a relocation can point 42 bytes past the end of a string.
1406 // If we change such a relocation to use the section, the linker would think
1407 // that it pointed to another string and subtracting 42 at runtime will
1408 // produce the wrong value.
1409 if (Sym->isInSection()) {
1410 auto &Sec = cast<MCSectionELF>(Sym->getSection());
1411 unsigned Flags = Sec.getFlags();
1412 if (Flags & ELF::SHF_MERGE) {
1413 if (C != 0)
1414 return true;
1416 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
1417 // only handle section relocations to mergeable sections if using RELA.
1418 if (!hasRelocationAddend())
1419 return true;
1422 // Most TLS relocations use a got, so they need the symbol. Even those that
1423 // are just an offset (@tpoff), require a symbol in gold versions before
1424 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1425 // http://sourceware.org/PR16773.
1426 if (Flags & ELF::SHF_TLS)
1427 return true;
1430 // If the symbol is a thumb function the final relocation must set the lowest
1431 // bit. With a symbol that is done by just having the symbol have that bit
1432 // set, so we would lose the bit if we relocated with the section.
1433 // FIXME: We could use the section but add the bit to the relocation value.
1434 if (Asm.isThumbFunc(Sym))
1435 return true;
1437 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1438 return true;
1439 return false;
1442 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1443 const MCAsmLayout &Layout,
1444 const MCFragment *Fragment,
1445 const MCFixup &Fixup, MCValue Target,
1446 uint64_t &FixedValue) {
1447 MCAsmBackend &Backend = Asm.getBackend();
1448 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1449 MCFixupKindInfo::FKF_IsPCRel;
1450 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1451 uint64_t C = Target.getConstant();
1452 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1453 MCContext &Ctx = Asm.getContext();
1455 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1456 const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1457 if (SymB.isUndefined()) {
1458 Ctx.reportError(Fixup.getLoc(),
1459 Twine("symbol '") + SymB.getName() +
1460 "' can not be undefined in a subtraction expression");
1461 return;
1464 assert(!SymB.isAbsolute() && "Should have been folded");
1465 const MCSection &SecB = SymB.getSection();
1466 if (&SecB != &FixupSection) {
1467 Ctx.reportError(Fixup.getLoc(),
1468 "Cannot represent a difference across sections");
1469 return;
1472 assert(!IsPCRel && "should have been folded");
1473 IsPCRel = true;
1474 C += FixupOffset - Layout.getSymbolOffset(SymB);
1477 // We either rejected the fixup or folded B into C at this point.
1478 const MCSymbolRefExpr *RefA = Target.getSymA();
1479 const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1481 bool ViaWeakRef = false;
1482 if (SymA && SymA->isVariable()) {
1483 const MCExpr *Expr = SymA->getVariableValue();
1484 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1485 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1486 SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1487 ViaWeakRef = true;
1492 const MCSectionELF *SecA = (SymA && SymA->isInSection())
1493 ? cast<MCSectionELF>(&SymA->getSection())
1494 : nullptr;
1495 if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
1496 return;
1498 unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1499 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
1500 uint64_t Addend = 0;
1502 FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
1503 ? C + Layout.getSymbolOffset(*SymA)
1504 : C;
1505 if (hasRelocationAddend()) {
1506 Addend = FixedValue;
1507 FixedValue = 0;
1510 if (!RelocateWithSymbol) {
1511 const auto *SectionSymbol =
1512 SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1513 if (SectionSymbol)
1514 SectionSymbol->setUsedInReloc();
1515 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
1516 Relocations[&FixupSection].push_back(Rec);
1517 return;
1520 const MCSymbolELF *RenamedSymA = SymA;
1521 if (SymA) {
1522 if (const MCSymbolELF *R = Renames.lookup(SymA))
1523 RenamedSymA = R;
1525 if (ViaWeakRef)
1526 RenamedSymA->setIsWeakrefUsedInReloc();
1527 else
1528 RenamedSymA->setUsedInReloc();
1530 ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
1531 Relocations[&FixupSection].push_back(Rec);
1534 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1535 const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1536 bool InSet, bool IsPCRel) const {
1537 const auto &SymA = cast<MCSymbolELF>(SA);
1538 if (IsPCRel) {
1539 assert(!InSet);
1540 if (isWeak(SymA))
1541 return false;
1543 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1544 InSet, IsPCRel);
1547 std::unique_ptr<MCObjectWriter>
1548 llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1549 raw_pwrite_stream &OS, bool IsLittleEndian) {
1550 return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1551 IsLittleEndian);
1554 std::unique_ptr<MCObjectWriter>
1555 llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1556 raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
1557 bool IsLittleEndian) {
1558 return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
1559 IsLittleEndian);