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 SectionIndexMapTy &SectionIndexMap;
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 SectionIndexMapTy &SectionIndexMap,
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);
94 static uint64_t DataSectionSize(const MCSectionData &SD);
95 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
98 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
99 const MCSectionData &SD);
101 /// Helper struct for containing some precomputed information on symbols.
102 struct ELFSymbolData {
103 MCSymbolData *SymbolData;
104 uint64_t StringIndex;
105 uint32_t SectionIndex;
108 // Support lexicographic sorting.
109 bool operator<(const ELFSymbolData &RHS) const {
110 unsigned LHSType = MCELF::GetType(*SymbolData);
111 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
112 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
114 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
116 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
117 return SectionIndex < RHS.SectionIndex;
118 return Name < RHS.Name;
122 /// The target specific ELF writer instance.
123 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
125 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
126 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
127 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
129 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
131 StringTableBuilder ShStrTabBuilder;
134 /// @name Symbol Table Data
137 StringTableBuilder StrTabBuilder;
138 std::vector<uint64_t> FileSymbolData;
139 std::vector<ELFSymbolData> LocalSymbolData;
140 std::vector<ELFSymbolData> ExternalSymbolData;
141 std::vector<ELFSymbolData> UndefinedSymbolData;
147 // This holds the symbol table index of the last local symbol.
148 unsigned LastLocalSymbolIndex;
149 // This holds the .strtab section index.
150 unsigned StringTableIndex;
151 // This holds the .symtab section index.
152 unsigned SymbolTableIndex;
154 unsigned ShstrtabIndex;
157 // TargetObjectWriter wrappers.
158 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
159 bool hasRelocationAddend() const {
160 return TargetObjectWriter->hasRelocationAddend();
162 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
163 bool IsPCRel) const {
164 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
168 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
170 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
171 TargetObjectWriter(MOTW), NeedsGOT(false) {}
173 void reset() override {
175 WeakrefUsedInReloc.clear();
178 ShStrTabBuilder.clear();
179 StrTabBuilder.clear();
180 FileSymbolData.clear();
181 LocalSymbolData.clear();
182 ExternalSymbolData.clear();
183 UndefinedSymbolData.clear();
184 MCObjectWriter::reset();
187 ~ELFObjectWriter() override;
189 void WriteWord(uint64_t W) {
196 template <typename T> void write(MCDataFragment &F, T Value) {
197 FWriter.write(F, Value);
200 void WriteHeader(const MCAssembler &Asm,
201 unsigned NumberOfSections);
203 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
204 const MCAsmLayout &Layout);
206 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
207 const MCAsmLayout &Layout,
208 SectionIndexMapTy &SectionIndexMap);
210 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
211 const MCSymbolRefExpr *RefA,
212 const MCSymbolData *SD, uint64_t C,
213 unsigned Type) const;
215 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
216 const MCFragment *Fragment, const MCFixup &Fixup,
217 MCValue Target, bool &IsPCRel,
218 uint64_t &FixedValue) override;
220 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
223 // Map from a group section to the signature symbol
224 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
225 // Map from a signature symbol to the group section
226 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
227 // Map from a section to its offset
228 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
230 /// Compute the symbol table data
232 /// \param Asm - The assembler.
233 /// \param SectionIndexMap - Maps a section to its index.
234 /// \param RevGroupMap - Maps a signature symbol to the group section.
235 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
236 const SectionIndexMapTy &SectionIndexMap,
237 const RevGroupMapTy &RevGroupMap);
239 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
241 MCSectionData *createRelocationSection(MCAssembler &Asm,
242 const MCSectionData &SD);
244 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
246 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
248 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
249 SectionIndexMapTy &SectionIndexMap);
251 // Create the sections that show up in the symbol table. Currently
252 // those are the .note.GNU-stack section and the group sections.
253 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
254 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
255 SectionIndexMapTy &SectionIndexMap);
257 void ExecutePostLayoutBinding(MCAssembler &Asm,
258 const MCAsmLayout &Layout) override;
260 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
261 const MCAsmLayout &Layout,
262 const SectionIndexMapTy &SectionIndexMap,
263 const SectionOffsetMapTy &SectionOffsetMap);
265 void ComputeSectionOrder(MCAssembler &Asm,
266 std::vector<const MCSectionELF*> &Sections);
268 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
269 uint64_t Address, uint64_t Offset,
270 uint64_t Size, uint32_t Link, uint32_t Info,
271 uint64_t Alignment, uint64_t EntrySize);
273 void WriteRelocationsFragment(const MCAssembler &Asm,
275 const MCSectionData *SD);
278 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
279 const MCSymbolData &DataA,
280 const MCSymbolData *DataB,
281 const MCFragment &FB,
283 bool IsPCRel) const override;
285 bool isWeak(const MCSymbolData &SD) const override;
287 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
288 void writeSection(MCAssembler &Asm,
289 const SectionIndexMapTy &SectionIndexMap,
290 uint32_t GroupSymbolIndex,
291 uint64_t Offset, uint64_t Size, uint64_t Alignment,
292 const MCSectionELF &Section);
296 FragmentWriter::FragmentWriter(bool IsLittleEndian)
297 : IsLittleEndian(IsLittleEndian) {}
299 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
301 Val = support::endian::byte_swap<T, support::little>(Val);
303 Val = support::endian::byte_swap<T, support::big>(Val);
304 const char *Start = (const char *)&Val;
305 F.getContents().append(Start, Start + sizeof(T));
308 void SymbolTableWriter::createSymtabShndx() {
312 MCContext &Ctx = Asm.getContext();
313 const MCSectionELF *SymtabShndxSection =
314 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
315 MCSectionData *SymtabShndxSD =
316 &Asm.getOrCreateSectionData(*SymtabShndxSection);
317 SymtabShndxSD->setAlignment(4);
318 ShndxF = new MCDataFragment(SymtabShndxSD);
319 unsigned Index = SectionIndexMap.size() + 1;
320 SectionIndexMap[SymtabShndxSection] = Index;
322 for (unsigned I = 0; I < NumWritten; ++I)
323 write(*ShndxF, uint32_t(0));
326 template <typename T>
327 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
328 FWriter.write(F, Value);
331 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
333 SectionIndexMapTy &SectionIndexMap,
334 MCDataFragment *SymtabF)
335 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
336 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
339 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
340 uint64_t size, uint8_t other,
341 uint32_t shndx, bool Reserved) {
342 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
349 write(*ShndxF, shndx);
351 write(*ShndxF, uint32_t(0));
354 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
357 write(*SymtabF, name); // st_name
358 write(*SymtabF, info); // st_info
359 write(*SymtabF, other); // st_other
360 write(*SymtabF, Index); // st_shndx
361 write(*SymtabF, value); // st_value
362 write(*SymtabF, size); // st_size
364 write(*SymtabF, name); // st_name
365 write(*SymtabF, uint32_t(value)); // st_value
366 write(*SymtabF, uint32_t(size)); // st_size
367 write(*SymtabF, info); // st_info
368 write(*SymtabF, other); // st_other
369 write(*SymtabF, Index); // st_shndx
375 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
376 const MCFixupKindInfo &FKI =
377 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
379 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
382 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
386 case MCSymbolRefExpr::VK_GOT:
387 case MCSymbolRefExpr::VK_PLT:
388 case MCSymbolRefExpr::VK_GOTPCREL:
389 case MCSymbolRefExpr::VK_GOTOFF:
390 case MCSymbolRefExpr::VK_TPOFF:
391 case MCSymbolRefExpr::VK_TLSGD:
392 case MCSymbolRefExpr::VK_GOTTPOFF:
393 case MCSymbolRefExpr::VK_INDNTPOFF:
394 case MCSymbolRefExpr::VK_NTPOFF:
395 case MCSymbolRefExpr::VK_GOTNTPOFF:
396 case MCSymbolRefExpr::VK_TLSLDM:
397 case MCSymbolRefExpr::VK_DTPOFF:
398 case MCSymbolRefExpr::VK_TLSLD:
403 ELFObjectWriter::~ELFObjectWriter()
406 // Emit the ELF header.
407 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
408 unsigned NumberOfSections) {
414 // emitWord method behaves differently for ELF32 and ELF64, writing
415 // 4 bytes in the former and 8 in the latter.
417 Write8(0x7f); // e_ident[EI_MAG0]
418 Write8('E'); // e_ident[EI_MAG1]
419 Write8('L'); // e_ident[EI_MAG2]
420 Write8('F'); // e_ident[EI_MAG3]
422 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
425 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
427 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
429 Write8(TargetObjectWriter->getOSABI());
430 Write8(0); // e_ident[EI_ABIVERSION]
432 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
434 Write16(ELF::ET_REL); // e_type
436 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
438 Write32(ELF::EV_CURRENT); // e_version
439 WriteWord(0); // e_entry, no entry point in .o file
440 WriteWord(0); // e_phoff, no program header for .o
441 WriteWord(0); // e_shoff = sec hdr table off in bytes
443 // e_flags = whatever the target wants
444 Write32(Asm.getELFHeaderEFlags());
446 // e_ehsize = ELF header size
447 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
449 Write16(0); // e_phentsize = prog header entry size
450 Write16(0); // e_phnum = # prog header entries = 0
452 // e_shentsize = Section header entry size
453 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
455 // e_shnum = # of section header ents
456 if (NumberOfSections >= ELF::SHN_LORESERVE)
457 Write16(ELF::SHN_UNDEF);
459 Write16(NumberOfSections);
461 // e_shstrndx = Section # of '.shstrtab'
462 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
463 Write16(ELF::SHN_XINDEX);
465 Write16(ShstrtabIndex);
468 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
469 const MCAsmLayout &Layout) {
470 if (Data.isCommon() && Data.isExternal())
471 return Data.getCommonAlignment();
474 if (!Layout.getSymbolOffset(&Data, Res))
477 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
483 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
484 const MCAsmLayout &Layout) {
485 // The presence of symbol versions causes undefined symbols and
486 // versions declared with @@@ to be renamed.
488 for (MCSymbolData &OriginalData : Asm.symbols()) {
489 const MCSymbol &Alias = OriginalData.getSymbol();
492 if (!Alias.isVariable())
494 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
497 const MCSymbol &Symbol = Ref->getSymbol();
498 MCSymbolData &SD = Asm.getSymbolData(Symbol);
500 StringRef AliasName = Alias.getName();
501 size_t Pos = AliasName.find('@');
502 if (Pos == StringRef::npos)
505 // Aliases defined with .symvar copy the binding from the symbol they alias.
506 // This is the first place we are able to copy this information.
507 OriginalData.setExternal(SD.isExternal());
508 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
510 StringRef Rest = AliasName.substr(Pos);
511 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
514 // FIXME: produce a better error message.
515 if (Symbol.isUndefined() && Rest.startswith("@@") &&
516 !Rest.startswith("@@@"))
517 report_fatal_error("A @@ version cannot be undefined");
519 Renames.insert(std::make_pair(&Symbol, &Alias));
523 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
524 uint8_t Type = newType;
526 // Propagation rules:
527 // IFUNC > FUNC > OBJECT > NOTYPE
528 // TLS_OBJECT > OBJECT > NOTYPE
530 // dont let the new type degrade the old type
534 case ELF::STT_GNU_IFUNC:
535 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
536 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
537 Type = ELF::STT_GNU_IFUNC;
540 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
541 Type == ELF::STT_TLS)
542 Type = ELF::STT_FUNC;
544 case ELF::STT_OBJECT:
545 if (Type == ELF::STT_NOTYPE)
546 Type = ELF::STT_OBJECT;
549 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
550 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
558 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
559 const MCAsmLayout &Layout) {
560 MCSymbolData &OrigData = *MSD.SymbolData;
561 assert((!OrigData.getFragment() ||
562 (&OrigData.getFragment()->getParent()->getSection() ==
563 &OrigData.getSymbol().getSection())) &&
564 "The symbol's section doesn't match the fragment's symbol");
565 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
567 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
569 bool IsReserved = !Base || OrigData.isCommon();
571 // Binding and Type share the same byte as upper and lower nibbles
572 uint8_t Binding = MCELF::GetBinding(OrigData);
573 uint8_t Type = MCELF::GetType(OrigData);
574 MCSymbolData *BaseSD = nullptr;
576 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
577 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
579 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
581 // Other and Visibility share the same byte with Visibility using the lower
583 uint8_t Visibility = MCELF::GetVisibility(OrigData);
584 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
587 uint64_t Value = SymbolValue(OrigData, Layout);
590 const MCExpr *ESize = OrigData.getSize();
592 ESize = BaseSD->getSize();
596 if (!ESize->evaluateKnownAbsolute(Res, Layout))
597 report_fatal_error("Size expression must be absolute.");
601 // Write out the symbol table entry
602 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
603 MSD.SectionIndex, IsReserved);
606 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
608 const MCAsmLayout &Layout,
609 SectionIndexMapTy &SectionIndexMap) {
610 // The string table must be emitted first because we need the index
611 // into the string table for all the symbol names.
613 // FIXME: Make sure the start of the symbol table is aligned.
615 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
617 // The first entry is the undefined symbol entry.
618 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
620 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
621 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
622 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
625 // Write the symbol table entries.
626 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
628 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
629 ELFSymbolData &MSD = LocalSymbolData[i];
630 WriteSymbol(Writer, MSD, Layout);
633 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
634 ELFSymbolData &MSD = ExternalSymbolData[i];
635 MCSymbolData &Data = *MSD.SymbolData;
636 assert(((Data.getFlags() & ELF_STB_Global) ||
637 (Data.getFlags() & ELF_STB_Weak)) &&
638 "External symbol requires STB_GLOBAL or STB_WEAK flag");
639 WriteSymbol(Writer, MSD, Layout);
640 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
641 LastLocalSymbolIndex++;
644 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
645 ELFSymbolData &MSD = UndefinedSymbolData[i];
646 MCSymbolData &Data = *MSD.SymbolData;
647 WriteSymbol(Writer, MSD, Layout);
648 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
649 LastLocalSymbolIndex++;
653 // It is always valid to create a relocation with a symbol. It is preferable
654 // to use a relocation with a section if that is possible. Using the section
655 // allows us to omit some local symbols from the symbol table.
656 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
657 const MCSymbolRefExpr *RefA,
658 const MCSymbolData *SD,
660 unsigned Type) const {
661 // A PCRel relocation to an absolute value has no symbol (or section). We
662 // represent that with a relocation to a null section.
666 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
670 // The .odp creation emits a relocation against the symbol ".TOC." which
671 // create a R_PPC64_TOC relocation. However the relocation symbol name
672 // in final object creation should be NULL, since the symbol does not
673 // really exist, it is just the reference to TOC base for the current
674 // object file. Since the symbol is undefined, returning false results
675 // in a relocation with a null section which is the desired result.
676 case MCSymbolRefExpr::VK_PPC_TOCBASE:
679 // These VariantKind cause the relocation to refer to something other than
680 // the symbol itself, like a linker generated table. Since the address of
681 // symbol is not relevant, we cannot replace the symbol with the
682 // section and patch the difference in the addend.
683 case MCSymbolRefExpr::VK_GOT:
684 case MCSymbolRefExpr::VK_PLT:
685 case MCSymbolRefExpr::VK_GOTPCREL:
686 case MCSymbolRefExpr::VK_Mips_GOT:
687 case MCSymbolRefExpr::VK_PPC_GOT_LO:
688 case MCSymbolRefExpr::VK_PPC_GOT_HI:
689 case MCSymbolRefExpr::VK_PPC_GOT_HA:
693 // An undefined symbol is not in any section, so the relocation has to point
694 // to the symbol itself.
695 const MCSymbol &Sym = SD->getSymbol();
696 if (Sym.isUndefined())
699 unsigned Binding = MCELF::GetBinding(*SD);
702 llvm_unreachable("Invalid Binding");
706 // If the symbol is weak, it might be overridden by a symbol in another
707 // file. The relocation has to point to the symbol so that the linker
710 case ELF::STB_GLOBAL:
711 // Global ELF symbols can be preempted by the dynamic linker. The relocation
712 // has to point to the symbol for a reason analogous to the STB_WEAK case.
716 // If a relocation points to a mergeable section, we have to be careful.
717 // If the offset is zero, a relocation with the section will encode the
718 // same information. With a non-zero offset, the situation is different.
719 // For example, a relocation can point 42 bytes past the end of a string.
720 // If we change such a relocation to use the section, the linker would think
721 // that it pointed to another string and subtracting 42 at runtime will
722 // produce the wrong value.
723 auto &Sec = cast<MCSectionELF>(Sym.getSection());
724 unsigned Flags = Sec.getFlags();
725 if (Flags & ELF::SHF_MERGE) {
729 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
730 // only handle section relocations to mergeable sections if using RELA.
731 if (!hasRelocationAddend())
735 // Most TLS relocations use a got, so they need the symbol. Even those that
736 // are just an offset (@tpoff), require a symbol in gold versions before
737 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
738 // http://sourceware.org/PR16773.
739 if (Flags & ELF::SHF_TLS)
742 // If the symbol is a thumb function the final relocation must set the lowest
743 // bit. With a symbol that is done by just having the symbol have that bit
744 // set, so we would lose the bit if we relocated with the section.
745 // FIXME: We could use the section but add the bit to the relocation value.
746 if (Asm.isThumbFunc(&Sym))
749 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
754 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
755 const MCSymbol &Sym = Ref.getSymbol();
757 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
760 if (!Sym.isVariable())
763 const MCExpr *Expr = Sym.getVariableValue();
764 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
768 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
769 return &Inner->getSymbol();
773 static bool isWeak(const MCSymbolData &D) {
774 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
777 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
778 const MCAsmLayout &Layout,
779 const MCFragment *Fragment,
780 const MCFixup &Fixup, MCValue Target,
781 bool &IsPCRel, uint64_t &FixedValue) {
782 const MCSectionData *FixupSection = Fragment->getParent();
783 uint64_t C = Target.getConstant();
784 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
786 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
787 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
788 "Should not have constructed this");
790 // Let A, B and C being the components of Target and R be the location of
791 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
792 // If it is pcrel, we want to compute (A - B + C - R).
794 // In general, ELF has no relocations for -B. It can only represent (A + C)
795 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
796 // replace B to implement it: (A - R - K + C)
798 Asm.getContext().FatalError(
800 "No relocation available to represent this relative expression");
802 const MCSymbol &SymB = RefB->getSymbol();
804 if (SymB.isUndefined())
805 Asm.getContext().FatalError(
807 Twine("symbol '") + SymB.getName() +
808 "' can not be undefined in a subtraction expression");
810 assert(!SymB.isAbsolute() && "Should have been folded");
811 const MCSection &SecB = SymB.getSection();
812 if (&SecB != &FixupSection->getSection())
813 Asm.getContext().FatalError(
814 Fixup.getLoc(), "Cannot represent a difference across sections");
816 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
818 Asm.getContext().FatalError(
819 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
821 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
822 uint64_t K = SymBOffset - FixupOffset;
827 // We either rejected the fixup or folded B into C at this point.
828 const MCSymbolRefExpr *RefA = Target.getSymA();
829 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
830 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
832 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
833 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
834 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
835 C += Layout.getSymbolOffset(SymAD);
838 if (hasRelocationAddend()) {
845 // FIXME: What is this!?!?
846 MCSymbolRefExpr::VariantKind Modifier =
847 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
848 if (RelocNeedsGOT(Modifier))
851 if (!RelocateWithSymbol) {
852 const MCSection *SecA =
853 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
854 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
855 MCSymbol *SectionSymbol =
856 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
858 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
859 Relocations[FixupSection].push_back(Rec);
864 if (const MCSymbol *R = Renames.lookup(SymA))
867 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
868 WeakrefUsedInReloc.insert(WeakRef);
870 UsedInReloc.insert(SymA);
872 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
873 Relocations[FixupSection].push_back(Rec);
879 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
881 const MCSymbolData &SD = Asm.getSymbolData(*S);
882 return SD.getIndex();
885 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
886 const MCSymbolData &Data, bool Used,
888 const MCSymbol &Symbol = Data.getSymbol();
889 if (Symbol.isVariable()) {
890 const MCExpr *Expr = Symbol.getVariableValue();
891 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
892 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
903 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
906 if (Symbol.isVariable()) {
907 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
908 if (Base && Base->isUndefined())
912 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
913 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
916 if (Symbol.isTemporary())
922 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
923 if (Data.isExternal())
926 const MCSymbol &Symbol = Data.getSymbol();
927 if (Symbol.isDefined())
936 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
937 SectionIndexMapTy &SectionIndexMap) {
939 for (MCAssembler::iterator it = Asm.begin(),
940 ie = Asm.end(); it != ie; ++it) {
941 const MCSectionELF &Section =
942 static_cast<const MCSectionELF &>(it->getSection());
943 if (Section.getType() != ELF::SHT_GROUP)
945 SectionIndexMap[&Section] = Index++;
948 for (MCAssembler::iterator it = Asm.begin(),
949 ie = Asm.end(); it != ie; ++it) {
950 const MCSectionData &SD = *it;
951 const MCSectionELF &Section =
952 static_cast<const MCSectionELF &>(SD.getSection());
953 if (Section.getType() == ELF::SHT_GROUP ||
954 Section.getType() == ELF::SHT_REL ||
955 Section.getType() == ELF::SHT_RELA)
957 SectionIndexMap[&Section] = Index++;
958 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
959 const MCSectionELF *RelSection =
960 static_cast<const MCSectionELF *>(&RelSD->getSection());
961 SectionIndexMap[RelSection] = Index++;
966 void ELFObjectWriter::computeSymbolTable(
967 MCAssembler &Asm, const MCAsmLayout &Layout,
968 const SectionIndexMapTy &SectionIndexMap,
969 const RevGroupMapTy &RevGroupMap) {
970 // FIXME: Is this the correct place to do this?
971 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
973 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
974 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
975 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
976 Data.setExternal(true);
977 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
980 // Add the data for the symbols.
981 for (MCSymbolData &SD : Asm.symbols()) {
982 const MCSymbol &Symbol = SD.getSymbol();
984 bool Used = UsedInReloc.count(&Symbol);
985 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
986 bool isSignature = RevGroupMap.count(&Symbol);
988 if (!isInSymtab(Layout, SD,
989 Used || WeakrefUsed || isSignature,
990 Renames.count(&Symbol)))
994 MSD.SymbolData = &SD;
995 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
997 // Undefined symbols are global, but this is the first place we
998 // are able to set it.
999 bool Local = isLocal(SD, Used);
1000 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1002 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1003 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1004 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1008 MSD.SectionIndex = ELF::SHN_ABS;
1009 } else if (SD.isCommon()) {
1011 MSD.SectionIndex = ELF::SHN_COMMON;
1012 } else if (BaseSymbol->isUndefined()) {
1013 if (isSignature && !Used)
1014 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1016 MSD.SectionIndex = ELF::SHN_UNDEF;
1017 if (!Used && WeakrefUsed)
1018 MCELF::SetBinding(SD, ELF::STB_WEAK);
1020 const MCSectionELF &Section =
1021 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1022 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1023 assert(MSD.SectionIndex && "Invalid section index!");
1026 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1029 // FIXME: All name handling should be done before we get to the writer,
1030 // including dealing with GNU-style version suffixes. Fixing this isn't
1033 // We thus have to be careful to not perform the symbol version replacement
1036 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1037 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1038 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1039 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1040 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1041 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1042 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1043 // "__imp_?" or "__imp_@?".
1045 // It would have been interesting to perform the MS mangling prefix check
1046 // only when the target triple is of the form *-pc-windows-elf. But, it
1047 // seems that this information is not easily accessible from the
1049 StringRef Name = Symbol.getName();
1050 if (!Name.startswith("?") && !Name.startswith("@?") &&
1051 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1052 // This symbol isn't following the MSVC C++ name mangling convention. We
1053 // can thus safely interpret the @@@ in symbol names as specifying symbol
1055 SmallString<32> Buf;
1056 size_t Pos = Name.find("@@@");
1057 if (Pos != StringRef::npos) {
1058 Buf += Name.substr(0, Pos);
1059 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1060 Buf += Name.substr(Pos + Skip);
1065 // Sections have their own string table
1066 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1067 MSD.Name = StrTabBuilder.add(Name);
1069 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1070 UndefinedSymbolData.push_back(MSD);
1072 LocalSymbolData.push_back(MSD);
1074 ExternalSymbolData.push_back(MSD);
1077 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1078 StrTabBuilder.add(*i);
1080 StrTabBuilder.finalize(StringTableBuilder::ELF);
1082 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1083 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1085 for (ELFSymbolData &MSD : LocalSymbolData)
1086 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1088 : StrTabBuilder.getOffset(MSD.Name);
1089 for (ELFSymbolData &MSD : ExternalSymbolData)
1090 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1091 for (ELFSymbolData& MSD : UndefinedSymbolData)
1092 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1094 // Symbols are required to be in lexicographic order.
1095 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1096 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1097 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1099 // Set the symbol indices. Local symbols must come before all other
1100 // symbols with non-local bindings.
1101 unsigned Index = FileSymbolData.size() + 1;
1102 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1103 LocalSymbolData[i].SymbolData->setIndex(Index++);
1105 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1106 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1107 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1108 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1112 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1113 const MCSectionData &SD) {
1114 if (Relocations[&SD].empty())
1117 MCContext &Ctx = Asm.getContext();
1118 const MCSectionELF &Section =
1119 static_cast<const MCSectionELF &>(SD.getSection());
1121 const StringRef SectionName = Section.getSectionName();
1122 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1123 RelaSectionName += SectionName;
1126 if (hasRelocationAddend())
1127 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1129 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1132 if (Section.getFlags() & ELF::SHF_GROUP)
1133 Flags = ELF::SHF_GROUP;
1135 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1136 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1137 Flags, EntrySize, Section.getGroup(), &Section);
1138 return &Asm.getOrCreateSectionData(*RelaSection);
1141 static SmallVector<char, 128>
1142 getUncompressedData(MCAsmLayout &Layout,
1143 MCSectionData::FragmentListType &Fragments) {
1144 SmallVector<char, 128> UncompressedData;
1145 for (const MCFragment &F : Fragments) {
1146 const SmallVectorImpl<char> *Contents;
1147 switch (F.getKind()) {
1148 case MCFragment::FT_Data:
1149 Contents = &cast<MCDataFragment>(F).getContents();
1151 case MCFragment::FT_Dwarf:
1152 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1154 case MCFragment::FT_DwarfFrame:
1155 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1159 "Not expecting any other fragment types in a debug_* section");
1161 UncompressedData.append(Contents->begin(), Contents->end());
1163 return UncompressedData;
1166 // Include the debug info compression header:
1167 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1168 // useful for consumers to preallocate a buffer to decompress into.
1170 prependCompressionHeader(uint64_t Size,
1171 SmallVectorImpl<char> &CompressedContents) {
1172 const StringRef Magic = "ZLIB";
1173 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1175 if (sys::IsLittleEndianHost)
1176 sys::swapByteOrder(Size);
1177 CompressedContents.insert(CompressedContents.begin(),
1178 Magic.size() + sizeof(Size), 0);
1179 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1180 std::copy(reinterpret_cast<char *>(&Size),
1181 reinterpret_cast<char *>(&Size + 1),
1182 CompressedContents.begin() + Magic.size());
1186 // Return a single fragment containing the compressed contents of the whole
1187 // section. Null if the section was not compressed for any reason.
1188 static std::unique_ptr<MCDataFragment>
1189 getCompressedFragment(MCAsmLayout &Layout,
1190 MCSectionData::FragmentListType &Fragments) {
1191 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1193 // Gather the uncompressed data from all the fragments, recording the
1194 // alignment fragment, if seen, and any fixups.
1195 SmallVector<char, 128> UncompressedData =
1196 getUncompressedData(Layout, Fragments);
1198 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1200 zlib::Status Success = zlib::compress(
1201 StringRef(UncompressedData.data(), UncompressedData.size()),
1202 CompressedContents);
1203 if (Success != zlib::StatusOK)
1206 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1209 return CompressedFragment;
1212 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1215 static void UpdateSymbols(const MCAsmLayout &Layout,
1216 const std::vector<MCSymbolData *> &Symbols,
1217 MCFragment &NewFragment) {
1218 for (MCSymbolData *Sym : Symbols) {
1219 Sym->setOffset(Sym->getOffset() +
1220 Layout.getFragmentOffset(Sym->getFragment()));
1221 Sym->setFragment(&NewFragment);
1225 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1226 const DefiningSymbolMap &DefiningSymbols,
1227 const MCSectionELF &Section,
1228 MCSectionData &SD) {
1229 StringRef SectionName = Section.getSectionName();
1230 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1232 std::unique_ptr<MCDataFragment> CompressedFragment =
1233 getCompressedFragment(Layout, Fragments);
1235 // Leave the section as-is if the fragments could not be compressed.
1236 if (!CompressedFragment)
1239 // Update the fragment+offsets of any symbols referring to fragments in this
1240 // section to refer to the new fragment.
1241 auto I = DefiningSymbols.find(&SD);
1242 if (I != DefiningSymbols.end())
1243 UpdateSymbols(Layout, I->second, *CompressedFragment);
1245 // Invalidate the layout for the whole section since it will have new and
1246 // different fragments now.
1247 Layout.invalidateFragmentsFrom(&Fragments.front());
1250 // Complete the initialization of the new fragment
1251 CompressedFragment->setParent(&SD);
1252 CompressedFragment->setLayoutOrder(0);
1253 Fragments.push_back(CompressedFragment.release());
1255 // Rename from .debug_* to .zdebug_*
1256 Asm.getContext().renameELFSection(&Section,
1257 (".z" + SectionName.drop_front(1)).str());
1260 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1261 MCAsmLayout &Layout) {
1262 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1265 DefiningSymbolMap DefiningSymbols;
1267 for (MCSymbolData &SD : Asm.symbols())
1268 if (MCFragment *F = SD.getFragment())
1269 DefiningSymbols[F->getParent()].push_back(&SD);
1271 for (MCSectionData &SD : Asm) {
1272 const MCSectionELF &Section =
1273 static_cast<const MCSectionELF &>(SD.getSection());
1274 StringRef SectionName = Section.getSectionName();
1276 // Compressing debug_frame requires handling alignment fragments which is
1277 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1278 // for writing to arbitrary buffers) for little benefit.
1279 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1282 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1286 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1287 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1288 MCSectionData &RelSD = *it;
1289 const MCSectionELF &RelSection =
1290 static_cast<const MCSectionELF &>(RelSD.getSection());
1292 unsigned Type = RelSection.getType();
1293 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1296 const MCSectionELF *Section = RelSection.getAssociatedSection();
1297 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1298 RelSD.setAlignment(is64Bit() ? 8 : 4);
1300 MCDataFragment *F = new MCDataFragment(&RelSD);
1301 WriteRelocationsFragment(Asm, F, &SD);
1305 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1306 uint64_t Flags, uint64_t Address,
1307 uint64_t Offset, uint64_t Size,
1308 uint32_t Link, uint32_t Info,
1310 uint64_t EntrySize) {
1311 Write32(Name); // sh_name: index into string table
1312 Write32(Type); // sh_type
1313 WriteWord(Flags); // sh_flags
1314 WriteWord(Address); // sh_addr
1315 WriteWord(Offset); // sh_offset
1316 WriteWord(Size); // sh_size
1317 Write32(Link); // sh_link
1318 Write32(Info); // sh_info
1319 WriteWord(Alignment); // sh_addralign
1320 WriteWord(EntrySize); // sh_entsize
1323 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1325 const MCSectionData *SD) {
1326 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1328 // Sort the relocation entries. Most targets just sort by Offset, but some
1329 // (e.g., MIPS) have additional constraints.
1330 TargetObjectWriter->sortRelocs(Asm, Relocs);
1332 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1333 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1335 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1338 write(*F, Entry.Offset);
1339 if (TargetObjectWriter->isN64()) {
1340 write(*F, uint32_t(Index));
1342 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1343 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1344 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1345 write(*F, TargetObjectWriter->getRType(Entry.Type));
1347 struct ELF::Elf64_Rela ERE64;
1348 ERE64.setSymbolAndType(Index, Entry.Type);
1349 write(*F, ERE64.r_info);
1351 if (hasRelocationAddend())
1352 write(*F, Entry.Addend);
1354 write(*F, uint32_t(Entry.Offset));
1356 struct ELF::Elf32_Rela ERE32;
1357 ERE32.setSymbolAndType(Index, Entry.Type);
1358 write(*F, ERE32.r_info);
1360 if (hasRelocationAddend())
1361 write(*F, uint32_t(Entry.Addend));
1366 void ELFObjectWriter::CreateMetadataSections(
1367 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1368 MCContext &Ctx = Asm.getContext();
1371 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1373 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1374 const MCSectionELF *ShstrtabSection =
1375 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1376 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1377 ShstrtabSD.setAlignment(1);
1378 ShstrtabIndex = SectionIndexMap.size() + 1;
1379 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1381 const MCSectionELF *SymtabSection =
1382 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1384 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1385 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1386 SymbolTableIndex = SectionIndexMap.size() + 1;
1387 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1389 const MCSectionELF *StrtabSection;
1390 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1391 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1392 StrtabSD.setAlignment(1);
1393 StringTableIndex = SectionIndexMap.size() + 1;
1394 SectionIndexMap[StrtabSection] = StringTableIndex;
1397 F = new MCDataFragment(&SymtabSD);
1398 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1400 F = new MCDataFragment(&StrtabSD);
1401 F->getContents().append(StrTabBuilder.data().begin(),
1402 StrTabBuilder.data().end());
1404 F = new MCDataFragment(&ShstrtabSD);
1406 // Section header string table.
1407 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1408 const MCSectionELF &Section =
1409 static_cast<const MCSectionELF&>(it->getSection());
1410 ShStrTabBuilder.add(Section.getSectionName());
1412 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1413 F->getContents().append(ShStrTabBuilder.data().begin(),
1414 ShStrTabBuilder.data().end());
1417 void ELFObjectWriter::createIndexedSections(
1418 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1419 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1420 MCContext &Ctx = Asm.getContext();
1423 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1425 const MCSectionELF &Section =
1426 static_cast<const MCSectionELF&>(it->getSection());
1427 if (!(Section.getFlags() & ELF::SHF_GROUP))
1430 const MCSymbol *SignatureSymbol = Section.getGroup();
1431 Asm.getOrCreateSymbolData(*SignatureSymbol);
1432 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1434 Group = Ctx.CreateELFGroupSection();
1435 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1436 Data.setAlignment(4);
1437 MCDataFragment *F = new MCDataFragment(&Data);
1438 write(*F, uint32_t(ELF::GRP_COMDAT));
1440 GroupMap[Group] = SignatureSymbol;
1443 computeIndexMap(Asm, SectionIndexMap);
1445 // Add sections to the groups
1446 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1448 const MCSectionELF &Section =
1449 static_cast<const MCSectionELF&>(it->getSection());
1450 if (!(Section.getFlags() & ELF::SHF_GROUP))
1452 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1453 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1454 // FIXME: we could use the previous fragment
1455 MCDataFragment *F = new MCDataFragment(&Data);
1456 uint32_t Index = SectionIndexMap.lookup(&Section);
1461 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1462 const SectionIndexMapTy &SectionIndexMap,
1463 uint32_t GroupSymbolIndex,
1464 uint64_t Offset, uint64_t Size,
1466 const MCSectionELF &Section) {
1467 uint64_t sh_link = 0;
1468 uint64_t sh_info = 0;
1470 switch(Section.getType()) {
1475 case ELF::SHT_DYNAMIC:
1476 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1480 case ELF::SHT_RELA: {
1481 sh_link = SymbolTableIndex;
1482 assert(sh_link && ".symtab not found");
1483 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1484 sh_info = SectionIndexMap.lookup(InfoSection);
1488 case ELF::SHT_SYMTAB:
1489 case ELF::SHT_DYNSYM:
1490 sh_link = StringTableIndex;
1491 sh_info = LastLocalSymbolIndex;
1494 case ELF::SHT_SYMTAB_SHNDX:
1495 sh_link = SymbolTableIndex;
1498 case ELF::SHT_GROUP:
1499 sh_link = SymbolTableIndex;
1500 sh_info = GroupSymbolIndex;
1504 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1505 Section.getType() == ELF::SHT_ARM_EXIDX)
1506 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1508 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1510 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1511 Alignment, Section.getEntrySize());
1514 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1515 return SD.getOrdinal() == ~UINT32_C(0) &&
1516 !SD.getSection().isVirtualSection();
1519 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1521 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1523 const MCFragment &F = *i;
1524 assert(F.getKind() == MCFragment::FT_Data);
1525 Ret += cast<MCDataFragment>(F).getContents().size();
1530 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1531 const MCSectionData &SD) {
1532 if (IsELFMetaDataSection(SD))
1533 return DataSectionSize(SD);
1534 return Layout.getSectionAddressSize(&SD);
1537 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1538 const MCAsmLayout &Layout,
1539 const MCSectionData &SD) {
1540 if (IsELFMetaDataSection(SD)) {
1541 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1543 const MCFragment &F = *i;
1544 assert(F.getKind() == MCFragment::FT_Data);
1545 WriteBytes(cast<MCDataFragment>(F).getContents());
1548 Asm.writeSectionData(&SD, Layout);
1552 void ELFObjectWriter::writeSectionHeader(
1553 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1554 const SectionIndexMapTy &SectionIndexMap,
1555 const SectionOffsetMapTy &SectionOffsetMap) {
1556 const unsigned NumSections = Asm.size() + 1;
1558 std::vector<const MCSectionELF*> Sections;
1559 Sections.resize(NumSections - 1);
1561 for (SectionIndexMapTy::const_iterator i=
1562 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1563 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1564 Sections[p.second - 1] = p.first;
1567 // Null section first.
1568 uint64_t FirstSectionSize =
1569 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1570 uint32_t FirstSectionLink =
1571 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1572 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1574 for (unsigned i = 0; i < NumSections - 1; ++i) {
1575 const MCSectionELF &Section = *Sections[i];
1576 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1577 uint32_t GroupSymbolIndex;
1578 if (Section.getType() != ELF::SHT_GROUP)
1579 GroupSymbolIndex = 0;
1581 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1582 GroupMap.lookup(&Section));
1584 uint64_t Size = GetSectionAddressSize(Layout, SD);
1586 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1587 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1592 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1593 std::vector<const MCSectionELF*> &Sections) {
1594 for (MCAssembler::iterator it = Asm.begin(),
1595 ie = Asm.end(); it != ie; ++it) {
1596 const MCSectionELF &Section =
1597 static_cast<const MCSectionELF &>(it->getSection());
1598 if (Section.getType() == ELF::SHT_GROUP)
1599 Sections.push_back(&Section);
1602 for (MCAssembler::iterator it = Asm.begin(),
1603 ie = Asm.end(); it != ie; ++it) {
1604 const MCSectionELF &Section =
1605 static_cast<const MCSectionELF &>(it->getSection());
1606 if (Section.getType() != ELF::SHT_GROUP &&
1607 Section.getType() != ELF::SHT_REL &&
1608 Section.getType() != ELF::SHT_RELA)
1609 Sections.push_back(&Section);
1612 for (MCAssembler::iterator it = Asm.begin(),
1613 ie = Asm.end(); it != ie; ++it) {
1614 const MCSectionELF &Section =
1615 static_cast<const MCSectionELF &>(it->getSection());
1616 if (Section.getType() == ELF::SHT_REL ||
1617 Section.getType() == ELF::SHT_RELA)
1618 Sections.push_back(&Section);
1622 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1623 const MCAsmLayout &Layout) {
1624 GroupMapTy GroupMap;
1625 RevGroupMapTy RevGroupMap;
1626 SectionIndexMapTy SectionIndexMap;
1628 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1629 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1630 RevGroupMap, SectionIndexMap);
1632 // Compute symbol table information.
1633 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1635 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1637 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1638 const_cast<MCAsmLayout&>(Layout),
1641 std::vector<const MCSectionELF*> Sections;
1642 ComputeSectionOrder(Asm, Sections);
1643 unsigned NumSections = Sections.size();
1644 SectionOffsetMapTy SectionOffsetMap;
1646 // Write out the ELF header ...
1647 WriteHeader(Asm, NumSections + 1);
1649 // ... then the sections ...
1650 for (unsigned i = 0; i < NumSections; ++i) {
1651 const MCSectionELF &Section = *Sections[i];
1652 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1653 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1654 WriteZeros(Padding);
1656 // Remember the offset into the file for this section.
1657 SectionOffsetMap[&Section] = OS.tell();
1659 writeDataSectionData(Asm, Layout, SD);
1662 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1663 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1664 WriteZeros(Padding);
1666 const unsigned SectionHeaderOffset = OS.tell();
1668 // ... then the section header table ...
1669 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1672 uint64_t Val = SectionHeaderOffset;
1673 if (sys::IsLittleEndianHost != IsLittleEndian)
1674 sys::swapByteOrder(Val);
1675 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1676 offsetof(ELF::Elf64_Ehdr, e_shoff));
1678 uint32_t Val = SectionHeaderOffset;
1679 if (sys::IsLittleEndianHost != IsLittleEndian)
1680 sys::swapByteOrder(Val);
1681 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1682 offsetof(ELF::Elf32_Ehdr, e_shoff));
1686 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1687 const MCAssembler &Asm, const MCSymbolData &DataA,
1688 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1689 bool IsPCRel) const {
1690 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1692 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1693 Asm, DataA, DataB, FB, InSet, IsPCRel);
1696 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1697 return ::isWeak(SD);
1700 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1701 raw_pwrite_stream &OS,
1702 bool IsLittleEndian) {
1703 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);