1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSymbolELF.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/MC/StringTableBuilder.h"
31 #include "llvm/Support/Compression.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ELF.h"
34 #include "llvm/Support/Endian.h"
35 #include "llvm/Support/ErrorHandling.h"
40 #define DEBUG_TYPE "reloc-info"
44 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
46 class ELFObjectWriter;
48 class SymbolTableWriter {
49 ELFObjectWriter &EWriter;
52 // indexes we are going to write to .symtab_shndx.
53 std::vector<uint32_t> ShndxIndexes;
55 // The numbel of symbols written so far.
58 void createSymtabShndx();
60 template <typename T> void write(T Value);
63 SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
65 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
66 uint8_t other, uint32_t shndx, bool Reserved);
68 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
71 class ELFObjectWriter : public MCObjectWriter {
72 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
73 static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
74 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
75 bool Used, bool Renamed);
77 /// Helper struct for containing some precomputed information on symbols.
78 struct ELFSymbolData {
79 const MCSymbolELF *Symbol;
80 uint32_t SectionIndex;
83 // Support lexicographic sorting.
84 bool operator<(const ELFSymbolData &RHS) const {
85 unsigned LHSType = Symbol->getType();
86 unsigned RHSType = RHS.Symbol->getType();
87 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
89 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
91 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
92 return SectionIndex < RHS.SectionIndex;
93 return Name < RHS.Name;
97 /// The target specific ELF writer instance.
98 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
100 DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
102 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
106 /// @name Symbol Table Data
109 StringTableBuilder StrTabBuilder;
113 // This holds the symbol table index of the last local symbol.
114 unsigned LastLocalSymbolIndex;
115 // This holds the .strtab section index.
116 unsigned StringTableIndex;
117 // This holds the .symtab section index.
118 unsigned SymbolTableIndex;
120 // Sections in the order they are to be output in the section table.
121 std::vector<const MCSectionELF *> SectionTable;
122 unsigned addToSectionTable(const MCSectionELF *Sec);
124 // TargetObjectWriter wrappers.
125 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
126 bool hasRelocationAddend() const {
127 return TargetObjectWriter->hasRelocationAddend();
129 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
130 bool IsPCRel) const {
131 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
134 void align(unsigned Alignment);
137 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
139 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
141 void reset() override {
144 StrTabBuilder.clear();
145 SectionTable.clear();
146 MCObjectWriter::reset();
149 ~ELFObjectWriter() override;
151 void WriteWord(uint64_t W) {
158 template <typename T> void write(T Val) {
160 support::endian::Writer<support::little>(getStream()).write(Val);
162 support::endian::Writer<support::big>(getStream()).write(Val);
165 void writeHeader(const MCAssembler &Asm);
167 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
168 ELFSymbolData &MSD, const MCAsmLayout &Layout);
170 // Start and end offset of each section
171 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
174 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
175 const MCSymbolRefExpr *RefA,
176 const MCSymbol *Sym, uint64_t C,
177 unsigned Type) const;
179 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
180 const MCFragment *Fragment, const MCFixup &Fixup,
181 MCValue Target, bool &IsPCRel,
182 uint64_t &FixedValue) override;
184 // Map from a signature symbol to the group section index
185 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
187 /// Compute the symbol table data
189 /// \param Asm - The assembler.
190 /// \param SectionIndexMap - Maps a section to its index.
191 /// \param RevGroupMap - Maps a signature symbol to the group section.
192 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
193 const SectionIndexMapTy &SectionIndexMap,
194 const RevGroupMapTy &RevGroupMap,
195 SectionOffsetsTy &SectionOffsets);
197 MCSectionELF *createRelocationSection(MCContext &Ctx,
198 const MCSectionELF &Sec);
200 const MCSectionELF *createStringTable(MCContext &Ctx);
202 void executePostLayoutBinding(MCAssembler &Asm,
203 const MCAsmLayout &Layout) override;
205 void writeSectionHeader(const MCAsmLayout &Layout,
206 const SectionIndexMapTy &SectionIndexMap,
207 const SectionOffsetsTy &SectionOffsets);
209 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
210 const MCAsmLayout &Layout);
212 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
213 uint64_t Address, uint64_t Offset, uint64_t Size,
214 uint32_t Link, uint32_t Info, uint64_t Alignment,
217 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
219 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
220 const MCSymbol &SymA,
221 const MCFragment &FB,
223 bool IsPCRel) const override;
225 bool isWeak(const MCSymbol &Sym) const override;
227 void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
228 void writeSection(const SectionIndexMapTy &SectionIndexMap,
229 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
230 const MCSectionELF &Section);
234 void ELFObjectWriter::align(unsigned Alignment) {
235 uint64_t Padding = OffsetToAlignment(getStream().tell(), Alignment);
239 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
240 SectionTable.push_back(Sec);
241 StrTabBuilder.add(Sec->getSectionName());
242 return SectionTable.size();
245 void SymbolTableWriter::createSymtabShndx() {
246 if (!ShndxIndexes.empty())
249 ShndxIndexes.resize(NumWritten);
252 template <typename T> void SymbolTableWriter::write(T Value) {
253 EWriter.write(Value);
256 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
257 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
259 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
260 uint64_t size, uint8_t other,
261 uint32_t shndx, bool Reserved) {
262 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
267 if (!ShndxIndexes.empty()) {
269 ShndxIndexes.push_back(shndx);
271 ShndxIndexes.push_back(0);
274 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
277 write(name); // st_name
278 write(info); // st_info
279 write(other); // st_other
280 write(Index); // st_shndx
281 write(value); // st_value
282 write(size); // st_size
284 write(name); // st_name
285 write(uint32_t(value)); // st_value
286 write(uint32_t(size)); // st_size
287 write(info); // st_info
288 write(other); // st_other
289 write(Index); // st_shndx
295 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
296 const MCFixupKindInfo &FKI =
297 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
299 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
302 ELFObjectWriter::~ELFObjectWriter()
305 // Emit the ELF header.
306 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
312 // emitWord method behaves differently for ELF32 and ELF64, writing
313 // 4 bytes in the former and 8 in the latter.
315 writeBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
317 write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
320 write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
322 write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
324 write8(TargetObjectWriter->getOSABI());
325 write8(0); // e_ident[EI_ABIVERSION]
327 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
329 write16(ELF::ET_REL); // e_type
331 write16(TargetObjectWriter->getEMachine()); // e_machine = target
333 write32(ELF::EV_CURRENT); // e_version
334 WriteWord(0); // e_entry, no entry point in .o file
335 WriteWord(0); // e_phoff, no program header for .o
336 WriteWord(0); // e_shoff = sec hdr table off in bytes
338 // e_flags = whatever the target wants
339 write32(Asm.getELFHeaderEFlags());
341 // e_ehsize = ELF header size
342 write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
344 write16(0); // e_phentsize = prog header entry size
345 write16(0); // e_phnum = # prog header entries = 0
347 // e_shentsize = Section header entry size
348 write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
350 // e_shnum = # of section header ents
353 // e_shstrndx = Section # of '.shstrtab'
354 assert(StringTableIndex < ELF::SHN_LORESERVE);
355 write16(StringTableIndex);
358 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
359 const MCAsmLayout &Layout) {
360 if (Sym.isCommon() && Sym.isExternal())
361 return Sym.getCommonAlignment();
364 if (!Layout.getSymbolOffset(Sym, Res))
367 if (Layout.getAssembler().isThumbFunc(&Sym))
373 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
374 const MCAsmLayout &Layout) {
375 // The presence of symbol versions causes undefined symbols and
376 // versions declared with @@@ to be renamed.
378 for (const MCSymbol &A : Asm.symbols()) {
379 const auto &Alias = cast<MCSymbolELF>(A);
381 if (!Alias.isVariable())
383 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
386 const auto &Symbol = cast<MCSymbolELF>(Ref->getSymbol());
388 StringRef AliasName = Alias.getName();
389 size_t Pos = AliasName.find('@');
390 if (Pos == StringRef::npos)
393 // Aliases defined with .symvar copy the binding from the symbol they alias.
394 // This is the first place we are able to copy this information.
395 Alias.setExternal(Symbol.isExternal());
396 Alias.setBinding(Symbol.getBinding());
398 StringRef Rest = AliasName.substr(Pos);
399 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
402 // FIXME: produce a better error message.
403 if (Symbol.isUndefined() && Rest.startswith("@@") &&
404 !Rest.startswith("@@@"))
405 report_fatal_error("A @@ version cannot be undefined");
407 Renames.insert(std::make_pair(&Symbol, &Alias));
411 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
412 uint8_t Type = newType;
414 // Propagation rules:
415 // IFUNC > FUNC > OBJECT > NOTYPE
416 // TLS_OBJECT > OBJECT > NOTYPE
418 // dont let the new type degrade the old type
422 case ELF::STT_GNU_IFUNC:
423 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
424 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
425 Type = ELF::STT_GNU_IFUNC;
428 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
429 Type == ELF::STT_TLS)
430 Type = ELF::STT_FUNC;
432 case ELF::STT_OBJECT:
433 if (Type == ELF::STT_NOTYPE)
434 Type = ELF::STT_OBJECT;
437 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
438 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
446 void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
447 uint32_t StringIndex, ELFSymbolData &MSD,
448 const MCAsmLayout &Layout) {
449 const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
450 const MCSymbolELF *Base =
451 cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
453 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
455 bool IsReserved = !Base || Symbol.isCommon();
457 // Binding and Type share the same byte as upper and lower nibbles
458 uint8_t Binding = Symbol.getBinding();
459 uint8_t Type = Symbol.getType();
461 Type = mergeTypeForSet(Type, Base->getType());
463 uint8_t Info = (Binding << 4) | Type;
465 // Other and Visibility share the same byte with Visibility using the lower
467 uint8_t Visibility = Symbol.getVisibility();
468 uint8_t Other = Symbol.getOther() | Visibility;
470 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
473 const MCExpr *ESize = MSD.Symbol->getSize();
475 ESize = Base->getSize();
479 if (!ESize->evaluateKnownAbsolute(Res, Layout))
480 report_fatal_error("Size expression must be absolute.");
484 // Write out the symbol table entry
485 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
489 // It is always valid to create a relocation with a symbol. It is preferable
490 // to use a relocation with a section if that is possible. Using the section
491 // allows us to omit some local symbols from the symbol table.
492 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
493 const MCSymbolRefExpr *RefA,
494 const MCSymbol *S, uint64_t C,
495 unsigned Type) const {
496 const auto *Sym = cast_or_null<MCSymbolELF>(S);
497 // A PCRel relocation to an absolute value has no symbol (or section). We
498 // represent that with a relocation to a null section.
502 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
506 // The .odp creation emits a relocation against the symbol ".TOC." which
507 // create a R_PPC64_TOC relocation. However the relocation symbol name
508 // in final object creation should be NULL, since the symbol does not
509 // really exist, it is just the reference to TOC base for the current
510 // object file. Since the symbol is undefined, returning false results
511 // in a relocation with a null section which is the desired result.
512 case MCSymbolRefExpr::VK_PPC_TOCBASE:
515 // These VariantKind cause the relocation to refer to something other than
516 // the symbol itself, like a linker generated table. Since the address of
517 // symbol is not relevant, we cannot replace the symbol with the
518 // section and patch the difference in the addend.
519 case MCSymbolRefExpr::VK_GOT:
520 case MCSymbolRefExpr::VK_PLT:
521 case MCSymbolRefExpr::VK_GOTPCREL:
522 case MCSymbolRefExpr::VK_Mips_GOT:
523 case MCSymbolRefExpr::VK_PPC_GOT_LO:
524 case MCSymbolRefExpr::VK_PPC_GOT_HI:
525 case MCSymbolRefExpr::VK_PPC_GOT_HA:
529 // An undefined symbol is not in any section, so the relocation has to point
530 // to the symbol itself.
531 assert(Sym && "Expected a symbol");
532 if (Sym->isUndefined())
535 unsigned Binding = Sym->getBinding();
538 llvm_unreachable("Invalid Binding");
542 // If the symbol is weak, it might be overridden by a symbol in another
543 // file. The relocation has to point to the symbol so that the linker
546 case ELF::STB_GLOBAL:
547 // Global ELF symbols can be preempted by the dynamic linker. The relocation
548 // has to point to the symbol for a reason analogous to the STB_WEAK case.
552 // If a relocation points to a mergeable section, we have to be careful.
553 // If the offset is zero, a relocation with the section will encode the
554 // same information. With a non-zero offset, the situation is different.
555 // For example, a relocation can point 42 bytes past the end of a string.
556 // If we change such a relocation to use the section, the linker would think
557 // that it pointed to another string and subtracting 42 at runtime will
558 // produce the wrong value.
559 auto &Sec = cast<MCSectionELF>(Sym->getSection());
560 unsigned Flags = Sec.getFlags();
561 if (Flags & ELF::SHF_MERGE) {
565 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
566 // only handle section relocations to mergeable sections if using RELA.
567 if (!hasRelocationAddend())
571 // Most TLS relocations use a got, so they need the symbol. Even those that
572 // are just an offset (@tpoff), require a symbol in gold versions before
573 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
574 // http://sourceware.org/PR16773.
575 if (Flags & ELF::SHF_TLS)
578 // If the symbol is a thumb function the final relocation must set the lowest
579 // bit. With a symbol that is done by just having the symbol have that bit
580 // set, so we would lose the bit if we relocated with the section.
581 // FIXME: We could use the section but add the bit to the relocation value.
582 if (Asm.isThumbFunc(Sym))
585 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
590 // True if the assembler knows nothing about the final value of the symbol.
591 // This doesn't cover the comdat issues, since in those cases the assembler
592 // can at least know that all symbols in the section will move together.
593 static bool isWeak(const MCSymbolELF &Sym) {
594 if (Sym.getType() == ELF::STT_GNU_IFUNC)
597 switch (Sym.getBinding()) {
599 llvm_unreachable("Unknown binding");
602 case ELF::STB_GLOBAL:
605 case ELF::STB_GNU_UNIQUE:
610 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
611 const MCAsmLayout &Layout,
612 const MCFragment *Fragment,
613 const MCFixup &Fixup, MCValue Target,
614 bool &IsPCRel, uint64_t &FixedValue) {
615 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
616 uint64_t C = Target.getConstant();
617 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
619 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
620 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
621 "Should not have constructed this");
623 // Let A, B and C being the components of Target and R be the location of
624 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
625 // If it is pcrel, we want to compute (A - B + C - R).
627 // In general, ELF has no relocations for -B. It can only represent (A + C)
628 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
629 // replace B to implement it: (A - R - K + C)
631 Asm.getContext().reportFatalError(
633 "No relocation available to represent this relative expression");
635 const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
637 if (SymB.isUndefined())
638 Asm.getContext().reportFatalError(
640 Twine("symbol '") + SymB.getName() +
641 "' can not be undefined in a subtraction expression");
643 assert(!SymB.isAbsolute() && "Should have been folded");
644 const MCSection &SecB = SymB.getSection();
645 if (&SecB != &FixupSection)
646 Asm.getContext().reportFatalError(
647 Fixup.getLoc(), "Cannot represent a difference across sections");
650 Asm.getContext().reportFatalError(
651 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
653 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
654 uint64_t K = SymBOffset - FixupOffset;
659 // We either rejected the fixup or folded B into C at this point.
660 const MCSymbolRefExpr *RefA = Target.getSymA();
661 const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
663 bool ViaWeakRef = false;
664 if (SymA && SymA->isVariable()) {
665 const MCExpr *Expr = SymA->getVariableValue();
666 if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
667 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
668 SymA = cast<MCSymbolELF>(&Inner->getSymbol());
674 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
675 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
676 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
677 C += Layout.getSymbolOffset(*SymA);
680 if (hasRelocationAddend()) {
687 if (!RelocateWithSymbol) {
688 const MCSection *SecA =
689 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
690 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
691 const auto *SectionSymbol =
692 ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr;
694 SectionSymbol->setUsedInReloc();
695 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
696 Relocations[&FixupSection].push_back(Rec);
701 if (const MCSymbolELF *R = Renames.lookup(SymA))
705 SymA->setIsWeakrefUsedInReloc();
707 SymA->setUsedInReloc();
709 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
710 Relocations[&FixupSection].push_back(Rec);
714 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
715 const MCSymbolELF &Symbol, bool Used,
717 if (Symbol.isVariable()) {
718 const MCExpr *Expr = Symbol.getVariableValue();
719 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
720 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
731 if (Symbol.isVariable() && Symbol.isUndefined()) {
732 // FIXME: this is here just to diagnose the case of a var = commmon_sym.
733 Layout.getBaseSymbol(Symbol);
737 if (Symbol.isUndefined() && !Symbol.isBindingSet())
740 if (Symbol.isTemporary())
743 if (Symbol.getType() == ELF::STT_SECTION)
749 void ELFObjectWriter::computeSymbolTable(
750 MCAssembler &Asm, const MCAsmLayout &Layout,
751 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
752 SectionOffsetsTy &SectionOffsets) {
753 MCContext &Ctx = Asm.getContext();
754 SymbolTableWriter Writer(*this, is64Bit());
757 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
758 MCSectionELF *SymtabSection =
759 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
760 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
761 SymbolTableIndex = addToSectionTable(SymtabSection);
763 align(SymtabSection->getAlignment());
764 uint64_t SecStart = getStream().tell();
766 // The first entry is the undefined symbol entry.
767 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
769 std::vector<ELFSymbolData> LocalSymbolData;
770 std::vector<ELFSymbolData> ExternalSymbolData;
772 // Add the data for the symbols.
773 bool HasLargeSectionIndex = false;
774 for (const MCSymbol &S : Asm.symbols()) {
775 const auto &Symbol = cast<MCSymbolELF>(S);
776 bool Used = Symbol.isUsedInReloc();
777 bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
778 bool isSignature = Symbol.isSignature();
780 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
781 Renames.count(&Symbol)))
784 if (Symbol.isTemporary() && Symbol.isUndefined())
785 Ctx.reportFatalError(SMLoc(), "Undefined temporary");
788 MSD.Symbol = cast<MCSymbolELF>(&Symbol);
790 bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
791 assert(Local || !Symbol.isTemporary());
793 if (Symbol.isAbsolute()) {
794 MSD.SectionIndex = ELF::SHN_ABS;
795 } else if (Symbol.isCommon()) {
797 MSD.SectionIndex = ELF::SHN_COMMON;
798 } else if (Symbol.isUndefined()) {
799 if (isSignature && !Used) {
800 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
801 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
802 HasLargeSectionIndex = true;
804 MSD.SectionIndex = ELF::SHN_UNDEF;
807 const MCSectionELF &Section =
808 static_cast<const MCSectionELF &>(Symbol.getSection());
809 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
810 assert(MSD.SectionIndex && "Invalid section index!");
811 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
812 HasLargeSectionIndex = true;
815 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
818 // FIXME: All name handling should be done before we get to the writer,
819 // including dealing with GNU-style version suffixes. Fixing this isn't
822 // We thus have to be careful to not perform the symbol version replacement
825 // The ELF format is used on Windows by the MCJIT engine. Thus, on
826 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
827 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
828 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
829 // the EFLObjectWriter should not interpret the "@@@" sub-string as
830 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
831 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
832 // "__imp_?" or "__imp_@?".
834 // It would have been interesting to perform the MS mangling prefix check
835 // only when the target triple is of the form *-pc-windows-elf. But, it
836 // seems that this information is not easily accessible from the
838 StringRef Name = Symbol.getName();
840 if (!Name.startswith("?") && !Name.startswith("@?") &&
841 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
842 // This symbol isn't following the MSVC C++ name mangling convention. We
843 // can thus safely interpret the @@@ in symbol names as specifying symbol
845 size_t Pos = Name.find("@@@");
846 if (Pos != StringRef::npos) {
847 Buf += Name.substr(0, Pos);
848 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
849 Buf += Name.substr(Pos + Skip);
854 // Sections have their own string table
855 if (Symbol.getType() != ELF::STT_SECTION)
856 MSD.Name = StrTabBuilder.add(Name);
859 LocalSymbolData.push_back(MSD);
861 ExternalSymbolData.push_back(MSD);
864 // This holds the .symtab_shndx section index.
865 unsigned SymtabShndxSectionIndex = 0;
867 if (HasLargeSectionIndex) {
868 MCSectionELF *SymtabShndxSection =
869 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
870 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
871 SymtabShndxSection->setAlignment(4);
874 ArrayRef<std::string> FileNames = Asm.getFileNames();
875 for (const std::string &Name : FileNames)
876 StrTabBuilder.add(Name);
878 StrTabBuilder.finalize(StringTableBuilder::ELF);
880 for (const std::string &Name : FileNames)
881 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
882 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
885 // Symbols are required to be in lexicographic order.
886 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
887 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
889 // Set the symbol indices. Local symbols must come before all other
890 // symbols with non-local bindings.
891 unsigned Index = FileNames.size() + 1;
893 for (ELFSymbolData &MSD : LocalSymbolData) {
894 unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
896 : StrTabBuilder.getOffset(MSD.Name);
897 MSD.Symbol->setIndex(Index++);
898 writeSymbol(Writer, StringIndex, MSD, Layout);
901 // Write the symbol table entries.
902 LastLocalSymbolIndex = Index;
904 for (ELFSymbolData &MSD : ExternalSymbolData) {
905 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
906 MSD.Symbol->setIndex(Index++);
907 writeSymbol(Writer, StringIndex, MSD, Layout);
908 assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
911 uint64_t SecEnd = getStream().tell();
912 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
914 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
915 if (ShndxIndexes.empty()) {
916 assert(SymtabShndxSectionIndex == 0);
919 assert(SymtabShndxSectionIndex != 0);
921 SecStart = getStream().tell();
922 const MCSectionELF *SymtabShndxSection =
923 SectionTable[SymtabShndxSectionIndex - 1];
924 for (uint32_t Index : ShndxIndexes)
926 SecEnd = getStream().tell();
927 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
931 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
932 const MCSectionELF &Sec) {
933 if (Relocations[&Sec].empty())
936 const StringRef SectionName = Sec.getSectionName();
937 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
938 RelaSectionName += SectionName;
941 if (hasRelocationAddend())
942 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
944 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
947 if (Sec.getFlags() & ELF::SHF_GROUP)
948 Flags = ELF::SHF_GROUP;
950 MCSectionELF *RelaSection = Ctx.createELFRelSection(
951 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
952 Flags, EntrySize, Sec.getGroup(), &Sec);
953 RelaSection->setAlignment(is64Bit() ? 8 : 4);
957 // Include the debug info compression header:
958 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
959 // useful for consumers to preallocate a buffer to decompress into.
961 prependCompressionHeader(uint64_t Size,
962 SmallVectorImpl<char> &CompressedContents) {
963 const StringRef Magic = "ZLIB";
964 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
966 if (sys::IsLittleEndianHost)
967 sys::swapByteOrder(Size);
968 CompressedContents.insert(CompressedContents.begin(),
969 Magic.size() + sizeof(Size), 0);
970 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
971 std::copy(reinterpret_cast<char *>(&Size),
972 reinterpret_cast<char *>(&Size + 1),
973 CompressedContents.begin() + Magic.size());
977 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
978 const MCAsmLayout &Layout) {
979 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
980 StringRef SectionName = Section.getSectionName();
982 // Compressing debug_frame requires handling alignment fragments which is
983 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
984 // for writing to arbitrary buffers) for little benefit.
985 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
986 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
987 Asm.writeSectionData(&Section, Layout);
991 SmallVector<char, 128> UncompressedData;
992 raw_svector_ostream VecOS(UncompressedData);
993 raw_pwrite_stream &OldStream = getStream();
995 Asm.writeSectionData(&Section, Layout);
996 setStream(OldStream);
998 SmallVector<char, 128> CompressedContents;
999 zlib::Status Success = zlib::compress(
1000 StringRef(UncompressedData.data(), UncompressedData.size()),
1001 CompressedContents);
1002 if (Success != zlib::StatusOK) {
1003 getStream() << UncompressedData;
1007 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1008 getStream() << UncompressedData;
1011 Asm.getContext().renameELFSection(&Section,
1012 (".z" + SectionName.drop_front(1)).str());
1013 getStream() << CompressedContents;
1016 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1017 uint64_t Flags, uint64_t Address,
1018 uint64_t Offset, uint64_t Size,
1019 uint32_t Link, uint32_t Info,
1021 uint64_t EntrySize) {
1022 write32(Name); // sh_name: index into string table
1023 write32(Type); // sh_type
1024 WriteWord(Flags); // sh_flags
1025 WriteWord(Address); // sh_addr
1026 WriteWord(Offset); // sh_offset
1027 WriteWord(Size); // sh_size
1028 write32(Link); // sh_link
1029 write32(Info); // sh_info
1030 WriteWord(Alignment); // sh_addralign
1031 WriteWord(EntrySize); // sh_entsize
1034 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1035 const MCSectionELF &Sec) {
1036 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1038 // Sort the relocation entries. Most targets just sort by Offset, but some
1039 // (e.g., MIPS) have additional constraints.
1040 TargetObjectWriter->sortRelocs(Asm, Relocs);
1042 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1043 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1044 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1047 write(Entry.Offset);
1048 if (TargetObjectWriter->isN64()) {
1049 write(uint32_t(Index));
1051 write(TargetObjectWriter->getRSsym(Entry.Type));
1052 write(TargetObjectWriter->getRType3(Entry.Type));
1053 write(TargetObjectWriter->getRType2(Entry.Type));
1054 write(TargetObjectWriter->getRType(Entry.Type));
1056 struct ELF::Elf64_Rela ERE64;
1057 ERE64.setSymbolAndType(Index, Entry.Type);
1058 write(ERE64.r_info);
1060 if (hasRelocationAddend())
1061 write(Entry.Addend);
1063 write(uint32_t(Entry.Offset));
1065 struct ELF::Elf32_Rela ERE32;
1066 ERE32.setSymbolAndType(Index, Entry.Type);
1067 write(ERE32.r_info);
1069 if (hasRelocationAddend())
1070 write(uint32_t(Entry.Addend));
1075 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1076 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1077 getStream() << StrTabBuilder.data();
1078 return StrtabSection;
1081 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1082 uint32_t GroupSymbolIndex, uint64_t Offset,
1083 uint64_t Size, const MCSectionELF &Section) {
1084 uint64_t sh_link = 0;
1085 uint64_t sh_info = 0;
1087 switch(Section.getType()) {
1092 case ELF::SHT_DYNAMIC:
1093 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1096 case ELF::SHT_RELA: {
1097 sh_link = SymbolTableIndex;
1098 assert(sh_link && ".symtab not found");
1099 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1100 sh_info = SectionIndexMap.lookup(InfoSection);
1104 case ELF::SHT_SYMTAB:
1105 case ELF::SHT_DYNSYM:
1106 sh_link = StringTableIndex;
1107 sh_info = LastLocalSymbolIndex;
1110 case ELF::SHT_SYMTAB_SHNDX:
1111 sh_link = SymbolTableIndex;
1114 case ELF::SHT_GROUP:
1115 sh_link = SymbolTableIndex;
1116 sh_info = GroupSymbolIndex;
1120 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1121 Section.getType() == ELF::SHT_ARM_EXIDX)
1122 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1124 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1125 Section.getType(), Section.getFlags(), 0, Offset, Size,
1126 sh_link, sh_info, Section.getAlignment(),
1127 Section.getEntrySize());
1130 void ELFObjectWriter::writeSectionHeader(
1131 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1132 const SectionOffsetsTy &SectionOffsets) {
1133 const unsigned NumSections = SectionTable.size();
1135 // Null section first.
1136 uint64_t FirstSectionSize =
1137 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1138 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1140 for (const MCSectionELF *Section : SectionTable) {
1141 uint32_t GroupSymbolIndex;
1142 unsigned Type = Section->getType();
1143 if (Type != ELF::SHT_GROUP)
1144 GroupSymbolIndex = 0;
1146 GroupSymbolIndex = Section->getGroup()->getIndex();
1148 const std::pair<uint64_t, uint64_t> &Offsets =
1149 SectionOffsets.find(Section)->second;
1151 if (Type == ELF::SHT_NOBITS)
1152 Size = Layout.getSectionAddressSize(Section);
1154 Size = Offsets.second - Offsets.first;
1156 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1161 void ELFObjectWriter::writeObject(MCAssembler &Asm,
1162 const MCAsmLayout &Layout) {
1163 MCContext &Ctx = Asm.getContext();
1164 MCSectionELF *StrtabSection =
1165 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1166 StringTableIndex = addToSectionTable(StrtabSection);
1168 RevGroupMapTy RevGroupMap;
1169 SectionIndexMapTy SectionIndexMap;
1171 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1173 // Write out the ELF header ...
1176 // ... then the sections ...
1177 SectionOffsetsTy SectionOffsets;
1178 std::vector<MCSectionELF *> Groups;
1179 std::vector<MCSectionELF *> Relocations;
1180 for (MCSection &Sec : Asm) {
1181 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1183 align(Section.getAlignment());
1185 // Remember the offset into the file for this section.
1186 uint64_t SecStart = getStream().tell();
1188 const MCSymbolELF *SignatureSymbol = Section.getGroup();
1189 writeSectionData(Asm, Section, Layout);
1191 uint64_t SecEnd = getStream().tell();
1192 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1194 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1196 if (SignatureSymbol) {
1197 Asm.registerSymbol(*SignatureSymbol);
1198 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1200 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1201 GroupIdx = addToSectionTable(Group);
1202 Group->setAlignment(4);
1203 Groups.push_back(Group);
1205 std::vector<const MCSectionELF *> &Members =
1206 GroupMembers[SignatureSymbol];
1207 Members.push_back(&Section);
1209 Members.push_back(RelSection);
1212 SectionIndexMap[&Section] = addToSectionTable(&Section);
1214 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1215 Relocations.push_back(RelSection);
1219 for (MCSectionELF *Group : Groups) {
1220 align(Group->getAlignment());
1222 // Remember the offset into the file for this section.
1223 uint64_t SecStart = getStream().tell();
1225 const MCSymbol *SignatureSymbol = Group->getGroup();
1226 assert(SignatureSymbol);
1227 write(uint32_t(ELF::GRP_COMDAT));
1228 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1229 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1233 uint64_t SecEnd = getStream().tell();
1234 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1237 // Compute symbol table information.
1238 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1240 for (MCSectionELF *RelSection : Relocations) {
1241 align(RelSection->getAlignment());
1243 // Remember the offset into the file for this section.
1244 uint64_t SecStart = getStream().tell();
1246 writeRelocations(Asm, *RelSection->getAssociatedSection());
1248 uint64_t SecEnd = getStream().tell();
1249 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1253 uint64_t SecStart = getStream().tell();
1254 const MCSectionELF *Sec = createStringTable(Ctx);
1255 uint64_t SecEnd = getStream().tell();
1256 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1259 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1260 align(NaturalAlignment);
1262 const unsigned SectionHeaderOffset = getStream().tell();
1264 // ... then the section header table ...
1265 writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1267 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1268 ? (uint16_t)ELF::SHN_UNDEF
1269 : SectionTable.size() + 1;
1270 if (sys::IsLittleEndianHost != IsLittleEndian)
1271 sys::swapByteOrder(NumSections);
1272 unsigned NumSectionsOffset;
1275 uint64_t Val = SectionHeaderOffset;
1276 if (sys::IsLittleEndianHost != IsLittleEndian)
1277 sys::swapByteOrder(Val);
1278 getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1279 offsetof(ELF::Elf64_Ehdr, e_shoff));
1280 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1282 uint32_t Val = SectionHeaderOffset;
1283 if (sys::IsLittleEndianHost != IsLittleEndian)
1284 sys::swapByteOrder(Val);
1285 getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1286 offsetof(ELF::Elf32_Ehdr, e_shoff));
1287 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1289 getStream().pwrite(reinterpret_cast<char *>(&NumSections),
1290 sizeof(NumSections), NumSectionsOffset);
1293 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1294 const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1295 bool InSet, bool IsPCRel) const {
1296 const auto &SymA = cast<MCSymbolELF>(SA);
1302 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1306 bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
1307 const auto &Sym = cast<MCSymbolELF>(S);
1311 // It is invalid to replace a reference to a global in a comdat
1312 // with a reference to a local since out of comdat references
1313 // to a local are forbidden.
1314 // We could try to return false for more cases, like the reference
1315 // being in the same comdat or Sym being an alias to another global,
1316 // but it is not clear if it is worth the effort.
1317 if (Sym.getBinding() != ELF::STB_GLOBAL)
1320 if (!Sym.isInSection())
1323 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1324 return Sec.getGroup();
1327 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1328 raw_pwrite_stream &OS,
1329 bool IsLittleEndian) {
1330 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);