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/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
41 #define DEBUG_TYPE "reloc-info"
45 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
47 class ELFObjectWriter;
49 class SymbolTableWriter {
50 ELFObjectWriter &EWriter;
53 // indexes we are going to write to .symtab_shndx.
54 std::vector<uint32_t> ShndxIndexes;
56 // The numbel of symbols written so far.
59 void createSymtabShndx();
61 template <typename T> void write(T Value);
64 SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
66 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
67 uint8_t other, uint32_t shndx, bool Reserved);
69 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
72 class ELFObjectWriter : public MCObjectWriter {
73 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
74 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
75 static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
76 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbol &Symbol,
77 bool Used, bool Renamed);
78 static bool isLocal(const MCSymbol &Symbol, bool isUsedInReloc);
80 /// Helper struct for containing some precomputed information on symbols.
81 struct ELFSymbolData {
82 const MCSymbol *Symbol;
84 uint32_t SectionIndex;
87 // Support lexicographic sorting.
88 bool operator<(const ELFSymbolData &RHS) const {
89 unsigned LHSType = MCELF::GetType(Symbol->getData());
90 unsigned RHSType = MCELF::GetType(RHS.Symbol->getData());
91 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
93 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
95 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
96 return SectionIndex < RHS.SectionIndex;
97 return Name < RHS.Name;
101 /// The target specific ELF writer instance.
102 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
104 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
105 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
106 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
108 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
112 /// @name Symbol Table Data
115 StringTableBuilder StrTabBuilder;
116 std::vector<uint64_t> FileSymbolData;
117 std::vector<ELFSymbolData> LocalSymbolData;
118 std::vector<ELFSymbolData> ExternalSymbolData;
119 std::vector<ELFSymbolData> UndefinedSymbolData;
125 // This holds the symbol table index of the last local symbol.
126 unsigned LastLocalSymbolIndex;
127 // This holds the .strtab section index.
128 unsigned StringTableIndex;
129 // This holds the .symtab section index.
130 unsigned SymbolTableIndex;
131 // This holds the .symtab_shndx section index.
132 unsigned SymtabShndxSectionIndex = 0;
134 // Sections in the order they are to be output in the section table.
135 std::vector<const MCSectionELF *> SectionTable;
136 unsigned addToSectionTable(const MCSectionELF *Sec);
138 // TargetObjectWriter wrappers.
139 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
140 bool hasRelocationAddend() const {
141 return TargetObjectWriter->hasRelocationAddend();
143 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
144 bool IsPCRel) const {
145 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
149 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
151 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW),
154 void reset() override {
156 WeakrefUsedInReloc.clear();
159 StrTabBuilder.clear();
160 FileSymbolData.clear();
161 LocalSymbolData.clear();
162 ExternalSymbolData.clear();
163 UndefinedSymbolData.clear();
165 SectionTable.clear();
166 MCObjectWriter::reset();
169 ~ELFObjectWriter() override;
171 void WriteWord(uint64_t W) {
178 template <typename T> void write(T Val) {
180 support::endian::Writer<support::little>(OS).write(Val);
182 support::endian::Writer<support::big>(OS).write(Val);
185 void writeHeader(const MCAssembler &Asm);
187 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
188 const MCAsmLayout &Layout);
190 // Start and end offset of each section
191 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
194 void writeSymbolTable(MCContext &Ctx, const MCAsmLayout &Layout,
195 SectionOffsetsTy &SectionOffsets);
197 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
198 const MCSymbolRefExpr *RefA,
199 const MCSymbol *Sym, uint64_t C,
200 unsigned Type) const;
202 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
203 const MCFragment *Fragment, const MCFixup &Fixup,
204 MCValue Target, bool &IsPCRel,
205 uint64_t &FixedValue) override;
207 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
210 // Map from a signature symbol to the group section index
211 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
213 /// Compute the symbol table data
215 /// \param Asm - The assembler.
216 /// \param SectionIndexMap - Maps a section to its index.
217 /// \param RevGroupMap - Maps a signature symbol to the group section.
218 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
219 const SectionIndexMapTy &SectionIndexMap,
220 const RevGroupMapTy &RevGroupMap);
222 MCSectionELF *createRelocationSection(MCContext &Ctx,
223 const MCSectionELF &Sec);
225 const MCSectionELF *createStringTable(MCContext &Ctx);
227 void ExecutePostLayoutBinding(MCAssembler &Asm,
228 const MCAsmLayout &Layout) override;
230 void writeSectionHeader(const MCAssembler &Asm, const MCAsmLayout &Layout,
231 const SectionIndexMapTy &SectionIndexMap,
232 const SectionOffsetsTy &SectionOffsets);
234 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
235 const MCAsmLayout &Layout);
237 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
238 uint64_t Address, uint64_t Offset, uint64_t Size,
239 uint32_t Link, uint32_t Info, uint64_t Alignment,
242 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
244 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
245 const MCSymbol &SymA,
246 const MCFragment &FB,
248 bool IsPCRel) const override;
250 bool isWeak(const MCSymbol &Sym) const override;
252 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
253 void writeSection(const SectionIndexMapTy &SectionIndexMap,
254 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
255 const MCSectionELF &Section);
259 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
260 SectionTable.push_back(Sec);
261 StrTabBuilder.add(Sec->getSectionName());
262 return SectionTable.size();
265 void SymbolTableWriter::createSymtabShndx() {
266 if (!ShndxIndexes.empty())
269 ShndxIndexes.resize(NumWritten);
272 template <typename T> void SymbolTableWriter::write(T Value) {
273 EWriter.write(Value);
276 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
277 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
279 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
280 uint64_t size, uint8_t other,
281 uint32_t shndx, bool Reserved) {
282 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
287 if (!ShndxIndexes.empty()) {
289 ShndxIndexes.push_back(shndx);
291 ShndxIndexes.push_back(0);
294 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
297 write(name); // st_name
298 write(info); // st_info
299 write(other); // st_other
300 write(Index); // st_shndx
301 write(value); // st_value
302 write(size); // st_size
304 write(name); // st_name
305 write(uint32_t(value)); // st_value
306 write(uint32_t(size)); // st_size
307 write(info); // st_info
308 write(other); // st_other
309 write(Index); // st_shndx
315 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
316 const MCFixupKindInfo &FKI =
317 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
319 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
322 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
326 case MCSymbolRefExpr::VK_GOT:
327 case MCSymbolRefExpr::VK_PLT:
328 case MCSymbolRefExpr::VK_GOTPCREL:
329 case MCSymbolRefExpr::VK_GOTOFF:
330 case MCSymbolRefExpr::VK_TPOFF:
331 case MCSymbolRefExpr::VK_TLSGD:
332 case MCSymbolRefExpr::VK_GOTTPOFF:
333 case MCSymbolRefExpr::VK_INDNTPOFF:
334 case MCSymbolRefExpr::VK_NTPOFF:
335 case MCSymbolRefExpr::VK_GOTNTPOFF:
336 case MCSymbolRefExpr::VK_TLSLDM:
337 case MCSymbolRefExpr::VK_DTPOFF:
338 case MCSymbolRefExpr::VK_TLSLD:
343 ELFObjectWriter::~ELFObjectWriter()
346 // Emit the ELF header.
347 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
353 // emitWord method behaves differently for ELF32 and ELF64, writing
354 // 4 bytes in the former and 8 in the latter.
356 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
358 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
361 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
363 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
365 Write8(TargetObjectWriter->getOSABI());
366 Write8(0); // e_ident[EI_ABIVERSION]
368 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
370 Write16(ELF::ET_REL); // e_type
372 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
374 Write32(ELF::EV_CURRENT); // e_version
375 WriteWord(0); // e_entry, no entry point in .o file
376 WriteWord(0); // e_phoff, no program header for .o
377 WriteWord(0); // e_shoff = sec hdr table off in bytes
379 // e_flags = whatever the target wants
380 Write32(Asm.getELFHeaderEFlags());
382 // e_ehsize = ELF header size
383 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
385 Write16(0); // e_phentsize = prog header entry size
386 Write16(0); // e_phnum = # prog header entries = 0
388 // e_shentsize = Section header entry size
389 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
391 // e_shnum = # of section header ents
394 // e_shstrndx = Section # of '.shstrtab'
395 assert(StringTableIndex < ELF::SHN_LORESERVE);
396 Write16(StringTableIndex);
399 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
400 const MCAsmLayout &Layout) {
401 MCSymbolData &Data = Sym.getData();
402 if (Data.isCommon() && Data.isExternal())
403 return Data.getCommonAlignment();
406 if (!Layout.getSymbolOffset(Sym, Res))
409 if (Layout.getAssembler().isThumbFunc(&Sym))
415 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
416 const MCAsmLayout &Layout) {
417 // The presence of symbol versions causes undefined symbols and
418 // versions declared with @@@ to be renamed.
420 for (const MCSymbol &Alias : Asm.symbols()) {
421 MCSymbolData &OriginalData = Alias.getData();
424 if (!Alias.isVariable())
426 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
429 const MCSymbol &Symbol = Ref->getSymbol();
430 MCSymbolData &SD = Asm.getSymbolData(Symbol);
432 StringRef AliasName = Alias.getName();
433 size_t Pos = AliasName.find('@');
434 if (Pos == StringRef::npos)
437 // Aliases defined with .symvar copy the binding from the symbol they alias.
438 // This is the first place we are able to copy this information.
439 OriginalData.setExternal(SD.isExternal());
440 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
442 StringRef Rest = AliasName.substr(Pos);
443 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
446 // FIXME: produce a better error message.
447 if (Symbol.isUndefined() && Rest.startswith("@@") &&
448 !Rest.startswith("@@@"))
449 report_fatal_error("A @@ version cannot be undefined");
451 Renames.insert(std::make_pair(&Symbol, &Alias));
455 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
456 uint8_t Type = newType;
458 // Propagation rules:
459 // IFUNC > FUNC > OBJECT > NOTYPE
460 // TLS_OBJECT > OBJECT > NOTYPE
462 // dont let the new type degrade the old type
466 case ELF::STT_GNU_IFUNC:
467 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
468 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
469 Type = ELF::STT_GNU_IFUNC;
472 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
473 Type == ELF::STT_TLS)
474 Type = ELF::STT_FUNC;
476 case ELF::STT_OBJECT:
477 if (Type == ELF::STT_NOTYPE)
478 Type = ELF::STT_OBJECT;
481 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
482 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
490 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
491 const MCAsmLayout &Layout) {
492 MCSymbolData &OrigData = MSD.Symbol->getData();
493 assert((!OrigData.getFragment() ||
494 (OrigData.getFragment()->getParent() == &MSD.Symbol->getSection())) &&
495 "The symbol's section doesn't match the fragment's symbol");
496 const MCSymbol *Base = Layout.getBaseSymbol(*MSD.Symbol);
498 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
500 bool IsReserved = !Base || OrigData.isCommon();
502 // Binding and Type share the same byte as upper and lower nibbles
503 uint8_t Binding = MCELF::GetBinding(OrigData);
504 uint8_t Type = MCELF::GetType(OrigData);
505 MCSymbolData *BaseSD = nullptr;
507 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
508 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
510 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
512 // Other and Visibility share the same byte with Visibility using the lower
514 uint8_t Visibility = MCELF::GetVisibility(OrigData);
515 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
518 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
521 const MCExpr *ESize = OrigData.getSize();
523 ESize = BaseSD->getSize();
527 if (!ESize->evaluateKnownAbsolute(Res, Layout))
528 report_fatal_error("Size expression must be absolute.");
532 // Write out the symbol table entry
533 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
534 MSD.SectionIndex, IsReserved);
537 void ELFObjectWriter::writeSymbolTable(MCContext &Ctx,
538 const MCAsmLayout &Layout,
539 SectionOffsetsTy &SectionOffsets) {
540 const MCSectionELF *SymtabSection = SectionTable[SymbolTableIndex - 1];
542 // The string table must be emitted first because we need the index
543 // into the string table for all the symbol names.
545 SymbolTableWriter Writer(*this, is64Bit());
548 OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
551 uint64_t SecStart = OS.tell();
553 // The first entry is the undefined symbol entry.
554 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
556 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
557 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
558 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
561 // Write the symbol table entries.
562 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
564 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
565 ELFSymbolData &MSD = LocalSymbolData[i];
566 WriteSymbol(Writer, MSD, Layout);
569 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
570 ELFSymbolData &MSD = ExternalSymbolData[i];
571 MCSymbolData &Data = MSD.Symbol->getData();
572 assert(((Data.getFlags() & ELF_STB_Global) ||
573 (Data.getFlags() & ELF_STB_Weak)) &&
574 "External symbol requires STB_GLOBAL or STB_WEAK flag");
575 WriteSymbol(Writer, MSD, Layout);
576 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
577 LastLocalSymbolIndex++;
580 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
581 ELFSymbolData &MSD = UndefinedSymbolData[i];
582 MCSymbolData &Data = MSD.Symbol->getData();
583 WriteSymbol(Writer, MSD, Layout);
584 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
585 LastLocalSymbolIndex++;
588 uint64_t SecEnd = OS.tell();
589 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
591 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
592 if (ShndxIndexes.empty()) {
593 assert(SymtabShndxSectionIndex == 0);
596 assert(SymtabShndxSectionIndex != 0);
598 SecStart = OS.tell();
599 const MCSectionELF *SymtabShndxSection =
600 SectionTable[SymtabShndxSectionIndex - 1];
601 for (uint32_t Index : ShndxIndexes)
604 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
607 // It is always valid to create a relocation with a symbol. It is preferable
608 // to use a relocation with a section if that is possible. Using the section
609 // allows us to omit some local symbols from the symbol table.
610 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
611 const MCSymbolRefExpr *RefA,
612 const MCSymbol *Sym, uint64_t C,
613 unsigned Type) const {
614 MCSymbolData *SD = Sym ? &Sym->getData() : nullptr;
616 // A PCRel relocation to an absolute value has no symbol (or section). We
617 // represent that with a relocation to a null section.
621 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
625 // The .odp creation emits a relocation against the symbol ".TOC." which
626 // create a R_PPC64_TOC relocation. However the relocation symbol name
627 // in final object creation should be NULL, since the symbol does not
628 // really exist, it is just the reference to TOC base for the current
629 // object file. Since the symbol is undefined, returning false results
630 // in a relocation with a null section which is the desired result.
631 case MCSymbolRefExpr::VK_PPC_TOCBASE:
634 // These VariantKind cause the relocation to refer to something other than
635 // the symbol itself, like a linker generated table. Since the address of
636 // symbol is not relevant, we cannot replace the symbol with the
637 // section and patch the difference in the addend.
638 case MCSymbolRefExpr::VK_GOT:
639 case MCSymbolRefExpr::VK_PLT:
640 case MCSymbolRefExpr::VK_GOTPCREL:
641 case MCSymbolRefExpr::VK_Mips_GOT:
642 case MCSymbolRefExpr::VK_PPC_GOT_LO:
643 case MCSymbolRefExpr::VK_PPC_GOT_HI:
644 case MCSymbolRefExpr::VK_PPC_GOT_HA:
648 // An undefined symbol is not in any section, so the relocation has to point
649 // to the symbol itself.
650 assert(Sym && "Expected a symbol");
651 if (Sym->isUndefined())
654 unsigned Binding = MCELF::GetBinding(*SD);
657 llvm_unreachable("Invalid Binding");
661 // If the symbol is weak, it might be overridden by a symbol in another
662 // file. The relocation has to point to the symbol so that the linker
665 case ELF::STB_GLOBAL:
666 // Global ELF symbols can be preempted by the dynamic linker. The relocation
667 // has to point to the symbol for a reason analogous to the STB_WEAK case.
671 // If a relocation points to a mergeable section, we have to be careful.
672 // If the offset is zero, a relocation with the section will encode the
673 // same information. With a non-zero offset, the situation is different.
674 // For example, a relocation can point 42 bytes past the end of a string.
675 // If we change such a relocation to use the section, the linker would think
676 // that it pointed to another string and subtracting 42 at runtime will
677 // produce the wrong value.
678 auto &Sec = cast<MCSectionELF>(Sym->getSection());
679 unsigned Flags = Sec.getFlags();
680 if (Flags & ELF::SHF_MERGE) {
684 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
685 // only handle section relocations to mergeable sections if using RELA.
686 if (!hasRelocationAddend())
690 // Most TLS relocations use a got, so they need the symbol. Even those that
691 // are just an offset (@tpoff), require a symbol in gold versions before
692 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
693 // http://sourceware.org/PR16773.
694 if (Flags & ELF::SHF_TLS)
697 // If the symbol is a thumb function the final relocation must set the lowest
698 // bit. With a symbol that is done by just having the symbol have that bit
699 // set, so we would lose the bit if we relocated with the section.
700 // FIXME: We could use the section but add the bit to the relocation value.
701 if (Asm.isThumbFunc(Sym))
704 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
709 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
710 const MCSymbol &Sym = Ref.getSymbol();
712 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
715 if (!Sym.isVariable())
718 const MCExpr *Expr = Sym.getVariableValue();
719 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
723 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
724 return &Inner->getSymbol();
728 // True if the assembler knows nothing about the final value of the symbol.
729 // This doesn't cover the comdat issues, since in those cases the assembler
730 // can at least know that all symbols in the section will move together.
731 static bool isWeak(const MCSymbolData &D) {
732 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
735 switch (MCELF::GetBinding(D)) {
737 llvm_unreachable("Unknown binding");
740 case ELF::STB_GLOBAL:
743 case ELF::STB_GNU_UNIQUE:
748 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
749 const MCAsmLayout &Layout,
750 const MCFragment *Fragment,
751 const MCFixup &Fixup, MCValue Target,
752 bool &IsPCRel, uint64_t &FixedValue) {
753 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
754 uint64_t C = Target.getConstant();
755 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
757 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
758 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
759 "Should not have constructed this");
761 // Let A, B and C being the components of Target and R be the location of
762 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
763 // If it is pcrel, we want to compute (A - B + C - R).
765 // In general, ELF has no relocations for -B. It can only represent (A + C)
766 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
767 // replace B to implement it: (A - R - K + C)
769 Asm.getContext().reportFatalError(
771 "No relocation available to represent this relative expression");
773 const MCSymbol &SymB = RefB->getSymbol();
775 if (SymB.isUndefined())
776 Asm.getContext().reportFatalError(
778 Twine("symbol '") + SymB.getName() +
779 "' can not be undefined in a subtraction expression");
781 assert(!SymB.isAbsolute() && "Should have been folded");
782 const MCSection &SecB = SymB.getSection();
783 if (&SecB != &FixupSection)
784 Asm.getContext().reportFatalError(
785 Fixup.getLoc(), "Cannot represent a difference across sections");
787 if (::isWeak(SymB.getData()))
788 Asm.getContext().reportFatalError(
789 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
791 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
792 uint64_t K = SymBOffset - FixupOffset;
797 // We either rejected the fixup or folded B into C at this point.
798 const MCSymbolRefExpr *RefA = Target.getSymA();
799 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
801 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
802 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
803 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
804 C += Layout.getSymbolOffset(*SymA);
807 if (hasRelocationAddend()) {
814 // FIXME: What is this!?!?
815 MCSymbolRefExpr::VariantKind Modifier =
816 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
817 if (RelocNeedsGOT(Modifier))
820 if (!RelocateWithSymbol) {
821 const MCSection *SecA =
822 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
823 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
824 const MCSymbol *SectionSymbol = ELFSec ? ELFSec->getBeginSymbol() : nullptr;
825 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
826 Relocations[&FixupSection].push_back(Rec);
831 if (const MCSymbol *R = Renames.lookup(SymA))
834 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
835 WeakrefUsedInReloc.insert(WeakRef);
837 UsedInReloc.insert(SymA);
839 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
840 Relocations[&FixupSection].push_back(Rec);
846 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
848 assert(S->hasData());
849 return S->getIndex();
852 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
853 const MCSymbol &Symbol, bool Used,
855 const MCSymbolData &Data = Symbol.getData();
856 if (Symbol.isVariable()) {
857 const MCExpr *Expr = Symbol.getVariableValue();
858 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
859 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
870 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
873 if (Symbol.isVariable()) {
874 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
875 if (Base && Base->isUndefined())
879 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
880 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
883 if (MCELF::GetType(Data) == ELF::STT_SECTION)
886 if (Symbol.isTemporary())
892 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool isUsedInReloc) {
893 const MCSymbolData &Data = Symbol.getData();
894 if (Data.isExternal())
897 if (Symbol.isDefined())
906 void ELFObjectWriter::computeSymbolTable(
907 MCAssembler &Asm, const MCAsmLayout &Layout,
908 const SectionIndexMapTy &SectionIndexMap,
909 const RevGroupMapTy &RevGroupMap) {
910 MCContext &Ctx = Asm.getContext();
912 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
913 MCSectionELF *SymtabSection =
914 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
915 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
916 SymbolTableIndex = addToSectionTable(SymtabSection);
918 // FIXME: Is this the correct place to do this?
919 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
921 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
922 MCSymbol *Sym = Asm.getContext().getOrCreateSymbol(Name);
923 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
924 Data.setExternal(true);
925 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
928 // Add the data for the symbols.
929 bool HasLargeSectionIndex = false;
930 for (const MCSymbol &Symbol : Asm.symbols()) {
931 MCSymbolData &SD = Symbol.getData();
933 bool Used = UsedInReloc.count(&Symbol);
934 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
935 bool isSignature = RevGroupMap.count(&Symbol);
937 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
938 Renames.count(&Symbol)))
942 MSD.Symbol = &Symbol;
943 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
945 // Undefined symbols are global, but this is the first place we
946 // are able to set it.
947 bool Local = isLocal(Symbol, Used);
948 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
950 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
951 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
952 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
956 MSD.SectionIndex = ELF::SHN_ABS;
957 } else if (SD.isCommon()) {
959 MSD.SectionIndex = ELF::SHN_COMMON;
960 } else if (BaseSymbol->isUndefined()) {
961 if (isSignature && !Used) {
962 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
963 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
964 HasLargeSectionIndex = true;
966 MSD.SectionIndex = ELF::SHN_UNDEF;
968 if (!Used && WeakrefUsed)
969 MCELF::SetBinding(SD, ELF::STB_WEAK);
971 const MCSectionELF &Section =
972 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
973 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
974 assert(MSD.SectionIndex && "Invalid section index!");
975 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
976 HasLargeSectionIndex = true;
979 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
982 // FIXME: All name handling should be done before we get to the writer,
983 // including dealing with GNU-style version suffixes. Fixing this isn't
986 // We thus have to be careful to not perform the symbol version replacement
989 // The ELF format is used on Windows by the MCJIT engine. Thus, on
990 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
991 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
992 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
993 // the EFLObjectWriter should not interpret the "@@@" sub-string as
994 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
995 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
996 // "__imp_?" or "__imp_@?".
998 // It would have been interesting to perform the MS mangling prefix check
999 // only when the target triple is of the form *-pc-windows-elf. But, it
1000 // seems that this information is not easily accessible from the
1002 StringRef Name = Symbol.getName();
1003 if (!Name.startswith("?") && !Name.startswith("@?") &&
1004 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1005 // This symbol isn't following the MSVC C++ name mangling convention. We
1006 // can thus safely interpret the @@@ in symbol names as specifying symbol
1008 SmallString<32> Buf;
1009 size_t Pos = Name.find("@@@");
1010 if (Pos != StringRef::npos) {
1011 Buf += Name.substr(0, Pos);
1012 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1013 Buf += Name.substr(Pos + Skip);
1018 // Sections have their own string table
1019 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1020 MSD.Name = StrTabBuilder.add(Name);
1022 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1023 UndefinedSymbolData.push_back(MSD);
1025 LocalSymbolData.push_back(MSD);
1027 ExternalSymbolData.push_back(MSD);
1030 if (HasLargeSectionIndex) {
1031 MCSectionELF *SymtabShndxSection =
1032 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
1033 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
1034 SymtabShndxSection->setAlignment(4);
1037 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1038 StrTabBuilder.add(*i);
1040 StrTabBuilder.finalize(StringTableBuilder::ELF);
1042 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1043 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1045 for (ELFSymbolData &MSD : LocalSymbolData)
1046 MSD.StringIndex = MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
1048 : StrTabBuilder.getOffset(MSD.Name);
1049 for (ELFSymbolData &MSD : ExternalSymbolData)
1050 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1051 for (ELFSymbolData& MSD : UndefinedSymbolData)
1052 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1054 // Symbols are required to be in lexicographic order.
1055 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1056 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1057 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1059 // Set the symbol indices. Local symbols must come before all other
1060 // symbols with non-local bindings.
1061 unsigned Index = FileSymbolData.size() + 1;
1062 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1063 LocalSymbolData[i].Symbol->setIndex(Index++);
1065 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1066 ExternalSymbolData[i].Symbol->setIndex(Index++);
1067 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1068 UndefinedSymbolData[i].Symbol->setIndex(Index++);
1072 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
1073 const MCSectionELF &Sec) {
1074 if (Relocations[&Sec].empty())
1077 const StringRef SectionName = Sec.getSectionName();
1078 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1079 RelaSectionName += SectionName;
1082 if (hasRelocationAddend())
1083 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1085 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1088 if (Sec.getFlags() & ELF::SHF_GROUP)
1089 Flags = ELF::SHF_GROUP;
1091 MCSectionELF *RelaSection = Ctx.createELFRelSection(
1092 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1093 Flags, EntrySize, Sec.getGroup(), &Sec);
1094 RelaSection->setAlignment(is64Bit() ? 8 : 4);
1098 static SmallVector<char, 128>
1099 getUncompressedData(const MCAsmLayout &Layout,
1100 const MCSection::FragmentListType &Fragments) {
1101 SmallVector<char, 128> UncompressedData;
1102 for (const MCFragment &F : Fragments) {
1103 const SmallVectorImpl<char> *Contents;
1104 switch (F.getKind()) {
1105 case MCFragment::FT_Data:
1106 Contents = &cast<MCDataFragment>(F).getContents();
1108 case MCFragment::FT_Dwarf:
1109 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1111 case MCFragment::FT_DwarfFrame:
1112 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1116 "Not expecting any other fragment types in a debug_* section");
1118 UncompressedData.append(Contents->begin(), Contents->end());
1120 return UncompressedData;
1123 // Include the debug info compression header:
1124 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1125 // useful for consumers to preallocate a buffer to decompress into.
1127 prependCompressionHeader(uint64_t Size,
1128 SmallVectorImpl<char> &CompressedContents) {
1129 const StringRef Magic = "ZLIB";
1130 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1132 if (sys::IsLittleEndianHost)
1133 sys::swapByteOrder(Size);
1134 CompressedContents.insert(CompressedContents.begin(),
1135 Magic.size() + sizeof(Size), 0);
1136 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1137 std::copy(reinterpret_cast<char *>(&Size),
1138 reinterpret_cast<char *>(&Size + 1),
1139 CompressedContents.begin() + Magic.size());
1143 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1144 const MCAsmLayout &Layout) {
1145 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1146 StringRef SectionName = Section.getSectionName();
1148 // Compressing debug_frame requires handling alignment fragments which is
1149 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1150 // for writing to arbitrary buffers) for little benefit.
1151 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1152 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1153 Asm.writeSectionData(&Section, Layout);
1157 // Gather the uncompressed data from all the fragments.
1158 const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1159 SmallVector<char, 128> UncompressedData =
1160 getUncompressedData(Layout, Fragments);
1162 SmallVector<char, 128> CompressedContents;
1163 zlib::Status Success = zlib::compress(
1164 StringRef(UncompressedData.data(), UncompressedData.size()),
1165 CompressedContents);
1166 if (Success != zlib::StatusOK) {
1167 Asm.writeSectionData(&Section, Layout);
1171 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1172 Asm.writeSectionData(&Section, Layout);
1175 Asm.getContext().renameELFSection(&Section,
1176 (".z" + SectionName.drop_front(1)).str());
1177 OS << CompressedContents;
1180 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1181 uint64_t Flags, uint64_t Address,
1182 uint64_t Offset, uint64_t Size,
1183 uint32_t Link, uint32_t Info,
1185 uint64_t EntrySize) {
1186 Write32(Name); // sh_name: index into string table
1187 Write32(Type); // sh_type
1188 WriteWord(Flags); // sh_flags
1189 WriteWord(Address); // sh_addr
1190 WriteWord(Offset); // sh_offset
1191 WriteWord(Size); // sh_size
1192 Write32(Link); // sh_link
1193 Write32(Info); // sh_info
1194 WriteWord(Alignment); // sh_addralign
1195 WriteWord(EntrySize); // sh_entsize
1198 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1199 const MCSectionELF &Sec) {
1200 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1202 // Sort the relocation entries. Most targets just sort by Offset, but some
1203 // (e.g., MIPS) have additional constraints.
1204 TargetObjectWriter->sortRelocs(Asm, Relocs);
1206 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1207 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1209 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1212 write(Entry.Offset);
1213 if (TargetObjectWriter->isN64()) {
1214 write(uint32_t(Index));
1216 write(TargetObjectWriter->getRSsym(Entry.Type));
1217 write(TargetObjectWriter->getRType3(Entry.Type));
1218 write(TargetObjectWriter->getRType2(Entry.Type));
1219 write(TargetObjectWriter->getRType(Entry.Type));
1221 struct ELF::Elf64_Rela ERE64;
1222 ERE64.setSymbolAndType(Index, Entry.Type);
1223 write(ERE64.r_info);
1225 if (hasRelocationAddend())
1226 write(Entry.Addend);
1228 write(uint32_t(Entry.Offset));
1230 struct ELF::Elf32_Rela ERE32;
1231 ERE32.setSymbolAndType(Index, Entry.Type);
1232 write(ERE32.r_info);
1234 if (hasRelocationAddend())
1235 write(uint32_t(Entry.Addend));
1240 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1241 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1242 OS << StrTabBuilder.data();
1243 return StrtabSection;
1246 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1247 uint32_t GroupSymbolIndex, uint64_t Offset,
1248 uint64_t Size, const MCSectionELF &Section) {
1249 uint64_t sh_link = 0;
1250 uint64_t sh_info = 0;
1252 switch(Section.getType()) {
1257 case ELF::SHT_DYNAMIC:
1258 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1261 case ELF::SHT_RELA: {
1262 sh_link = SymbolTableIndex;
1263 assert(sh_link && ".symtab not found");
1264 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1265 sh_info = SectionIndexMap.lookup(InfoSection);
1269 case ELF::SHT_SYMTAB:
1270 case ELF::SHT_DYNSYM:
1271 sh_link = StringTableIndex;
1272 sh_info = LastLocalSymbolIndex;
1275 case ELF::SHT_SYMTAB_SHNDX:
1276 sh_link = SymbolTableIndex;
1279 case ELF::SHT_GROUP:
1280 sh_link = SymbolTableIndex;
1281 sh_info = GroupSymbolIndex;
1285 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1286 Section.getType() == ELF::SHT_ARM_EXIDX)
1287 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1289 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1290 Section.getType(), Section.getFlags(), 0, Offset, Size,
1291 sh_link, sh_info, Section.getAlignment(),
1292 Section.getEntrySize());
1295 void ELFObjectWriter::writeSectionHeader(
1296 const MCAssembler &Asm, const MCAsmLayout &Layout,
1297 const SectionIndexMapTy &SectionIndexMap,
1298 const SectionOffsetsTy &SectionOffsets) {
1299 const unsigned NumSections = SectionTable.size();
1301 // Null section first.
1302 uint64_t FirstSectionSize =
1303 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1304 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1306 for (const MCSectionELF *Section : SectionTable) {
1307 uint32_t GroupSymbolIndex;
1308 unsigned Type = Section->getType();
1309 if (Type != ELF::SHT_GROUP)
1310 GroupSymbolIndex = 0;
1312 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section->getGroup());
1314 const std::pair<uint64_t, uint64_t> &Offsets =
1315 SectionOffsets.find(Section)->second;
1317 if (Type == ELF::SHT_NOBITS)
1318 Size = Layout.getSectionAddressSize(Section);
1320 Size = Offsets.second - Offsets.first;
1322 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1327 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1328 const MCAsmLayout &Layout) {
1329 MCContext &Ctx = Asm.getContext();
1330 MCSectionELF *StrtabSection =
1331 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1332 StringTableIndex = addToSectionTable(StrtabSection);
1334 RevGroupMapTy RevGroupMap;
1335 SectionIndexMapTy SectionIndexMap;
1337 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1339 // Write out the ELF header ...
1342 // ... then the sections ...
1343 SectionOffsetsTy SectionOffsets;
1344 std::vector<MCSectionELF *> Groups;
1345 std::vector<MCSectionELF *> Relocations;
1346 for (MCSection &Sec : Asm) {
1347 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1349 uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1350 WriteZeros(Padding);
1352 // Remember the offset into the file for this section.
1353 uint64_t SecStart = OS.tell();
1355 const MCSymbol *SignatureSymbol = Section.getGroup();
1356 writeSectionData(Asm, Section, Layout);
1358 uint64_t SecEnd = OS.tell();
1359 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1361 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1363 if (SignatureSymbol) {
1364 Asm.getOrCreateSymbolData(*SignatureSymbol);
1365 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1367 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1368 GroupIdx = addToSectionTable(Group);
1369 Group->setAlignment(4);
1370 Groups.push_back(Group);
1372 GroupMembers[SignatureSymbol].push_back(&Section);
1374 GroupMembers[SignatureSymbol].push_back(RelSection);
1377 SectionIndexMap[&Section] = addToSectionTable(&Section);
1379 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1380 Relocations.push_back(RelSection);
1384 for (MCSectionELF *Group : Groups) {
1385 uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1386 WriteZeros(Padding);
1388 // Remember the offset into the file for this section.
1389 uint64_t SecStart = OS.tell();
1391 const MCSymbol *SignatureSymbol = Group->getGroup();
1392 assert(SignatureSymbol);
1393 write(uint32_t(ELF::GRP_COMDAT));
1394 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1395 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1399 uint64_t SecEnd = OS.tell();
1400 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1403 // Compute symbol table information.
1404 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1406 for (MCSectionELF *RelSection : Relocations) {
1407 uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1408 WriteZeros(Padding);
1410 // Remember the offset into the file for this section.
1411 uint64_t SecStart = OS.tell();
1413 writeRelocations(Asm, *RelSection->getAssociatedSection());
1415 uint64_t SecEnd = OS.tell();
1416 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1419 writeSymbolTable(Ctx, Layout, SectionOffsets);
1422 uint64_t SecStart = OS.tell();
1423 const MCSectionELF *Sec = createStringTable(Ctx);
1424 uint64_t SecEnd = OS.tell();
1425 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1428 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1429 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1430 WriteZeros(Padding);
1432 const unsigned SectionHeaderOffset = OS.tell();
1434 // ... then the section header table ...
1435 writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1437 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1438 ? (uint16_t)ELF::SHN_UNDEF
1439 : SectionTable.size() + 1;
1440 if (sys::IsLittleEndianHost != IsLittleEndian)
1441 sys::swapByteOrder(NumSections);
1442 unsigned NumSectionsOffset;
1445 uint64_t Val = SectionHeaderOffset;
1446 if (sys::IsLittleEndianHost != IsLittleEndian)
1447 sys::swapByteOrder(Val);
1448 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1449 offsetof(ELF::Elf64_Ehdr, e_shoff));
1450 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1452 uint32_t Val = SectionHeaderOffset;
1453 if (sys::IsLittleEndianHost != IsLittleEndian)
1454 sys::swapByteOrder(Val);
1455 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1456 offsetof(ELF::Elf32_Ehdr, e_shoff));
1457 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1459 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1463 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1464 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1465 bool InSet, bool IsPCRel) const {
1468 if (::isWeak(SymA.getData()))
1471 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1475 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1476 const MCSymbolData &SD = Sym.getData();
1480 // It is invalid to replace a reference to a global in a comdat
1481 // with a reference to a local since out of comdat references
1482 // to a local are forbidden.
1483 // We could try to return false for more cases, like the reference
1484 // being in the same comdat or Sym being an alias to another global,
1485 // but it is not clear if it is worth the effort.
1486 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1489 if (!Sym.isInSection())
1492 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1493 return Sec.getGroup();
1496 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1497 raw_pwrite_stream &OS,
1498 bool IsLittleEndian) {
1499 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);