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, const MCSectionData &SD,
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()->getSection() ==
495 &MSD.Symbol->getSection())) &&
496 "The symbol's section doesn't match the fragment's symbol");
497 const MCSymbol *Base = Layout.getBaseSymbol(*MSD.Symbol);
499 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
501 bool IsReserved = !Base || OrigData.isCommon();
503 // Binding and Type share the same byte as upper and lower nibbles
504 uint8_t Binding = MCELF::GetBinding(OrigData);
505 uint8_t Type = MCELF::GetType(OrigData);
506 MCSymbolData *BaseSD = nullptr;
508 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
509 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
511 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
513 // Other and Visibility share the same byte with Visibility using the lower
515 uint8_t Visibility = MCELF::GetVisibility(OrigData);
516 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
519 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
522 const MCExpr *ESize = OrigData.getSize();
524 ESize = BaseSD->getSize();
528 if (!ESize->evaluateKnownAbsolute(Res, Layout))
529 report_fatal_error("Size expression must be absolute.");
533 // Write out the symbol table entry
534 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
535 MSD.SectionIndex, IsReserved);
538 void ELFObjectWriter::writeSymbolTable(MCContext &Ctx,
539 const MCAsmLayout &Layout,
540 SectionOffsetsTy &SectionOffsets) {
541 const MCSectionELF *SymtabSection = SectionTable[SymbolTableIndex - 1];
543 // The string table must be emitted first because we need the index
544 // into the string table for all the symbol names.
546 SymbolTableWriter Writer(*this, is64Bit());
549 OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
552 uint64_t SecStart = OS.tell();
554 // The first entry is the undefined symbol entry.
555 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
557 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
558 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
559 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
562 // Write the symbol table entries.
563 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
565 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
566 ELFSymbolData &MSD = LocalSymbolData[i];
567 WriteSymbol(Writer, MSD, Layout);
570 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
571 ELFSymbolData &MSD = ExternalSymbolData[i];
572 MCSymbolData &Data = MSD.Symbol->getData();
573 assert(((Data.getFlags() & ELF_STB_Global) ||
574 (Data.getFlags() & ELF_STB_Weak)) &&
575 "External symbol requires STB_GLOBAL or STB_WEAK flag");
576 WriteSymbol(Writer, MSD, Layout);
577 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
578 LastLocalSymbolIndex++;
581 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
582 ELFSymbolData &MSD = UndefinedSymbolData[i];
583 MCSymbolData &Data = MSD.Symbol->getData();
584 WriteSymbol(Writer, MSD, Layout);
585 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
586 LastLocalSymbolIndex++;
589 uint64_t SecEnd = OS.tell();
590 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
592 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
593 if (ShndxIndexes.empty()) {
594 assert(SymtabShndxSectionIndex == 0);
597 assert(SymtabShndxSectionIndex != 0);
599 SecStart = OS.tell();
600 const MCSectionELF *SymtabShndxSection =
601 SectionTable[SymtabShndxSectionIndex - 1];
602 for (uint32_t Index : ShndxIndexes)
605 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
608 // It is always valid to create a relocation with a symbol. It is preferable
609 // to use a relocation with a section if that is possible. Using the section
610 // allows us to omit some local symbols from the symbol table.
611 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
612 const MCSymbolRefExpr *RefA,
613 const MCSymbol *Sym, uint64_t C,
614 unsigned Type) const {
615 MCSymbolData *SD = Sym ? &Sym->getData() : nullptr;
617 // A PCRel relocation to an absolute value has no symbol (or section). We
618 // represent that with a relocation to a null section.
622 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
626 // The .odp creation emits a relocation against the symbol ".TOC." which
627 // create a R_PPC64_TOC relocation. However the relocation symbol name
628 // in final object creation should be NULL, since the symbol does not
629 // really exist, it is just the reference to TOC base for the current
630 // object file. Since the symbol is undefined, returning false results
631 // in a relocation with a null section which is the desired result.
632 case MCSymbolRefExpr::VK_PPC_TOCBASE:
635 // These VariantKind cause the relocation to refer to something other than
636 // the symbol itself, like a linker generated table. Since the address of
637 // symbol is not relevant, we cannot replace the symbol with the
638 // section and patch the difference in the addend.
639 case MCSymbolRefExpr::VK_GOT:
640 case MCSymbolRefExpr::VK_PLT:
641 case MCSymbolRefExpr::VK_GOTPCREL:
642 case MCSymbolRefExpr::VK_Mips_GOT:
643 case MCSymbolRefExpr::VK_PPC_GOT_LO:
644 case MCSymbolRefExpr::VK_PPC_GOT_HI:
645 case MCSymbolRefExpr::VK_PPC_GOT_HA:
649 // An undefined symbol is not in any section, so the relocation has to point
650 // to the symbol itself.
651 assert(Sym && "Expected a symbol");
652 if (Sym->isUndefined())
655 unsigned Binding = MCELF::GetBinding(*SD);
658 llvm_unreachable("Invalid Binding");
662 // If the symbol is weak, it might be overridden by a symbol in another
663 // file. The relocation has to point to the symbol so that the linker
666 case ELF::STB_GLOBAL:
667 // Global ELF symbols can be preempted by the dynamic linker. The relocation
668 // has to point to the symbol for a reason analogous to the STB_WEAK case.
672 // If a relocation points to a mergeable section, we have to be careful.
673 // If the offset is zero, a relocation with the section will encode the
674 // same information. With a non-zero offset, the situation is different.
675 // For example, a relocation can point 42 bytes past the end of a string.
676 // If we change such a relocation to use the section, the linker would think
677 // that it pointed to another string and subtracting 42 at runtime will
678 // produce the wrong value.
679 auto &Sec = cast<MCSectionELF>(Sym->getSection());
680 unsigned Flags = Sec.getFlags();
681 if (Flags & ELF::SHF_MERGE) {
685 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
686 // only handle section relocations to mergeable sections if using RELA.
687 if (!hasRelocationAddend())
691 // Most TLS relocations use a got, so they need the symbol. Even those that
692 // are just an offset (@tpoff), require a symbol in gold versions before
693 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
694 // http://sourceware.org/PR16773.
695 if (Flags & ELF::SHF_TLS)
698 // If the symbol is a thumb function the final relocation must set the lowest
699 // bit. With a symbol that is done by just having the symbol have that bit
700 // set, so we would lose the bit if we relocated with the section.
701 // FIXME: We could use the section but add the bit to the relocation value.
702 if (Asm.isThumbFunc(Sym))
705 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
710 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
711 const MCSymbol &Sym = Ref.getSymbol();
713 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
716 if (!Sym.isVariable())
719 const MCExpr *Expr = Sym.getVariableValue();
720 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
724 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
725 return &Inner->getSymbol();
729 // True if the assembler knows nothing about the final value of the symbol.
730 // This doesn't cover the comdat issues, since in those cases the assembler
731 // can at least know that all symbols in the section will move together.
732 static bool isWeak(const MCSymbolData &D) {
733 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
736 switch (MCELF::GetBinding(D)) {
738 llvm_unreachable("Unknown binding");
741 case ELF::STB_GLOBAL:
744 case ELF::STB_GNU_UNIQUE:
749 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
750 const MCAsmLayout &Layout,
751 const MCFragment *Fragment,
752 const MCFixup &Fixup, MCValue Target,
753 bool &IsPCRel, uint64_t &FixedValue) {
754 const MCSectionData *FixupSectionD = Fragment->getParent();
755 const MCSectionELF &FixupSection =
756 cast<MCSectionELF>(FixupSectionD->getSection());
757 uint64_t C = Target.getConstant();
758 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
760 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
761 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
762 "Should not have constructed this");
764 // Let A, B and C being the components of Target and R be the location of
765 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
766 // If it is pcrel, we want to compute (A - B + C - R).
768 // In general, ELF has no relocations for -B. It can only represent (A + C)
769 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
770 // replace B to implement it: (A - R - K + C)
772 Asm.getContext().reportFatalError(
774 "No relocation available to represent this relative expression");
776 const MCSymbol &SymB = RefB->getSymbol();
778 if (SymB.isUndefined())
779 Asm.getContext().reportFatalError(
781 Twine("symbol '") + SymB.getName() +
782 "' can not be undefined in a subtraction expression");
784 assert(!SymB.isAbsolute() && "Should have been folded");
785 const MCSection &SecB = SymB.getSection();
786 if (&SecB != &FixupSection)
787 Asm.getContext().reportFatalError(
788 Fixup.getLoc(), "Cannot represent a difference across sections");
790 if (::isWeak(SymB.getData()))
791 Asm.getContext().reportFatalError(
792 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
794 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
795 uint64_t K = SymBOffset - FixupOffset;
800 // We either rejected the fixup or folded B into C at this point.
801 const MCSymbolRefExpr *RefA = Target.getSymA();
802 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
804 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
805 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
806 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
807 C += Layout.getSymbolOffset(*SymA);
810 if (hasRelocationAddend()) {
817 // FIXME: What is this!?!?
818 MCSymbolRefExpr::VariantKind Modifier =
819 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
820 if (RelocNeedsGOT(Modifier))
823 if (!RelocateWithSymbol) {
824 const MCSection *SecA =
825 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
826 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
827 MCSymbol *SectionSymbol =
828 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
830 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
831 Relocations[&FixupSection].push_back(Rec);
836 if (const MCSymbol *R = Renames.lookup(SymA))
839 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
840 WeakrefUsedInReloc.insert(WeakRef);
842 UsedInReloc.insert(SymA);
844 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
845 Relocations[&FixupSection].push_back(Rec);
851 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
853 assert(S->hasData());
854 return S->getIndex();
857 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
858 const MCSymbol &Symbol, bool Used,
860 const MCSymbolData &Data = Symbol.getData();
861 if (Symbol.isVariable()) {
862 const MCExpr *Expr = Symbol.getVariableValue();
863 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
864 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
875 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
878 if (Symbol.isVariable()) {
879 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
880 if (Base && Base->isUndefined())
884 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
885 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
888 if (Symbol.isTemporary())
894 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool isUsedInReloc) {
895 const MCSymbolData &Data = Symbol.getData();
896 if (Data.isExternal())
899 if (Symbol.isDefined())
908 void ELFObjectWriter::computeSymbolTable(
909 MCAssembler &Asm, const MCAsmLayout &Layout,
910 const SectionIndexMapTy &SectionIndexMap,
911 const RevGroupMapTy &RevGroupMap) {
912 MCContext &Ctx = Asm.getContext();
914 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
915 MCSectionELF *SymtabSection =
916 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
917 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
918 SymbolTableIndex = addToSectionTable(SymtabSection);
920 // FIXME: Is this the correct place to do this?
921 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
923 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
924 MCSymbol *Sym = Asm.getContext().getOrCreateSymbol(Name);
925 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
926 Data.setExternal(true);
927 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
930 // Add the data for the symbols.
931 bool HasLargeSectionIndex = false;
932 for (const MCSymbol &Symbol : Asm.symbols()) {
933 MCSymbolData &SD = Symbol.getData();
935 bool Used = UsedInReloc.count(&Symbol);
936 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
937 bool isSignature = RevGroupMap.count(&Symbol);
939 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
940 Renames.count(&Symbol)))
944 MSD.Symbol = &Symbol;
945 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
947 // Undefined symbols are global, but this is the first place we
948 // are able to set it.
949 bool Local = isLocal(Symbol, Used);
950 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
952 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
953 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
954 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
958 MSD.SectionIndex = ELF::SHN_ABS;
959 } else if (SD.isCommon()) {
961 MSD.SectionIndex = ELF::SHN_COMMON;
962 } else if (BaseSymbol->isUndefined()) {
963 if (isSignature && !Used) {
964 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
965 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
966 HasLargeSectionIndex = true;
968 MSD.SectionIndex = ELF::SHN_UNDEF;
970 if (!Used && WeakrefUsed)
971 MCELF::SetBinding(SD, ELF::STB_WEAK);
973 const MCSectionELF &Section =
974 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
975 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
976 assert(MSD.SectionIndex && "Invalid section index!");
977 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
978 HasLargeSectionIndex = true;
981 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
984 // FIXME: All name handling should be done before we get to the writer,
985 // including dealing with GNU-style version suffixes. Fixing this isn't
988 // We thus have to be careful to not perform the symbol version replacement
991 // The ELF format is used on Windows by the MCJIT engine. Thus, on
992 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
993 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
994 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
995 // the EFLObjectWriter should not interpret the "@@@" sub-string as
996 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
997 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
998 // "__imp_?" or "__imp_@?".
1000 // It would have been interesting to perform the MS mangling prefix check
1001 // only when the target triple is of the form *-pc-windows-elf. But, it
1002 // seems that this information is not easily accessible from the
1004 StringRef Name = Symbol.getName();
1005 if (!Name.startswith("?") && !Name.startswith("@?") &&
1006 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1007 // This symbol isn't following the MSVC C++ name mangling convention. We
1008 // can thus safely interpret the @@@ in symbol names as specifying symbol
1010 SmallString<32> Buf;
1011 size_t Pos = Name.find("@@@");
1012 if (Pos != StringRef::npos) {
1013 Buf += Name.substr(0, Pos);
1014 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1015 Buf += Name.substr(Pos + Skip);
1020 // Sections have their own string table
1021 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1022 MSD.Name = StrTabBuilder.add(Name);
1024 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1025 UndefinedSymbolData.push_back(MSD);
1027 LocalSymbolData.push_back(MSD);
1029 ExternalSymbolData.push_back(MSD);
1032 if (HasLargeSectionIndex) {
1033 MCSectionELF *SymtabShndxSection =
1034 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
1035 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
1036 SymtabShndxSection->setAlignment(4);
1039 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1040 StrTabBuilder.add(*i);
1042 StrTabBuilder.finalize(StringTableBuilder::ELF);
1044 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1045 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1047 for (ELFSymbolData &MSD : LocalSymbolData)
1048 MSD.StringIndex = MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
1050 : StrTabBuilder.getOffset(MSD.Name);
1051 for (ELFSymbolData &MSD : ExternalSymbolData)
1052 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1053 for (ELFSymbolData& MSD : UndefinedSymbolData)
1054 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1056 // Symbols are required to be in lexicographic order.
1057 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1058 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1059 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1061 // Set the symbol indices. Local symbols must come before all other
1062 // symbols with non-local bindings.
1063 unsigned Index = FileSymbolData.size() + 1;
1064 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1065 LocalSymbolData[i].Symbol->setIndex(Index++);
1067 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1068 ExternalSymbolData[i].Symbol->setIndex(Index++);
1069 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1070 UndefinedSymbolData[i].Symbol->setIndex(Index++);
1074 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
1075 const MCSectionELF &Sec) {
1076 if (Relocations[&Sec].empty())
1079 const StringRef SectionName = Sec.getSectionName();
1080 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1081 RelaSectionName += SectionName;
1084 if (hasRelocationAddend())
1085 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1087 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1090 if (Sec.getFlags() & ELF::SHF_GROUP)
1091 Flags = ELF::SHF_GROUP;
1093 MCSectionELF *RelaSection = Ctx.createELFRelSection(
1094 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1095 Flags, EntrySize, Sec.getGroup(), &Sec);
1096 RelaSection->setAlignment(is64Bit() ? 8 : 4);
1100 static SmallVector<char, 128>
1101 getUncompressedData(const MCAsmLayout &Layout,
1102 const MCSectionData::FragmentListType &Fragments) {
1103 SmallVector<char, 128> UncompressedData;
1104 for (const MCFragment &F : Fragments) {
1105 const SmallVectorImpl<char> *Contents;
1106 switch (F.getKind()) {
1107 case MCFragment::FT_Data:
1108 Contents = &cast<MCDataFragment>(F).getContents();
1110 case MCFragment::FT_Dwarf:
1111 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1113 case MCFragment::FT_DwarfFrame:
1114 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1118 "Not expecting any other fragment types in a debug_* section");
1120 UncompressedData.append(Contents->begin(), Contents->end());
1122 return UncompressedData;
1125 // Include the debug info compression header:
1126 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1127 // useful for consumers to preallocate a buffer to decompress into.
1129 prependCompressionHeader(uint64_t Size,
1130 SmallVectorImpl<char> &CompressedContents) {
1131 const StringRef Magic = "ZLIB";
1132 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1134 if (sys::IsLittleEndianHost)
1135 sys::swapByteOrder(Size);
1136 CompressedContents.insert(CompressedContents.begin(),
1137 Magic.size() + sizeof(Size), 0);
1138 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1139 std::copy(reinterpret_cast<char *>(&Size),
1140 reinterpret_cast<char *>(&Size + 1),
1141 CompressedContents.begin() + Magic.size());
1145 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm,
1146 const MCSectionData &SD,
1147 const MCAsmLayout &Layout) {
1148 MCSectionELF &Section = static_cast<MCSectionELF &>(SD.getSection());
1149 StringRef SectionName = Section.getSectionName();
1151 // Compressing debug_frame requires handling alignment fragments which is
1152 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1153 // for writing to arbitrary buffers) for little benefit.
1154 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1155 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1156 Asm.writeSectionData(&SD, Layout);
1160 // Gather the uncompressed data from all the fragments.
1161 const MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1162 SmallVector<char, 128> UncompressedData =
1163 getUncompressedData(Layout, Fragments);
1165 SmallVector<char, 128> CompressedContents;
1166 zlib::Status Success = zlib::compress(
1167 StringRef(UncompressedData.data(), UncompressedData.size()),
1168 CompressedContents);
1169 if (Success != zlib::StatusOK) {
1170 Asm.writeSectionData(&SD, Layout);
1174 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1175 Asm.writeSectionData(&SD, Layout);
1178 Asm.getContext().renameELFSection(&Section,
1179 (".z" + SectionName.drop_front(1)).str());
1180 OS << CompressedContents;
1183 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1184 uint64_t Flags, uint64_t Address,
1185 uint64_t Offset, uint64_t Size,
1186 uint32_t Link, uint32_t Info,
1188 uint64_t EntrySize) {
1189 Write32(Name); // sh_name: index into string table
1190 Write32(Type); // sh_type
1191 WriteWord(Flags); // sh_flags
1192 WriteWord(Address); // sh_addr
1193 WriteWord(Offset); // sh_offset
1194 WriteWord(Size); // sh_size
1195 Write32(Link); // sh_link
1196 Write32(Info); // sh_info
1197 WriteWord(Alignment); // sh_addralign
1198 WriteWord(EntrySize); // sh_entsize
1201 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1202 const MCSectionELF &Sec) {
1203 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1205 // Sort the relocation entries. Most targets just sort by Offset, but some
1206 // (e.g., MIPS) have additional constraints.
1207 TargetObjectWriter->sortRelocs(Asm, Relocs);
1209 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1210 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1212 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1215 write(Entry.Offset);
1216 if (TargetObjectWriter->isN64()) {
1217 write(uint32_t(Index));
1219 write(TargetObjectWriter->getRSsym(Entry.Type));
1220 write(TargetObjectWriter->getRType3(Entry.Type));
1221 write(TargetObjectWriter->getRType2(Entry.Type));
1222 write(TargetObjectWriter->getRType(Entry.Type));
1224 struct ELF::Elf64_Rela ERE64;
1225 ERE64.setSymbolAndType(Index, Entry.Type);
1226 write(ERE64.r_info);
1228 if (hasRelocationAddend())
1229 write(Entry.Addend);
1231 write(uint32_t(Entry.Offset));
1233 struct ELF::Elf32_Rela ERE32;
1234 ERE32.setSymbolAndType(Index, Entry.Type);
1235 write(ERE32.r_info);
1237 if (hasRelocationAddend())
1238 write(uint32_t(Entry.Addend));
1243 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1244 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1245 OS << StrTabBuilder.data();
1246 return StrtabSection;
1249 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1250 uint32_t GroupSymbolIndex, uint64_t Offset,
1251 uint64_t Size, const MCSectionELF &Section) {
1252 uint64_t sh_link = 0;
1253 uint64_t sh_info = 0;
1255 switch(Section.getType()) {
1260 case ELF::SHT_DYNAMIC:
1261 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1264 case ELF::SHT_RELA: {
1265 sh_link = SymbolTableIndex;
1266 assert(sh_link && ".symtab not found");
1267 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1268 sh_info = SectionIndexMap.lookup(InfoSection);
1272 case ELF::SHT_SYMTAB:
1273 case ELF::SHT_DYNSYM:
1274 sh_link = StringTableIndex;
1275 sh_info = LastLocalSymbolIndex;
1278 case ELF::SHT_SYMTAB_SHNDX:
1279 sh_link = SymbolTableIndex;
1282 case ELF::SHT_GROUP:
1283 sh_link = SymbolTableIndex;
1284 sh_info = GroupSymbolIndex;
1288 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1289 Section.getType() == ELF::SHT_ARM_EXIDX)
1290 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1292 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1293 Section.getType(), Section.getFlags(), 0, Offset, Size,
1294 sh_link, sh_info, Section.getAlignment(),
1295 Section.getEntrySize());
1298 void ELFObjectWriter::writeSectionHeader(
1299 const MCAssembler &Asm, const MCAsmLayout &Layout,
1300 const SectionIndexMapTy &SectionIndexMap,
1301 const SectionOffsetsTy &SectionOffsets) {
1302 const unsigned NumSections = SectionTable.size();
1304 // Null section first.
1305 uint64_t FirstSectionSize =
1306 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1307 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1309 for (const MCSectionELF *Section : SectionTable) {
1310 uint32_t GroupSymbolIndex;
1311 unsigned Type = Section->getType();
1312 if (Type != ELF::SHT_GROUP)
1313 GroupSymbolIndex = 0;
1315 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section->getGroup());
1317 const std::pair<uint64_t, uint64_t> &Offsets =
1318 SectionOffsets.find(Section)->second;
1320 if (Type == ELF::SHT_NOBITS) {
1321 const MCSectionData &SD = Asm.getSectionData(*Section);
1322 Size = Layout.getSectionAddressSize(&SD);
1324 Size = Offsets.second - Offsets.first;
1327 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1332 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1333 const MCAsmLayout &Layout) {
1334 MCContext &Ctx = Asm.getContext();
1335 MCSectionELF *StrtabSection =
1336 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1337 StringTableIndex = addToSectionTable(StrtabSection);
1339 RevGroupMapTy RevGroupMap;
1340 SectionIndexMapTy SectionIndexMap;
1342 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1344 // Write out the ELF header ...
1347 // ... then the sections ...
1348 SectionOffsetsTy SectionOffsets;
1349 std::vector<MCSectionELF *> Groups;
1350 std::vector<MCSectionELF *> Relocations;
1351 for (const MCSectionData &SD : Asm) {
1352 const MCSectionELF &Section = static_cast<MCSectionELF &>(SD.getSection());
1354 uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1355 WriteZeros(Padding);
1357 // Remember the offset into the file for this section.
1358 uint64_t SecStart = OS.tell();
1360 const MCSymbol *SignatureSymbol = Section.getGroup();
1361 writeSectionData(Asm, SD, Layout);
1363 uint64_t SecEnd = OS.tell();
1364 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1366 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1368 if (SignatureSymbol) {
1369 Asm.getOrCreateSymbolData(*SignatureSymbol);
1370 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1372 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1373 GroupIdx = addToSectionTable(Group);
1374 Group->setAlignment(4);
1375 Groups.push_back(Group);
1377 GroupMembers[SignatureSymbol].push_back(&Section);
1379 GroupMembers[SignatureSymbol].push_back(RelSection);
1382 SectionIndexMap[&Section] = addToSectionTable(&Section);
1384 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1385 Relocations.push_back(RelSection);
1389 for (MCSectionELF *Group : Groups) {
1390 uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1391 WriteZeros(Padding);
1393 // Remember the offset into the file for this section.
1394 uint64_t SecStart = OS.tell();
1396 const MCSymbol *SignatureSymbol = Group->getGroup();
1397 assert(SignatureSymbol);
1398 write(uint32_t(ELF::GRP_COMDAT));
1399 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1400 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1404 uint64_t SecEnd = OS.tell();
1405 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1408 // Compute symbol table information.
1409 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1411 for (MCSectionELF *RelSection : Relocations) {
1412 uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1413 WriteZeros(Padding);
1415 // Remember the offset into the file for this section.
1416 uint64_t SecStart = OS.tell();
1418 writeRelocations(Asm, *RelSection->getAssociatedSection());
1420 uint64_t SecEnd = OS.tell();
1421 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1424 writeSymbolTable(Ctx, Layout, SectionOffsets);
1427 uint64_t SecStart = OS.tell();
1428 const MCSectionELF *Sec = createStringTable(Ctx);
1429 uint64_t SecEnd = OS.tell();
1430 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1433 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1434 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1435 WriteZeros(Padding);
1437 const unsigned SectionHeaderOffset = OS.tell();
1439 // ... then the section header table ...
1440 writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1442 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1443 ? (uint16_t)ELF::SHN_UNDEF
1444 : SectionTable.size() + 1;
1445 if (sys::IsLittleEndianHost != IsLittleEndian)
1446 sys::swapByteOrder(NumSections);
1447 unsigned NumSectionsOffset;
1450 uint64_t Val = SectionHeaderOffset;
1451 if (sys::IsLittleEndianHost != IsLittleEndian)
1452 sys::swapByteOrder(Val);
1453 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1454 offsetof(ELF::Elf64_Ehdr, e_shoff));
1455 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1457 uint32_t Val = SectionHeaderOffset;
1458 if (sys::IsLittleEndianHost != IsLittleEndian)
1459 sys::swapByteOrder(Val);
1460 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1461 offsetof(ELF::Elf32_Ehdr, e_shoff));
1462 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1464 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1468 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1469 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1470 bool InSet, bool IsPCRel) const {
1473 if (::isWeak(SymA.getData()))
1476 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1480 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1481 const MCSymbolData &SD = Sym.getData();
1485 // It is invalid to replace a reference to a global in a comdat
1486 // with a reference to a local since out of comdat references
1487 // to a local are forbidden.
1488 // We could try to return false for more cases, like the reference
1489 // being in the same comdat or Sym being an alias to another global,
1490 // but it is not clear if it is worth the effort.
1491 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1494 if (!Sym.isInSection())
1497 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1498 return Sec.getGroup();
1501 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1502 raw_pwrite_stream &OS,
1503 bool IsLittleEndian) {
1504 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);