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 {
75 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
76 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
77 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
78 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
79 bool Used, bool Renamed);
80 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
81 static bool IsELFMetaDataSection(const MCSectionData &SD);
83 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
84 const MCSectionData &SD);
86 /// Helper struct for containing some precomputed information on symbols.
87 struct ELFSymbolData {
88 MCSymbolData *SymbolData;
90 uint32_t SectionIndex;
93 // Support lexicographic sorting.
94 bool operator<(const ELFSymbolData &RHS) const {
95 unsigned LHSType = MCELF::GetType(*SymbolData);
96 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
97 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
99 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
101 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
102 return SectionIndex < RHS.SectionIndex;
103 return Name < RHS.Name;
107 /// The target specific ELF writer instance.
108 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
110 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
111 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
112 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
114 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
116 StringTableBuilder ShStrTabBuilder;
119 /// @name Symbol Table Data
122 StringTableBuilder StrTabBuilder;
123 std::vector<uint64_t> FileSymbolData;
124 std::vector<ELFSymbolData> LocalSymbolData;
125 std::vector<ELFSymbolData> ExternalSymbolData;
126 std::vector<ELFSymbolData> UndefinedSymbolData;
132 // This holds the symbol table index of the last local symbol.
133 unsigned LastLocalSymbolIndex;
134 // This holds the .strtab section index.
135 unsigned StringTableIndex;
136 // This holds the .symtab section index.
137 unsigned SymbolTableIndex;
139 unsigned ShstrtabIndex;
142 // TargetObjectWriter wrappers.
143 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
144 bool hasRelocationAddend() const {
145 return TargetObjectWriter->hasRelocationAddend();
147 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
148 bool IsPCRel) const {
149 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
153 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
155 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW),
158 void reset() override {
160 WeakrefUsedInReloc.clear();
163 ShStrTabBuilder.clear();
164 StrTabBuilder.clear();
165 FileSymbolData.clear();
166 LocalSymbolData.clear();
167 ExternalSymbolData.clear();
168 UndefinedSymbolData.clear();
169 MCObjectWriter::reset();
172 ~ELFObjectWriter() override;
174 void WriteWord(uint64_t W) {
181 template <typename T> void write(T Val) {
183 support::endian::Writer<support::little>(OS).write(Val);
185 support::endian::Writer<support::big>(OS).write(Val);
188 template <typename T> void write(MCDataFragment &F, T Value);
190 void writeHeader(const MCAssembler &Asm);
192 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
193 const MCAsmLayout &Layout);
195 // Start and end offset of each section
196 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
198 void WriteSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
199 std::vector<const MCSectionELF *> &Sections,
200 SectionOffsetsTy &SectionOffsets);
202 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
203 const MCSymbolRefExpr *RefA,
204 const MCSymbolData *SD, uint64_t C,
205 unsigned Type) const;
207 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
208 const MCFragment *Fragment, const MCFixup &Fixup,
209 MCValue Target, bool &IsPCRel,
210 uint64_t &FixedValue) override;
212 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
215 // Map from a signature symbol to the group section index
216 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
218 /// Compute the symbol table data
220 /// \param Asm - The assembler.
221 /// \param SectionIndexMap - Maps a section to its index.
222 /// \param RevGroupMap - Maps a signature symbol to the group section.
223 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
224 const SectionIndexMapTy &SectionIndexMap,
225 const RevGroupMapTy &RevGroupMap);
227 void maybeAddToGroup(MCAssembler &Asm,
228 ArrayRef<const MCSectionELF *> Sections,
229 const RevGroupMapTy &RevGroupMap,
230 const MCSectionELF &Section, unsigned Index);
232 void computeIndexMap(MCAssembler &Asm,
233 std::vector<const MCSectionELF *> &Sections,
234 SectionIndexMapTy &SectionIndexMap,
235 const RevGroupMapTy &RevGroupMap);
237 void createRelocationSection(MCAssembler &Asm, const MCSectionData &SD);
239 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
241 void WriteRelocations(MCAssembler &Asm, const MCAsmLayout &Layout);
244 createSectionHeaderStringTable(MCAssembler &Asm,
245 std::vector<const MCSectionELF *> &Sections);
246 void createStringTable(MCAssembler &Asm,
247 std::vector<const MCSectionELF *> &Sections);
249 // Create the sections that show up in the symbol table. Currently
250 // those are the .note.GNU-stack section and the group sections.
251 void createIndexedSections(MCAssembler &Asm, const MCAsmLayout &Layout,
252 RevGroupMapTy &RevGroupMap,
253 std::vector<const MCSectionELF *> &Sections,
254 SectionIndexMapTy &SectionIndexMap);
256 void ExecutePostLayoutBinding(MCAssembler &Asm,
257 const MCAsmLayout &Layout) override;
259 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
260 MCAssembler &Asm, const MCAsmLayout &Layout,
261 const SectionIndexMapTy &SectionIndexMap,
262 const SectionOffsetsTy &SectionOffsets);
264 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
265 uint64_t Address, uint64_t Offset,
266 uint64_t Size, uint32_t Link, uint32_t Info,
267 uint64_t Alignment, uint64_t EntrySize);
269 void WriteRelocationsFragment(const MCAssembler &Asm,
271 const MCSectionData *SD);
274 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
275 const MCSymbolData &DataA,
276 const MCFragment &FB,
278 bool IsPCRel) const override;
280 bool isWeak(const MCSymbolData &SD) const override;
282 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
283 void writeSection(MCAssembler &Asm,
284 const SectionIndexMapTy &SectionIndexMap,
285 uint32_t GroupSymbolIndex,
286 uint64_t Offset, uint64_t Size, uint64_t Alignment,
287 const MCSectionELF &Section);
291 template <typename T> void ELFObjectWriter::write(MCDataFragment &F, T Val) {
293 Val = support::endian::byte_swap<T, support::little>(Val);
295 Val = support::endian::byte_swap<T, support::big>(Val);
296 const char *Start = (const char *)&Val;
297 F.getContents().append(Start, Start + sizeof(T));
300 void SymbolTableWriter::createSymtabShndx() {
301 if (!ShndxIndexes.empty())
304 ShndxIndexes.resize(NumWritten);
307 template <typename T> void SymbolTableWriter::write(T Value) {
308 EWriter.write(Value);
311 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
312 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
314 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
315 uint64_t size, uint8_t other,
316 uint32_t shndx, bool Reserved) {
317 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
322 if (!ShndxIndexes.empty()) {
324 ShndxIndexes.push_back(shndx);
326 ShndxIndexes.push_back(0);
329 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
332 write(name); // st_name
333 write(info); // st_info
334 write(other); // st_other
335 write(Index); // st_shndx
336 write(value); // st_value
337 write(size); // st_size
339 write(name); // st_name
340 write(uint32_t(value)); // st_value
341 write(uint32_t(size)); // st_size
342 write(info); // st_info
343 write(other); // st_other
344 write(Index); // st_shndx
350 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
351 const MCFixupKindInfo &FKI =
352 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
354 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
357 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
361 case MCSymbolRefExpr::VK_GOT:
362 case MCSymbolRefExpr::VK_PLT:
363 case MCSymbolRefExpr::VK_GOTPCREL:
364 case MCSymbolRefExpr::VK_GOTOFF:
365 case MCSymbolRefExpr::VK_TPOFF:
366 case MCSymbolRefExpr::VK_TLSGD:
367 case MCSymbolRefExpr::VK_GOTTPOFF:
368 case MCSymbolRefExpr::VK_INDNTPOFF:
369 case MCSymbolRefExpr::VK_NTPOFF:
370 case MCSymbolRefExpr::VK_GOTNTPOFF:
371 case MCSymbolRefExpr::VK_TLSLDM:
372 case MCSymbolRefExpr::VK_DTPOFF:
373 case MCSymbolRefExpr::VK_TLSLD:
378 ELFObjectWriter::~ELFObjectWriter()
381 // Emit the ELF header.
382 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
388 // emitWord method behaves differently for ELF32 and ELF64, writing
389 // 4 bytes in the former and 8 in the latter.
391 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
393 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
396 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
398 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
400 Write8(TargetObjectWriter->getOSABI());
401 Write8(0); // e_ident[EI_ABIVERSION]
403 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
405 Write16(ELF::ET_REL); // e_type
407 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
409 Write32(ELF::EV_CURRENT); // e_version
410 WriteWord(0); // e_entry, no entry point in .o file
411 WriteWord(0); // e_phoff, no program header for .o
412 WriteWord(0); // e_shoff = sec hdr table off in bytes
414 // e_flags = whatever the target wants
415 Write32(Asm.getELFHeaderEFlags());
417 // e_ehsize = ELF header size
418 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
420 Write16(0); // e_phentsize = prog header entry size
421 Write16(0); // e_phnum = # prog header entries = 0
423 // e_shentsize = Section header entry size
424 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
426 // e_shnum = # of section header ents
429 // e_shstrndx = Section # of '.shstrtab'
430 assert(ShstrtabIndex < ELF::SHN_LORESERVE);
431 Write16(ShstrtabIndex);
434 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
435 const MCAsmLayout &Layout) {
436 if (Data.isCommon() && Data.isExternal())
437 return Data.getCommonAlignment();
440 if (!Layout.getSymbolOffset(&Data, Res))
443 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
449 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
450 const MCAsmLayout &Layout) {
451 // The presence of symbol versions causes undefined symbols and
452 // versions declared with @@@ to be renamed.
454 for (MCSymbolData &OriginalData : Asm.symbols()) {
455 const MCSymbol &Alias = OriginalData.getSymbol();
458 if (!Alias.isVariable())
460 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
463 const MCSymbol &Symbol = Ref->getSymbol();
464 MCSymbolData &SD = Asm.getSymbolData(Symbol);
466 StringRef AliasName = Alias.getName();
467 size_t Pos = AliasName.find('@');
468 if (Pos == StringRef::npos)
471 // Aliases defined with .symvar copy the binding from the symbol they alias.
472 // This is the first place we are able to copy this information.
473 OriginalData.setExternal(SD.isExternal());
474 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
476 StringRef Rest = AliasName.substr(Pos);
477 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
480 // FIXME: produce a better error message.
481 if (Symbol.isUndefined() && Rest.startswith("@@") &&
482 !Rest.startswith("@@@"))
483 report_fatal_error("A @@ version cannot be undefined");
485 Renames.insert(std::make_pair(&Symbol, &Alias));
489 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
490 uint8_t Type = newType;
492 // Propagation rules:
493 // IFUNC > FUNC > OBJECT > NOTYPE
494 // TLS_OBJECT > OBJECT > NOTYPE
496 // dont let the new type degrade the old type
500 case ELF::STT_GNU_IFUNC:
501 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
502 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
503 Type = ELF::STT_GNU_IFUNC;
506 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
507 Type == ELF::STT_TLS)
508 Type = ELF::STT_FUNC;
510 case ELF::STT_OBJECT:
511 if (Type == ELF::STT_NOTYPE)
512 Type = ELF::STT_OBJECT;
515 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
516 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
524 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
525 const MCAsmLayout &Layout) {
526 MCSymbolData &OrigData = *MSD.SymbolData;
527 assert((!OrigData.getFragment() ||
528 (&OrigData.getFragment()->getParent()->getSection() ==
529 &OrigData.getSymbol().getSection())) &&
530 "The symbol's section doesn't match the fragment's symbol");
531 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
533 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
535 bool IsReserved = !Base || OrigData.isCommon();
537 // Binding and Type share the same byte as upper and lower nibbles
538 uint8_t Binding = MCELF::GetBinding(OrigData);
539 uint8_t Type = MCELF::GetType(OrigData);
540 MCSymbolData *BaseSD = nullptr;
542 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
543 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
545 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
547 // Other and Visibility share the same byte with Visibility using the lower
549 uint8_t Visibility = MCELF::GetVisibility(OrigData);
550 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
553 uint64_t Value = SymbolValue(OrigData, Layout);
556 const MCExpr *ESize = OrigData.getSize();
558 ESize = BaseSD->getSize();
562 if (!ESize->evaluateKnownAbsolute(Res, Layout))
563 report_fatal_error("Size expression must be absolute.");
567 // Write out the symbol table entry
568 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
569 MSD.SectionIndex, IsReserved);
572 void ELFObjectWriter::WriteSymbolTable(
573 MCAssembler &Asm, const MCAsmLayout &Layout,
574 std::vector<const MCSectionELF *> &Sections,
575 SectionOffsetsTy &SectionOffsets) {
577 MCContext &Ctx = Asm.getContext();
579 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
582 const MCSectionELF *SymtabSection =
583 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
584 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
585 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
586 SymbolTableIndex = Sections.size() + 1;
587 Sections.push_back(SymtabSection);
589 // The string table must be emitted first because we need the index
590 // into the string table for all the symbol names.
592 SymbolTableWriter Writer(*this, is64Bit());
594 uint64_t Padding = OffsetToAlignment(OS.tell(), SymtabSD.getAlignment());
597 uint64_t SecStart = OS.tell();
599 // The first entry is the undefined symbol entry.
600 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
602 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
603 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
604 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
607 // Write the symbol table entries.
608 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
610 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
611 ELFSymbolData &MSD = LocalSymbolData[i];
612 WriteSymbol(Writer, MSD, Layout);
615 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
616 ELFSymbolData &MSD = ExternalSymbolData[i];
617 MCSymbolData &Data = *MSD.SymbolData;
618 assert(((Data.getFlags() & ELF_STB_Global) ||
619 (Data.getFlags() & ELF_STB_Weak)) &&
620 "External symbol requires STB_GLOBAL or STB_WEAK flag");
621 WriteSymbol(Writer, MSD, Layout);
622 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
623 LastLocalSymbolIndex++;
626 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
627 ELFSymbolData &MSD = UndefinedSymbolData[i];
628 MCSymbolData &Data = *MSD.SymbolData;
629 WriteSymbol(Writer, MSD, Layout);
630 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
631 LastLocalSymbolIndex++;
634 uint64_t SecEnd = OS.tell();
635 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
637 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
638 if (ShndxIndexes.empty())
641 SecStart = OS.tell();
642 const MCSectionELF *SymtabShndxSection =
643 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
644 Sections.push_back(SymtabShndxSection);
645 MCSectionData *SymtabShndxSD =
646 &Asm.getOrCreateSectionData(*SymtabShndxSection);
647 SymtabShndxSD->setAlignment(4);
648 for (uint32_t Index : ShndxIndexes)
651 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
654 // It is always valid to create a relocation with a symbol. It is preferable
655 // to use a relocation with a section if that is possible. Using the section
656 // allows us to omit some local symbols from the symbol table.
657 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
658 const MCSymbolRefExpr *RefA,
659 const MCSymbolData *SD,
661 unsigned Type) const {
662 // A PCRel relocation to an absolute value has no symbol (or section). We
663 // represent that with a relocation to a null section.
667 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
671 // The .odp creation emits a relocation against the symbol ".TOC." which
672 // create a R_PPC64_TOC relocation. However the relocation symbol name
673 // in final object creation should be NULL, since the symbol does not
674 // really exist, it is just the reference to TOC base for the current
675 // object file. Since the symbol is undefined, returning false results
676 // in a relocation with a null section which is the desired result.
677 case MCSymbolRefExpr::VK_PPC_TOCBASE:
680 // These VariantKind cause the relocation to refer to something other than
681 // the symbol itself, like a linker generated table. Since the address of
682 // symbol is not relevant, we cannot replace the symbol with the
683 // section and patch the difference in the addend.
684 case MCSymbolRefExpr::VK_GOT:
685 case MCSymbolRefExpr::VK_PLT:
686 case MCSymbolRefExpr::VK_GOTPCREL:
687 case MCSymbolRefExpr::VK_Mips_GOT:
688 case MCSymbolRefExpr::VK_PPC_GOT_LO:
689 case MCSymbolRefExpr::VK_PPC_GOT_HI:
690 case MCSymbolRefExpr::VK_PPC_GOT_HA:
694 // An undefined symbol is not in any section, so the relocation has to point
695 // to the symbol itself.
696 const MCSymbol &Sym = SD->getSymbol();
697 if (Sym.isUndefined())
700 unsigned Binding = MCELF::GetBinding(*SD);
703 llvm_unreachable("Invalid Binding");
707 // If the symbol is weak, it might be overridden by a symbol in another
708 // file. The relocation has to point to the symbol so that the linker
711 case ELF::STB_GLOBAL:
712 // Global ELF symbols can be preempted by the dynamic linker. The relocation
713 // has to point to the symbol for a reason analogous to the STB_WEAK case.
717 // If a relocation points to a mergeable section, we have to be careful.
718 // If the offset is zero, a relocation with the section will encode the
719 // same information. With a non-zero offset, the situation is different.
720 // For example, a relocation can point 42 bytes past the end of a string.
721 // If we change such a relocation to use the section, the linker would think
722 // that it pointed to another string and subtracting 42 at runtime will
723 // produce the wrong value.
724 auto &Sec = cast<MCSectionELF>(Sym.getSection());
725 unsigned Flags = Sec.getFlags();
726 if (Flags & ELF::SHF_MERGE) {
730 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
731 // only handle section relocations to mergeable sections if using RELA.
732 if (!hasRelocationAddend())
736 // Most TLS relocations use a got, so they need the symbol. Even those that
737 // are just an offset (@tpoff), require a symbol in gold versions before
738 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
739 // http://sourceware.org/PR16773.
740 if (Flags & ELF::SHF_TLS)
743 // If the symbol is a thumb function the final relocation must set the lowest
744 // bit. With a symbol that is done by just having the symbol have that bit
745 // set, so we would lose the bit if we relocated with the section.
746 // FIXME: We could use the section but add the bit to the relocation value.
747 if (Asm.isThumbFunc(&Sym))
750 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
755 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
756 const MCSymbol &Sym = Ref.getSymbol();
758 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
761 if (!Sym.isVariable())
764 const MCExpr *Expr = Sym.getVariableValue();
765 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
769 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
770 return &Inner->getSymbol();
774 // True if the assembler knows nothing about the final value of the symbol.
775 // This doesn't cover the comdat issues, since in those cases the assembler
776 // can at least know that all symbols in the section will move together.
777 static bool isWeak(const MCSymbolData &D) {
778 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
781 switch (MCELF::GetBinding(D)) {
783 llvm_unreachable("Unknown binding");
786 case ELF::STB_GLOBAL:
789 case ELF::STB_GNU_UNIQUE:
794 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
795 const MCAsmLayout &Layout,
796 const MCFragment *Fragment,
797 const MCFixup &Fixup, MCValue Target,
798 bool &IsPCRel, uint64_t &FixedValue) {
799 const MCSectionData *FixupSection = Fragment->getParent();
800 uint64_t C = Target.getConstant();
801 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
803 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
804 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
805 "Should not have constructed this");
807 // Let A, B and C being the components of Target and R be the location of
808 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
809 // If it is pcrel, we want to compute (A - B + C - R).
811 // In general, ELF has no relocations for -B. It can only represent (A + C)
812 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
813 // replace B to implement it: (A - R - K + C)
815 Asm.getContext().FatalError(
817 "No relocation available to represent this relative expression");
819 const MCSymbol &SymB = RefB->getSymbol();
821 if (SymB.isUndefined())
822 Asm.getContext().FatalError(
824 Twine("symbol '") + SymB.getName() +
825 "' can not be undefined in a subtraction expression");
827 assert(!SymB.isAbsolute() && "Should have been folded");
828 const MCSection &SecB = SymB.getSection();
829 if (&SecB != &FixupSection->getSection())
830 Asm.getContext().FatalError(
831 Fixup.getLoc(), "Cannot represent a difference across sections");
833 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
835 Asm.getContext().FatalError(
836 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
838 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
839 uint64_t K = SymBOffset - FixupOffset;
844 // We either rejected the fixup or folded B into C at this point.
845 const MCSymbolRefExpr *RefA = Target.getSymA();
846 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
847 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
849 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
850 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
851 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
852 C += Layout.getSymbolOffset(SymAD);
855 if (hasRelocationAddend()) {
862 // FIXME: What is this!?!?
863 MCSymbolRefExpr::VariantKind Modifier =
864 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
865 if (RelocNeedsGOT(Modifier))
868 if (!RelocateWithSymbol) {
869 const MCSection *SecA =
870 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
871 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
872 MCSymbol *SectionSymbol =
873 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
875 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
876 Relocations[FixupSection].push_back(Rec);
881 if (const MCSymbol *R = Renames.lookup(SymA))
884 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
885 WeakrefUsedInReloc.insert(WeakRef);
887 UsedInReloc.insert(SymA);
889 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
890 Relocations[FixupSection].push_back(Rec);
896 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
898 const MCSymbolData &SD = Asm.getSymbolData(*S);
899 return SD.getIndex();
902 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
903 const MCSymbolData &Data, bool Used,
905 const MCSymbol &Symbol = Data.getSymbol();
906 if (Symbol.isVariable()) {
907 const MCExpr *Expr = Symbol.getVariableValue();
908 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
909 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
920 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
923 if (Symbol.isVariable()) {
924 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
925 if (Base && Base->isUndefined())
929 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
930 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
933 if (Symbol.isTemporary())
939 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
940 if (Data.isExternal())
943 const MCSymbol &Symbol = Data.getSymbol();
944 if (Symbol.isDefined())
953 void ELFObjectWriter::maybeAddToGroup(MCAssembler &Asm,
954 ArrayRef<const MCSectionELF *> Sections,
955 const RevGroupMapTy &RevGroupMap,
956 const MCSectionELF &Section,
958 const MCSymbol *Sym = Section.getGroup();
961 const MCSectionELF *Group = Sections[RevGroupMap.lookup(Sym) - 1];
962 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
963 // FIXME: we could use the previous fragment
964 MCDataFragment *F = new MCDataFragment(&Data);
968 void ELFObjectWriter::computeIndexMap(
969 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections,
970 SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap) {
971 for (const MCSectionData &SD : Asm) {
972 const MCSectionELF &Section =
973 static_cast<const MCSectionELF &>(SD.getSection());
974 if (Section.getType() == ELF::SHT_GROUP)
976 Sections.push_back(&Section);
977 unsigned Index = Sections.size();
978 SectionIndexMap[&Section] = Index;
979 maybeAddToGroup(Asm, Sections, RevGroupMap, Section, Index);
980 createRelocationSection(Asm, SD);
984 void ELFObjectWriter::computeSymbolTable(
985 MCAssembler &Asm, const MCAsmLayout &Layout,
986 const SectionIndexMapTy &SectionIndexMap,
987 const RevGroupMapTy &RevGroupMap) {
988 // FIXME: Is this the correct place to do this?
989 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
991 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
992 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
993 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
994 Data.setExternal(true);
995 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
998 // Add the data for the symbols.
999 for (MCSymbolData &SD : Asm.symbols()) {
1000 const MCSymbol &Symbol = SD.getSymbol();
1002 bool Used = UsedInReloc.count(&Symbol);
1003 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1004 bool isSignature = RevGroupMap.count(&Symbol);
1006 if (!isInSymtab(Layout, SD,
1007 Used || WeakrefUsed || isSignature,
1008 Renames.count(&Symbol)))
1012 MSD.SymbolData = &SD;
1013 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1015 // Undefined symbols are global, but this is the first place we
1016 // are able to set it.
1017 bool Local = isLocal(SD, Used);
1018 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1020 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1021 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1022 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1026 MSD.SectionIndex = ELF::SHN_ABS;
1027 } else if (SD.isCommon()) {
1029 MSD.SectionIndex = ELF::SHN_COMMON;
1030 } else if (BaseSymbol->isUndefined()) {
1031 if (isSignature && !Used)
1032 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
1034 MSD.SectionIndex = ELF::SHN_UNDEF;
1035 if (!Used && WeakrefUsed)
1036 MCELF::SetBinding(SD, ELF::STB_WEAK);
1038 const MCSectionELF &Section =
1039 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1040 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1041 assert(MSD.SectionIndex && "Invalid section index!");
1044 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1047 // FIXME: All name handling should be done before we get to the writer,
1048 // including dealing with GNU-style version suffixes. Fixing this isn't
1051 // We thus have to be careful to not perform the symbol version replacement
1054 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1055 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1056 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1057 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1058 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1059 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1060 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1061 // "__imp_?" or "__imp_@?".
1063 // It would have been interesting to perform the MS mangling prefix check
1064 // only when the target triple is of the form *-pc-windows-elf. But, it
1065 // seems that this information is not easily accessible from the
1067 StringRef Name = Symbol.getName();
1068 if (!Name.startswith("?") && !Name.startswith("@?") &&
1069 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1070 // This symbol isn't following the MSVC C++ name mangling convention. We
1071 // can thus safely interpret the @@@ in symbol names as specifying symbol
1073 SmallString<32> Buf;
1074 size_t Pos = Name.find("@@@");
1075 if (Pos != StringRef::npos) {
1076 Buf += Name.substr(0, Pos);
1077 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1078 Buf += Name.substr(Pos + Skip);
1083 // Sections have their own string table
1084 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1085 MSD.Name = StrTabBuilder.add(Name);
1087 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1088 UndefinedSymbolData.push_back(MSD);
1090 LocalSymbolData.push_back(MSD);
1092 ExternalSymbolData.push_back(MSD);
1095 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1096 StrTabBuilder.add(*i);
1098 StrTabBuilder.finalize(StringTableBuilder::ELF);
1100 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1101 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1103 for (ELFSymbolData &MSD : LocalSymbolData)
1104 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1106 : StrTabBuilder.getOffset(MSD.Name);
1107 for (ELFSymbolData &MSD : ExternalSymbolData)
1108 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1109 for (ELFSymbolData& MSD : UndefinedSymbolData)
1110 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1112 // Symbols are required to be in lexicographic order.
1113 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1114 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1115 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1117 // Set the symbol indices. Local symbols must come before all other
1118 // symbols with non-local bindings.
1119 unsigned Index = FileSymbolData.size() + 1;
1120 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1121 LocalSymbolData[i].SymbolData->setIndex(Index++);
1123 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1124 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1125 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1126 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1129 void ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1130 const MCSectionData &SD) {
1131 if (Relocations[&SD].empty())
1134 MCContext &Ctx = Asm.getContext();
1135 const MCSectionELF &Section =
1136 static_cast<const MCSectionELF &>(SD.getSection());
1138 const StringRef SectionName = Section.getSectionName();
1139 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1140 RelaSectionName += SectionName;
1143 if (hasRelocationAddend())
1144 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1146 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1149 if (Section.getFlags() & ELF::SHF_GROUP)
1150 Flags = ELF::SHF_GROUP;
1152 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1153 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1154 Flags, EntrySize, Section.getGroup(), &Section);
1155 Asm.getOrCreateSectionData(*RelaSection);
1158 static SmallVector<char, 128>
1159 getUncompressedData(const MCAsmLayout &Layout,
1160 MCSectionData::FragmentListType &Fragments) {
1161 SmallVector<char, 128> UncompressedData;
1162 for (const MCFragment &F : Fragments) {
1163 const SmallVectorImpl<char> *Contents;
1164 switch (F.getKind()) {
1165 case MCFragment::FT_Data:
1166 Contents = &cast<MCDataFragment>(F).getContents();
1168 case MCFragment::FT_Dwarf:
1169 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1171 case MCFragment::FT_DwarfFrame:
1172 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1176 "Not expecting any other fragment types in a debug_* section");
1178 UncompressedData.append(Contents->begin(), Contents->end());
1180 return UncompressedData;
1183 // Include the debug info compression header:
1184 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1185 // useful for consumers to preallocate a buffer to decompress into.
1187 prependCompressionHeader(uint64_t Size,
1188 SmallVectorImpl<char> &CompressedContents) {
1189 const StringRef Magic = "ZLIB";
1190 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1192 if (sys::IsLittleEndianHost)
1193 sys::swapByteOrder(Size);
1194 CompressedContents.insert(CompressedContents.begin(),
1195 Magic.size() + sizeof(Size), 0);
1196 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1197 std::copy(reinterpret_cast<char *>(&Size),
1198 reinterpret_cast<char *>(&Size + 1),
1199 CompressedContents.begin() + Magic.size());
1203 // Return a single fragment containing the compressed contents of the whole
1204 // section. Null if the section was not compressed for any reason.
1205 static std::unique_ptr<MCDataFragment>
1206 getCompressedFragment(const MCAsmLayout &Layout,
1207 MCSectionData::FragmentListType &Fragments) {
1208 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1210 // Gather the uncompressed data from all the fragments, recording the
1211 // alignment fragment, if seen, and any fixups.
1212 SmallVector<char, 128> UncompressedData =
1213 getUncompressedData(Layout, Fragments);
1215 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1217 zlib::Status Success = zlib::compress(
1218 StringRef(UncompressedData.data(), UncompressedData.size()),
1219 CompressedContents);
1220 if (Success != zlib::StatusOK)
1223 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1226 return CompressedFragment;
1229 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1232 static void UpdateSymbols(const MCAsmLayout &Layout,
1233 const std::vector<MCSymbolData *> &Symbols,
1234 MCFragment &NewFragment) {
1235 for (MCSymbolData *Sym : Symbols) {
1236 Sym->setOffset(Sym->getOffset() +
1237 Layout.getFragmentOffset(Sym->getFragment()));
1238 Sym->setFragment(&NewFragment);
1242 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1243 const DefiningSymbolMap &DefiningSymbols,
1244 const MCSectionELF &Section,
1245 MCSectionData &SD) {
1246 StringRef SectionName = Section.getSectionName();
1247 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1249 std::unique_ptr<MCDataFragment> CompressedFragment =
1250 getCompressedFragment(Layout, Fragments);
1252 // Leave the section as-is if the fragments could not be compressed.
1253 if (!CompressedFragment)
1256 // Update the fragment+offsets of any symbols referring to fragments in this
1257 // section to refer to the new fragment.
1258 auto I = DefiningSymbols.find(&SD);
1259 if (I != DefiningSymbols.end())
1260 UpdateSymbols(Layout, I->second, *CompressedFragment);
1262 // Invalidate the layout for the whole section since it will have new and
1263 // different fragments now.
1264 Layout.invalidateFragmentsFrom(&Fragments.front());
1267 // Complete the initialization of the new fragment
1268 CompressedFragment->setParent(&SD);
1269 CompressedFragment->setLayoutOrder(0);
1270 Fragments.push_back(CompressedFragment.release());
1272 // Rename from .debug_* to .zdebug_*
1273 Asm.getContext().renameELFSection(&Section,
1274 (".z" + SectionName.drop_front(1)).str());
1277 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1278 MCAsmLayout &Layout) {
1279 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1282 DefiningSymbolMap DefiningSymbols;
1284 for (MCSymbolData &SD : Asm.symbols())
1285 if (MCFragment *F = SD.getFragment())
1286 DefiningSymbols[F->getParent()].push_back(&SD);
1288 for (MCSectionData &SD : Asm) {
1289 const MCSectionELF &Section =
1290 static_cast<const MCSectionELF &>(SD.getSection());
1291 StringRef SectionName = Section.getSectionName();
1293 // Compressing debug_frame requires handling alignment fragments which is
1294 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1295 // for writing to arbitrary buffers) for little benefit.
1296 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1299 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1303 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm,
1304 const MCAsmLayout &Layout) {
1305 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1306 MCSectionData &RelSD = *it;
1307 const MCSectionELF &RelSection =
1308 static_cast<const MCSectionELF &>(RelSD.getSection());
1310 unsigned Type = RelSection.getType();
1311 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1314 const MCSectionELF *Section = RelSection.getAssociatedSection();
1315 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1316 RelSD.setAlignment(is64Bit() ? 8 : 4);
1318 MCDataFragment *F = new MCDataFragment(&RelSD);
1319 WriteRelocationsFragment(Asm, F, &SD);
1323 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1324 uint64_t Flags, uint64_t Address,
1325 uint64_t Offset, uint64_t Size,
1326 uint32_t Link, uint32_t Info,
1328 uint64_t EntrySize) {
1329 Write32(Name); // sh_name: index into string table
1330 Write32(Type); // sh_type
1331 WriteWord(Flags); // sh_flags
1332 WriteWord(Address); // sh_addr
1333 WriteWord(Offset); // sh_offset
1334 WriteWord(Size); // sh_size
1335 Write32(Link); // sh_link
1336 Write32(Info); // sh_info
1337 WriteWord(Alignment); // sh_addralign
1338 WriteWord(EntrySize); // sh_entsize
1341 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1343 const MCSectionData *SD) {
1344 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1346 // Sort the relocation entries. Most targets just sort by Offset, but some
1347 // (e.g., MIPS) have additional constraints.
1348 TargetObjectWriter->sortRelocs(Asm, Relocs);
1350 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1351 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1353 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1356 write(*F, Entry.Offset);
1357 if (TargetObjectWriter->isN64()) {
1358 write(*F, uint32_t(Index));
1360 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1361 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1362 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1363 write(*F, TargetObjectWriter->getRType(Entry.Type));
1365 struct ELF::Elf64_Rela ERE64;
1366 ERE64.setSymbolAndType(Index, Entry.Type);
1367 write(*F, ERE64.r_info);
1369 if (hasRelocationAddend())
1370 write(*F, Entry.Addend);
1372 write(*F, uint32_t(Entry.Offset));
1374 struct ELF::Elf32_Rela ERE32;
1375 ERE32.setSymbolAndType(Index, Entry.Type);
1376 write(*F, ERE32.r_info);
1378 if (hasRelocationAddend())
1379 write(*F, uint32_t(Entry.Addend));
1384 void ELFObjectWriter::createSectionHeaderStringTable(
1385 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1386 const MCSectionELF *ShstrtabSection = Sections[ShstrtabIndex - 1];
1388 Asm.getOrCreateSectionData(*ShstrtabSection);
1390 for (MCSectionData &SD : Asm) {
1391 const MCSectionELF &Section =
1392 static_cast<const MCSectionELF &>(SD.getSection());
1393 ShStrTabBuilder.add(Section.getSectionName());
1395 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1396 OS << ShStrTabBuilder.data();
1399 void ELFObjectWriter::createStringTable(
1400 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1401 MCContext &Ctx = Asm.getContext();
1402 const MCSectionELF *StrtabSection =
1403 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1404 Asm.getOrCreateSectionData(*StrtabSection);
1405 Sections.push_back(StrtabSection);
1406 StringTableIndex = Sections.size();
1407 OS << StrTabBuilder.data();
1410 void ELFObjectWriter::createIndexedSections(
1411 MCAssembler &Asm, const MCAsmLayout &Layout, RevGroupMapTy &RevGroupMap,
1412 std::vector<const MCSectionELF *> &Sections,
1413 SectionIndexMapTy &SectionIndexMap) {
1414 MCContext &Ctx = Asm.getContext();
1416 const MCSectionELF *ShstrtabSection =
1417 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1418 Sections.push_back(ShstrtabSection);
1419 ShstrtabIndex = Sections.size();
1420 assert(ShstrtabIndex == 1);
1423 for (const MCSectionData &SD : Asm) {
1424 const MCSectionELF &Section =
1425 static_cast<const MCSectionELF &>(SD.getSection());
1426 if (!(Section.getFlags() & ELF::SHF_GROUP))
1429 const MCSymbol *SignatureSymbol = Section.getGroup();
1430 Asm.getOrCreateSymbolData(*SignatureSymbol);
1431 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1433 const MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1434 Sections.push_back(Group);
1435 GroupIdx = Sections.size();
1437 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1438 Data.setAlignment(4);
1439 MCDataFragment *F = new MCDataFragment(&Data);
1440 write(*F, uint32_t(ELF::GRP_COMDAT));
1444 computeIndexMap(Asm, Sections, SectionIndexMap, RevGroupMap);
1447 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1448 const SectionIndexMapTy &SectionIndexMap,
1449 uint32_t GroupSymbolIndex,
1450 uint64_t Offset, uint64_t Size,
1452 const MCSectionELF &Section) {
1453 uint64_t sh_link = 0;
1454 uint64_t sh_info = 0;
1456 switch(Section.getType()) {
1461 case ELF::SHT_DYNAMIC:
1462 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1466 case ELF::SHT_RELA: {
1467 sh_link = SymbolTableIndex;
1468 assert(sh_link && ".symtab not found");
1469 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1470 sh_info = SectionIndexMap.lookup(InfoSection);
1474 case ELF::SHT_SYMTAB:
1475 case ELF::SHT_DYNSYM:
1476 sh_link = StringTableIndex;
1477 sh_info = LastLocalSymbolIndex;
1480 case ELF::SHT_SYMTAB_SHNDX:
1481 sh_link = SymbolTableIndex;
1484 case ELF::SHT_GROUP:
1485 sh_link = SymbolTableIndex;
1486 sh_info = GroupSymbolIndex;
1490 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1491 Section.getType() == ELF::SHT_ARM_EXIDX)
1492 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1494 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1496 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1497 Alignment, Section.getEntrySize());
1500 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1501 return SD.getOrdinal() == ~UINT32_C(0) &&
1502 !SD.getSection().isVirtualSection();
1505 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1506 const MCAsmLayout &Layout,
1507 const MCSectionData &SD) {
1508 if (IsELFMetaDataSection(SD)) {
1509 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1511 const MCFragment &F = *i;
1512 assert(F.getKind() == MCFragment::FT_Data);
1513 WriteBytes(cast<MCDataFragment>(F).getContents());
1516 Asm.writeSectionData(&SD, Layout);
1520 void ELFObjectWriter::writeSectionHeader(
1521 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1522 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1523 const SectionOffsetsTy &SectionOffsets) {
1524 const unsigned NumSections = Asm.size();
1526 // Null section first.
1527 uint64_t FirstSectionSize =
1528 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1529 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1531 for (unsigned i = 0; i < NumSections; ++i) {
1532 const MCSectionELF &Section = *Sections[i];
1533 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1534 uint32_t GroupSymbolIndex;
1535 if (Section.getType() != ELF::SHT_GROUP)
1536 GroupSymbolIndex = 0;
1538 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section.getGroup());
1540 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
1541 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1542 ? Layout.getSectionAddressSize(&SD)
1543 : Offsets.second - Offsets.first;
1545 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1546 SD.getAlignment(), Section);
1550 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1551 const MCAsmLayout &Layout) {
1552 RevGroupMapTy RevGroupMap;
1553 SectionIndexMapTy SectionIndexMap;
1555 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1556 std::vector<const MCSectionELF *> Sections;
1557 createIndexedSections(Asm, Layout, RevGroupMap, Sections, SectionIndexMap);
1559 // Compute symbol table information.
1560 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1562 WriteRelocations(Asm, Layout);
1565 SectionOffsetsTy SectionOffsets;
1567 // Write out the ELF header ...
1570 // ... then the sections ...
1571 SectionOffsets.push_back(std::make_pair(0, 0));
1572 for (auto I = ++Sections.begin(), E = Sections.end(); I != E; ++I) {
1573 const MCSectionData &SD = Asm.getOrCreateSectionData(**I);
1574 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1575 WriteZeros(Padding);
1577 // Remember the offset into the file for this section.
1578 uint64_t SecStart = OS.tell();
1579 writeDataSectionData(Asm, Layout, SD);
1580 uint64_t SecEnd = OS.tell();
1581 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1584 WriteSymbolTable(Asm, Layout, Sections, SectionOffsets);
1587 uint64_t SecStart = OS.tell();
1588 createStringTable(Asm, Sections);
1589 uint64_t SecEnd = OS.tell();
1590 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1594 uint64_t SecStart = OS.tell();
1595 createSectionHeaderStringTable(Asm, Sections);
1596 uint64_t SecEnd = OS.tell();
1597 SectionOffsets[0] = std::make_pair(SecStart, SecEnd);
1600 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1601 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1602 WriteZeros(Padding);
1604 const unsigned SectionHeaderOffset = OS.tell();
1606 // ... then the section header table ...
1607 writeSectionHeader(Sections, Asm, Layout, SectionIndexMap, SectionOffsets);
1609 uint16_t NumSections = (Sections.size() + 1 >= ELF::SHN_LORESERVE)
1611 : Sections.size() + 1;
1612 if (sys::IsLittleEndianHost != IsLittleEndian)
1613 sys::swapByteOrder(NumSections);
1614 unsigned NumSectionsOffset;
1617 uint64_t Val = SectionHeaderOffset;
1618 if (sys::IsLittleEndianHost != IsLittleEndian)
1619 sys::swapByteOrder(Val);
1620 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1621 offsetof(ELF::Elf64_Ehdr, e_shoff));
1622 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1624 uint32_t Val = SectionHeaderOffset;
1625 if (sys::IsLittleEndianHost != IsLittleEndian)
1626 sys::swapByteOrder(Val);
1627 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1628 offsetof(ELF::Elf32_Ehdr, e_shoff));
1629 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1631 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1635 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1636 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1637 bool InSet, bool IsPCRel) const {
1640 if (::isWeak(DataA))
1643 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1647 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1651 // It is invalid to replace a reference to a global in a comdat
1652 // with a reference to a local since out of comdat references
1653 // to a local are forbidden.
1654 // We could try to return false for more cases, like the reference
1655 // being in the same comdat or Sym being an alias to another global,
1656 // but it is not clear if it is worth the effort.
1657 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1660 const MCSymbol &Sym = SD.getSymbol();
1661 if (!Sym.isInSection())
1664 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1665 return Sec.getGroup();
1668 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1669 raw_pwrite_stream &OS,
1670 bool IsLittleEndian) {
1671 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);