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);
79 /// Helper struct for containing some precomputed information on symbols.
80 struct ELFSymbolData {
81 const MCSymbol *Symbol;
82 uint32_t SectionIndex;
85 // Support lexicographic sorting.
86 bool operator<(const ELFSymbolData &RHS) const {
87 unsigned LHSType = MCELF::GetType(Symbol->getData());
88 unsigned RHSType = MCELF::GetType(RHS.Symbol->getData());
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> UsedInReloc;
103 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
104 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
106 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
110 /// @name Symbol Table Data
113 StringTableBuilder StrTabBuilder;
117 // This holds the symbol table index of the last local symbol.
118 unsigned LastLocalSymbolIndex;
119 // This holds the .strtab section index.
120 unsigned StringTableIndex;
121 // This holds the .symtab section index.
122 unsigned SymbolTableIndex;
123 // This holds the .symtab_shndx section index.
124 unsigned SymtabShndxSectionIndex = 0;
126 // Sections in the order they are to be output in the section table.
127 std::vector<const MCSectionELF *> SectionTable;
128 unsigned addToSectionTable(const MCSectionELF *Sec);
130 // TargetObjectWriter wrappers.
131 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
132 bool hasRelocationAddend() const {
133 return TargetObjectWriter->hasRelocationAddend();
135 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
136 bool IsPCRel) const {
137 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
141 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
143 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
145 void reset() override {
147 WeakrefUsedInReloc.clear();
150 StrTabBuilder.clear();
151 SectionTable.clear();
152 MCObjectWriter::reset();
155 ~ELFObjectWriter() override;
157 void WriteWord(uint64_t W) {
164 template <typename T> void write(T Val) {
166 support::endian::Writer<support::little>(OS).write(Val);
168 support::endian::Writer<support::big>(OS).write(Val);
171 void writeHeader(const MCAssembler &Asm);
173 void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
174 ELFSymbolData &MSD, const MCAsmLayout &Layout);
176 // Start and end offset of each section
177 typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
180 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
181 const MCSymbolRefExpr *RefA,
182 const MCSymbol *Sym, uint64_t C,
183 unsigned Type) const;
185 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
186 const MCFragment *Fragment, const MCFixup &Fixup,
187 MCValue Target, bool &IsPCRel,
188 uint64_t &FixedValue) override;
190 // Map from a signature symbol to the group section index
191 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
193 /// Compute the symbol table data
195 /// \param Asm - The assembler.
196 /// \param SectionIndexMap - Maps a section to its index.
197 /// \param RevGroupMap - Maps a signature symbol to the group section.
198 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
199 const SectionIndexMapTy &SectionIndexMap,
200 const RevGroupMapTy &RevGroupMap,
201 SectionOffsetsTy &SectionOffsets);
203 MCSectionELF *createRelocationSection(MCContext &Ctx,
204 const MCSectionELF &Sec);
206 const MCSectionELF *createStringTable(MCContext &Ctx);
208 void ExecutePostLayoutBinding(MCAssembler &Asm,
209 const MCAsmLayout &Layout) override;
211 void writeSectionHeader(const MCAssembler &Asm, const MCAsmLayout &Layout,
212 const SectionIndexMapTy &SectionIndexMap,
213 const SectionOffsetsTy &SectionOffsets);
215 void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
216 const MCAsmLayout &Layout);
218 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
219 uint64_t Address, uint64_t Offset, uint64_t Size,
220 uint32_t Link, uint32_t Info, uint64_t Alignment,
223 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
225 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
226 const MCSymbol &SymA,
227 const MCFragment &FB,
229 bool IsPCRel) const override;
231 bool isWeak(const MCSymbol &Sym) const override;
233 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
234 void writeSection(const SectionIndexMapTy &SectionIndexMap,
235 uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
236 const MCSectionELF &Section);
240 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
241 SectionTable.push_back(Sec);
242 StrTabBuilder.add(Sec->getSectionName());
243 return SectionTable.size();
246 void SymbolTableWriter::createSymtabShndx() {
247 if (!ShndxIndexes.empty())
250 ShndxIndexes.resize(NumWritten);
253 template <typename T> void SymbolTableWriter::write(T Value) {
254 EWriter.write(Value);
257 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
258 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
260 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
261 uint64_t size, uint8_t other,
262 uint32_t shndx, bool Reserved) {
263 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
268 if (!ShndxIndexes.empty()) {
270 ShndxIndexes.push_back(shndx);
272 ShndxIndexes.push_back(0);
275 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
278 write(name); // st_name
279 write(info); // st_info
280 write(other); // st_other
281 write(Index); // st_shndx
282 write(value); // st_value
283 write(size); // st_size
285 write(name); // st_name
286 write(uint32_t(value)); // st_value
287 write(uint32_t(size)); // st_size
288 write(info); // st_info
289 write(other); // st_other
290 write(Index); // st_shndx
296 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
297 const MCFixupKindInfo &FKI =
298 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
300 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
303 ELFObjectWriter::~ELFObjectWriter()
306 // Emit the ELF header.
307 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
313 // emitWord method behaves differently for ELF32 and ELF64, writing
314 // 4 bytes in the former and 8 in the latter.
316 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
318 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
321 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
323 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
325 Write8(TargetObjectWriter->getOSABI());
326 Write8(0); // e_ident[EI_ABIVERSION]
328 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
330 Write16(ELF::ET_REL); // e_type
332 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
334 Write32(ELF::EV_CURRENT); // e_version
335 WriteWord(0); // e_entry, no entry point in .o file
336 WriteWord(0); // e_phoff, no program header for .o
337 WriteWord(0); // e_shoff = sec hdr table off in bytes
339 // e_flags = whatever the target wants
340 Write32(Asm.getELFHeaderEFlags());
342 // e_ehsize = ELF header size
343 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
345 Write16(0); // e_phentsize = prog header entry size
346 Write16(0); // e_phnum = # prog header entries = 0
348 // e_shentsize = Section header entry size
349 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
351 // e_shnum = # of section header ents
354 // e_shstrndx = Section # of '.shstrtab'
355 assert(StringTableIndex < ELF::SHN_LORESERVE);
356 Write16(StringTableIndex);
359 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
360 const MCAsmLayout &Layout) {
361 MCSymbolData &Data = Sym.getData();
362 if (Data.isCommon() && Data.isExternal())
363 return Data.getCommonAlignment();
366 if (!Layout.getSymbolOffset(Sym, Res))
369 if (Layout.getAssembler().isThumbFunc(&Sym))
375 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
376 const MCAsmLayout &Layout) {
377 // The presence of symbol versions causes undefined symbols and
378 // versions declared with @@@ to be renamed.
380 for (const MCSymbol &Alias : Asm.symbols()) {
381 MCSymbolData &OriginalData = Alias.getData();
384 if (!Alias.isVariable())
386 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
389 const MCSymbol &Symbol = Ref->getSymbol();
390 MCSymbolData &SD = Symbol.getData();
392 StringRef AliasName = Alias.getName();
393 size_t Pos = AliasName.find('@');
394 if (Pos == StringRef::npos)
397 // Aliases defined with .symvar copy the binding from the symbol they alias.
398 // This is the first place we are able to copy this information.
399 OriginalData.setExternal(SD.isExternal());
400 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
402 StringRef Rest = AliasName.substr(Pos);
403 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
406 // FIXME: produce a better error message.
407 if (Symbol.isUndefined() && Rest.startswith("@@") &&
408 !Rest.startswith("@@@"))
409 report_fatal_error("A @@ version cannot be undefined");
411 Renames.insert(std::make_pair(&Symbol, &Alias));
415 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
416 uint8_t Type = newType;
418 // Propagation rules:
419 // IFUNC > FUNC > OBJECT > NOTYPE
420 // TLS_OBJECT > OBJECT > NOTYPE
422 // dont let the new type degrade the old type
426 case ELF::STT_GNU_IFUNC:
427 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
428 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
429 Type = ELF::STT_GNU_IFUNC;
432 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
433 Type == ELF::STT_TLS)
434 Type = ELF::STT_FUNC;
436 case ELF::STT_OBJECT:
437 if (Type == ELF::STT_NOTYPE)
438 Type = ELF::STT_OBJECT;
441 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
442 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
450 void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
451 uint32_t StringIndex, ELFSymbolData &MSD,
452 const MCAsmLayout &Layout) {
453 MCSymbolData &OrigData = MSD.Symbol->getData();
454 assert((!OrigData.getFragment() ||
455 (OrigData.getFragment()->getParent() == &MSD.Symbol->getSection())) &&
456 "The symbol's section doesn't match the fragment's symbol");
457 const MCSymbol *Base = Layout.getBaseSymbol(*MSD.Symbol);
459 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
461 bool IsReserved = !Base || OrigData.isCommon();
463 // Binding and Type share the same byte as upper and lower nibbles
464 uint8_t Binding = MCELF::GetBinding(OrigData);
465 uint8_t Type = MCELF::GetType(OrigData);
466 MCSymbolData *BaseSD = nullptr;
468 BaseSD = &Base->getData();
469 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
471 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
473 // Other and Visibility share the same byte with Visibility using the lower
475 uint8_t Visibility = MCELF::GetVisibility(OrigData);
476 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
479 uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
482 const MCExpr *ESize = OrigData.getSize();
484 ESize = BaseSD->getSize();
488 if (!ESize->evaluateKnownAbsolute(Res, Layout))
489 report_fatal_error("Size expression must be absolute.");
493 // Write out the symbol table entry
494 Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
498 // It is always valid to create a relocation with a symbol. It is preferable
499 // to use a relocation with a section if that is possible. Using the section
500 // allows us to omit some local symbols from the symbol table.
501 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
502 const MCSymbolRefExpr *RefA,
503 const MCSymbol *Sym, uint64_t C,
504 unsigned Type) const {
505 MCSymbolData *SD = Sym ? &Sym->getData() : nullptr;
507 // A PCRel relocation to an absolute value has no symbol (or section). We
508 // represent that with a relocation to a null section.
512 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
516 // The .odp creation emits a relocation against the symbol ".TOC." which
517 // create a R_PPC64_TOC relocation. However the relocation symbol name
518 // in final object creation should be NULL, since the symbol does not
519 // really exist, it is just the reference to TOC base for the current
520 // object file. Since the symbol is undefined, returning false results
521 // in a relocation with a null section which is the desired result.
522 case MCSymbolRefExpr::VK_PPC_TOCBASE:
525 // These VariantKind cause the relocation to refer to something other than
526 // the symbol itself, like a linker generated table. Since the address of
527 // symbol is not relevant, we cannot replace the symbol with the
528 // section and patch the difference in the addend.
529 case MCSymbolRefExpr::VK_GOT:
530 case MCSymbolRefExpr::VK_PLT:
531 case MCSymbolRefExpr::VK_GOTPCREL:
532 case MCSymbolRefExpr::VK_Mips_GOT:
533 case MCSymbolRefExpr::VK_PPC_GOT_LO:
534 case MCSymbolRefExpr::VK_PPC_GOT_HI:
535 case MCSymbolRefExpr::VK_PPC_GOT_HA:
539 // An undefined symbol is not in any section, so the relocation has to point
540 // to the symbol itself.
541 assert(Sym && "Expected a symbol");
542 if (Sym->isUndefined())
545 unsigned Binding = MCELF::GetBinding(*SD);
548 llvm_unreachable("Invalid Binding");
552 // If the symbol is weak, it might be overridden by a symbol in another
553 // file. The relocation has to point to the symbol so that the linker
556 case ELF::STB_GLOBAL:
557 // Global ELF symbols can be preempted by the dynamic linker. The relocation
558 // has to point to the symbol for a reason analogous to the STB_WEAK case.
562 // If a relocation points to a mergeable section, we have to be careful.
563 // If the offset is zero, a relocation with the section will encode the
564 // same information. With a non-zero offset, the situation is different.
565 // For example, a relocation can point 42 bytes past the end of a string.
566 // If we change such a relocation to use the section, the linker would think
567 // that it pointed to another string and subtracting 42 at runtime will
568 // produce the wrong value.
569 auto &Sec = cast<MCSectionELF>(Sym->getSection());
570 unsigned Flags = Sec.getFlags();
571 if (Flags & ELF::SHF_MERGE) {
575 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
576 // only handle section relocations to mergeable sections if using RELA.
577 if (!hasRelocationAddend())
581 // Most TLS relocations use a got, so they need the symbol. Even those that
582 // are just an offset (@tpoff), require a symbol in gold versions before
583 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
584 // http://sourceware.org/PR16773.
585 if (Flags & ELF::SHF_TLS)
588 // If the symbol is a thumb function the final relocation must set the lowest
589 // bit. With a symbol that is done by just having the symbol have that bit
590 // set, so we would lose the bit if we relocated with the section.
591 // FIXME: We could use the section but add the bit to the relocation value.
592 if (Asm.isThumbFunc(Sym))
595 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
600 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
601 const MCSymbol &Sym = Ref.getSymbol();
603 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
606 if (!Sym.isVariable())
609 const MCExpr *Expr = Sym.getVariableValue();
610 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
614 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
615 return &Inner->getSymbol();
619 // True if the assembler knows nothing about the final value of the symbol.
620 // This doesn't cover the comdat issues, since in those cases the assembler
621 // can at least know that all symbols in the section will move together.
622 static bool isWeak(const MCSymbolData &D) {
623 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
626 switch (MCELF::GetBinding(D)) {
628 llvm_unreachable("Unknown binding");
631 case ELF::STB_GLOBAL:
634 case ELF::STB_GNU_UNIQUE:
639 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
640 const MCAsmLayout &Layout,
641 const MCFragment *Fragment,
642 const MCFixup &Fixup, MCValue Target,
643 bool &IsPCRel, uint64_t &FixedValue) {
644 const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
645 uint64_t C = Target.getConstant();
646 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
648 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
649 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
650 "Should not have constructed this");
652 // Let A, B and C being the components of Target and R be the location of
653 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
654 // If it is pcrel, we want to compute (A - B + C - R).
656 // In general, ELF has no relocations for -B. It can only represent (A + C)
657 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
658 // replace B to implement it: (A - R - K + C)
660 Asm.getContext().reportFatalError(
662 "No relocation available to represent this relative expression");
664 const MCSymbol &SymB = RefB->getSymbol();
666 if (SymB.isUndefined())
667 Asm.getContext().reportFatalError(
669 Twine("symbol '") + SymB.getName() +
670 "' can not be undefined in a subtraction expression");
672 assert(!SymB.isAbsolute() && "Should have been folded");
673 const MCSection &SecB = SymB.getSection();
674 if (&SecB != &FixupSection)
675 Asm.getContext().reportFatalError(
676 Fixup.getLoc(), "Cannot represent a difference across sections");
678 if (::isWeak(SymB.getData()))
679 Asm.getContext().reportFatalError(
680 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
682 uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
683 uint64_t K = SymBOffset - FixupOffset;
688 // We either rejected the fixup or folded B into C at this point.
689 const MCSymbolRefExpr *RefA = Target.getSymA();
690 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
692 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
693 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
694 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
695 C += Layout.getSymbolOffset(*SymA);
698 if (hasRelocationAddend()) {
705 if (!RelocateWithSymbol) {
706 const MCSection *SecA =
707 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
708 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
709 const MCSymbol *SectionSymbol = ELFSec ? ELFSec->getBeginSymbol() : nullptr;
710 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
711 Relocations[&FixupSection].push_back(Rec);
716 if (const MCSymbol *R = Renames.lookup(SymA))
719 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
720 WeakrefUsedInReloc.insert(WeakRef);
722 UsedInReloc.insert(SymA);
724 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
725 Relocations[&FixupSection].push_back(Rec);
729 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
730 const MCSymbol &Symbol, bool Used,
732 const MCSymbolData &Data = Symbol.getData();
733 if (Symbol.isVariable()) {
734 const MCExpr *Expr = Symbol.getVariableValue();
735 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
736 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
747 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
750 if (Symbol.isVariable()) {
751 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
752 if (Base && Base->isUndefined())
756 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
757 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
760 if (MCELF::GetType(Data) == ELF::STT_SECTION)
763 if (Symbol.isTemporary())
769 bool ELFObjectWriter::isLocal(const MCSymbol &Symbol, bool isUsedInReloc) {
770 const MCSymbolData &Data = Symbol.getData();
771 if (Data.isExternal())
774 if (Symbol.isDefined())
783 void ELFObjectWriter::computeSymbolTable(
784 MCAssembler &Asm, const MCAsmLayout &Layout,
785 const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
786 SectionOffsetsTy &SectionOffsets) {
787 MCContext &Ctx = Asm.getContext();
788 SymbolTableWriter Writer(*this, is64Bit());
791 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
792 MCSectionELF *SymtabSection =
793 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
794 SymtabSection->setAlignment(is64Bit() ? 8 : 4);
795 SymbolTableIndex = addToSectionTable(SymtabSection);
798 OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
801 uint64_t SecStart = OS.tell();
803 // The first entry is the undefined symbol entry.
804 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
806 std::vector<ELFSymbolData> LocalSymbolData;
807 std::vector<ELFSymbolData> ExternalSymbolData;
808 std::vector<ELFSymbolData> UndefinedSymbolData;
810 // Add the data for the symbols.
811 bool HasLargeSectionIndex = false;
812 for (const MCSymbol &Symbol : Asm.symbols()) {
813 MCSymbolData &SD = Symbol.getData();
815 bool Used = UsedInReloc.count(&Symbol);
816 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
817 bool isSignature = RevGroupMap.count(&Symbol);
819 if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
820 Renames.count(&Symbol)))
824 MSD.Symbol = &Symbol;
825 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
827 // Undefined symbols are global, but this is the first place we
828 // are able to set it.
829 bool Local = isLocal(Symbol, Used);
830 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
832 MCSymbolData &BaseData = BaseSymbol->getData();
833 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
834 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
838 MSD.SectionIndex = ELF::SHN_ABS;
839 } else if (SD.isCommon()) {
841 MSD.SectionIndex = ELF::SHN_COMMON;
842 } else if (BaseSymbol->isUndefined()) {
843 if (isSignature && !Used) {
844 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
845 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
846 HasLargeSectionIndex = true;
848 MSD.SectionIndex = ELF::SHN_UNDEF;
850 if (!Used && WeakrefUsed)
851 MCELF::SetBinding(SD, ELF::STB_WEAK);
853 const MCSectionELF &Section =
854 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
855 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
856 assert(MSD.SectionIndex && "Invalid section index!");
857 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
858 HasLargeSectionIndex = true;
861 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
864 // FIXME: All name handling should be done before we get to the writer,
865 // including dealing with GNU-style version suffixes. Fixing this isn't
868 // We thus have to be careful to not perform the symbol version replacement
871 // The ELF format is used on Windows by the MCJIT engine. Thus, on
872 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
873 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
874 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
875 // the EFLObjectWriter should not interpret the "@@@" sub-string as
876 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
877 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
878 // "__imp_?" or "__imp_@?".
880 // It would have been interesting to perform the MS mangling prefix check
881 // only when the target triple is of the form *-pc-windows-elf. But, it
882 // seems that this information is not easily accessible from the
884 StringRef Name = Symbol.getName();
885 if (!Name.startswith("?") && !Name.startswith("@?") &&
886 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
887 // This symbol isn't following the MSVC C++ name mangling convention. We
888 // can thus safely interpret the @@@ in symbol names as specifying symbol
891 size_t Pos = Name.find("@@@");
892 if (Pos != StringRef::npos) {
893 Buf += Name.substr(0, Pos);
894 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
895 Buf += Name.substr(Pos + Skip);
900 // Sections have their own string table
901 if (MCELF::GetType(SD) != ELF::STT_SECTION)
902 MSD.Name = StrTabBuilder.add(Name);
904 if (MSD.SectionIndex == ELF::SHN_UNDEF)
905 UndefinedSymbolData.push_back(MSD);
907 LocalSymbolData.push_back(MSD);
909 ExternalSymbolData.push_back(MSD);
912 if (HasLargeSectionIndex) {
913 MCSectionELF *SymtabShndxSection =
914 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
915 SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
916 SymtabShndxSection->setAlignment(4);
919 ArrayRef<std::string> FileNames = Asm.getFileNames();
920 for (const std::string &Name : FileNames)
921 StrTabBuilder.add(Name);
923 StrTabBuilder.finalize(StringTableBuilder::ELF);
925 for (const std::string &Name : FileNames)
926 Writer.writeSymbol(StrTabBuilder.getOffset(Name),
927 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
930 // Symbols are required to be in lexicographic order.
931 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
932 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
933 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
935 // Set the symbol indices. Local symbols must come before all other
936 // symbols with non-local bindings.
937 unsigned Index = FileNames.size() + 1;
939 for (ELFSymbolData &MSD : LocalSymbolData) {
940 unsigned StringIndex =
941 MCELF::GetType(MSD.Symbol->getData()) == ELF::STT_SECTION
943 : StrTabBuilder.getOffset(MSD.Name);
944 MSD.Symbol->setIndex(Index++);
945 writeSymbol(Writer, StringIndex, MSD, Layout);
948 // Write the symbol table entries.
949 LastLocalSymbolIndex = Index;
951 for (ELFSymbolData &MSD : ExternalSymbolData) {
952 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
953 MSD.Symbol->setIndex(Index++);
954 writeSymbol(Writer, StringIndex, MSD, Layout);
955 assert(MCELF::GetBinding(MSD.Symbol->getData()) != ELF::STB_LOCAL);
957 for (ELFSymbolData &MSD : UndefinedSymbolData) {
958 unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
959 MSD.Symbol->setIndex(Index++);
960 writeSymbol(Writer, StringIndex, MSD, Layout);
961 assert(MCELF::GetBinding(MSD.Symbol->getData()) != ELF::STB_LOCAL);
964 uint64_t SecEnd = OS.tell();
965 SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
967 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
968 if (ShndxIndexes.empty()) {
969 assert(SymtabShndxSectionIndex == 0);
972 assert(SymtabShndxSectionIndex != 0);
974 SecStart = OS.tell();
975 const MCSectionELF *SymtabShndxSection =
976 SectionTable[SymtabShndxSectionIndex - 1];
977 for (uint32_t Index : ShndxIndexes)
980 SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
984 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
985 const MCSectionELF &Sec) {
986 if (Relocations[&Sec].empty())
989 const StringRef SectionName = Sec.getSectionName();
990 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
991 RelaSectionName += SectionName;
994 if (hasRelocationAddend())
995 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
997 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1000 if (Sec.getFlags() & ELF::SHF_GROUP)
1001 Flags = ELF::SHF_GROUP;
1003 MCSectionELF *RelaSection = Ctx.createELFRelSection(
1004 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1005 Flags, EntrySize, Sec.getGroup(), &Sec);
1006 RelaSection->setAlignment(is64Bit() ? 8 : 4);
1010 static SmallVector<char, 128>
1011 getUncompressedData(const MCAsmLayout &Layout,
1012 const MCSection::FragmentListType &Fragments) {
1013 SmallVector<char, 128> UncompressedData;
1014 for (const MCFragment &F : Fragments) {
1015 const SmallVectorImpl<char> *Contents;
1016 switch (F.getKind()) {
1017 case MCFragment::FT_Data:
1018 Contents = &cast<MCDataFragment>(F).getContents();
1020 case MCFragment::FT_Dwarf:
1021 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1023 case MCFragment::FT_DwarfFrame:
1024 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1028 "Not expecting any other fragment types in a debug_* section");
1030 UncompressedData.append(Contents->begin(), Contents->end());
1032 return UncompressedData;
1035 // Include the debug info compression header:
1036 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1037 // useful for consumers to preallocate a buffer to decompress into.
1039 prependCompressionHeader(uint64_t Size,
1040 SmallVectorImpl<char> &CompressedContents) {
1041 const StringRef Magic = "ZLIB";
1042 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1044 if (sys::IsLittleEndianHost)
1045 sys::swapByteOrder(Size);
1046 CompressedContents.insert(CompressedContents.begin(),
1047 Magic.size() + sizeof(Size), 0);
1048 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1049 std::copy(reinterpret_cast<char *>(&Size),
1050 reinterpret_cast<char *>(&Size + 1),
1051 CompressedContents.begin() + Magic.size());
1055 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1056 const MCAsmLayout &Layout) {
1057 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1058 StringRef SectionName = Section.getSectionName();
1060 // Compressing debug_frame requires handling alignment fragments which is
1061 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1062 // for writing to arbitrary buffers) for little benefit.
1063 if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1064 !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1065 Asm.writeSectionData(&Section, Layout);
1069 // Gather the uncompressed data from all the fragments.
1070 const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1071 SmallVector<char, 128> UncompressedData =
1072 getUncompressedData(Layout, Fragments);
1074 SmallVector<char, 128> CompressedContents;
1075 zlib::Status Success = zlib::compress(
1076 StringRef(UncompressedData.data(), UncompressedData.size()),
1077 CompressedContents);
1078 if (Success != zlib::StatusOK) {
1079 Asm.writeSectionData(&Section, Layout);
1083 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1084 Asm.writeSectionData(&Section, Layout);
1087 Asm.getContext().renameELFSection(&Section,
1088 (".z" + SectionName.drop_front(1)).str());
1089 OS << CompressedContents;
1092 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1093 uint64_t Flags, uint64_t Address,
1094 uint64_t Offset, uint64_t Size,
1095 uint32_t Link, uint32_t Info,
1097 uint64_t EntrySize) {
1098 Write32(Name); // sh_name: index into string table
1099 Write32(Type); // sh_type
1100 WriteWord(Flags); // sh_flags
1101 WriteWord(Address); // sh_addr
1102 WriteWord(Offset); // sh_offset
1103 WriteWord(Size); // sh_size
1104 Write32(Link); // sh_link
1105 Write32(Info); // sh_info
1106 WriteWord(Alignment); // sh_addralign
1107 WriteWord(EntrySize); // sh_entsize
1110 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1111 const MCSectionELF &Sec) {
1112 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1114 // Sort the relocation entries. Most targets just sort by Offset, but some
1115 // (e.g., MIPS) have additional constraints.
1116 TargetObjectWriter->sortRelocs(Asm, Relocs);
1118 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1119 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1120 unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1123 write(Entry.Offset);
1124 if (TargetObjectWriter->isN64()) {
1125 write(uint32_t(Index));
1127 write(TargetObjectWriter->getRSsym(Entry.Type));
1128 write(TargetObjectWriter->getRType3(Entry.Type));
1129 write(TargetObjectWriter->getRType2(Entry.Type));
1130 write(TargetObjectWriter->getRType(Entry.Type));
1132 struct ELF::Elf64_Rela ERE64;
1133 ERE64.setSymbolAndType(Index, Entry.Type);
1134 write(ERE64.r_info);
1136 if (hasRelocationAddend())
1137 write(Entry.Addend);
1139 write(uint32_t(Entry.Offset));
1141 struct ELF::Elf32_Rela ERE32;
1142 ERE32.setSymbolAndType(Index, Entry.Type);
1143 write(ERE32.r_info);
1145 if (hasRelocationAddend())
1146 write(uint32_t(Entry.Addend));
1151 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1152 const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1153 OS << StrTabBuilder.data();
1154 return StrtabSection;
1157 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1158 uint32_t GroupSymbolIndex, uint64_t Offset,
1159 uint64_t Size, const MCSectionELF &Section) {
1160 uint64_t sh_link = 0;
1161 uint64_t sh_info = 0;
1163 switch(Section.getType()) {
1168 case ELF::SHT_DYNAMIC:
1169 llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1172 case ELF::SHT_RELA: {
1173 sh_link = SymbolTableIndex;
1174 assert(sh_link && ".symtab not found");
1175 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1176 sh_info = SectionIndexMap.lookup(InfoSection);
1180 case ELF::SHT_SYMTAB:
1181 case ELF::SHT_DYNSYM:
1182 sh_link = StringTableIndex;
1183 sh_info = LastLocalSymbolIndex;
1186 case ELF::SHT_SYMTAB_SHNDX:
1187 sh_link = SymbolTableIndex;
1190 case ELF::SHT_GROUP:
1191 sh_link = SymbolTableIndex;
1192 sh_info = GroupSymbolIndex;
1196 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1197 Section.getType() == ELF::SHT_ARM_EXIDX)
1198 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1200 WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1201 Section.getType(), Section.getFlags(), 0, Offset, Size,
1202 sh_link, sh_info, Section.getAlignment(),
1203 Section.getEntrySize());
1206 void ELFObjectWriter::writeSectionHeader(
1207 const MCAssembler &Asm, const MCAsmLayout &Layout,
1208 const SectionIndexMapTy &SectionIndexMap,
1209 const SectionOffsetsTy &SectionOffsets) {
1210 const unsigned NumSections = SectionTable.size();
1212 // Null section first.
1213 uint64_t FirstSectionSize =
1214 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1215 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1217 for (const MCSectionELF *Section : SectionTable) {
1218 uint32_t GroupSymbolIndex;
1219 unsigned Type = Section->getType();
1220 if (Type != ELF::SHT_GROUP)
1221 GroupSymbolIndex = 0;
1223 GroupSymbolIndex = Section->getGroup()->getIndex();
1225 const std::pair<uint64_t, uint64_t> &Offsets =
1226 SectionOffsets.find(Section)->second;
1228 if (Type == ELF::SHT_NOBITS)
1229 Size = Layout.getSectionAddressSize(Section);
1231 Size = Offsets.second - Offsets.first;
1233 writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1238 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1239 const MCAsmLayout &Layout) {
1240 MCContext &Ctx = Asm.getContext();
1241 MCSectionELF *StrtabSection =
1242 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1243 StringTableIndex = addToSectionTable(StrtabSection);
1245 RevGroupMapTy RevGroupMap;
1246 SectionIndexMapTy SectionIndexMap;
1248 std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1250 // Write out the ELF header ...
1253 // ... then the sections ...
1254 SectionOffsetsTy SectionOffsets;
1255 std::vector<MCSectionELF *> Groups;
1256 std::vector<MCSectionELF *> Relocations;
1257 for (MCSection &Sec : Asm) {
1258 MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1260 uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1261 WriteZeros(Padding);
1263 // Remember the offset into the file for this section.
1264 uint64_t SecStart = OS.tell();
1266 const MCSymbol *SignatureSymbol = Section.getGroup();
1267 writeSectionData(Asm, Section, Layout);
1269 uint64_t SecEnd = OS.tell();
1270 SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1272 MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1274 if (SignatureSymbol) {
1275 Asm.getOrCreateSymbolData(*SignatureSymbol);
1276 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1278 MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1279 GroupIdx = addToSectionTable(Group);
1280 Group->setAlignment(4);
1281 Groups.push_back(Group);
1283 GroupMembers[SignatureSymbol].push_back(&Section);
1285 GroupMembers[SignatureSymbol].push_back(RelSection);
1288 SectionIndexMap[&Section] = addToSectionTable(&Section);
1290 SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1291 Relocations.push_back(RelSection);
1295 for (MCSectionELF *Group : Groups) {
1296 uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1297 WriteZeros(Padding);
1299 // Remember the offset into the file for this section.
1300 uint64_t SecStart = OS.tell();
1302 const MCSymbol *SignatureSymbol = Group->getGroup();
1303 assert(SignatureSymbol);
1304 write(uint32_t(ELF::GRP_COMDAT));
1305 for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1306 uint32_t SecIndex = SectionIndexMap.lookup(Member);
1310 uint64_t SecEnd = OS.tell();
1311 SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1314 // Compute symbol table information.
1315 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1317 for (MCSectionELF *RelSection : Relocations) {
1318 uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1319 WriteZeros(Padding);
1321 // Remember the offset into the file for this section.
1322 uint64_t SecStart = OS.tell();
1324 writeRelocations(Asm, *RelSection->getAssociatedSection());
1326 uint64_t SecEnd = OS.tell();
1327 SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1331 uint64_t SecStart = OS.tell();
1332 const MCSectionELF *Sec = createStringTable(Ctx);
1333 uint64_t SecEnd = OS.tell();
1334 SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1337 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1338 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1339 WriteZeros(Padding);
1341 const unsigned SectionHeaderOffset = OS.tell();
1343 // ... then the section header table ...
1344 writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1346 uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1347 ? (uint16_t)ELF::SHN_UNDEF
1348 : SectionTable.size() + 1;
1349 if (sys::IsLittleEndianHost != IsLittleEndian)
1350 sys::swapByteOrder(NumSections);
1351 unsigned NumSectionsOffset;
1354 uint64_t Val = SectionHeaderOffset;
1355 if (sys::IsLittleEndianHost != IsLittleEndian)
1356 sys::swapByteOrder(Val);
1357 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1358 offsetof(ELF::Elf64_Ehdr, e_shoff));
1359 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1361 uint32_t Val = SectionHeaderOffset;
1362 if (sys::IsLittleEndianHost != IsLittleEndian)
1363 sys::swapByteOrder(Val);
1364 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1365 offsetof(ELF::Elf32_Ehdr, e_shoff));
1366 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1368 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1372 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1373 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
1374 bool InSet, bool IsPCRel) const {
1377 if (::isWeak(SymA.getData()))
1380 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1384 bool ELFObjectWriter::isWeak(const MCSymbol &Sym) const {
1385 const MCSymbolData &SD = Sym.getData();
1389 // It is invalid to replace a reference to a global in a comdat
1390 // with a reference to a local since out of comdat references
1391 // to a local are forbidden.
1392 // We could try to return false for more cases, like the reference
1393 // being in the same comdat or Sym being an alias to another global,
1394 // but it is not clear if it is worth the effort.
1395 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1398 if (!Sym.isInSection())
1401 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1402 return Sec.getGroup();
1405 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1406 raw_pwrite_stream &OS,
1407 bool IsLittleEndian) {
1408 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);