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 uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
75 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbol &Symbol,
76 bool Used, bool Renamed);
77 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;
83 uint32_t SectionIndex;
86 // Support lexicographic sorting.
87 bool operator<(const ELFSymbolData &RHS) const {
88 unsigned LHSType = MCELF::GetType(*Symbol);
89 unsigned RHSType = MCELF::GetType(*RHS.Symbol);
90 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
92 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
94 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
95 return SectionIndex < RHS.SectionIndex;
96 return Name < RHS.Name;
100 /// The target specific ELF writer instance.
101 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
103 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
104 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
105 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
107 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
111 /// @name Symbol Table Data
114 StringTableBuilder StrTabBuilder;
118 // This holds the symbol table index of the last local symbol.
119 unsigned LastLocalSymbolIndex;
120 // This holds the .strtab section index.
121 unsigned StringTableIndex;
122 // This holds the .symtab section index.
123 unsigned SymbolTableIndex;
124 // This holds the .symtab_shndx section index.
125 unsigned SymtabShndxSectionIndex = 0;
127 // Sections in the order they are to be output in the section table.
128 std::vector<const MCSectionELF *> SectionTable;
129 unsigned addToSectionTable(const MCSectionELF *Sec);
131 // TargetObjectWriter wrappers.
132 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
133 bool hasRelocationAddend() const {
134 return TargetObjectWriter->hasRelocationAddend();
136 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
137 bool IsPCRel) const {
138 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
142 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
144 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
146 void reset() override {
148 WeakrefUsedInReloc.clear();
151 StrTabBuilder.clear();
152 SectionTable.clear();
153 MCObjectWriter::reset();
156 ~ELFObjectWriter() override;
158 void WriteWord(uint64_t W) {
165 template <typename T> void write(T Val) {
167 support::endian::Writer<support::little>(OS).write(Val);
169 support::endian::Writer<support::big>(OS).write(Val);
172 void writeHeader(const MCAssembler &Asm);
174 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
175 ELFSymbolData &MSD, const MCAsmLayout &Layout);
177 // Start and end offset of each section
178 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
181 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
182 const MCSymbolRefExpr *RefA,
183 const MCSymbol *Sym, uint64_t C,
184 unsigned Type) const;
186 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
187 const MCFragment *Fragment, const MCFixup &Fixup,
188 MCValue Target, bool &IsPCRel,
189 uint64_t &FixedValue) override;
191 // Map from a signature symbol to the group section index
192 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
194 /// Compute the symbol table data
196 /// \param Asm - The assembler.
197 /// \param SectionIndexMap - Maps a section to its index.
198 /// \param RevGroupMap - Maps a signature symbol to the group section.
199 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
200 const SectionIndexMapTy &SectionIndexMap,
201 const RevGroupMapTy &RevGroupMap,
202 SectionOffsetsTy &SectionOffsets);
204 MCSectionELF *createRelocationSection(MCContext &Ctx,
205 const MCSectionELF &Sec);
207 const MCSectionELF *createStringTable(MCContext &Ctx);
209 void ExecutePostLayoutBinding(MCAssembler &Asm,
210 const MCAsmLayout &Layout) override;
212 void writeSectionHeader(const MCAssembler &Asm, const MCAsmLayout &Layout,
213 const SectionIndexMapTy &SectionIndexMap,
214 const SectionOffsetsTy &SectionOffsets);
216 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
217 const MCAsmLayout &Layout);
219 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
220 uint64_t Address, uint64_t Offset, uint64_t Size,
221 uint32_t Link, uint32_t Info, uint64_t Alignment,
224 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
226 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
227 const MCSymbol &SymA,
228 const MCFragment &FB,
230 bool IsPCRel) const override;
232 bool isWeak(const MCSymbol &Sym) const override;
234 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
235 void writeSection(const SectionIndexMapTy &SectionIndexMap,
236 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
237 const MCSectionELF &Section);
241 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
242 SectionTable.push_back(Sec);
243 StrTabBuilder.add(Sec->getSectionName());
244 return SectionTable.size();
247 void SymbolTableWriter::createSymtabShndx() {
248 if (!ShndxIndexes.empty())
251 ShndxIndexes.resize(NumWritten);
254 template <typename T> void SymbolTableWriter::write(T Value) {
255 EWriter.write(Value);
258 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
259 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
261 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
262 uint64_t size, uint8_t other,
263 uint32_t shndx, bool Reserved) {
264 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
269 if (!ShndxIndexes.empty()) {
271 ShndxIndexes.push_back(shndx);
273 ShndxIndexes.push_back(0);
276 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
279 write(name); // st_name
280 write(info); // st_info
281 write(other); // st_other
282 write(Index); // st_shndx
283 write(value); // st_value
284 write(size); // st_size
286 write(name); // st_name
287 write(uint32_t(value)); // st_value
288 write(uint32_t(size)); // st_size
289 write(info); // st_info
290 write(other); // st_other
291 write(Index); // st_shndx
297 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
298 const MCFixupKindInfo &FKI =
299 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
301 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
304 ELFObjectWriter::~ELFObjectWriter()
307 // Emit the ELF header.
308 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
314 // emitWord method behaves differently for ELF32 and ELF64, writing
315 // 4 bytes in the former and 8 in the latter.
317 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
319 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
322 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
324 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
326 Write8(TargetObjectWriter->getOSABI());
327 Write8(0); // e_ident[EI_ABIVERSION]
329 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
331 Write16(ELF::ET_REL); // e_type
333 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
335 Write32(ELF::EV_CURRENT); // e_version
336 WriteWord(0); // e_entry, no entry point in .o file
337 WriteWord(0); // e_phoff, no program header for .o
338 WriteWord(0); // e_shoff = sec hdr table off in bytes
340 // e_flags = whatever the target wants
341 Write32(Asm.getELFHeaderEFlags());
343 // e_ehsize = ELF header size
344 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
346 Write16(0); // e_phentsize = prog header entry size
347 Write16(0); // e_phnum = # prog header entries = 0
349 // e_shentsize = Section header entry size
350 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
352 // e_shnum = # of section header ents
355 // e_shstrndx = Section # of '.shstrtab'
356 assert(StringTableIndex < ELF::SHN_LORESERVE);
357 Write16(StringTableIndex);
360 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
361 const MCAsmLayout &Layout) {
362 MCSymbolData &Data = Sym.getData();
363 if (Sym.isCommon() && Data.isExternal())
364 return Sym.getCommonAlignment();
367 if (!Layout.getSymbolOffset(Sym, Res))
370 if (Layout.getAssembler().isThumbFunc(&Sym))
376 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
377 const MCAsmLayout &Layout) {
378 // The presence of symbol versions causes undefined symbols and
379 // versions declared with @@@ to be renamed.
381 for (const MCSymbol &Alias : Asm.symbols()) {
382 MCSymbolData &OriginalData = Alias.getData();
385 if (!Alias.isVariable())
387 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
390 const MCSymbol &Symbol = Ref->getSymbol();
391 MCSymbolData &SD = Symbol.getData();
393 StringRef AliasName = Alias.getName();
394 size_t Pos = AliasName.find('@');
395 if (Pos == StringRef::npos)
398 // Aliases defined with .symvar copy the binding from the symbol they alias.
399 // This is the first place we are able to copy this information.
400 OriginalData.setExternal(SD.isExternal());
401 MCELF::SetBinding(Alias, MCELF::GetBinding(Symbol));
403 StringRef Rest = AliasName.substr(Pos);
404 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
407 // FIXME: produce a better error message.
408 if (Symbol.isUndefined() && Rest.startswith("@@") &&
409 !Rest.startswith("@@@"))
410 report_fatal_error("A @@ version cannot be undefined");
412 Renames.insert(std::make_pair(&Symbol, &Alias));
416 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
417 uint8_t Type = newType;
419 // Propagation rules:
420 // IFUNC > FUNC > OBJECT > NOTYPE
421 // TLS_OBJECT > OBJECT > NOTYPE
423 // dont let the new type degrade the old type
427 case ELF::STT_GNU_IFUNC:
428 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
429 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
430 Type = ELF::STT_GNU_IFUNC;
433 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
434 Type == ELF::STT_TLS)
435 Type = ELF::STT_FUNC;
437 case ELF::STT_OBJECT:
438 if (Type == ELF::STT_NOTYPE)
439 Type = ELF::STT_OBJECT;
442 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
443 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
451 void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
452 uint32_t StringIndex, ELFSymbolData &MSD,
453 const MCAsmLayout &Layout) {
455 MCSymbolData &OrigData = MSD.Symbol->getData();
456 assert((!OrigData.getFragment() ||
457 (OrigData.getFragment()->getParent() == &MSD.Symbol->getSection())) &&
458 "The symbol's section doesn't match the fragment's symbol");
460 const MCSymbol *Base = Layout.getBaseSymbol(*MSD.Symbol);
462 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
464 bool IsReserved = !Base || MSD.Symbol->isCommon();
466 // Binding and Type share the same byte as upper and lower nibbles
467 uint8_t Binding = MCELF::GetBinding(*MSD.Symbol);
468 uint8_t Type = MCELF::GetType(*MSD.Symbol);
469 MCSymbolData *BaseSD = nullptr;
471 BaseSD = &Base->getData();
472 Type = mergeTypeForSet(Type, MCELF::GetType(*Base));
474 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
476 // Other and Visibility share the same byte with Visibility using the lower
478 uint8_t Visibility = MCELF::GetVisibility(*MSD.Symbol);
479 uint8_t Other = MCELF::getOther(*MSD.Symbol)
480 << (ELF_STO_Shift - ELF_STV_Shift);
483 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
486 const MCExpr *ESize = MSD.Symbol->getSize();
488 ESize = Base->getSize();
492 if (!ESize->evaluateKnownAbsolute(Res, Layout))
493 report_fatal_error("Size expression must be absolute.");
497 // Write out the symbol table entry
498 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
502 // It is always valid to create a relocation with a symbol. It is preferable
503 // to use a relocation with a section if that is possible. Using the section
504 // allows us to omit some local symbols from the symbol table.
505 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
506 const MCSymbolRefExpr *RefA,
507 const MCSymbol *Sym, uint64_t C,
508 unsigned Type) const {
509 // A PCRel relocation to an absolute value has no symbol (or section). We
510 // represent that with a relocation to a null section.
514 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
518 // The .odp creation emits a relocation against the symbol ".TOC." which
519 // create a R_PPC64_TOC relocation. However the relocation symbol name
520 // in final object creation should be NULL, since the symbol does not
521 // really exist, it is just the reference to TOC base for the current
522 // object file. Since the symbol is undefined, returning false results
523 // in a relocation with a null section which is the desired result.
524 case MCSymbolRefExpr::VK_PPC_TOCBASE:
527 // These VariantKind cause the relocation to refer to something other than
528 // the symbol itself, like a linker generated table. Since the address of
529 // symbol is not relevant, we cannot replace the symbol with the
530 // section and patch the difference in the addend.
531 case MCSymbolRefExpr::VK_GOT:
532 case MCSymbolRefExpr::VK_PLT:
533 case MCSymbolRefExpr::VK_GOTPCREL:
534 case MCSymbolRefExpr::VK_Mips_GOT:
535 case MCSymbolRefExpr::VK_PPC_GOT_LO:
536 case MCSymbolRefExpr::VK_PPC_GOT_HI:
537 case MCSymbolRefExpr::VK_PPC_GOT_HA:
541 // An undefined symbol is not in any section, so the relocation has to point
542 // to the symbol itself.
543 assert(Sym && "Expected a symbol");
544 if (Sym->isUndefined())
547 unsigned Binding = MCELF::GetBinding(*Sym);
550 llvm_unreachable("Invalid Binding");
554 // If the symbol is weak, it might be overridden by a symbol in another
555 // file. The relocation has to point to the symbol so that the linker
558 case ELF::STB_GLOBAL:
559 // Global ELF symbols can be preempted by the dynamic linker. The relocation
560 // has to point to the symbol for a reason analogous to the STB_WEAK case.
564 // If a relocation points to a mergeable section, we have to be careful.
565 // If the offset is zero, a relocation with the section will encode the
566 // same information. With a non-zero offset, the situation is different.
567 // For example, a relocation can point 42 bytes past the end of a string.
568 // If we change such a relocation to use the section, the linker would think
569 // that it pointed to another string and subtracting 42 at runtime will
570 // produce the wrong value.
571 auto &Sec = cast<MCSectionELF>(Sym->getSection());
572 unsigned Flags = Sec.getFlags();
573 if (Flags & ELF::SHF_MERGE) {
577 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
578 // only handle section relocations to mergeable sections if using RELA.
579 if (!hasRelocationAddend())
583 // Most TLS relocations use a got, so they need the symbol. Even those that
584 // are just an offset (@tpoff), require a symbol in gold versions before
585 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
586 // http://sourceware.org/PR16773.
587 if (Flags & ELF::SHF_TLS)
590 // If the symbol is a thumb function the final relocation must set the lowest
591 // bit. With a symbol that is done by just having the symbol have that bit
592 // set, so we would lose the bit if we relocated with the section.
593 // FIXME: We could use the section but add the bit to the relocation value.
594 if (Asm.isThumbFunc(Sym))
597 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
602 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
603 const MCSymbol &Sym = Ref.getSymbol();
605 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
608 if (!Sym.isVariable())
611 const MCExpr *Expr = Sym.getVariableValue();
612 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
616 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
617 return &Inner->getSymbol();
621 // True if the assembler knows nothing about the final value of the symbol.
622 // This doesn't cover the comdat issues, since in those cases the assembler
623 // can at least know that all symbols in the section will move together.
624 static bool isWeak(const MCSymbol &Sym) {
625 if (MCELF::GetType(Sym) == ELF::STT_GNU_IFUNC)
628 switch (MCELF::GetBinding(Sym)) {
630 llvm_unreachable("Unknown binding");
633 case ELF::STB_GLOBAL:
636 case ELF::STB_GNU_UNIQUE:
641 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
642 const MCAsmLayout &Layout,
643 const MCFragment *Fragment,
644 const MCFixup &Fixup, MCValue Target,
645 bool &IsPCRel, uint64_t &FixedValue) {
646 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
647 uint64_t C = Target.getConstant();
648 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
650 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
651 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
652 "Should not have constructed this");
654 // Let A, B and C being the components of Target and R be the location of
655 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
656 // If it is pcrel, we want to compute (A - B + C - R).
658 // In general, ELF has no relocations for -B. It can only represent (A + C)
659 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
660 // replace B to implement it: (A - R - K + C)
662 Asm.getContext().reportFatalError(
664 "No relocation available to represent this relative expression");
666 const MCSymbol &SymB = RefB->getSymbol();
668 if (SymB.isUndefined())
669 Asm.getContext().reportFatalError(
671 Twine("symbol '") + SymB.getName() +
672 "' can not be undefined in a subtraction expression");
674 assert(!SymB.isAbsolute() && "Should have been folded");
675 const MCSection &SecB = SymB.getSection();
676 if (&SecB != &FixupSection)
677 Asm.getContext().reportFatalError(
678 Fixup.getLoc(), "Cannot represent a difference across sections");
681 Asm.getContext().reportFatalError(
682 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
684 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
685 uint64_t K = SymBOffset - FixupOffset;
690 // We either rejected the fixup or folded B into C at this point.
691 const MCSymbolRefExpr *RefA = Target.getSymA();
692 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
694 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
695 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
696 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
697 C += Layout.getSymbolOffset(*SymA);
700 if (hasRelocationAddend()) {
707 if (!RelocateWithSymbol) {
708 const MCSection *SecA =
709 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
710 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
711 const MCSymbol *SectionSymbol = ELFSec ? ELFSec->getBeginSymbol() : nullptr;
712 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
713 Relocations[&FixupSection].push_back(Rec);
718 if (const MCSymbol *R = Renames.lookup(SymA))
721 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
722 WeakrefUsedInReloc.insert(WeakRef);
724 UsedInReloc.insert(SymA);
726 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
727 Relocations[&FixupSection].push_back(Rec);
731 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
732 const MCSymbol &Symbol, bool Used,
734 if (Symbol.isVariable()) {
735 const MCExpr *Expr = Symbol.getVariableValue();
736 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
737 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
748 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
751 if (Symbol.isVariable()) {
752 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
753 if (Base && Base->isUndefined())
757 bool IsGlobal = MCELF::GetBinding(Symbol) == ELF::STB_GLOBAL;
758 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
761 if (MCELF::GetType(Symbol) == ELF::STT_SECTION)
764 if (Symbol.isTemporary())
770 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool IsUsedInReloc,
772 const MCSymbolData &Data = Symbol.getData();
773 if (Data.isExternal())
776 if (Symbol.isDefined())
785 void ELFObjectWriter::computeSymbolTable(
786 MCAssembler &Asm, const MCAsmLayout &Layout,
787 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
788 SectionOffsetsTy &SectionOffsets) {
789 MCContext &Ctx = Asm.getContext();
790 SymbolTableWriter Writer(*this, is64Bit());
793 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
794 MCSectionELF *SymtabSection =
795 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
796 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
797 SymbolTableIndex = addToSectionTable(SymtabSection);
800 OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
803 uint64_t SecStart = OS.tell();
805 // The first entry is the undefined symbol entry.
806 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
808 std::vector<ELFSymbolData> LocalSymbolData;
809 std::vector<ELFSymbolData> ExternalSymbolData;
811 // Add the data for the symbols.
812 bool HasLargeSectionIndex = false;
813 for (const MCSymbol &Symbol : Asm.symbols()) {
814 bool Used = UsedInReloc.count(&Symbol);
815 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
816 bool isSignature = RevGroupMap.count(&Symbol);
818 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
819 Renames.count(&Symbol)))
823 MSD.Symbol = &Symbol;
825 // Undefined symbols are global, but this is the first place we
826 // are able to set it.
827 bool Local = isLocal(Symbol, Used, isSignature);
828 if (!Local && MCELF::GetBinding(Symbol) == ELF::STB_LOCAL)
829 MCELF::SetBinding(Symbol, ELF::STB_GLOBAL);
831 if (Symbol.isAbsolute()) {
832 MSD.SectionIndex = ELF::SHN_ABS;
833 } else if (Symbol.isCommon()) {
835 MSD.SectionIndex = ELF::SHN_COMMON;
836 } else if (Symbol.isUndefined()) {
837 if (isSignature && !Used) {
838 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
839 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
840 HasLargeSectionIndex = true;
842 MSD.SectionIndex = ELF::SHN_UNDEF;
844 if (!Used && WeakrefUsed)
845 MCELF::SetBinding(Symbol, ELF::STB_WEAK);
847 const MCSectionELF &Section =
848 static_cast<const MCSectionELF &>(Symbol.getSection());
849 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
850 assert(MSD.SectionIndex && "Invalid section index!");
851 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
852 HasLargeSectionIndex = true;
855 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
858 // FIXME: All name handling should be done before we get to the writer,
859 // including dealing with GNU-style version suffixes. Fixing this isn't
862 // We thus have to be careful to not perform the symbol version replacement
865 // The ELF format is used on Windows by the MCJIT engine. Thus, on
866 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
867 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
868 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
869 // the EFLObjectWriter should not interpret the "@@@" sub-string as
870 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
871 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
872 // "__imp_?" or "__imp_@?".
874 // It would have been interesting to perform the MS mangling prefix check
875 // only when the target triple is of the form *-pc-windows-elf. But, it
876 // seems that this information is not easily accessible from the
878 StringRef Name = Symbol.getName();
879 if (!Name.startswith("?") && !Name.startswith("@?") &&
880 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
881 // This symbol isn't following the MSVC C++ name mangling convention. We
882 // can thus safely interpret the @@@ in symbol names as specifying symbol
885 size_t Pos = Name.find("@@@");
886 if (Pos != StringRef::npos) {
887 Buf += Name.substr(0, Pos);
888 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
889 Buf += Name.substr(Pos + Skip);
894 // Sections have their own string table
895 if (MCELF::GetType(Symbol) != ELF::STT_SECTION)
896 MSD.Name = StrTabBuilder.add(Name);
899 LocalSymbolData.push_back(MSD);
901 ExternalSymbolData.push_back(MSD);
904 if (HasLargeSectionIndex) {
905 MCSectionELF *SymtabShndxSection =
906 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
907 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
908 SymtabShndxSection->setAlignment(4);
911 ArrayRef<std::string> FileNames = Asm.getFileNames();
912 for (const std::string &Name : FileNames)
913 StrTabBuilder.add(Name);
915 StrTabBuilder.finalize(StringTableBuilder::ELF);
917 for (const std::string &Name : FileNames)
918 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
919 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
922 // Symbols are required to be in lexicographic order.
923 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
924 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
926 // Set the symbol indices. Local symbols must come before all other
927 // symbols with non-local bindings.
928 unsigned Index = FileNames.size() + 1;
930 for (ELFSymbolData &MSD : LocalSymbolData) {
931 unsigned StringIndex = MCELF::GetType(*MSD.Symbol) == ELF::STT_SECTION
933 : StrTabBuilder.getOffset(MSD.Name);
934 MSD.Symbol->setIndex(Index++);
935 writeSymbol(Writer, StringIndex, MSD, Layout);
938 // Write the symbol table entries.
939 LastLocalSymbolIndex = Index;
941 for (ELFSymbolData &MSD : ExternalSymbolData) {
942 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
943 MSD.Symbol->setIndex(Index++);
944 writeSymbol(Writer, StringIndex, MSD, Layout);
945 assert(MCELF::GetBinding(*MSD.Symbol) != ELF::STB_LOCAL);
948 uint64_t SecEnd = OS.tell();
949 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
951 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
952 if (ShndxIndexes.empty()) {
953 assert(SymtabShndxSectionIndex == 0);
956 assert(SymtabShndxSectionIndex != 0);
958 SecStart = OS.tell();
959 const MCSectionELF *SymtabShndxSection =
960 SectionTable[SymtabShndxSectionIndex - 1];
961 for (uint32_t Index : ShndxIndexes)
964 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
968 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
969 const MCSectionELF &Sec) {
970 if (Relocations[&Sec].empty())
973 const StringRef SectionName = Sec.getSectionName();
974 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
975 RelaSectionName += SectionName;
978 if (hasRelocationAddend())
979 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
981 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
984 if (Sec.getFlags() & ELF::SHF_GROUP)
985 Flags = ELF::SHF_GROUP;
987 MCSectionELF *RelaSection = Ctx.createELFRelSection(
988 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
989 Flags, EntrySize, Sec.getGroup(), &Sec);
990 RelaSection->setAlignment(is64Bit() ? 8 : 4);
994 static SmallVector<char, 128>
995 getUncompressedData(const MCAsmLayout &Layout,
996 const MCSection::FragmentListType &Fragments) {
997 SmallVector<char, 128> UncompressedData;
998 for (const MCFragment &F : Fragments) {
999 const SmallVectorImpl<char> *Contents;
1000 switch (F.getKind()) {
1001 case MCFragment::FT_Data:
1002 Contents = &cast<MCDataFragment>(F).getContents();
1004 case MCFragment::FT_Dwarf:
1005 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1007 case MCFragment::FT_DwarfFrame:
1008 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1012 "Not expecting any other fragment types in a debug_* section");
1014 UncompressedData.append(Contents->begin(), Contents->end());
1016 return UncompressedData;
1019 // Include the debug info compression header:
1020 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1021 // useful for consumers to preallocate a buffer to decompress into.
1023 prependCompressionHeader(uint64_t Size,
1024 SmallVectorImpl<char> &CompressedContents) {
1025 const StringRef Magic = "ZLIB";
1026 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1028 if (sys::IsLittleEndianHost)
1029 sys::swapByteOrder(Size);
1030 CompressedContents.insert(CompressedContents.begin(),
1031 Magic.size() + sizeof(Size), 0);
1032 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1033 std::copy(reinterpret_cast<char *>(&Size),
1034 reinterpret_cast<char *>(&Size + 1),
1035 CompressedContents.begin() + Magic.size());
1039 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1040 const MCAsmLayout &Layout) {
1041 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1042 StringRef SectionName = Section.getSectionName();
1044 // Compressing debug_frame requires handling alignment fragments which is
1045 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1046 // for writing to arbitrary buffers) for little benefit.
1047 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1048 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1049 Asm.writeSectionData(&Section, Layout);
1053 // Gather the uncompressed data from all the fragments.
1054 const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1055 SmallVector<char, 128> UncompressedData =
1056 getUncompressedData(Layout, Fragments);
1058 SmallVector<char, 128> CompressedContents;
1059 zlib::Status Success = zlib::compress(
1060 StringRef(UncompressedData.data(), UncompressedData.size()),
1061 CompressedContents);
1062 if (Success != zlib::StatusOK) {
1063 Asm.writeSectionData(&Section, Layout);
1067 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1068 Asm.writeSectionData(&Section, Layout);
1071 Asm.getContext().renameELFSection(&Section,
1072 (".z" + SectionName.drop_front(1)).str());
1073 OS << CompressedContents;
1076 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1077 uint64_t Flags, uint64_t Address,
1078 uint64_t Offset, uint64_t Size,
1079 uint32_t Link, uint32_t Info,
1081 uint64_t EntrySize) {
1082 Write32(Name); // sh_name: index into string table
1083 Write32(Type); // sh_type
1084 WriteWord(Flags); // sh_flags
1085 WriteWord(Address); // sh_addr
1086 WriteWord(Offset); // sh_offset
1087 WriteWord(Size); // sh_size
1088 Write32(Link); // sh_link
1089 Write32(Info); // sh_info
1090 WriteWord(Alignment); // sh_addralign
1091 WriteWord(EntrySize); // sh_entsize
1094 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1095 const MCSectionELF &Sec) {
1096 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1098 // Sort the relocation entries. Most targets just sort by Offset, but some
1099 // (e.g., MIPS) have additional constraints.
1100 TargetObjectWriter->sortRelocs(Asm, Relocs);
1102 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1103 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1104 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1107 write(Entry.Offset);
1108 if (TargetObjectWriter->isN64()) {
1109 write(uint32_t(Index));
1111 write(TargetObjectWriter->getRSsym(Entry.Type));
1112 write(TargetObjectWriter->getRType3(Entry.Type));
1113 write(TargetObjectWriter->getRType2(Entry.Type));
1114 write(TargetObjectWriter->getRType(Entry.Type));
1116 struct ELF::Elf64_Rela ERE64;
1117 ERE64.setSymbolAndType(Index, Entry.Type);
1118 write(ERE64.r_info);
1120 if (hasRelocationAddend())
1121 write(Entry.Addend);
1123 write(uint32_t(Entry.Offset));
1125 struct ELF::Elf32_Rela ERE32;
1126 ERE32.setSymbolAndType(Index, Entry.Type);
1127 write(ERE32.r_info);
1129 if (hasRelocationAddend())
1130 write(uint32_t(Entry.Addend));
1135 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1136 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1137 OS << StrTabBuilder.data();
1138 return StrtabSection;
1141 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1142 uint32_t GroupSymbolIndex, uint64_t Offset,
1143 uint64_t Size, const MCSectionELF &Section) {
1144 uint64_t sh_link = 0;
1145 uint64_t sh_info = 0;
1147 switch(Section.getType()) {
1152 case ELF::SHT_DYNAMIC:
1153 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1156 case ELF::SHT_RELA: {
1157 sh_link = SymbolTableIndex;
1158 assert(sh_link && ".symtab not found");
1159 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1160 sh_info = SectionIndexMap.lookup(InfoSection);
1164 case ELF::SHT_SYMTAB:
1165 case ELF::SHT_DYNSYM:
1166 sh_link = StringTableIndex;
1167 sh_info = LastLocalSymbolIndex;
1170 case ELF::SHT_SYMTAB_SHNDX:
1171 sh_link = SymbolTableIndex;
1174 case ELF::SHT_GROUP:
1175 sh_link = SymbolTableIndex;
1176 sh_info = GroupSymbolIndex;
1180 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1181 Section.getType() == ELF::SHT_ARM_EXIDX)
1182 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1184 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1185 Section.getType(), Section.getFlags(), 0, Offset, Size,
1186 sh_link, sh_info, Section.getAlignment(),
1187 Section.getEntrySize());
1190 void ELFObjectWriter::writeSectionHeader(
1191 const MCAssembler &Asm, const MCAsmLayout &Layout,
1192 const SectionIndexMapTy &SectionIndexMap,
1193 const SectionOffsetsTy &SectionOffsets) {
1194 const unsigned NumSections = SectionTable.size();
1196 // Null section first.
1197 uint64_t FirstSectionSize =
1198 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1199 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1201 for (const MCSectionELF *Section : SectionTable) {
1202 uint32_t GroupSymbolIndex;
1203 unsigned Type = Section->getType();
1204 if (Type != ELF::SHT_GROUP)
1205 GroupSymbolIndex = 0;
1207 GroupSymbolIndex = Section->getGroup()->getIndex();
1209 const std::pair<uint64_t, uint64_t> &Offsets =
1210 SectionOffsets.find(Section)->second;
1212 if (Type == ELF::SHT_NOBITS)
1213 Size = Layout.getSectionAddressSize(Section);
1215 Size = Offsets.second - Offsets.first;
1217 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1222 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1223 const MCAsmLayout &Layout) {
1224 MCContext &Ctx = Asm.getContext();
1225 MCSectionELF *StrtabSection =
1226 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1227 StringTableIndex = addToSectionTable(StrtabSection);
1229 RevGroupMapTy RevGroupMap;
1230 SectionIndexMapTy SectionIndexMap;
1232 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1234 // Write out the ELF header ...
1237 // ... then the sections ...
1238 SectionOffsetsTy SectionOffsets;
1239 std::vector<MCSectionELF *> Groups;
1240 std::vector<MCSectionELF *> Relocations;
1241 for (MCSection &Sec : Asm) {
1242 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1244 uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1245 WriteZeros(Padding);
1247 // Remember the offset into the file for this section.
1248 uint64_t SecStart = OS.tell();
1250 const MCSymbol *SignatureSymbol = Section.getGroup();
1251 writeSectionData(Asm, Section, Layout);
1253 uint64_t SecEnd = OS.tell();
1254 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1256 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1258 if (SignatureSymbol) {
1259 Asm.getOrCreateSymbolData(*SignatureSymbol);
1260 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1262 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1263 GroupIdx = addToSectionTable(Group);
1264 Group->setAlignment(4);
1265 Groups.push_back(Group);
1267 GroupMembers[SignatureSymbol].push_back(&Section);
1269 GroupMembers[SignatureSymbol].push_back(RelSection);
1272 SectionIndexMap[&Section] = addToSectionTable(&Section);
1274 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1275 Relocations.push_back(RelSection);
1279 for (MCSectionELF *Group : Groups) {
1280 uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1281 WriteZeros(Padding);
1283 // Remember the offset into the file for this section.
1284 uint64_t SecStart = OS.tell();
1286 const MCSymbol *SignatureSymbol = Group->getGroup();
1287 assert(SignatureSymbol);
1288 write(uint32_t(ELF::GRP_COMDAT));
1289 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1290 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1294 uint64_t SecEnd = OS.tell();
1295 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1298 // Compute symbol table information.
1299 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1301 for (MCSectionELF *RelSection : Relocations) {
1302 uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1303 WriteZeros(Padding);
1305 // Remember the offset into the file for this section.
1306 uint64_t SecStart = OS.tell();
1308 writeRelocations(Asm, *RelSection->getAssociatedSection());
1310 uint64_t SecEnd = OS.tell();
1311 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1315 uint64_t SecStart = OS.tell();
1316 const MCSectionELF *Sec = createStringTable(Ctx);
1317 uint64_t SecEnd = OS.tell();
1318 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1321 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1322 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1323 WriteZeros(Padding);
1325 const unsigned SectionHeaderOffset = OS.tell();
1327 // ... then the section header table ...
1328 writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1330 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1331 ? (uint16_t)ELF::SHN_UNDEF
1332 : SectionTable.size() + 1;
1333 if (sys::IsLittleEndianHost != IsLittleEndian)
1334 sys::swapByteOrder(NumSections);
1335 unsigned NumSectionsOffset;
1338 uint64_t Val = SectionHeaderOffset;
1339 if (sys::IsLittleEndianHost != IsLittleEndian)
1340 sys::swapByteOrder(Val);
1341 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1342 offsetof(ELF::Elf64_Ehdr, e_shoff));
1343 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1345 uint32_t Val = SectionHeaderOffset;
1346 if (sys::IsLittleEndianHost != IsLittleEndian)
1347 sys::swapByteOrder(Val);
1348 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1349 offsetof(ELF::Elf32_Ehdr, e_shoff));
1350 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1352 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1356 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1357 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1358 bool InSet, bool IsPCRel) const {
1364 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1368 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1372 // It is invalid to replace a reference to a global in a comdat
1373 // with a reference to a local since out of comdat references
1374 // to a local are forbidden.
1375 // We could try to return false for more cases, like the reference
1376 // being in the same comdat or Sym being an alias to another global,
1377 // but it is not clear if it is worth the effort.
1378 if (MCELF::GetBinding(Sym) != ELF::STB_GLOBAL)
1381 if (!Sym.isInSection())
1384 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1385 return Sec.getGroup();
1388 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1389 raw_pwrite_stream &OS,
1390 bool IsLittleEndian) {
1391 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);