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/MCELFSymbolFlags.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCFixupKindInfo.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCSymbolELF.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 MCSymbolELF &Symbol,
76 bool Used, bool Renamed);
77 static bool isLocal(const MCSymbolELF &Symbol, bool IsSignature);
79 /// Helper struct for containing some precomputed information on symbols.
80 struct ELFSymbolData {
81 const MCSymbolELF *Symbol;
82 uint32_t SectionIndex;
85 // Support lexicographic sorting.
86 bool operator<(const ELFSymbolData &RHS) const {
87 unsigned LHSType = Symbol->getType();
88 unsigned RHSType = RHS.Symbol->getType();
89 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
91 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
93 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
94 return SectionIndex < RHS.SectionIndex;
95 return Name < RHS.Name;
99 /// The target specific ELF writer instance.
100 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
102 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
103 DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
105 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
109 /// @name Symbol Table Data
112 StringTableBuilder StrTabBuilder;
116 // This holds the symbol table index of the last local symbol.
117 unsigned LastLocalSymbolIndex;
118 // This holds the .strtab section index.
119 unsigned StringTableIndex;
120 // This holds the .symtab section index.
121 unsigned SymbolTableIndex;
122 // This holds the .symtab_shndx section index.
123 unsigned SymtabShndxSectionIndex = 0;
125 // Sections in the order they are to be output in the section table.
126 std::vector<const MCSectionELF *> SectionTable;
127 unsigned addToSectionTable(const MCSectionELF *Sec);
129 // TargetObjectWriter wrappers.
130 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
131 bool hasRelocationAddend() const {
132 return TargetObjectWriter->hasRelocationAddend();
134 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
135 bool IsPCRel) const {
136 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
140 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
142 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
144 void reset() override {
145 WeakrefUsedInReloc.clear();
148 StrTabBuilder.clear();
149 SectionTable.clear();
150 MCObjectWriter::reset();
153 ~ELFObjectWriter() override;
155 void WriteWord(uint64_t W) {
162 template <typename T> void write(T Val) {
164 support::endian::Writer<support::little>(OS).write(Val);
166 support::endian::Writer<support::big>(OS).write(Val);
169 void writeHeader(const MCAssembler &Asm);
171 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
172 ELFSymbolData &MSD, const MCAsmLayout &Layout);
174 // Start and end offset of each section
175 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
178 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
179 const MCSymbolRefExpr *RefA,
180 const MCSymbol *Sym, uint64_t C,
181 unsigned Type) const;
183 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
184 const MCFragment *Fragment, const MCFixup &Fixup,
185 MCValue Target, bool &IsPCRel,
186 uint64_t &FixedValue) override;
188 // Map from a signature symbol to the group section index
189 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
191 /// Compute the symbol table data
193 /// \param Asm - The assembler.
194 /// \param SectionIndexMap - Maps a section to its index.
195 /// \param RevGroupMap - Maps a signature symbol to the group section.
196 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
197 const SectionIndexMapTy &SectionIndexMap,
198 const RevGroupMapTy &RevGroupMap,
199 SectionOffsetsTy &SectionOffsets);
201 MCSectionELF *createRelocationSection(MCContext &Ctx,
202 const MCSectionELF &Sec);
204 const MCSectionELF *createStringTable(MCContext &Ctx);
206 void ExecutePostLayoutBinding(MCAssembler &Asm,
207 const MCAsmLayout &Layout) override;
209 void writeSectionHeader(const MCAssembler &Asm, const MCAsmLayout &Layout,
210 const SectionIndexMapTy &SectionIndexMap,
211 const SectionOffsetsTy &SectionOffsets);
213 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
214 const MCAsmLayout &Layout);
216 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
217 uint64_t Address, uint64_t Offset, uint64_t Size,
218 uint32_t Link, uint32_t Info, uint64_t Alignment,
221 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
223 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
224 const MCSymbol &SymA,
225 const MCFragment &FB,
227 bool IsPCRel) const override;
229 bool isWeak(const MCSymbol &Sym) const override;
231 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
232 void writeSection(const SectionIndexMapTy &SectionIndexMap,
233 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
234 const MCSectionELF &Section);
238 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
239 SectionTable.push_back(Sec);
240 StrTabBuilder.add(Sec->getSectionName());
241 return SectionTable.size();
244 void SymbolTableWriter::createSymtabShndx() {
245 if (!ShndxIndexes.empty())
248 ShndxIndexes.resize(NumWritten);
251 template <typename T> void SymbolTableWriter::write(T Value) {
252 EWriter.write(Value);
255 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
256 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
258 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
259 uint64_t size, uint8_t other,
260 uint32_t shndx, bool Reserved) {
261 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
266 if (!ShndxIndexes.empty()) {
268 ShndxIndexes.push_back(shndx);
270 ShndxIndexes.push_back(0);
273 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
276 write(name); // st_name
277 write(info); // st_info
278 write(other); // st_other
279 write(Index); // st_shndx
280 write(value); // st_value
281 write(size); // st_size
283 write(name); // st_name
284 write(uint32_t(value)); // st_value
285 write(uint32_t(size)); // st_size
286 write(info); // st_info
287 write(other); // st_other
288 write(Index); // st_shndx
294 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
295 const MCFixupKindInfo &FKI =
296 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
298 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
301 ELFObjectWriter::~ELFObjectWriter()
304 // Emit the ELF header.
305 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
311 // emitWord method behaves differently for ELF32 and ELF64, writing
312 // 4 bytes in the former and 8 in the latter.
314 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
316 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
319 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
321 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
323 Write8(TargetObjectWriter->getOSABI());
324 Write8(0); // e_ident[EI_ABIVERSION]
326 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
328 Write16(ELF::ET_REL); // e_type
330 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
332 Write32(ELF::EV_CURRENT); // e_version
333 WriteWord(0); // e_entry, no entry point in .o file
334 WriteWord(0); // e_phoff, no program header for .o
335 WriteWord(0); // e_shoff = sec hdr table off in bytes
337 // e_flags = whatever the target wants
338 Write32(Asm.getELFHeaderEFlags());
340 // e_ehsize = ELF header size
341 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
343 Write16(0); // e_phentsize = prog header entry size
344 Write16(0); // e_phnum = # prog header entries = 0
346 // e_shentsize = Section header entry size
347 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
349 // e_shnum = # of section header ents
352 // e_shstrndx = Section # of '.shstrtab'
353 assert(StringTableIndex < ELF::SHN_LORESERVE);
354 Write16(StringTableIndex);
357 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
358 const MCAsmLayout &Layout) {
359 if (Sym.isCommon() && Sym.isExternal())
360 return Sym.getCommonAlignment();
363 if (!Layout.getSymbolOffset(Sym, Res))
366 if (Layout.getAssembler().isThumbFunc(&Sym))
372 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
373 const MCAsmLayout &Layout) {
374 // The presence of symbol versions causes undefined symbols and
375 // versions declared with @@@ to be renamed.
377 for (const MCSymbol &A : Asm.symbols()) {
378 const auto &Alias = cast<MCSymbolELF>(A);
380 if (!Alias.isVariable())
382 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
385 const auto &Symbol = cast<MCSymbolELF>(Ref->getSymbol());
387 StringRef AliasName = Alias.getName();
388 size_t Pos = AliasName.find('@');
389 if (Pos == StringRef::npos)
392 // Aliases defined with .symvar copy the binding from the symbol they alias.
393 // This is the first place we are able to copy this information.
394 Alias.setExternal(Symbol.isExternal());
395 Alias.setBinding(Symbol.getBinding());
397 StringRef Rest = AliasName.substr(Pos);
398 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
401 // FIXME: produce a better error message.
402 if (Symbol.isUndefined() && Rest.startswith("@@") &&
403 !Rest.startswith("@@@"))
404 report_fatal_error("A @@ version cannot be undefined");
406 Renames.insert(std::make_pair(&Symbol, &Alias));
410 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
411 uint8_t Type = newType;
413 // Propagation rules:
414 // IFUNC > FUNC > OBJECT > NOTYPE
415 // TLS_OBJECT > OBJECT > NOTYPE
417 // dont let the new type degrade the old type
421 case ELF::STT_GNU_IFUNC:
422 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
423 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
424 Type = ELF::STT_GNU_IFUNC;
427 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
428 Type == ELF::STT_TLS)
429 Type = ELF::STT_FUNC;
431 case ELF::STT_OBJECT:
432 if (Type == ELF::STT_NOTYPE)
433 Type = ELF::STT_OBJECT;
436 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
437 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
445 void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
446 uint32_t StringIndex, ELFSymbolData &MSD,
447 const MCAsmLayout &Layout) {
448 const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
449 assert((!Symbol.getFragment() ||
450 (Symbol.getFragment()->getParent() == &Symbol.getSection())) &&
451 "The symbol's section doesn't match the fragment's symbol");
452 const MCSymbolELF *Base =
453 cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
455 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
457 bool IsReserved = !Base || Symbol.isCommon();
459 // Binding and Type share the same byte as upper and lower nibbles
460 uint8_t Binding = Symbol.getBinding();
461 uint8_t Type = Symbol.getType();
463 Type = mergeTypeForSet(Type, Base->getType());
465 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
467 // Other and Visibility share the same byte with Visibility using the lower
469 uint8_t Visibility = Symbol.getVisibility();
470 uint8_t Other = Symbol.getOther() << (ELF_STO_Shift - ELF_STV_Shift);
473 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
476 const MCExpr *ESize = MSD.Symbol->getSize();
478 ESize = Base->getSize();
482 if (!ESize->evaluateKnownAbsolute(Res, Layout))
483 report_fatal_error("Size expression must be absolute.");
487 // Write out the symbol table entry
488 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
492 // It is always valid to create a relocation with a symbol. It is preferable
493 // to use a relocation with a section if that is possible. Using the section
494 // allows us to omit some local symbols from the symbol table.
495 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
496 const MCSymbolRefExpr *RefA,
497 const MCSymbol *S, uint64_t C,
498 unsigned Type) const {
499 const auto *Sym = cast_or_null<MCSymbolELF>(S);
500 // A PCRel relocation to an absolute value has no symbol (or section). We
501 // represent that with a relocation to a null section.
505 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
509 // The .odp creation emits a relocation against the symbol ".TOC." which
510 // create a R_PPC64_TOC relocation. However the relocation symbol name
511 // in final object creation should be NULL, since the symbol does not
512 // really exist, it is just the reference to TOC base for the current
513 // object file. Since the symbol is undefined, returning false results
514 // in a relocation with a null section which is the desired result.
515 case MCSymbolRefExpr::VK_PPC_TOCBASE:
518 // These VariantKind cause the relocation to refer to something other than
519 // the symbol itself, like a linker generated table. Since the address of
520 // symbol is not relevant, we cannot replace the symbol with the
521 // section and patch the difference in the addend.
522 case MCSymbolRefExpr::VK_GOT:
523 case MCSymbolRefExpr::VK_PLT:
524 case MCSymbolRefExpr::VK_GOTPCREL:
525 case MCSymbolRefExpr::VK_Mips_GOT:
526 case MCSymbolRefExpr::VK_PPC_GOT_LO:
527 case MCSymbolRefExpr::VK_PPC_GOT_HI:
528 case MCSymbolRefExpr::VK_PPC_GOT_HA:
532 // An undefined symbol is not in any section, so the relocation has to point
533 // to the symbol itself.
534 assert(Sym && "Expected a symbol");
535 if (Sym->isUndefined())
538 unsigned Binding = Sym->getBinding();
541 llvm_unreachable("Invalid Binding");
545 // If the symbol is weak, it might be overridden by a symbol in another
546 // file. The relocation has to point to the symbol so that the linker
549 case ELF::STB_GLOBAL:
550 // Global ELF symbols can be preempted by the dynamic linker. The relocation
551 // has to point to the symbol for a reason analogous to the STB_WEAK case.
555 // If a relocation points to a mergeable section, we have to be careful.
556 // If the offset is zero, a relocation with the section will encode the
557 // same information. With a non-zero offset, the situation is different.
558 // For example, a relocation can point 42 bytes past the end of a string.
559 // If we change such a relocation to use the section, the linker would think
560 // that it pointed to another string and subtracting 42 at runtime will
561 // produce the wrong value.
562 auto &Sec = cast<MCSectionELF>(Sym->getSection());
563 unsigned Flags = Sec.getFlags();
564 if (Flags & ELF::SHF_MERGE) {
568 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
569 // only handle section relocations to mergeable sections if using RELA.
570 if (!hasRelocationAddend())
574 // Most TLS relocations use a got, so they need the symbol. Even those that
575 // are just an offset (@tpoff), require a symbol in gold versions before
576 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
577 // http://sourceware.org/PR16773.
578 if (Flags & ELF::SHF_TLS)
581 // If the symbol is a thumb function the final relocation must set the lowest
582 // bit. With a symbol that is done by just having the symbol have that bit
583 // set, so we would lose the bit if we relocated with the section.
584 // FIXME: We could use the section but add the bit to the relocation value.
585 if (Asm.isThumbFunc(Sym))
588 if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
593 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
594 const MCSymbol &Sym = Ref.getSymbol();
596 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
599 if (!Sym.isVariable())
602 const MCExpr *Expr = Sym.getVariableValue();
603 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
607 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
608 return &Inner->getSymbol();
612 // True if the assembler knows nothing about the final value of the symbol.
613 // This doesn't cover the comdat issues, since in those cases the assembler
614 // can at least know that all symbols in the section will move together.
615 static bool isWeak(const MCSymbolELF &Sym) {
616 if (Sym.getType() == ELF::STT_GNU_IFUNC)
619 switch (Sym.getBinding()) {
621 llvm_unreachable("Unknown binding");
624 case ELF::STB_GLOBAL:
627 case ELF::STB_GNU_UNIQUE:
632 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
633 const MCAsmLayout &Layout,
634 const MCFragment *Fragment,
635 const MCFixup &Fixup, MCValue Target,
636 bool &IsPCRel, uint64_t &FixedValue) {
637 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
638 uint64_t C = Target.getConstant();
639 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
641 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
642 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
643 "Should not have constructed this");
645 // Let A, B and C being the components of Target and R be the location of
646 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
647 // If it is pcrel, we want to compute (A - B + C - R).
649 // In general, ELF has no relocations for -B. It can only represent (A + C)
650 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
651 // replace B to implement it: (A - R - K + C)
653 Asm.getContext().reportFatalError(
655 "No relocation available to represent this relative expression");
657 const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
659 if (SymB.isUndefined())
660 Asm.getContext().reportFatalError(
662 Twine("symbol '") + SymB.getName() +
663 "' can not be undefined in a subtraction expression");
665 assert(!SymB.isAbsolute() && "Should have been folded");
666 const MCSection &SecB = SymB.getSection();
667 if (&SecB != &FixupSection)
668 Asm.getContext().reportFatalError(
669 Fixup.getLoc(), "Cannot represent a difference across sections");
672 Asm.getContext().reportFatalError(
673 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
675 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
676 uint64_t K = SymBOffset - FixupOffset;
681 // We either rejected the fixup or folded B into C at this point.
682 const MCSymbolRefExpr *RefA = Target.getSymA();
683 const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
685 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
686 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
687 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
688 C += Layout.getSymbolOffset(*SymA);
691 if (hasRelocationAddend()) {
698 if (!RelocateWithSymbol) {
699 const MCSection *SecA =
700 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
701 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
702 const auto *SectionSymbol =
703 ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr;
704 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
705 Relocations[&FixupSection].push_back(Rec);
710 if (const MCSymbolELF *R = Renames.lookup(SymA))
713 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
714 WeakrefUsedInReloc.insert(WeakRef);
716 SymA->setUsedInReloc();
718 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
719 Relocations[&FixupSection].push_back(Rec);
723 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
724 const MCSymbolELF &Symbol, bool Used,
726 if (Symbol.isVariable()) {
727 const MCExpr *Expr = Symbol.getVariableValue();
728 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
729 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
740 if (Symbol.isVariable() && Symbol.isUndefined()) {
741 // FIXME: this is here just to diagnose the case of a var = commmon_sym.
742 Layout.getBaseSymbol(Symbol);
746 if (Symbol.isUndefined() && !Symbol.isBindingSet())
749 if (Symbol.getType() == ELF::STT_SECTION)
752 if (Symbol.isTemporary())
758 bool ELFObjectWriter::isLocal(const MCSymbolELF &Symbol, bool IsSignature) {
759 if (Symbol.isExternal())
762 if (Symbol.isDefined())
765 if (Symbol.isUsedInReloc())
771 void ELFObjectWriter::computeSymbolTable(
772 MCAssembler &Asm, const MCAsmLayout &Layout,
773 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
774 SectionOffsetsTy &SectionOffsets) {
775 MCContext &Ctx = Asm.getContext();
776 SymbolTableWriter Writer(*this, is64Bit());
779 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
780 MCSectionELF *SymtabSection =
781 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
782 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
783 SymbolTableIndex = addToSectionTable(SymtabSection);
786 OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
789 uint64_t SecStart = OS.tell();
791 // The first entry is the undefined symbol entry.
792 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
794 std::vector<ELFSymbolData> LocalSymbolData;
795 std::vector<ELFSymbolData> ExternalSymbolData;
797 // Add the data for the symbols.
798 bool HasLargeSectionIndex = false;
799 for (const MCSymbol &S : Asm.symbols()) {
800 const auto &Symbol = cast<MCSymbolELF>(S);
801 bool Used = Symbol.isUsedInReloc();
802 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
803 bool isSignature = RevGroupMap.count(&Symbol);
805 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
806 Renames.count(&Symbol)))
810 MSD.Symbol = cast<MCSymbolELF>(&Symbol);
812 // Undefined symbols are global, but this is the first place we
813 // are able to set it.
814 bool Local = isLocal(Symbol, isSignature);
815 if (!Local && Symbol.getBinding() == ELF::STB_LOCAL)
816 Symbol.setBinding(ELF::STB_GLOBAL);
818 if (Symbol.isAbsolute()) {
819 MSD.SectionIndex = ELF::SHN_ABS;
820 } else if (Symbol.isCommon()) {
822 MSD.SectionIndex = ELF::SHN_COMMON;
823 } else if (Symbol.isUndefined()) {
824 if (isSignature && !Used) {
825 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
826 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
827 HasLargeSectionIndex = true;
829 MSD.SectionIndex = ELF::SHN_UNDEF;
831 if (!Used && WeakrefUsed)
832 Symbol.setBinding(ELF::STB_WEAK);
834 const MCSectionELF &Section =
835 static_cast<const MCSectionELF &>(Symbol.getSection());
836 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
837 assert(MSD.SectionIndex && "Invalid section index!");
838 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
839 HasLargeSectionIndex = true;
842 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
845 // FIXME: All name handling should be done before we get to the writer,
846 // including dealing with GNU-style version suffixes. Fixing this isn't
849 // We thus have to be careful to not perform the symbol version replacement
852 // The ELF format is used on Windows by the MCJIT engine. Thus, on
853 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
854 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
855 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
856 // the EFLObjectWriter should not interpret the "@@@" sub-string as
857 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
858 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
859 // "__imp_?" or "__imp_@?".
861 // It would have been interesting to perform the MS mangling prefix check
862 // only when the target triple is of the form *-pc-windows-elf. But, it
863 // seems that this information is not easily accessible from the
865 StringRef Name = Symbol.getName();
866 if (!Name.startswith("?") && !Name.startswith("@?") &&
867 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
868 // This symbol isn't following the MSVC C++ name mangling convention. We
869 // can thus safely interpret the @@@ in symbol names as specifying symbol
872 size_t Pos = Name.find("@@@");
873 if (Pos != StringRef::npos) {
874 Buf += Name.substr(0, Pos);
875 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
876 Buf += Name.substr(Pos + Skip);
881 // Sections have their own string table
882 if (Symbol.getType() != ELF::STT_SECTION)
883 MSD.Name = StrTabBuilder.add(Name);
886 LocalSymbolData.push_back(MSD);
888 ExternalSymbolData.push_back(MSD);
891 if (HasLargeSectionIndex) {
892 MCSectionELF *SymtabShndxSection =
893 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
894 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
895 SymtabShndxSection->setAlignment(4);
898 ArrayRef<std::string> FileNames = Asm.getFileNames();
899 for (const std::string &Name : FileNames)
900 StrTabBuilder.add(Name);
902 StrTabBuilder.finalize(StringTableBuilder::ELF);
904 for (const std::string &Name : FileNames)
905 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
906 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
909 // Symbols are required to be in lexicographic order.
910 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
911 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
913 // Set the symbol indices. Local symbols must come before all other
914 // symbols with non-local bindings.
915 unsigned Index = FileNames.size() + 1;
917 for (ELFSymbolData &MSD : LocalSymbolData) {
918 unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
920 : StrTabBuilder.getOffset(MSD.Name);
921 MSD.Symbol->setIndex(Index++);
922 writeSymbol(Writer, StringIndex, MSD, Layout);
925 // Write the symbol table entries.
926 LastLocalSymbolIndex = Index;
928 for (ELFSymbolData &MSD : ExternalSymbolData) {
929 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
930 MSD.Symbol->setIndex(Index++);
931 writeSymbol(Writer, StringIndex, MSD, Layout);
932 assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
935 uint64_t SecEnd = OS.tell();
936 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
938 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
939 if (ShndxIndexes.empty()) {
940 assert(SymtabShndxSectionIndex == 0);
943 assert(SymtabShndxSectionIndex != 0);
945 SecStart = OS.tell();
946 const MCSectionELF *SymtabShndxSection =
947 SectionTable[SymtabShndxSectionIndex - 1];
948 for (uint32_t Index : ShndxIndexes)
951 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
955 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
956 const MCSectionELF &Sec) {
957 if (Relocations[&Sec].empty())
960 const StringRef SectionName = Sec.getSectionName();
961 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
962 RelaSectionName += SectionName;
965 if (hasRelocationAddend())
966 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
968 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
971 if (Sec.getFlags() & ELF::SHF_GROUP)
972 Flags = ELF::SHF_GROUP;
974 MCSectionELF *RelaSection = Ctx.createELFRelSection(
975 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
976 Flags, EntrySize, Sec.getGroup(), &Sec);
977 RelaSection->setAlignment(is64Bit() ? 8 : 4);
981 static SmallVector<char, 128>
982 getUncompressedData(const MCAsmLayout &Layout,
983 const MCSection::FragmentListType &Fragments) {
984 SmallVector<char, 128> UncompressedData;
985 for (const MCFragment &F : Fragments) {
986 const SmallVectorImpl<char> *Contents;
987 switch (F.getKind()) {
988 case MCFragment::FT_Data:
989 Contents = &cast<MCDataFragment>(F).getContents();
991 case MCFragment::FT_Dwarf:
992 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
994 case MCFragment::FT_DwarfFrame:
995 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
999 "Not expecting any other fragment types in a debug_* section");
1001 UncompressedData.append(Contents->begin(), Contents->end());
1003 return UncompressedData;
1006 // Include the debug info compression header:
1007 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1008 // useful for consumers to preallocate a buffer to decompress into.
1010 prependCompressionHeader(uint64_t Size,
1011 SmallVectorImpl<char> &CompressedContents) {
1012 const StringRef Magic = "ZLIB";
1013 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1015 if (sys::IsLittleEndianHost)
1016 sys::swapByteOrder(Size);
1017 CompressedContents.insert(CompressedContents.begin(),
1018 Magic.size() + sizeof(Size), 0);
1019 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1020 std::copy(reinterpret_cast<char *>(&Size),
1021 reinterpret_cast<char *>(&Size + 1),
1022 CompressedContents.begin() + Magic.size());
1026 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1027 const MCAsmLayout &Layout) {
1028 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1029 StringRef SectionName = Section.getSectionName();
1031 // Compressing debug_frame requires handling alignment fragments which is
1032 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1033 // for writing to arbitrary buffers) for little benefit.
1034 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1035 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1036 Asm.writeSectionData(&Section, Layout);
1040 // Gather the uncompressed data from all the fragments.
1041 const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1042 SmallVector<char, 128> UncompressedData =
1043 getUncompressedData(Layout, Fragments);
1045 SmallVector<char, 128> CompressedContents;
1046 zlib::Status Success = zlib::compress(
1047 StringRef(UncompressedData.data(), UncompressedData.size()),
1048 CompressedContents);
1049 if (Success != zlib::StatusOK) {
1050 Asm.writeSectionData(&Section, Layout);
1054 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1055 Asm.writeSectionData(&Section, Layout);
1058 Asm.getContext().renameELFSection(&Section,
1059 (".z" + SectionName.drop_front(1)).str());
1060 OS << CompressedContents;
1063 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1064 uint64_t Flags, uint64_t Address,
1065 uint64_t Offset, uint64_t Size,
1066 uint32_t Link, uint32_t Info,
1068 uint64_t EntrySize) {
1069 Write32(Name); // sh_name: index into string table
1070 Write32(Type); // sh_type
1071 WriteWord(Flags); // sh_flags
1072 WriteWord(Address); // sh_addr
1073 WriteWord(Offset); // sh_offset
1074 WriteWord(Size); // sh_size
1075 Write32(Link); // sh_link
1076 Write32(Info); // sh_info
1077 WriteWord(Alignment); // sh_addralign
1078 WriteWord(EntrySize); // sh_entsize
1081 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1082 const MCSectionELF &Sec) {
1083 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1085 // Sort the relocation entries. Most targets just sort by Offset, but some
1086 // (e.g., MIPS) have additional constraints.
1087 TargetObjectWriter->sortRelocs(Asm, Relocs);
1089 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1090 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1091 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1094 write(Entry.Offset);
1095 if (TargetObjectWriter->isN64()) {
1096 write(uint32_t(Index));
1098 write(TargetObjectWriter->getRSsym(Entry.Type));
1099 write(TargetObjectWriter->getRType3(Entry.Type));
1100 write(TargetObjectWriter->getRType2(Entry.Type));
1101 write(TargetObjectWriter->getRType(Entry.Type));
1103 struct ELF::Elf64_Rela ERE64;
1104 ERE64.setSymbolAndType(Index, Entry.Type);
1105 write(ERE64.r_info);
1107 if (hasRelocationAddend())
1108 write(Entry.Addend);
1110 write(uint32_t(Entry.Offset));
1112 struct ELF::Elf32_Rela ERE32;
1113 ERE32.setSymbolAndType(Index, Entry.Type);
1114 write(ERE32.r_info);
1116 if (hasRelocationAddend())
1117 write(uint32_t(Entry.Addend));
1122 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1123 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1124 OS << StrTabBuilder.data();
1125 return StrtabSection;
1128 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1129 uint32_t GroupSymbolIndex, uint64_t Offset,
1130 uint64_t Size, const MCSectionELF &Section) {
1131 uint64_t sh_link = 0;
1132 uint64_t sh_info = 0;
1134 switch(Section.getType()) {
1139 case ELF::SHT_DYNAMIC:
1140 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1143 case ELF::SHT_RELA: {
1144 sh_link = SymbolTableIndex;
1145 assert(sh_link && ".symtab not found");
1146 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1147 sh_info = SectionIndexMap.lookup(InfoSection);
1151 case ELF::SHT_SYMTAB:
1152 case ELF::SHT_DYNSYM:
1153 sh_link = StringTableIndex;
1154 sh_info = LastLocalSymbolIndex;
1157 case ELF::SHT_SYMTAB_SHNDX:
1158 sh_link = SymbolTableIndex;
1161 case ELF::SHT_GROUP:
1162 sh_link = SymbolTableIndex;
1163 sh_info = GroupSymbolIndex;
1167 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1168 Section.getType() == ELF::SHT_ARM_EXIDX)
1169 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1171 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1172 Section.getType(), Section.getFlags(), 0, Offset, Size,
1173 sh_link, sh_info, Section.getAlignment(),
1174 Section.getEntrySize());
1177 void ELFObjectWriter::writeSectionHeader(
1178 const MCAssembler &Asm, const MCAsmLayout &Layout,
1179 const SectionIndexMapTy &SectionIndexMap,
1180 const SectionOffsetsTy &SectionOffsets) {
1181 const unsigned NumSections = SectionTable.size();
1183 // Null section first.
1184 uint64_t FirstSectionSize =
1185 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1186 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1188 for (const MCSectionELF *Section : SectionTable) {
1189 uint32_t GroupSymbolIndex;
1190 unsigned Type = Section->getType();
1191 if (Type != ELF::SHT_GROUP)
1192 GroupSymbolIndex = 0;
1194 GroupSymbolIndex = Section->getGroup()->getIndex();
1196 const std::pair<uint64_t, uint64_t> &Offsets =
1197 SectionOffsets.find(Section)->second;
1199 if (Type == ELF::SHT_NOBITS)
1200 Size = Layout.getSectionAddressSize(Section);
1202 Size = Offsets.second - Offsets.first;
1204 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1209 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1210 const MCAsmLayout &Layout) {
1211 MCContext &Ctx = Asm.getContext();
1212 MCSectionELF *StrtabSection =
1213 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1214 StringTableIndex = addToSectionTable(StrtabSection);
1216 RevGroupMapTy RevGroupMap;
1217 SectionIndexMapTy SectionIndexMap;
1219 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1221 // Write out the ELF header ...
1224 // ... then the sections ...
1225 SectionOffsetsTy SectionOffsets;
1226 std::vector<MCSectionELF *> Groups;
1227 std::vector<MCSectionELF *> Relocations;
1228 for (MCSection &Sec : Asm) {
1229 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1231 uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1232 WriteZeros(Padding);
1234 // Remember the offset into the file for this section.
1235 uint64_t SecStart = OS.tell();
1237 const MCSymbolELF *SignatureSymbol = Section.getGroup();
1238 writeSectionData(Asm, Section, Layout);
1240 uint64_t SecEnd = OS.tell();
1241 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1243 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1245 if (SignatureSymbol) {
1246 Asm.registerSymbol(*SignatureSymbol);
1247 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1249 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1250 GroupIdx = addToSectionTable(Group);
1251 Group->setAlignment(4);
1252 Groups.push_back(Group);
1254 GroupMembers[SignatureSymbol].push_back(&Section);
1256 GroupMembers[SignatureSymbol].push_back(RelSection);
1259 SectionIndexMap[&Section] = addToSectionTable(&Section);
1261 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1262 Relocations.push_back(RelSection);
1266 for (MCSectionELF *Group : Groups) {
1267 uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1268 WriteZeros(Padding);
1270 // Remember the offset into the file for this section.
1271 uint64_t SecStart = OS.tell();
1273 const MCSymbol *SignatureSymbol = Group->getGroup();
1274 assert(SignatureSymbol);
1275 write(uint32_t(ELF::GRP_COMDAT));
1276 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1277 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1281 uint64_t SecEnd = OS.tell();
1282 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1285 // Compute symbol table information.
1286 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1288 for (MCSectionELF *RelSection : Relocations) {
1289 uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1290 WriteZeros(Padding);
1292 // Remember the offset into the file for this section.
1293 uint64_t SecStart = OS.tell();
1295 writeRelocations(Asm, *RelSection->getAssociatedSection());
1297 uint64_t SecEnd = OS.tell();
1298 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1302 uint64_t SecStart = OS.tell();
1303 const MCSectionELF *Sec = createStringTable(Ctx);
1304 uint64_t SecEnd = OS.tell();
1305 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1308 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1309 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1310 WriteZeros(Padding);
1312 const unsigned SectionHeaderOffset = OS.tell();
1314 // ... then the section header table ...
1315 writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1317 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1318 ? (uint16_t)ELF::SHN_UNDEF
1319 : SectionTable.size() + 1;
1320 if (sys::IsLittleEndianHost != IsLittleEndian)
1321 sys::swapByteOrder(NumSections);
1322 unsigned NumSectionsOffset;
1325 uint64_t Val = SectionHeaderOffset;
1326 if (sys::IsLittleEndianHost != IsLittleEndian)
1327 sys::swapByteOrder(Val);
1328 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1329 offsetof(ELF::Elf64_Ehdr, e_shoff));
1330 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1332 uint32_t Val = SectionHeaderOffset;
1333 if (sys::IsLittleEndianHost != IsLittleEndian)
1334 sys::swapByteOrder(Val);
1335 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1336 offsetof(ELF::Elf32_Ehdr, e_shoff));
1337 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1339 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1343 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1344 const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1345 bool InSet, bool IsPCRel) const {
1346 const auto &SymA = cast<MCSymbolELF>(SA);
1352 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1356 bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
1357 const auto &Sym = cast<MCSymbolELF>(S);
1361 // It is invalid to replace a reference to a global in a comdat
1362 // with a reference to a local since out of comdat references
1363 // to a local are forbidden.
1364 // We could try to return false for more cases, like the reference
1365 // being in the same comdat or Sym being an alias to another global,
1366 // but it is not clear if it is worth the effort.
1367 if (Sym.getBinding() != ELF::STB_GLOBAL)
1370 if (!Sym.isInSection())
1373 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1374 return Sec.getGroup();
1377 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1378 raw_pwrite_stream &OS,
1379 bool IsLittleEndian) {
1380 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);