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"
44 class FragmentWriter {
48 FragmentWriter(bool IsLittleEndian);
49 template <typename T> void write(MCDataFragment &F, T Val);
52 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
54 class SymbolTableWriter {
56 FragmentWriter &FWriter;
58 std::vector<const MCSectionELF *> &Sections;
60 // The symbol .symtab fragment we are writting to.
61 MCDataFragment *SymtabF;
63 // .symtab_shndx fragment we are writting to.
64 MCDataFragment *ShndxF;
66 // The numbel of symbols written so far.
69 void createSymtabShndx();
71 template <typename T> void write(MCDataFragment &F, T Value);
74 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75 std::vector<const MCSectionELF *> &Sections,
76 MCDataFragment *SymtabF);
78 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79 uint8_t other, uint32_t shndx, bool Reserved);
82 class ELFObjectWriter : public MCObjectWriter {
83 FragmentWriter FWriter;
87 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
88 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
89 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
90 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
91 bool Used, bool Renamed);
92 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
93 static bool IsELFMetaDataSection(const MCSectionData &SD);
95 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
96 const MCSectionData &SD);
98 /// Helper struct for containing some precomputed information on symbols.
99 struct ELFSymbolData {
100 MCSymbolData *SymbolData;
101 uint64_t StringIndex;
102 uint32_t SectionIndex;
105 // Support lexicographic sorting.
106 bool operator<(const ELFSymbolData &RHS) const {
107 unsigned LHSType = MCELF::GetType(*SymbolData);
108 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
109 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
111 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
113 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
114 return SectionIndex < RHS.SectionIndex;
115 return Name < RHS.Name;
119 /// The target specific ELF writer instance.
120 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
122 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
123 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
124 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
126 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
128 StringTableBuilder ShStrTabBuilder;
131 /// @name Symbol Table Data
134 StringTableBuilder StrTabBuilder;
135 std::vector<uint64_t> FileSymbolData;
136 std::vector<ELFSymbolData> LocalSymbolData;
137 std::vector<ELFSymbolData> ExternalSymbolData;
138 std::vector<ELFSymbolData> UndefinedSymbolData;
144 // This holds the symbol table index of the last local symbol.
145 unsigned LastLocalSymbolIndex;
146 // This holds the .strtab section index.
147 unsigned StringTableIndex;
148 // This holds the .symtab section index.
149 unsigned SymbolTableIndex;
151 unsigned ShstrtabIndex;
154 // TargetObjectWriter wrappers.
155 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
156 bool hasRelocationAddend() const {
157 return TargetObjectWriter->hasRelocationAddend();
159 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
160 bool IsPCRel) const {
161 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
165 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
167 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
168 TargetObjectWriter(MOTW), NeedsGOT(false) {}
170 void reset() override {
172 WeakrefUsedInReloc.clear();
175 ShStrTabBuilder.clear();
176 StrTabBuilder.clear();
177 FileSymbolData.clear();
178 LocalSymbolData.clear();
179 ExternalSymbolData.clear();
180 UndefinedSymbolData.clear();
181 MCObjectWriter::reset();
184 ~ELFObjectWriter() override;
186 void WriteWord(uint64_t W) {
193 template <typename T> void write(MCDataFragment &F, T Value) {
194 FWriter.write(F, Value);
197 void WriteHeader(const MCAssembler &Asm,
198 unsigned NumberOfSections);
200 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
201 const MCAsmLayout &Layout);
203 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
204 const MCAsmLayout &Layout,
205 std::vector<const MCSectionELF *> &Sections);
207 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
208 const MCSymbolRefExpr *RefA,
209 const MCSymbolData *SD, uint64_t C,
210 unsigned Type) const;
212 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
213 const MCFragment *Fragment, const MCFixup &Fixup,
214 MCValue Target, bool &IsPCRel,
215 uint64_t &FixedValue) override;
217 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
220 // Map from a signature symbol to the group section index
221 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
222 // Start and end offset of each section
223 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
225 /// Compute the symbol table data
227 /// \param Asm - The assembler.
228 /// \param SectionIndexMap - Maps a section to its index.
229 /// \param RevGroupMap - Maps a signature symbol to the group section.
230 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
231 const SectionIndexMapTy &SectionIndexMap,
232 const RevGroupMapTy &RevGroupMap);
234 void maybeAddToGroup(MCAssembler &Asm,
235 ArrayRef<const MCSectionELF *> Sections,
236 const RevGroupMapTy &RevGroupMap,
237 const MCSectionELF &Section, unsigned Index);
239 void computeIndexMap(MCAssembler &Asm,
240 std::vector<const MCSectionELF *> &Sections,
241 SectionIndexMapTy &SectionIndexMap,
242 const RevGroupMapTy &RevGroupMap);
244 void createRelocationSection(MCAssembler &Asm, const MCSectionData &SD);
246 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
248 void WriteRelocations(MCAssembler &Asm, const MCAsmLayout &Layout);
251 createSectionHeaderStringTable(MCAssembler &Asm,
252 std::vector<const MCSectionELF *> &Sections);
253 void CreateMetadataSections(MCAssembler &Asm, const MCAsmLayout &Layout,
254 std::vector<const MCSectionELF *> &Sections);
256 // Create the sections that show up in the symbol table. Currently
257 // those are the .note.GNU-stack section and the group sections.
258 void createIndexedSections(MCAssembler &Asm, const MCAsmLayout &Layout,
259 RevGroupMapTy &RevGroupMap,
260 std::vector<const MCSectionELF *> &Sections,
261 SectionIndexMapTy &SectionIndexMap);
263 void ExecutePostLayoutBinding(MCAssembler &Asm,
264 const MCAsmLayout &Layout) override;
266 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
267 MCAssembler &Asm, const MCAsmLayout &Layout,
268 const SectionIndexMapTy &SectionIndexMap,
269 const SectionOffsetsTy &SectionOffsets);
271 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
272 uint64_t Address, uint64_t Offset,
273 uint64_t Size, uint32_t Link, uint32_t Info,
274 uint64_t Alignment, uint64_t EntrySize);
276 void WriteRelocationsFragment(const MCAssembler &Asm,
278 const MCSectionData *SD);
281 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
282 const MCSymbolData &DataA,
283 const MCFragment &FB,
285 bool IsPCRel) const override;
287 bool isWeak(const MCSymbolData &SD) const override;
289 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
290 void writeSection(MCAssembler &Asm,
291 const SectionIndexMapTy &SectionIndexMap,
292 uint32_t GroupSymbolIndex,
293 uint64_t Offset, uint64_t Size, uint64_t Alignment,
294 const MCSectionELF &Section);
298 FragmentWriter::FragmentWriter(bool IsLittleEndian)
299 : IsLittleEndian(IsLittleEndian) {}
301 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
303 Val = support::endian::byte_swap<T, support::little>(Val);
305 Val = support::endian::byte_swap<T, support::big>(Val);
306 const char *Start = (const char *)&Val;
307 F.getContents().append(Start, Start + sizeof(T));
310 void SymbolTableWriter::createSymtabShndx() {
314 MCContext &Ctx = Asm.getContext();
315 const MCSectionELF *SymtabShndxSection =
316 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
317 MCSectionData *SymtabShndxSD =
318 &Asm.getOrCreateSectionData(*SymtabShndxSection);
319 SymtabShndxSD->setAlignment(4);
320 ShndxF = new MCDataFragment(SymtabShndxSD);
321 Sections.push_back(SymtabShndxSection);
323 for (unsigned I = 0; I < NumWritten; ++I)
324 write(*ShndxF, uint32_t(0));
327 template <typename T>
328 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
329 FWriter.write(F, Value);
332 SymbolTableWriter::SymbolTableWriter(
333 MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
334 std::vector<const MCSectionELF *> &Sections, MCDataFragment *SymtabF)
335 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit), Sections(Sections),
336 SymtabF(SymtabF), ShndxF(nullptr), NumWritten(0) {}
338 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
339 uint64_t size, uint8_t other,
340 uint32_t shndx, bool Reserved) {
341 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
348 write(*ShndxF, shndx);
350 write(*ShndxF, uint32_t(0));
353 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
356 write(*SymtabF, name); // st_name
357 write(*SymtabF, info); // st_info
358 write(*SymtabF, other); // st_other
359 write(*SymtabF, Index); // st_shndx
360 write(*SymtabF, value); // st_value
361 write(*SymtabF, size); // st_size
363 write(*SymtabF, name); // st_name
364 write(*SymtabF, uint32_t(value)); // st_value
365 write(*SymtabF, uint32_t(size)); // st_size
366 write(*SymtabF, info); // st_info
367 write(*SymtabF, other); // st_other
368 write(*SymtabF, Index); // st_shndx
374 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
375 const MCFixupKindInfo &FKI =
376 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
378 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
381 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
385 case MCSymbolRefExpr::VK_GOT:
386 case MCSymbolRefExpr::VK_PLT:
387 case MCSymbolRefExpr::VK_GOTPCREL:
388 case MCSymbolRefExpr::VK_GOTOFF:
389 case MCSymbolRefExpr::VK_TPOFF:
390 case MCSymbolRefExpr::VK_TLSGD:
391 case MCSymbolRefExpr::VK_GOTTPOFF:
392 case MCSymbolRefExpr::VK_INDNTPOFF:
393 case MCSymbolRefExpr::VK_NTPOFF:
394 case MCSymbolRefExpr::VK_GOTNTPOFF:
395 case MCSymbolRefExpr::VK_TLSLDM:
396 case MCSymbolRefExpr::VK_DTPOFF:
397 case MCSymbolRefExpr::VK_TLSLD:
402 ELFObjectWriter::~ELFObjectWriter()
405 // Emit the ELF header.
406 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
407 unsigned NumberOfSections) {
413 // emitWord method behaves differently for ELF32 and ELF64, writing
414 // 4 bytes in the former and 8 in the latter.
416 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
418 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
421 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
423 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
425 Write8(TargetObjectWriter->getOSABI());
426 Write8(0); // e_ident[EI_ABIVERSION]
428 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
430 Write16(ELF::ET_REL); // e_type
432 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
434 Write32(ELF::EV_CURRENT); // e_version
435 WriteWord(0); // e_entry, no entry point in .o file
436 WriteWord(0); // e_phoff, no program header for .o
437 WriteWord(0); // e_shoff = sec hdr table off in bytes
439 // e_flags = whatever the target wants
440 Write32(Asm.getELFHeaderEFlags());
442 // e_ehsize = ELF header size
443 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
445 Write16(0); // e_phentsize = prog header entry size
446 Write16(0); // e_phnum = # prog header entries = 0
448 // e_shentsize = Section header entry size
449 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
451 // e_shnum = # of section header ents
452 if (NumberOfSections >= ELF::SHN_LORESERVE)
453 Write16(ELF::SHN_UNDEF);
455 Write16(NumberOfSections);
457 // e_shstrndx = Section # of '.shstrtab'
458 assert(ShstrtabIndex < ELF::SHN_LORESERVE);
459 Write16(ShstrtabIndex);
462 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
463 const MCAsmLayout &Layout) {
464 if (Data.isCommon() && Data.isExternal())
465 return Data.getCommonAlignment();
468 if (!Layout.getSymbolOffset(&Data, Res))
471 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
477 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
478 const MCAsmLayout &Layout) {
479 // The presence of symbol versions causes undefined symbols and
480 // versions declared with @@@ to be renamed.
482 for (MCSymbolData &OriginalData : Asm.symbols()) {
483 const MCSymbol &Alias = OriginalData.getSymbol();
486 if (!Alias.isVariable())
488 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
491 const MCSymbol &Symbol = Ref->getSymbol();
492 MCSymbolData &SD = Asm.getSymbolData(Symbol);
494 StringRef AliasName = Alias.getName();
495 size_t Pos = AliasName.find('@');
496 if (Pos == StringRef::npos)
499 // Aliases defined with .symvar copy the binding from the symbol they alias.
500 // This is the first place we are able to copy this information.
501 OriginalData.setExternal(SD.isExternal());
502 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
504 StringRef Rest = AliasName.substr(Pos);
505 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
508 // FIXME: produce a better error message.
509 if (Symbol.isUndefined() && Rest.startswith("@@") &&
510 !Rest.startswith("@@@"))
511 report_fatal_error("A @@ version cannot be undefined");
513 Renames.insert(std::make_pair(&Symbol, &Alias));
517 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
518 uint8_t Type = newType;
520 // Propagation rules:
521 // IFUNC > FUNC > OBJECT > NOTYPE
522 // TLS_OBJECT > OBJECT > NOTYPE
524 // dont let the new type degrade the old type
528 case ELF::STT_GNU_IFUNC:
529 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
530 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
531 Type = ELF::STT_GNU_IFUNC;
534 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
535 Type == ELF::STT_TLS)
536 Type = ELF::STT_FUNC;
538 case ELF::STT_OBJECT:
539 if (Type == ELF::STT_NOTYPE)
540 Type = ELF::STT_OBJECT;
543 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
544 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
552 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
553 const MCAsmLayout &Layout) {
554 MCSymbolData &OrigData = *MSD.SymbolData;
555 assert((!OrigData.getFragment() ||
556 (&OrigData.getFragment()->getParent()->getSection() ==
557 &OrigData.getSymbol().getSection())) &&
558 "The symbol's section doesn't match the fragment's symbol");
559 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
561 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
563 bool IsReserved = !Base || OrigData.isCommon();
565 // Binding and Type share the same byte as upper and lower nibbles
566 uint8_t Binding = MCELF::GetBinding(OrigData);
567 uint8_t Type = MCELF::GetType(OrigData);
568 MCSymbolData *BaseSD = nullptr;
570 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
571 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
573 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
575 // Other and Visibility share the same byte with Visibility using the lower
577 uint8_t Visibility = MCELF::GetVisibility(OrigData);
578 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
581 uint64_t Value = SymbolValue(OrigData, Layout);
584 const MCExpr *ESize = OrigData.getSize();
586 ESize = BaseSD->getSize();
590 if (!ESize->evaluateKnownAbsolute(Res, Layout))
591 report_fatal_error("Size expression must be absolute.");
595 // Write out the symbol table entry
596 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
597 MSD.SectionIndex, IsReserved);
600 void ELFObjectWriter::WriteSymbolTable(
601 MCDataFragment *SymtabF, MCAssembler &Asm, const MCAsmLayout &Layout,
602 std::vector<const MCSectionELF *> &Sections) {
603 // The string table must be emitted first because we need the index
604 // into the string table for all the symbol names.
606 // FIXME: Make sure the start of the symbol table is aligned.
608 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), Sections, SymtabF);
610 // The first entry is the undefined symbol entry.
611 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
613 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
614 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
615 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
618 // Write the symbol table entries.
619 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
621 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
622 ELFSymbolData &MSD = LocalSymbolData[i];
623 WriteSymbol(Writer, MSD, Layout);
626 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
627 ELFSymbolData &MSD = ExternalSymbolData[i];
628 MCSymbolData &Data = *MSD.SymbolData;
629 assert(((Data.getFlags() & ELF_STB_Global) ||
630 (Data.getFlags() & ELF_STB_Weak)) &&
631 "External symbol requires STB_GLOBAL or STB_WEAK flag");
632 WriteSymbol(Writer, MSD, Layout);
633 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
634 LastLocalSymbolIndex++;
637 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
638 ELFSymbolData &MSD = UndefinedSymbolData[i];
639 MCSymbolData &Data = *MSD.SymbolData;
640 WriteSymbol(Writer, MSD, Layout);
641 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
642 LastLocalSymbolIndex++;
646 // It is always valid to create a relocation with a symbol. It is preferable
647 // to use a relocation with a section if that is possible. Using the section
648 // allows us to omit some local symbols from the symbol table.
649 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
650 const MCSymbolRefExpr *RefA,
651 const MCSymbolData *SD,
653 unsigned Type) const {
654 // A PCRel relocation to an absolute value has no symbol (or section). We
655 // represent that with a relocation to a null section.
659 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
663 // The .odp creation emits a relocation against the symbol ".TOC." which
664 // create a R_PPC64_TOC relocation. However the relocation symbol name
665 // in final object creation should be NULL, since the symbol does not
666 // really exist, it is just the reference to TOC base for the current
667 // object file. Since the symbol is undefined, returning false results
668 // in a relocation with a null section which is the desired result.
669 case MCSymbolRefExpr::VK_PPC_TOCBASE:
672 // These VariantKind cause the relocation to refer to something other than
673 // the symbol itself, like a linker generated table. Since the address of
674 // symbol is not relevant, we cannot replace the symbol with the
675 // section and patch the difference in the addend.
676 case MCSymbolRefExpr::VK_GOT:
677 case MCSymbolRefExpr::VK_PLT:
678 case MCSymbolRefExpr::VK_GOTPCREL:
679 case MCSymbolRefExpr::VK_Mips_GOT:
680 case MCSymbolRefExpr::VK_PPC_GOT_LO:
681 case MCSymbolRefExpr::VK_PPC_GOT_HI:
682 case MCSymbolRefExpr::VK_PPC_GOT_HA:
686 // An undefined symbol is not in any section, so the relocation has to point
687 // to the symbol itself.
688 const MCSymbol &Sym = SD->getSymbol();
689 if (Sym.isUndefined())
692 unsigned Binding = MCELF::GetBinding(*SD);
695 llvm_unreachable("Invalid Binding");
699 // If the symbol is weak, it might be overridden by a symbol in another
700 // file. The relocation has to point to the symbol so that the linker
703 case ELF::STB_GLOBAL:
704 // Global ELF symbols can be preempted by the dynamic linker. The relocation
705 // has to point to the symbol for a reason analogous to the STB_WEAK case.
709 // If a relocation points to a mergeable section, we have to be careful.
710 // If the offset is zero, a relocation with the section will encode the
711 // same information. With a non-zero offset, the situation is different.
712 // For example, a relocation can point 42 bytes past the end of a string.
713 // If we change such a relocation to use the section, the linker would think
714 // that it pointed to another string and subtracting 42 at runtime will
715 // produce the wrong value.
716 auto &Sec = cast<MCSectionELF>(Sym.getSection());
717 unsigned Flags = Sec.getFlags();
718 if (Flags & ELF::SHF_MERGE) {
722 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
723 // only handle section relocations to mergeable sections if using RELA.
724 if (!hasRelocationAddend())
728 // Most TLS relocations use a got, so they need the symbol. Even those that
729 // are just an offset (@tpoff), require a symbol in gold versions before
730 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
731 // http://sourceware.org/PR16773.
732 if (Flags & ELF::SHF_TLS)
735 // If the symbol is a thumb function the final relocation must set the lowest
736 // bit. With a symbol that is done by just having the symbol have that bit
737 // set, so we would lose the bit if we relocated with the section.
738 // FIXME: We could use the section but add the bit to the relocation value.
739 if (Asm.isThumbFunc(&Sym))
742 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
747 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
748 const MCSymbol &Sym = Ref.getSymbol();
750 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
753 if (!Sym.isVariable())
756 const MCExpr *Expr = Sym.getVariableValue();
757 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
761 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
762 return &Inner->getSymbol();
766 // True if the assembler knows nothing about the final value of the symbol.
767 // This doesn't cover the comdat issues, since in those cases the assembler
768 // can at least know that all symbols in the section will move together.
769 static bool isWeak(const MCSymbolData &D) {
770 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
773 switch (MCELF::GetBinding(D)) {
775 llvm_unreachable("Unknown binding");
778 case ELF::STB_GLOBAL:
781 case ELF::STB_GNU_UNIQUE:
786 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
787 const MCAsmLayout &Layout,
788 const MCFragment *Fragment,
789 const MCFixup &Fixup, MCValue Target,
790 bool &IsPCRel, uint64_t &FixedValue) {
791 const MCSectionData *FixupSection = Fragment->getParent();
792 uint64_t C = Target.getConstant();
793 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
795 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
796 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
797 "Should not have constructed this");
799 // Let A, B and C being the components of Target and R be the location of
800 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
801 // If it is pcrel, we want to compute (A - B + C - R).
803 // In general, ELF has no relocations for -B. It can only represent (A + C)
804 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
805 // replace B to implement it: (A - R - K + C)
807 Asm.getContext().FatalError(
809 "No relocation available to represent this relative expression");
811 const MCSymbol &SymB = RefB->getSymbol();
813 if (SymB.isUndefined())
814 Asm.getContext().FatalError(
816 Twine("symbol '") + SymB.getName() +
817 "' can not be undefined in a subtraction expression");
819 assert(!SymB.isAbsolute() && "Should have been folded");
820 const MCSection &SecB = SymB.getSection();
821 if (&SecB != &FixupSection->getSection())
822 Asm.getContext().FatalError(
823 Fixup.getLoc(), "Cannot represent a difference across sections");
825 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
827 Asm.getContext().FatalError(
828 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
830 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
831 uint64_t K = SymBOffset - FixupOffset;
836 // We either rejected the fixup or folded B into C at this point.
837 const MCSymbolRefExpr *RefA = Target.getSymA();
838 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
839 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
841 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
842 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
843 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
844 C += Layout.getSymbolOffset(SymAD);
847 if (hasRelocationAddend()) {
854 // FIXME: What is this!?!?
855 MCSymbolRefExpr::VariantKind Modifier =
856 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
857 if (RelocNeedsGOT(Modifier))
860 if (!RelocateWithSymbol) {
861 const MCSection *SecA =
862 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
863 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
864 MCSymbol *SectionSymbol =
865 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
867 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
868 Relocations[FixupSection].push_back(Rec);
873 if (const MCSymbol *R = Renames.lookup(SymA))
876 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
877 WeakrefUsedInReloc.insert(WeakRef);
879 UsedInReloc.insert(SymA);
881 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
882 Relocations[FixupSection].push_back(Rec);
888 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
890 const MCSymbolData &SD = Asm.getSymbolData(*S);
891 return SD.getIndex();
894 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
895 const MCSymbolData &Data, bool Used,
897 const MCSymbol &Symbol = Data.getSymbol();
898 if (Symbol.isVariable()) {
899 const MCExpr *Expr = Symbol.getVariableValue();
900 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
901 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
912 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
915 if (Symbol.isVariable()) {
916 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
917 if (Base && Base->isUndefined())
921 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
922 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
925 if (Symbol.isTemporary())
931 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
932 if (Data.isExternal())
935 const MCSymbol &Symbol = Data.getSymbol();
936 if (Symbol.isDefined())
945 void ELFObjectWriter::maybeAddToGroup(MCAssembler &Asm,
946 ArrayRef<const MCSectionELF *> Sections,
947 const RevGroupMapTy &RevGroupMap,
948 const MCSectionELF &Section,
950 const MCSymbol *Sym = Section.getGroup();
953 const MCSectionELF *Group = Sections[RevGroupMap.lookup(Sym) - 1];
954 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
955 // FIXME: we could use the previous fragment
956 MCDataFragment *F = new MCDataFragment(&Data);
960 void ELFObjectWriter::computeIndexMap(
961 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections,
962 SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap) {
963 for (const MCSectionData &SD : Asm) {
964 const MCSectionELF &Section =
965 static_cast<const MCSectionELF &>(SD.getSection());
966 if (Section.getType() == ELF::SHT_GROUP)
968 Sections.push_back(&Section);
969 unsigned Index = Sections.size();
970 SectionIndexMap[&Section] = Index;
971 maybeAddToGroup(Asm, Sections, RevGroupMap, Section, Index);
972 createRelocationSection(Asm, SD);
976 void ELFObjectWriter::computeSymbolTable(
977 MCAssembler &Asm, const MCAsmLayout &Layout,
978 const SectionIndexMapTy &SectionIndexMap,
979 const RevGroupMapTy &RevGroupMap) {
980 // FIXME: Is this the correct place to do this?
981 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
983 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
984 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
985 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
986 Data.setExternal(true);
987 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
990 // Add the data for the symbols.
991 for (MCSymbolData &SD : Asm.symbols()) {
992 const MCSymbol &Symbol = SD.getSymbol();
994 bool Used = UsedInReloc.count(&Symbol);
995 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
996 bool isSignature = RevGroupMap.count(&Symbol);
998 if (!isInSymtab(Layout, SD,
999 Used || WeakrefUsed || isSignature,
1000 Renames.count(&Symbol)))
1004 MSD.SymbolData = &SD;
1005 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1007 // Undefined symbols are global, but this is the first place we
1008 // are able to set it.
1009 bool Local = isLocal(SD, Used);
1010 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1012 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1013 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1014 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1018 MSD.SectionIndex = ELF::SHN_ABS;
1019 } else if (SD.isCommon()) {
1021 MSD.SectionIndex = ELF::SHN_COMMON;
1022 } else if (BaseSymbol->isUndefined()) {
1023 if (isSignature && !Used)
1024 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
1026 MSD.SectionIndex = ELF::SHN_UNDEF;
1027 if (!Used && WeakrefUsed)
1028 MCELF::SetBinding(SD, ELF::STB_WEAK);
1030 const MCSectionELF &Section =
1031 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1032 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1033 assert(MSD.SectionIndex && "Invalid section index!");
1036 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1039 // FIXME: All name handling should be done before we get to the writer,
1040 // including dealing with GNU-style version suffixes. Fixing this isn't
1043 // We thus have to be careful to not perform the symbol version replacement
1046 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1047 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1048 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1049 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1050 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1051 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1052 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1053 // "__imp_?" or "__imp_@?".
1055 // It would have been interesting to perform the MS mangling prefix check
1056 // only when the target triple is of the form *-pc-windows-elf. But, it
1057 // seems that this information is not easily accessible from the
1059 StringRef Name = Symbol.getName();
1060 if (!Name.startswith("?") && !Name.startswith("@?") &&
1061 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1062 // This symbol isn't following the MSVC C++ name mangling convention. We
1063 // can thus safely interpret the @@@ in symbol names as specifying symbol
1065 SmallString<32> Buf;
1066 size_t Pos = Name.find("@@@");
1067 if (Pos != StringRef::npos) {
1068 Buf += Name.substr(0, Pos);
1069 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1070 Buf += Name.substr(Pos + Skip);
1075 // Sections have their own string table
1076 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1077 MSD.Name = StrTabBuilder.add(Name);
1079 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1080 UndefinedSymbolData.push_back(MSD);
1082 LocalSymbolData.push_back(MSD);
1084 ExternalSymbolData.push_back(MSD);
1087 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1088 StrTabBuilder.add(*i);
1090 StrTabBuilder.finalize(StringTableBuilder::ELF);
1092 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1093 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1095 for (ELFSymbolData &MSD : LocalSymbolData)
1096 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1098 : StrTabBuilder.getOffset(MSD.Name);
1099 for (ELFSymbolData &MSD : ExternalSymbolData)
1100 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1101 for (ELFSymbolData& MSD : UndefinedSymbolData)
1102 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1104 // Symbols are required to be in lexicographic order.
1105 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1106 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1107 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1109 // Set the symbol indices. Local symbols must come before all other
1110 // symbols with non-local bindings.
1111 unsigned Index = FileSymbolData.size() + 1;
1112 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1113 LocalSymbolData[i].SymbolData->setIndex(Index++);
1115 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1116 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1117 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1118 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1121 void ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1122 const MCSectionData &SD) {
1123 if (Relocations[&SD].empty())
1126 MCContext &Ctx = Asm.getContext();
1127 const MCSectionELF &Section =
1128 static_cast<const MCSectionELF &>(SD.getSection());
1130 const StringRef SectionName = Section.getSectionName();
1131 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1132 RelaSectionName += SectionName;
1135 if (hasRelocationAddend())
1136 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1138 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1141 if (Section.getFlags() & ELF::SHF_GROUP)
1142 Flags = ELF::SHF_GROUP;
1144 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1145 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1146 Flags, EntrySize, Section.getGroup(), &Section);
1147 Asm.getOrCreateSectionData(*RelaSection);
1150 static SmallVector<char, 128>
1151 getUncompressedData(const MCAsmLayout &Layout,
1152 MCSectionData::FragmentListType &Fragments) {
1153 SmallVector<char, 128> UncompressedData;
1154 for (const MCFragment &F : Fragments) {
1155 const SmallVectorImpl<char> *Contents;
1156 switch (F.getKind()) {
1157 case MCFragment::FT_Data:
1158 Contents = &cast<MCDataFragment>(F).getContents();
1160 case MCFragment::FT_Dwarf:
1161 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1163 case MCFragment::FT_DwarfFrame:
1164 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1168 "Not expecting any other fragment types in a debug_* section");
1170 UncompressedData.append(Contents->begin(), Contents->end());
1172 return UncompressedData;
1175 // Include the debug info compression header:
1176 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1177 // useful for consumers to preallocate a buffer to decompress into.
1179 prependCompressionHeader(uint64_t Size,
1180 SmallVectorImpl<char> &CompressedContents) {
1181 const StringRef Magic = "ZLIB";
1182 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1184 if (sys::IsLittleEndianHost)
1185 sys::swapByteOrder(Size);
1186 CompressedContents.insert(CompressedContents.begin(),
1187 Magic.size() + sizeof(Size), 0);
1188 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1189 std::copy(reinterpret_cast<char *>(&Size),
1190 reinterpret_cast<char *>(&Size + 1),
1191 CompressedContents.begin() + Magic.size());
1195 // Return a single fragment containing the compressed contents of the whole
1196 // section. Null if the section was not compressed for any reason.
1197 static std::unique_ptr<MCDataFragment>
1198 getCompressedFragment(const MCAsmLayout &Layout,
1199 MCSectionData::FragmentListType &Fragments) {
1200 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1202 // Gather the uncompressed data from all the fragments, recording the
1203 // alignment fragment, if seen, and any fixups.
1204 SmallVector<char, 128> UncompressedData =
1205 getUncompressedData(Layout, Fragments);
1207 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1209 zlib::Status Success = zlib::compress(
1210 StringRef(UncompressedData.data(), UncompressedData.size()),
1211 CompressedContents);
1212 if (Success != zlib::StatusOK)
1215 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1218 return CompressedFragment;
1221 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1224 static void UpdateSymbols(const MCAsmLayout &Layout,
1225 const std::vector<MCSymbolData *> &Symbols,
1226 MCFragment &NewFragment) {
1227 for (MCSymbolData *Sym : Symbols) {
1228 Sym->setOffset(Sym->getOffset() +
1229 Layout.getFragmentOffset(Sym->getFragment()));
1230 Sym->setFragment(&NewFragment);
1234 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1235 const DefiningSymbolMap &DefiningSymbols,
1236 const MCSectionELF &Section,
1237 MCSectionData &SD) {
1238 StringRef SectionName = Section.getSectionName();
1239 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1241 std::unique_ptr<MCDataFragment> CompressedFragment =
1242 getCompressedFragment(Layout, Fragments);
1244 // Leave the section as-is if the fragments could not be compressed.
1245 if (!CompressedFragment)
1248 // Update the fragment+offsets of any symbols referring to fragments in this
1249 // section to refer to the new fragment.
1250 auto I = DefiningSymbols.find(&SD);
1251 if (I != DefiningSymbols.end())
1252 UpdateSymbols(Layout, I->second, *CompressedFragment);
1254 // Invalidate the layout for the whole section since it will have new and
1255 // different fragments now.
1256 Layout.invalidateFragmentsFrom(&Fragments.front());
1259 // Complete the initialization of the new fragment
1260 CompressedFragment->setParent(&SD);
1261 CompressedFragment->setLayoutOrder(0);
1262 Fragments.push_back(CompressedFragment.release());
1264 // Rename from .debug_* to .zdebug_*
1265 Asm.getContext().renameELFSection(&Section,
1266 (".z" + SectionName.drop_front(1)).str());
1269 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1270 MCAsmLayout &Layout) {
1271 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1274 DefiningSymbolMap DefiningSymbols;
1276 for (MCSymbolData &SD : Asm.symbols())
1277 if (MCFragment *F = SD.getFragment())
1278 DefiningSymbols[F->getParent()].push_back(&SD);
1280 for (MCSectionData &SD : Asm) {
1281 const MCSectionELF &Section =
1282 static_cast<const MCSectionELF &>(SD.getSection());
1283 StringRef SectionName = Section.getSectionName();
1285 // Compressing debug_frame requires handling alignment fragments which is
1286 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1287 // for writing to arbitrary buffers) for little benefit.
1288 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1291 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1295 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm,
1296 const MCAsmLayout &Layout) {
1297 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1298 MCSectionData &RelSD = *it;
1299 const MCSectionELF &RelSection =
1300 static_cast<const MCSectionELF &>(RelSD.getSection());
1302 unsigned Type = RelSection.getType();
1303 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1306 const MCSectionELF *Section = RelSection.getAssociatedSection();
1307 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1308 RelSD.setAlignment(is64Bit() ? 8 : 4);
1310 MCDataFragment *F = new MCDataFragment(&RelSD);
1311 WriteRelocationsFragment(Asm, F, &SD);
1315 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1316 uint64_t Flags, uint64_t Address,
1317 uint64_t Offset, uint64_t Size,
1318 uint32_t Link, uint32_t Info,
1320 uint64_t EntrySize) {
1321 Write32(Name); // sh_name: index into string table
1322 Write32(Type); // sh_type
1323 WriteWord(Flags); // sh_flags
1324 WriteWord(Address); // sh_addr
1325 WriteWord(Offset); // sh_offset
1326 WriteWord(Size); // sh_size
1327 Write32(Link); // sh_link
1328 Write32(Info); // sh_info
1329 WriteWord(Alignment); // sh_addralign
1330 WriteWord(EntrySize); // sh_entsize
1333 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1335 const MCSectionData *SD) {
1336 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1338 // Sort the relocation entries. Most targets just sort by Offset, but some
1339 // (e.g., MIPS) have additional constraints.
1340 TargetObjectWriter->sortRelocs(Asm, Relocs);
1342 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1343 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1345 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1348 write(*F, Entry.Offset);
1349 if (TargetObjectWriter->isN64()) {
1350 write(*F, uint32_t(Index));
1352 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1353 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1354 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1355 write(*F, TargetObjectWriter->getRType(Entry.Type));
1357 struct ELF::Elf64_Rela ERE64;
1358 ERE64.setSymbolAndType(Index, Entry.Type);
1359 write(*F, ERE64.r_info);
1361 if (hasRelocationAddend())
1362 write(*F, Entry.Addend);
1364 write(*F, uint32_t(Entry.Offset));
1366 struct ELF::Elf32_Rela ERE32;
1367 ERE32.setSymbolAndType(Index, Entry.Type);
1368 write(*F, ERE32.r_info);
1370 if (hasRelocationAddend())
1371 write(*F, uint32_t(Entry.Addend));
1376 void ELFObjectWriter::createSectionHeaderStringTable(
1377 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1378 const MCSectionELF *ShstrtabSection = Sections[ShstrtabIndex - 1];
1380 Asm.getOrCreateSectionData(*ShstrtabSection);
1382 for (MCSectionData &SD : Asm) {
1383 const MCSectionELF &Section =
1384 static_cast<const MCSectionELF &>(SD.getSection());
1385 ShStrTabBuilder.add(Section.getSectionName());
1387 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1388 OS << ShStrTabBuilder.data();
1391 void ELFObjectWriter::CreateMetadataSections(
1392 MCAssembler &Asm, const MCAsmLayout &Layout,
1393 std::vector<const MCSectionELF *> &Sections) {
1394 MCContext &Ctx = Asm.getContext();
1397 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1399 const MCSectionELF *SymtabSection =
1400 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1402 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1403 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1404 SymbolTableIndex = Sections.size() + 1;
1405 Sections.push_back(SymtabSection);
1407 const MCSectionELF *StrtabSection;
1408 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1409 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1410 StrtabSD.setAlignment(1);
1411 StringTableIndex = Sections.size() + 1;
1412 Sections.push_back(StrtabSection);
1415 F = new MCDataFragment(&SymtabSD);
1416 WriteSymbolTable(F, Asm, Layout, Sections);
1418 F = new MCDataFragment(&StrtabSD);
1419 F->getContents().append(StrTabBuilder.data().begin(),
1420 StrTabBuilder.data().end());
1423 void ELFObjectWriter::createIndexedSections(
1424 MCAssembler &Asm, const MCAsmLayout &Layout, RevGroupMapTy &RevGroupMap,
1425 std::vector<const MCSectionELF *> &Sections,
1426 SectionIndexMapTy &SectionIndexMap) {
1427 MCContext &Ctx = Asm.getContext();
1429 const MCSectionELF *ShstrtabSection =
1430 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1431 Sections.push_back(ShstrtabSection);
1432 ShstrtabIndex = Sections.size();
1433 assert(ShstrtabIndex == 1);
1436 for (const MCSectionData &SD : Asm) {
1437 const MCSectionELF &Section =
1438 static_cast<const MCSectionELF &>(SD.getSection());
1439 if (!(Section.getFlags() & ELF::SHF_GROUP))
1442 const MCSymbol *SignatureSymbol = Section.getGroup();
1443 Asm.getOrCreateSymbolData(*SignatureSymbol);
1444 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1446 const MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1447 Sections.push_back(Group);
1448 GroupIdx = Sections.size();
1450 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1451 Data.setAlignment(4);
1452 MCDataFragment *F = new MCDataFragment(&Data);
1453 write(*F, uint32_t(ELF::GRP_COMDAT));
1457 computeIndexMap(Asm, Sections, SectionIndexMap, RevGroupMap);
1460 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1461 const SectionIndexMapTy &SectionIndexMap,
1462 uint32_t GroupSymbolIndex,
1463 uint64_t Offset, uint64_t Size,
1465 const MCSectionELF &Section) {
1466 uint64_t sh_link = 0;
1467 uint64_t sh_info = 0;
1469 switch(Section.getType()) {
1474 case ELF::SHT_DYNAMIC:
1475 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1479 case ELF::SHT_RELA: {
1480 sh_link = SymbolTableIndex;
1481 assert(sh_link && ".symtab not found");
1482 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1483 sh_info = SectionIndexMap.lookup(InfoSection);
1487 case ELF::SHT_SYMTAB:
1488 case ELF::SHT_DYNSYM:
1489 sh_link = StringTableIndex;
1490 sh_info = LastLocalSymbolIndex;
1493 case ELF::SHT_SYMTAB_SHNDX:
1494 sh_link = SymbolTableIndex;
1497 case ELF::SHT_GROUP:
1498 sh_link = SymbolTableIndex;
1499 sh_info = GroupSymbolIndex;
1503 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1504 Section.getType() == ELF::SHT_ARM_EXIDX)
1505 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1507 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1509 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1510 Alignment, Section.getEntrySize());
1513 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1514 return SD.getOrdinal() == ~UINT32_C(0) &&
1515 !SD.getSection().isVirtualSection();
1518 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1519 const MCAsmLayout &Layout,
1520 const MCSectionData &SD) {
1521 if (IsELFMetaDataSection(SD)) {
1522 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1524 const MCFragment &F = *i;
1525 assert(F.getKind() == MCFragment::FT_Data);
1526 WriteBytes(cast<MCDataFragment>(F).getContents());
1529 Asm.writeSectionData(&SD, Layout);
1533 void ELFObjectWriter::writeSectionHeader(
1534 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1535 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1536 const SectionOffsetsTy &SectionOffsets) {
1537 const unsigned NumSections = Asm.size();
1539 // Null section first.
1540 uint64_t FirstSectionSize =
1541 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1542 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1544 for (unsigned i = 0; i < NumSections; ++i) {
1545 const MCSectionELF &Section = *Sections[i];
1546 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1547 uint32_t GroupSymbolIndex;
1548 if (Section.getType() != ELF::SHT_GROUP)
1549 GroupSymbolIndex = 0;
1551 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section.getGroup());
1553 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
1554 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1555 ? Layout.getSectionAddressSize(&SD)
1556 : Offsets.second - Offsets.first;
1558 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1559 SD.getAlignment(), Section);
1563 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1564 const MCAsmLayout &Layout) {
1565 RevGroupMapTy RevGroupMap;
1566 SectionIndexMapTy SectionIndexMap;
1568 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1569 std::vector<const MCSectionELF *> Sections;
1570 createIndexedSections(Asm, Layout, RevGroupMap, Sections, SectionIndexMap);
1572 // Compute symbol table information.
1573 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1575 WriteRelocations(Asm, Layout);
1577 CreateMetadataSections(Asm, Layout, Sections);
1579 unsigned NumSections = Asm.size() + 1;
1580 SectionOffsetsTy SectionOffsets;
1582 // Write out the ELF header ...
1583 WriteHeader(Asm, NumSections + 1);
1585 // ... then the sections ...
1586 SectionOffsets.push_back(std::make_pair(0, 0));
1587 for (auto I = ++Sections.begin(), E = Sections.end(); I != E; ++I) {
1588 const MCSectionData &SD = Asm.getOrCreateSectionData(**I);
1589 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1590 WriteZeros(Padding);
1592 // Remember the offset into the file for this section.
1593 uint64_t SecStart = OS.tell();
1594 writeDataSectionData(Asm, Layout, SD);
1595 uint64_t SecEnd = OS.tell();
1596 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1600 uint64_t SecStart = OS.tell();
1601 createSectionHeaderStringTable(Asm, Sections);
1602 uint64_t SecEnd = OS.tell();
1603 SectionOffsets[0] = std::make_pair(SecStart, SecEnd);
1606 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1607 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1608 WriteZeros(Padding);
1610 const unsigned SectionHeaderOffset = OS.tell();
1612 // ... then the section header table ...
1613 writeSectionHeader(Sections, Asm, Layout, SectionIndexMap, SectionOffsets);
1616 uint64_t Val = SectionHeaderOffset;
1617 if (sys::IsLittleEndianHost != IsLittleEndian)
1618 sys::swapByteOrder(Val);
1619 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1620 offsetof(ELF::Elf64_Ehdr, e_shoff));
1622 uint32_t Val = SectionHeaderOffset;
1623 if (sys::IsLittleEndianHost != IsLittleEndian)
1624 sys::swapByteOrder(Val);
1625 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1626 offsetof(ELF::Elf32_Ehdr, e_shoff));
1630 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1631 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1632 bool InSet, bool IsPCRel) const {
1635 if (::isWeak(DataA))
1638 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1642 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1646 // It is invalid to replace a reference to a global in a comdat
1647 // with a reference to a local since out of comdat references
1648 // to a local are forbidden.
1649 // We could try to return false for more cases, like the reference
1650 // being in the same comdat or Sym being an alias to another global,
1651 // but it is not clear if it is worth the effort.
1652 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1655 const MCSymbol &Sym = SD.getSymbol();
1656 if (!Sym.isInSection())
1659 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1660 return Sec.getGroup();
1663 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1664 raw_pwrite_stream &OS,
1665 bool IsLittleEndian) {
1666 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);