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 struct ELFRelocationEntry {
83 uint64_t Offset; // Where is the relocation.
84 const MCSymbol *Symbol; // The symbol to relocate with.
85 unsigned Type; // The type of the relocation.
86 uint64_t Addend; // The addend to use.
88 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
90 : Offset(Offset), Symbol(Symbol), Type(Type), Addend(Addend) {}
93 class ELFObjectWriter : public MCObjectWriter {
94 FragmentWriter FWriter;
98 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
99 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
100 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
101 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
102 bool Used, bool Renamed);
103 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
104 static bool IsELFMetaDataSection(const MCSectionData &SD);
105 static uint64_t DataSectionSize(const MCSectionData &SD);
106 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
107 const MCSectionData &SD);
108 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
109 const MCSectionData &SD);
111 void WriteDataSectionData(MCAssembler &Asm,
112 const MCAsmLayout &Layout,
113 const MCSectionELF &Section);
115 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
116 return Kind == X86::reloc_riprel_4byte ||
117 Kind == X86::reloc_riprel_4byte_movq_load;
120 /// ELFSymbolData - Helper struct for containing some precomputed
121 /// information on symbols.
122 struct ELFSymbolData {
123 MCSymbolData *SymbolData;
124 uint64_t StringIndex;
125 uint32_t SectionIndex;
128 // Support lexicographic sorting.
129 bool operator<(const ELFSymbolData &RHS) const {
130 unsigned LHSType = MCELF::GetType(*SymbolData);
131 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
132 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
134 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
136 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
137 return SectionIndex < RHS.SectionIndex;
138 return Name < RHS.Name;
142 /// The target specific ELF writer instance.
143 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
149 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
151 StringTableBuilder ShStrTabBuilder;
154 /// @name Symbol Table Data
157 StringTableBuilder StrTabBuilder;
158 std::vector<uint64_t> FileSymbolData;
159 std::vector<ELFSymbolData> LocalSymbolData;
160 std::vector<ELFSymbolData> ExternalSymbolData;
161 std::vector<ELFSymbolData> UndefinedSymbolData;
167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
171 // This holds the .symtab section index.
172 unsigned SymbolTableIndex;
174 unsigned ShstrtabIndex;
177 // TargetObjectWriter wrappers.
178 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
179 bool hasRelocationAddend() const {
180 return TargetObjectWriter->hasRelocationAddend();
182 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
183 bool IsPCRel) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
188 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
190 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
191 TargetObjectWriter(MOTW), NeedsGOT(false) {}
193 void reset() override {
195 WeakrefUsedInReloc.clear();
198 ShStrTabBuilder.clear();
199 StrTabBuilder.clear();
200 FileSymbolData.clear();
201 LocalSymbolData.clear();
202 ExternalSymbolData.clear();
203 UndefinedSymbolData.clear();
204 MCObjectWriter::reset();
207 virtual ~ELFObjectWriter();
209 void WriteWord(uint64_t W) {
216 template <typename T> void write(MCDataFragment &F, T Value) {
217 FWriter.write(F, Value);
220 void WriteHeader(const MCAssembler &Asm,
221 uint64_t SectionDataSize,
222 unsigned NumberOfSections);
224 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
225 const MCAsmLayout &Layout);
227 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
228 const MCAsmLayout &Layout,
229 SectionIndexMapTy &SectionIndexMap);
231 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
232 const MCSymbolRefExpr *RefA,
233 const MCSymbolData *SD, uint64_t C,
234 unsigned Type) const;
236 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
237 const MCFragment *Fragment, const MCFixup &Fixup,
238 MCValue Target, bool &IsPCRel,
239 uint64_t &FixedValue) override;
241 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
244 // Map from a group section to the signature symbol
245 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
246 // Map from a signature symbol to the group section
247 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
248 // Map from a section to its offset
249 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
251 /// Compute the symbol table data
253 /// \param Asm - The assembler.
254 /// \param SectionIndexMap - Maps a section to its index.
255 /// \param RevGroupMap - Maps a signature symbol to the group section.
256 /// \param NumRegularSections - Number of non-relocation sections.
257 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
258 const SectionIndexMapTy &SectionIndexMap,
259 const RevGroupMapTy &RevGroupMap);
261 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
263 MCSectionData *createRelocationSection(MCAssembler &Asm,
264 const MCSectionData &SD);
266 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
268 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
270 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
271 SectionIndexMapTy &SectionIndexMap);
273 // Create the sections that show up in the symbol table. Currently
274 // those are the .note.GNU-stack section and the group sections.
275 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
276 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
277 SectionIndexMapTy &SectionIndexMap);
279 void ExecutePostLayoutBinding(MCAssembler &Asm,
280 const MCAsmLayout &Layout) override;
282 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
283 const MCAsmLayout &Layout,
284 const SectionIndexMapTy &SectionIndexMap,
285 const SectionOffsetMapTy &SectionOffsetMap);
287 void ComputeSectionOrder(MCAssembler &Asm,
288 std::vector<const MCSectionELF*> &Sections);
290 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
291 uint64_t Address, uint64_t Offset,
292 uint64_t Size, uint32_t Link, uint32_t Info,
293 uint64_t Alignment, uint64_t EntrySize);
295 void WriteRelocationsFragment(const MCAssembler &Asm,
297 const MCSectionData *SD);
300 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
301 const MCSymbolData &DataA,
302 const MCSymbolData *DataB,
303 const MCFragment &FB,
305 bool IsPCRel) const override;
307 bool isWeak(const MCSymbolData &SD) const override;
309 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
310 void writeSection(MCAssembler &Asm,
311 const SectionIndexMapTy &SectionIndexMap,
312 uint32_t GroupSymbolIndex,
313 uint64_t Offset, uint64_t Size, uint64_t Alignment,
314 const MCSectionELF &Section);
318 FragmentWriter::FragmentWriter(bool IsLittleEndian)
319 : IsLittleEndian(IsLittleEndian) {}
321 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
323 Val = support::endian::byte_swap<T, support::little>(Val);
325 Val = support::endian::byte_swap<T, support::big>(Val);
326 const char *Start = (const char *)&Val;
327 F.getContents().append(Start, Start + sizeof(T));
330 void SymbolTableWriter::createSymtabShndx() {
334 MCContext &Ctx = Asm.getContext();
335 const MCSectionELF *SymtabShndxSection =
336 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
337 MCSectionData *SymtabShndxSD =
338 &Asm.getOrCreateSectionData(*SymtabShndxSection);
339 SymtabShndxSD->setAlignment(4);
340 ShndxF = new MCDataFragment(SymtabShndxSD);
341 unsigned Index = SectionIndexMap.size() + 1;
342 SectionIndexMap[SymtabShndxSection] = Index;
344 for (unsigned I = 0; I < NumWritten; ++I)
345 write(*ShndxF, uint32_t(0));
348 template <typename T>
349 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
350 FWriter.write(F, Value);
353 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
355 SectionIndexMapTy &SectionIndexMap,
356 MCDataFragment *SymtabF)
357 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
358 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
361 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
362 uint64_t size, uint8_t other,
363 uint32_t shndx, bool Reserved) {
364 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
371 write(*ShndxF, shndx);
373 write(*ShndxF, uint32_t(0));
376 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
378 raw_svector_ostream OS(SymtabF->getContents());
381 write(*SymtabF, name); // st_name
382 write(*SymtabF, info); // st_info
383 write(*SymtabF, other); // st_other
384 write(*SymtabF, Index); // st_shndx
385 write(*SymtabF, value); // st_value
386 write(*SymtabF, size); // st_size
388 write(*SymtabF, name); // st_name
389 write(*SymtabF, uint32_t(value)); // st_value
390 write(*SymtabF, uint32_t(size)); // st_size
391 write(*SymtabF, info); // st_info
392 write(*SymtabF, other); // st_other
393 write(*SymtabF, Index); // st_shndx
399 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
400 const MCFixupKindInfo &FKI =
401 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
403 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
406 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
410 case MCSymbolRefExpr::VK_GOT:
411 case MCSymbolRefExpr::VK_PLT:
412 case MCSymbolRefExpr::VK_GOTPCREL:
413 case MCSymbolRefExpr::VK_GOTOFF:
414 case MCSymbolRefExpr::VK_TPOFF:
415 case MCSymbolRefExpr::VK_TLSGD:
416 case MCSymbolRefExpr::VK_GOTTPOFF:
417 case MCSymbolRefExpr::VK_INDNTPOFF:
418 case MCSymbolRefExpr::VK_NTPOFF:
419 case MCSymbolRefExpr::VK_GOTNTPOFF:
420 case MCSymbolRefExpr::VK_TLSLDM:
421 case MCSymbolRefExpr::VK_DTPOFF:
422 case MCSymbolRefExpr::VK_TLSLD:
427 ELFObjectWriter::~ELFObjectWriter()
430 // Emit the ELF header.
431 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
432 uint64_t SectionDataSize,
433 unsigned NumberOfSections) {
439 // emitWord method behaves differently for ELF32 and ELF64, writing
440 // 4 bytes in the former and 8 in the latter.
442 Write8(0x7f); // e_ident[EI_MAG0]
443 Write8('E'); // e_ident[EI_MAG1]
444 Write8('L'); // e_ident[EI_MAG2]
445 Write8('F'); // e_ident[EI_MAG3]
447 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
450 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
452 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
454 Write8(TargetObjectWriter->getOSABI());
455 Write8(0); // e_ident[EI_ABIVERSION]
457 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
459 Write16(ELF::ET_REL); // e_type
461 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
463 Write32(ELF::EV_CURRENT); // e_version
464 WriteWord(0); // e_entry, no entry point in .o file
465 WriteWord(0); // e_phoff, no program header for .o
466 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
467 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
469 // e_flags = whatever the target wants
470 Write32(Asm.getELFHeaderEFlags());
472 // e_ehsize = ELF header size
473 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
475 Write16(0); // e_phentsize = prog header entry size
476 Write16(0); // e_phnum = # prog header entries = 0
478 // e_shentsize = Section header entry size
479 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
481 // e_shnum = # of section header ents
482 if (NumberOfSections >= ELF::SHN_LORESERVE)
483 Write16(ELF::SHN_UNDEF);
485 Write16(NumberOfSections);
487 // e_shstrndx = Section # of '.shstrtab'
488 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
489 Write16(ELF::SHN_XINDEX);
491 Write16(ShstrtabIndex);
494 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
495 const MCAsmLayout &Layout) {
496 if (Data.isCommon() && Data.isExternal())
497 return Data.getCommonAlignment();
500 if (!Layout.getSymbolOffset(&Data, Res))
503 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
509 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
510 const MCAsmLayout &Layout) {
511 // The presence of symbol versions causes undefined symbols and
512 // versions declared with @@@ to be renamed.
514 for (MCSymbolData &OriginalData : Asm.symbols()) {
515 const MCSymbol &Alias = OriginalData.getSymbol();
518 if (!Alias.isVariable())
520 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
523 const MCSymbol &Symbol = Ref->getSymbol();
524 MCSymbolData &SD = Asm.getSymbolData(Symbol);
526 StringRef AliasName = Alias.getName();
527 size_t Pos = AliasName.find('@');
528 if (Pos == StringRef::npos)
531 // Aliases defined with .symvar copy the binding from the symbol they alias.
532 // This is the first place we are able to copy this information.
533 OriginalData.setExternal(SD.isExternal());
534 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
536 StringRef Rest = AliasName.substr(Pos);
537 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
540 // FIXME: produce a better error message.
541 if (Symbol.isUndefined() && Rest.startswith("@@") &&
542 !Rest.startswith("@@@"))
543 report_fatal_error("A @@ version cannot be undefined");
545 Renames.insert(std::make_pair(&Symbol, &Alias));
549 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
550 uint8_t Type = newType;
552 // Propagation rules:
553 // IFUNC > FUNC > OBJECT > NOTYPE
554 // TLS_OBJECT > OBJECT > NOTYPE
556 // dont let the new type degrade the old type
560 case ELF::STT_GNU_IFUNC:
561 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
562 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
563 Type = ELF::STT_GNU_IFUNC;
566 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
567 Type == ELF::STT_TLS)
568 Type = ELF::STT_FUNC;
570 case ELF::STT_OBJECT:
571 if (Type == ELF::STT_NOTYPE)
572 Type = ELF::STT_OBJECT;
575 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
576 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
584 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
585 const MCAsmLayout &Layout) {
586 MCSymbolData &OrigData = *MSD.SymbolData;
587 assert((!OrigData.getFragment() ||
588 (&OrigData.getFragment()->getParent()->getSection() ==
589 &OrigData.getSymbol().getSection())) &&
590 "The symbol's section doesn't match the fragment's symbol");
591 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
593 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
595 bool IsReserved = !Base || OrigData.isCommon();
597 // Binding and Type share the same byte as upper and lower nibbles
598 uint8_t Binding = MCELF::GetBinding(OrigData);
599 uint8_t Type = MCELF::GetType(OrigData);
600 MCSymbolData *BaseSD = nullptr;
602 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
603 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
605 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
607 // Other and Visibility share the same byte with Visibility using the lower
609 uint8_t Visibility = MCELF::GetVisibility(OrigData);
610 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
613 uint64_t Value = SymbolValue(OrigData, Layout);
616 const MCExpr *ESize = OrigData.getSize();
618 ESize = BaseSD->getSize();
622 if (!ESize->evaluateKnownAbsolute(Res, Layout))
623 report_fatal_error("Size expression must be absolute.");
627 // Write out the symbol table entry
628 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
629 MSD.SectionIndex, IsReserved);
632 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
634 const MCAsmLayout &Layout,
635 SectionIndexMapTy &SectionIndexMap) {
636 // The string table must be emitted first because we need the index
637 // into the string table for all the symbol names.
639 // FIXME: Make sure the start of the symbol table is aligned.
641 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
643 // The first entry is the undefined symbol entry.
644 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
646 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
647 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
648 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
651 // Write the symbol table entries.
652 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
654 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
655 ELFSymbolData &MSD = LocalSymbolData[i];
656 WriteSymbol(Writer, MSD, Layout);
659 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
660 ELFSymbolData &MSD = ExternalSymbolData[i];
661 MCSymbolData &Data = *MSD.SymbolData;
662 assert(((Data.getFlags() & ELF_STB_Global) ||
663 (Data.getFlags() & ELF_STB_Weak)) &&
664 "External symbol requires STB_GLOBAL or STB_WEAK flag");
665 WriteSymbol(Writer, MSD, Layout);
666 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
667 LastLocalSymbolIndex++;
670 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
671 ELFSymbolData &MSD = UndefinedSymbolData[i];
672 MCSymbolData &Data = *MSD.SymbolData;
673 WriteSymbol(Writer, MSD, Layout);
674 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
675 LastLocalSymbolIndex++;
679 // It is always valid to create a relocation with a symbol. It is preferable
680 // to use a relocation with a section if that is possible. Using the section
681 // allows us to omit some local symbols from the symbol table.
682 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
683 const MCSymbolRefExpr *RefA,
684 const MCSymbolData *SD,
686 unsigned Type) const {
687 // A PCRel relocation to an absolute value has no symbol (or section). We
688 // represent that with a relocation to a null section.
692 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
696 // The .odp creation emits a relocation against the symbol ".TOC." which
697 // create a R_PPC64_TOC relocation. However the relocation symbol name
698 // in final object creation should be NULL, since the symbol does not
699 // really exist, it is just the reference to TOC base for the current
700 // object file. Since the symbol is undefined, returning false results
701 // in a relocation with a null section which is the desired result.
702 case MCSymbolRefExpr::VK_PPC_TOCBASE:
705 // These VariantKind cause the relocation to refer to something other than
706 // the symbol itself, like a linker generated table. Since the address of
707 // symbol is not relevant, we cannot replace the symbol with the
708 // section and patch the difference in the addend.
709 case MCSymbolRefExpr::VK_GOT:
710 case MCSymbolRefExpr::VK_PLT:
711 case MCSymbolRefExpr::VK_GOTPCREL:
712 case MCSymbolRefExpr::VK_Mips_GOT:
713 case MCSymbolRefExpr::VK_PPC_GOT_LO:
714 case MCSymbolRefExpr::VK_PPC_GOT_HI:
715 case MCSymbolRefExpr::VK_PPC_GOT_HA:
719 // An undefined symbol is not in any section, so the relocation has to point
720 // to the symbol itself.
721 const MCSymbol &Sym = SD->getSymbol();
722 if (Sym.isUndefined())
725 unsigned Binding = MCELF::GetBinding(*SD);
728 llvm_unreachable("Invalid Binding");
732 // If the symbol is weak, it might be overridden by a symbol in another
733 // file. The relocation has to point to the symbol so that the linker
736 case ELF::STB_GLOBAL:
737 // Global ELF symbols can be preempted by the dynamic linker. The relocation
738 // has to point to the symbol for a reason analogous to the STB_WEAK case.
742 // If a relocation points to a mergeable section, we have to be careful.
743 // If the offset is zero, a relocation with the section will encode the
744 // same information. With a non-zero offset, the situation is different.
745 // For example, a relocation can point 42 bytes past the end of a string.
746 // If we change such a relocation to use the section, the linker would think
747 // that it pointed to another string and subtracting 42 at runtime will
748 // produce the wrong value.
749 auto &Sec = cast<MCSectionELF>(Sym.getSection());
750 unsigned Flags = Sec.getFlags();
751 if (Flags & ELF::SHF_MERGE) {
755 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
756 // only handle section relocations to mergeable sections if using RELA.
757 if (!hasRelocationAddend())
761 // Most TLS relocations use a got, so they need the symbol. Even those that
762 // are just an offset (@tpoff), require a symbol in gold versions before
763 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
764 // http://sourceware.org/PR16773.
765 if (Flags & ELF::SHF_TLS)
768 // If the symbol is a thumb function the final relocation must set the lowest
769 // bit. With a symbol that is done by just having the symbol have that bit
770 // set, so we would lose the bit if we relocated with the section.
771 // FIXME: We could use the section but add the bit to the relocation value.
772 if (Asm.isThumbFunc(&Sym))
775 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
780 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
781 const MCSymbol &Sym = Ref.getSymbol();
783 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
786 if (!Sym.isVariable())
789 const MCExpr *Expr = Sym.getVariableValue();
790 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
794 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
795 return &Inner->getSymbol();
799 static bool isWeak(const MCSymbolData &D) {
800 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
803 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
804 const MCAsmLayout &Layout,
805 const MCFragment *Fragment,
806 const MCFixup &Fixup, MCValue Target,
807 bool &IsPCRel, uint64_t &FixedValue) {
808 const MCSectionData *FixupSection = Fragment->getParent();
809 uint64_t C = Target.getConstant();
810 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
812 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
813 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
814 "Should not have constructed this");
816 // Let A, B and C being the components of Target and R be the location of
817 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
818 // If it is pcrel, we want to compute (A - B + C - R).
820 // In general, ELF has no relocations for -B. It can only represent (A + C)
821 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
822 // replace B to implement it: (A - R - K + C)
824 Asm.getContext().FatalError(
826 "No relocation available to represent this relative expression");
828 const MCSymbol &SymB = RefB->getSymbol();
830 if (SymB.isUndefined())
831 Asm.getContext().FatalError(
833 Twine("symbol '") + SymB.getName() +
834 "' can not be undefined in a subtraction expression");
836 assert(!SymB.isAbsolute() && "Should have been folded");
837 const MCSection &SecB = SymB.getSection();
838 if (&SecB != &FixupSection->getSection())
839 Asm.getContext().FatalError(
840 Fixup.getLoc(), "Cannot represent a difference across sections");
842 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
844 Asm.getContext().FatalError(
845 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
847 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
848 uint64_t K = SymBOffset - FixupOffset;
853 // We either rejected the fixup or folded B into C at this point.
854 const MCSymbolRefExpr *RefA = Target.getSymA();
855 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
856 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
858 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
859 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
860 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
861 C += Layout.getSymbolOffset(SymAD);
864 if (hasRelocationAddend()) {
871 // FIXME: What is this!?!?
872 MCSymbolRefExpr::VariantKind Modifier =
873 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
874 if (RelocNeedsGOT(Modifier))
877 if (!RelocateWithSymbol) {
878 const MCSection *SecA =
879 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
880 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
881 MCSymbol *SectionSymbol =
882 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
884 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
885 Relocations[FixupSection].push_back(Rec);
890 if (const MCSymbol *R = Renames.lookup(SymA))
893 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
894 WeakrefUsedInReloc.insert(WeakRef);
896 UsedInReloc.insert(SymA);
898 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
899 Relocations[FixupSection].push_back(Rec);
905 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
907 const MCSymbolData &SD = Asm.getSymbolData(*S);
908 return SD.getIndex();
911 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
912 const MCSymbolData &Data, bool Used,
914 const MCSymbol &Symbol = Data.getSymbol();
915 if (Symbol.isVariable()) {
916 const MCExpr *Expr = Symbol.getVariableValue();
917 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
918 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
929 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
932 if (Symbol.isVariable()) {
933 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
934 if (Base && Base->isUndefined())
938 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
939 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
942 if (Symbol.isTemporary())
948 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
949 if (Data.isExternal())
952 const MCSymbol &Symbol = Data.getSymbol();
953 if (Symbol.isDefined())
962 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
963 SectionIndexMapTy &SectionIndexMap) {
965 for (MCAssembler::iterator it = Asm.begin(),
966 ie = Asm.end(); it != ie; ++it) {
967 const MCSectionELF &Section =
968 static_cast<const MCSectionELF &>(it->getSection());
969 if (Section.getType() != ELF::SHT_GROUP)
971 SectionIndexMap[&Section] = Index++;
974 for (MCAssembler::iterator it = Asm.begin(),
975 ie = Asm.end(); it != ie; ++it) {
976 const MCSectionData &SD = *it;
977 const MCSectionELF &Section =
978 static_cast<const MCSectionELF &>(SD.getSection());
979 if (Section.getType() == ELF::SHT_GROUP ||
980 Section.getType() == ELF::SHT_REL ||
981 Section.getType() == ELF::SHT_RELA)
983 SectionIndexMap[&Section] = Index++;
984 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
985 const MCSectionELF *RelSection =
986 static_cast<const MCSectionELF *>(&RelSD->getSection());
987 SectionIndexMap[RelSection] = Index++;
992 void ELFObjectWriter::computeSymbolTable(
993 MCAssembler &Asm, const MCAsmLayout &Layout,
994 const SectionIndexMapTy &SectionIndexMap,
995 const RevGroupMapTy &RevGroupMap) {
996 // FIXME: Is this the correct place to do this?
997 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
999 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1000 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1001 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1002 Data.setExternal(true);
1003 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1006 // Add the data for the symbols.
1007 for (MCSymbolData &SD : Asm.symbols()) {
1008 const MCSymbol &Symbol = SD.getSymbol();
1010 bool Used = UsedInReloc.count(&Symbol);
1011 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1012 bool isSignature = RevGroupMap.count(&Symbol);
1014 if (!isInSymtab(Layout, SD,
1015 Used || WeakrefUsed || isSignature,
1016 Renames.count(&Symbol)))
1020 MSD.SymbolData = &SD;
1021 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1023 // Undefined symbols are global, but this is the first place we
1024 // are able to set it.
1025 bool Local = isLocal(SD, Used);
1026 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1028 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1029 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1030 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1034 MSD.SectionIndex = ELF::SHN_ABS;
1035 } else if (SD.isCommon()) {
1037 MSD.SectionIndex = ELF::SHN_COMMON;
1038 } else if (BaseSymbol->isUndefined()) {
1039 if (isSignature && !Used)
1040 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1042 MSD.SectionIndex = ELF::SHN_UNDEF;
1043 if (!Used && WeakrefUsed)
1044 MCELF::SetBinding(SD, ELF::STB_WEAK);
1046 const MCSectionELF &Section =
1047 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1048 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1049 assert(MSD.SectionIndex && "Invalid section index!");
1052 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1055 // FIXME: All name handling should be done before we get to the writer,
1056 // including dealing with GNU-style version suffixes. Fixing this isn't
1059 // We thus have to be careful to not perform the symbol version replacement
1062 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1063 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1064 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1065 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1066 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1067 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1068 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1069 // "__imp_?" or "__imp_@?".
1071 // It would have been interesting to perform the MS mangling prefix check
1072 // only when the target triple is of the form *-pc-windows-elf. But, it
1073 // seems that this information is not easily accessible from the
1075 StringRef Name = Symbol.getName();
1076 if (!Name.startswith("?") && !Name.startswith("@?") &&
1077 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1078 // This symbol isn't following the MSVC C++ name mangling convention. We
1079 // can thus safely interpret the @@@ in symbol names as specifying symbol
1081 SmallString<32> Buf;
1082 size_t Pos = Name.find("@@@");
1083 if (Pos != StringRef::npos) {
1084 Buf += Name.substr(0, Pos);
1085 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1086 Buf += Name.substr(Pos + Skip);
1091 // Sections have their own string table
1092 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1093 MSD.Name = StrTabBuilder.add(Name);
1095 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1096 UndefinedSymbolData.push_back(MSD);
1098 LocalSymbolData.push_back(MSD);
1100 ExternalSymbolData.push_back(MSD);
1103 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1104 StrTabBuilder.add(*i);
1106 StrTabBuilder.finalize(StringTableBuilder::ELF);
1108 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1109 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1111 for (ELFSymbolData &MSD : LocalSymbolData)
1112 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1114 : StrTabBuilder.getOffset(MSD.Name);
1115 for (ELFSymbolData &MSD : ExternalSymbolData)
1116 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1117 for (ELFSymbolData& MSD : UndefinedSymbolData)
1118 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1120 // Symbols are required to be in lexicographic order.
1121 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1122 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1123 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1125 // Set the symbol indices. Local symbols must come before all other
1126 // symbols with non-local bindings.
1127 unsigned Index = FileSymbolData.size() + 1;
1128 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1129 LocalSymbolData[i].SymbolData->setIndex(Index++);
1131 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1132 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1133 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1134 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1138 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1139 const MCSectionData &SD) {
1140 if (Relocations[&SD].empty())
1143 MCContext &Ctx = Asm.getContext();
1144 const MCSectionELF &Section =
1145 static_cast<const MCSectionELF &>(SD.getSection());
1147 const StringRef SectionName = Section.getSectionName();
1148 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1149 RelaSectionName += SectionName;
1152 if (hasRelocationAddend())
1153 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1155 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1158 if (Section.getFlags() & ELF::SHF_GROUP)
1159 Flags = ELF::SHF_GROUP;
1161 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1162 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1163 Flags, EntrySize, Section.getGroup(), &Section);
1164 return &Asm.getOrCreateSectionData(*RelaSection);
1167 static SmallVector<char, 128>
1168 getUncompressedData(MCAsmLayout &Layout,
1169 MCSectionData::FragmentListType &Fragments) {
1170 SmallVector<char, 128> UncompressedData;
1171 for (const MCFragment &F : Fragments) {
1172 const SmallVectorImpl<char> *Contents;
1173 switch (F.getKind()) {
1174 case MCFragment::FT_Data:
1175 Contents = &cast<MCDataFragment>(F).getContents();
1177 case MCFragment::FT_Dwarf:
1178 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1180 case MCFragment::FT_DwarfFrame:
1181 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1185 "Not expecting any other fragment types in a debug_* section");
1187 UncompressedData.append(Contents->begin(), Contents->end());
1189 return UncompressedData;
1192 // Include the debug info compression header:
1193 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1194 // useful for consumers to preallocate a buffer to decompress into.
1196 prependCompressionHeader(uint64_t Size,
1197 SmallVectorImpl<char> &CompressedContents) {
1198 const StringRef Magic = "ZLIB";
1199 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1201 if (sys::IsLittleEndianHost)
1202 sys::swapByteOrder(Size);
1203 CompressedContents.insert(CompressedContents.begin(),
1204 Magic.size() + sizeof(Size), 0);
1205 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1206 std::copy(reinterpret_cast<char *>(&Size),
1207 reinterpret_cast<char *>(&Size + 1),
1208 CompressedContents.begin() + Magic.size());
1212 // Return a single fragment containing the compressed contents of the whole
1213 // section. Null if the section was not compressed for any reason.
1214 static std::unique_ptr<MCDataFragment>
1215 getCompressedFragment(MCAsmLayout &Layout,
1216 MCSectionData::FragmentListType &Fragments) {
1217 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1219 // Gather the uncompressed data from all the fragments, recording the
1220 // alignment fragment, if seen, and any fixups.
1221 SmallVector<char, 128> UncompressedData =
1222 getUncompressedData(Layout, Fragments);
1224 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1226 zlib::Status Success = zlib::compress(
1227 StringRef(UncompressedData.data(), UncompressedData.size()),
1228 CompressedContents);
1229 if (Success != zlib::StatusOK)
1232 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1235 return CompressedFragment;
1238 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1241 static void UpdateSymbols(const MCAsmLayout &Layout,
1242 const std::vector<MCSymbolData *> &Symbols,
1243 MCFragment &NewFragment) {
1244 for (MCSymbolData *Sym : Symbols) {
1245 Sym->setOffset(Sym->getOffset() +
1246 Layout.getFragmentOffset(Sym->getFragment()));
1247 Sym->setFragment(&NewFragment);
1251 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1252 const DefiningSymbolMap &DefiningSymbols,
1253 const MCSectionELF &Section,
1254 MCSectionData &SD) {
1255 StringRef SectionName = Section.getSectionName();
1256 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1258 std::unique_ptr<MCDataFragment> CompressedFragment =
1259 getCompressedFragment(Layout, Fragments);
1261 // Leave the section as-is if the fragments could not be compressed.
1262 if (!CompressedFragment)
1265 // Update the fragment+offsets of any symbols referring to fragments in this
1266 // section to refer to the new fragment.
1267 auto I = DefiningSymbols.find(&SD);
1268 if (I != DefiningSymbols.end())
1269 UpdateSymbols(Layout, I->second, *CompressedFragment);
1271 // Invalidate the layout for the whole section since it will have new and
1272 // different fragments now.
1273 Layout.invalidateFragmentsFrom(&Fragments.front());
1276 // Complete the initialization of the new fragment
1277 CompressedFragment->setParent(&SD);
1278 CompressedFragment->setLayoutOrder(0);
1279 Fragments.push_back(CompressedFragment.release());
1281 // Rename from .debug_* to .zdebug_*
1282 Asm.getContext().renameELFSection(&Section,
1283 (".z" + SectionName.drop_front(1)).str());
1286 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1287 MCAsmLayout &Layout) {
1288 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1291 DefiningSymbolMap DefiningSymbols;
1293 for (MCSymbolData &SD : Asm.symbols())
1294 if (MCFragment *F = SD.getFragment())
1295 DefiningSymbols[F->getParent()].push_back(&SD);
1297 for (MCSectionData &SD : Asm) {
1298 const MCSectionELF &Section =
1299 static_cast<const MCSectionELF &>(SD.getSection());
1300 StringRef SectionName = Section.getSectionName();
1302 // Compressing debug_frame requires handling alignment fragments which is
1303 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1304 // for writing to arbitrary buffers) for little benefit.
1305 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1308 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1312 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1313 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1314 MCSectionData &RelSD = *it;
1315 const MCSectionELF &RelSection =
1316 static_cast<const MCSectionELF &>(RelSD.getSection());
1318 unsigned Type = RelSection.getType();
1319 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1322 const MCSectionELF *Section = RelSection.getAssociatedSection();
1323 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1324 RelSD.setAlignment(is64Bit() ? 8 : 4);
1326 MCDataFragment *F = new MCDataFragment(&RelSD);
1327 WriteRelocationsFragment(Asm, F, &SD);
1331 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1332 uint64_t Flags, uint64_t Address,
1333 uint64_t Offset, uint64_t Size,
1334 uint32_t Link, uint32_t Info,
1336 uint64_t EntrySize) {
1337 Write32(Name); // sh_name: index into string table
1338 Write32(Type); // sh_type
1339 WriteWord(Flags); // sh_flags
1340 WriteWord(Address); // sh_addr
1341 WriteWord(Offset); // sh_offset
1342 WriteWord(Size); // sh_size
1343 Write32(Link); // sh_link
1344 Write32(Info); // sh_info
1345 WriteWord(Alignment); // sh_addralign
1346 WriteWord(EntrySize); // sh_entsize
1349 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1350 // just to match gnu as for easier comparison. The use type is an arbitrary way
1351 // of making the sort deterministic.
1352 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1353 const ELFRelocationEntry &A = *AP;
1354 const ELFRelocationEntry &B = *BP;
1355 if (A.Offset != B.Offset)
1356 return B.Offset - A.Offset;
1357 if (B.Type != A.Type)
1358 return A.Type - B.Type;
1359 //llvm_unreachable("ELFRelocs might be unstable!");
1363 static void sortRelocs(const MCAssembler &Asm,
1364 std::vector<ELFRelocationEntry> &Relocs) {
1365 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1368 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1370 const MCSectionData *SD) {
1371 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1373 sortRelocs(Asm, Relocs);
1375 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1376 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1378 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1381 write(*F, Entry.Offset);
1382 if (TargetObjectWriter->isN64()) {
1383 write(*F, uint32_t(Index));
1385 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1386 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1387 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1388 write(*F, TargetObjectWriter->getRType(Entry.Type));
1390 struct ELF::Elf64_Rela ERE64;
1391 ERE64.setSymbolAndType(Index, Entry.Type);
1392 write(*F, ERE64.r_info);
1394 if (hasRelocationAddend())
1395 write(*F, Entry.Addend);
1397 write(*F, uint32_t(Entry.Offset));
1399 struct ELF::Elf32_Rela ERE32;
1400 ERE32.setSymbolAndType(Index, Entry.Type);
1401 write(*F, ERE32.r_info);
1403 if (hasRelocationAddend())
1404 write(*F, uint32_t(Entry.Addend));
1409 void ELFObjectWriter::CreateMetadataSections(
1410 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1411 MCContext &Ctx = Asm.getContext();
1414 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1416 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1417 const MCSectionELF *ShstrtabSection =
1418 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1419 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1420 ShstrtabSD.setAlignment(1);
1421 ShstrtabIndex = SectionIndexMap.size() + 1;
1422 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1424 const MCSectionELF *SymtabSection =
1425 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1427 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1428 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1429 SymbolTableIndex = SectionIndexMap.size() + 1;
1430 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1432 const MCSectionELF *StrtabSection;
1433 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1434 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1435 StrtabSD.setAlignment(1);
1436 StringTableIndex = SectionIndexMap.size() + 1;
1437 SectionIndexMap[StrtabSection] = StringTableIndex;
1440 F = new MCDataFragment(&SymtabSD);
1441 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1443 F = new MCDataFragment(&StrtabSD);
1444 F->getContents().append(StrTabBuilder.data().begin(),
1445 StrTabBuilder.data().end());
1447 F = new MCDataFragment(&ShstrtabSD);
1449 // Section header string table.
1450 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1451 const MCSectionELF &Section =
1452 static_cast<const MCSectionELF&>(it->getSection());
1453 ShStrTabBuilder.add(Section.getSectionName());
1455 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1456 F->getContents().append(ShStrTabBuilder.data().begin(),
1457 ShStrTabBuilder.data().end());
1460 void ELFObjectWriter::createIndexedSections(
1461 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1462 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1463 MCContext &Ctx = Asm.getContext();
1466 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1468 const MCSectionELF &Section =
1469 static_cast<const MCSectionELF&>(it->getSection());
1470 if (!(Section.getFlags() & ELF::SHF_GROUP))
1473 const MCSymbol *SignatureSymbol = Section.getGroup();
1474 Asm.getOrCreateSymbolData(*SignatureSymbol);
1475 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1477 Group = Ctx.CreateELFGroupSection();
1478 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1479 Data.setAlignment(4);
1480 MCDataFragment *F = new MCDataFragment(&Data);
1481 write(*F, uint32_t(ELF::GRP_COMDAT));
1483 GroupMap[Group] = SignatureSymbol;
1486 computeIndexMap(Asm, SectionIndexMap);
1488 // Add sections to the groups
1489 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1491 const MCSectionELF &Section =
1492 static_cast<const MCSectionELF&>(it->getSection());
1493 if (!(Section.getFlags() & ELF::SHF_GROUP))
1495 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1496 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1497 // FIXME: we could use the previous fragment
1498 MCDataFragment *F = new MCDataFragment(&Data);
1499 uint32_t Index = SectionIndexMap.lookup(&Section);
1504 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1505 const SectionIndexMapTy &SectionIndexMap,
1506 uint32_t GroupSymbolIndex,
1507 uint64_t Offset, uint64_t Size,
1509 const MCSectionELF &Section) {
1510 uint64_t sh_link = 0;
1511 uint64_t sh_info = 0;
1513 switch(Section.getType()) {
1518 case ELF::SHT_DYNAMIC:
1519 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1523 case ELF::SHT_RELA: {
1524 sh_link = SymbolTableIndex;
1525 assert(sh_link && ".symtab not found");
1526 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1527 sh_info = SectionIndexMap.lookup(InfoSection);
1531 case ELF::SHT_SYMTAB:
1532 case ELF::SHT_DYNSYM:
1533 sh_link = StringTableIndex;
1534 sh_info = LastLocalSymbolIndex;
1537 case ELF::SHT_SYMTAB_SHNDX:
1538 sh_link = SymbolTableIndex;
1541 case ELF::SHT_GROUP:
1542 sh_link = SymbolTableIndex;
1543 sh_info = GroupSymbolIndex;
1547 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1548 Section.getType() == ELF::SHT_ARM_EXIDX)
1549 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1551 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1553 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1554 Alignment, Section.getEntrySize());
1557 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1558 return SD.getOrdinal() == ~UINT32_C(0) &&
1559 !SD.getSection().isVirtualSection();
1562 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1564 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1566 const MCFragment &F = *i;
1567 assert(F.getKind() == MCFragment::FT_Data);
1568 Ret += cast<MCDataFragment>(F).getContents().size();
1573 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1574 const MCSectionData &SD) {
1575 if (IsELFMetaDataSection(SD))
1576 return DataSectionSize(SD);
1577 return Layout.getSectionFileSize(&SD);
1580 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1581 const MCSectionData &SD) {
1582 if (IsELFMetaDataSection(SD))
1583 return DataSectionSize(SD);
1584 return Layout.getSectionAddressSize(&SD);
1587 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1588 const MCAsmLayout &Layout,
1589 const MCSectionELF &Section) {
1590 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1592 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1593 WriteZeros(Padding);
1595 if (IsELFMetaDataSection(SD)) {
1596 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1598 const MCFragment &F = *i;
1599 assert(F.getKind() == MCFragment::FT_Data);
1600 WriteBytes(cast<MCDataFragment>(F).getContents());
1603 Asm.writeSectionData(&SD, Layout);
1607 void ELFObjectWriter::writeSectionHeader(
1608 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1609 const SectionIndexMapTy &SectionIndexMap,
1610 const SectionOffsetMapTy &SectionOffsetMap) {
1611 const unsigned NumSections = Asm.size() + 1;
1613 std::vector<const MCSectionELF*> Sections;
1614 Sections.resize(NumSections - 1);
1616 for (SectionIndexMapTy::const_iterator i=
1617 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1618 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1619 Sections[p.second - 1] = p.first;
1622 // Null section first.
1623 uint64_t FirstSectionSize =
1624 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1625 uint32_t FirstSectionLink =
1626 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1627 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1629 for (unsigned i = 0; i < NumSections - 1; ++i) {
1630 const MCSectionELF &Section = *Sections[i];
1631 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1632 uint32_t GroupSymbolIndex;
1633 if (Section.getType() != ELF::SHT_GROUP)
1634 GroupSymbolIndex = 0;
1636 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1637 GroupMap.lookup(&Section));
1639 uint64_t Size = GetSectionAddressSize(Layout, SD);
1641 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1642 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1647 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1648 std::vector<const MCSectionELF*> &Sections) {
1649 for (MCAssembler::iterator it = Asm.begin(),
1650 ie = Asm.end(); it != ie; ++it) {
1651 const MCSectionELF &Section =
1652 static_cast<const MCSectionELF &>(it->getSection());
1653 if (Section.getType() == ELF::SHT_GROUP)
1654 Sections.push_back(&Section);
1657 for (MCAssembler::iterator it = Asm.begin(),
1658 ie = Asm.end(); it != ie; ++it) {
1659 const MCSectionELF &Section =
1660 static_cast<const MCSectionELF &>(it->getSection());
1661 if (Section.getType() != ELF::SHT_GROUP &&
1662 Section.getType() != ELF::SHT_REL &&
1663 Section.getType() != ELF::SHT_RELA)
1664 Sections.push_back(&Section);
1667 for (MCAssembler::iterator it = Asm.begin(),
1668 ie = Asm.end(); it != ie; ++it) {
1669 const MCSectionELF &Section =
1670 static_cast<const MCSectionELF &>(it->getSection());
1671 if (Section.getType() == ELF::SHT_REL ||
1672 Section.getType() == ELF::SHT_RELA)
1673 Sections.push_back(&Section);
1677 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1678 const MCAsmLayout &Layout) {
1679 GroupMapTy GroupMap;
1680 RevGroupMapTy RevGroupMap;
1681 SectionIndexMapTy SectionIndexMap;
1683 unsigned NumUserSections = Asm.size();
1685 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1687 const unsigned NumUserAndRelocSections = Asm.size();
1688 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1689 RevGroupMap, SectionIndexMap);
1690 const unsigned AllSections = Asm.size();
1691 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1693 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1695 // Compute symbol table information.
1696 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1698 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1700 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1701 const_cast<MCAsmLayout&>(Layout),
1704 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1705 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1706 sizeof(ELF::Elf32_Ehdr);
1707 uint64_t FileOff = HeaderSize;
1709 std::vector<const MCSectionELF*> Sections;
1710 ComputeSectionOrder(Asm, Sections);
1711 unsigned NumSections = Sections.size();
1712 SectionOffsetMapTy SectionOffsetMap;
1713 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1714 const MCSectionELF &Section = *Sections[i];
1715 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1717 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1719 // Remember the offset into the file for this section.
1720 SectionOffsetMap[&Section] = FileOff;
1722 // Get the size of the section in the output file (including padding).
1723 FileOff += GetSectionFileSize(Layout, SD);
1726 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1728 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1730 uint64_t SectionHeaderEntrySize = is64Bit() ?
1731 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1732 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1734 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1735 const MCSectionELF &Section = *Sections[i];
1736 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1738 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1740 // Remember the offset into the file for this section.
1741 SectionOffsetMap[&Section] = FileOff;
1743 // Get the size of the section in the output file (including padding).
1744 FileOff += GetSectionFileSize(Layout, SD);
1747 // Write out the ELF header ...
1748 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1750 // ... then the regular sections ...
1751 // + because of .shstrtab
1752 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1753 WriteDataSectionData(Asm, Layout, *Sections[i]);
1755 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1756 WriteZeros(Padding);
1758 // ... then the section header table ...
1759 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1761 // ... and then the remaining sections ...
1762 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1763 WriteDataSectionData(Asm, Layout, *Sections[i]);
1766 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1767 const MCAssembler &Asm, const MCSymbolData &DataA,
1768 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1769 bool IsPCRel) const {
1770 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1772 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1773 Asm, DataA, DataB, FB, InSet, IsPCRel);
1776 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1777 return ::isWeak(SD);
1780 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1782 bool IsLittleEndian) {
1783 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);