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,
260 unsigned NumRegularSections);
262 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
264 MCSectionData *createRelocationSection(MCAssembler &Asm,
265 const MCSectionData &SD);
267 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
269 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
271 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
272 SectionIndexMapTy &SectionIndexMap);
274 // Create the sections that show up in the symbol table. Currently
275 // those are the .note.GNU-stack section and the group sections.
276 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
277 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
278 SectionIndexMapTy &SectionIndexMap);
280 void ExecutePostLayoutBinding(MCAssembler &Asm,
281 const MCAsmLayout &Layout) override;
283 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
284 const MCAsmLayout &Layout,
285 const SectionIndexMapTy &SectionIndexMap,
286 const SectionOffsetMapTy &SectionOffsetMap);
288 void ComputeSectionOrder(MCAssembler &Asm,
289 std::vector<const MCSectionELF*> &Sections);
291 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
292 uint64_t Address, uint64_t Offset,
293 uint64_t Size, uint32_t Link, uint32_t Info,
294 uint64_t Alignment, uint64_t EntrySize);
296 void WriteRelocationsFragment(const MCAssembler &Asm,
298 const MCSectionData *SD);
301 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
302 const MCSymbolData &DataA,
303 const MCSymbolData *DataB,
304 const MCFragment &FB,
306 bool IsPCRel) const override;
308 bool isWeak(const MCSymbolData &SD) const override;
310 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
311 void writeSection(MCAssembler &Asm,
312 const SectionIndexMapTy &SectionIndexMap,
313 uint32_t GroupSymbolIndex,
314 uint64_t Offset, uint64_t Size, uint64_t Alignment,
315 const MCSectionELF &Section);
319 FragmentWriter::FragmentWriter(bool IsLittleEndian)
320 : IsLittleEndian(IsLittleEndian) {}
322 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
324 Val = support::endian::byte_swap<T, support::little>(Val);
326 Val = support::endian::byte_swap<T, support::big>(Val);
327 const char *Start = (const char *)&Val;
328 F.getContents().append(Start, Start + sizeof(T));
331 void SymbolTableWriter::createSymtabShndx() {
335 MCContext &Ctx = Asm.getContext();
336 const MCSectionELF *SymtabShndxSection =
337 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
338 MCSectionData *SymtabShndxSD =
339 &Asm.getOrCreateSectionData(*SymtabShndxSection);
340 SymtabShndxSD->setAlignment(4);
341 ShndxF = new MCDataFragment(SymtabShndxSD);
342 unsigned Index = SectionIndexMap.size() + 1;
343 SectionIndexMap[SymtabShndxSection] = Index;
345 for (unsigned I = 0; I < NumWritten; ++I)
346 write(*ShndxF, uint32_t(0));
349 template <typename T>
350 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
351 FWriter.write(F, Value);
354 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
356 SectionIndexMapTy &SectionIndexMap,
357 MCDataFragment *SymtabF)
358 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
359 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
362 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
363 uint64_t size, uint8_t other,
364 uint32_t shndx, bool Reserved) {
365 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
372 write(*ShndxF, shndx);
374 write(*ShndxF, uint32_t(0));
377 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
379 raw_svector_ostream OS(SymtabF->getContents());
382 write(*SymtabF, name); // st_name
383 write(*SymtabF, info); // st_info
384 write(*SymtabF, other); // st_other
385 write(*SymtabF, Index); // st_shndx
386 write(*SymtabF, value); // st_value
387 write(*SymtabF, size); // st_size
389 write(*SymtabF, name); // st_name
390 write(*SymtabF, uint32_t(value)); // st_value
391 write(*SymtabF, uint32_t(size)); // st_size
392 write(*SymtabF, info); // st_info
393 write(*SymtabF, other); // st_other
394 write(*SymtabF, Index); // st_shndx
400 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
401 const MCFixupKindInfo &FKI =
402 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
404 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
407 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
411 case MCSymbolRefExpr::VK_GOT:
412 case MCSymbolRefExpr::VK_PLT:
413 case MCSymbolRefExpr::VK_GOTPCREL:
414 case MCSymbolRefExpr::VK_GOTOFF:
415 case MCSymbolRefExpr::VK_TPOFF:
416 case MCSymbolRefExpr::VK_TLSGD:
417 case MCSymbolRefExpr::VK_GOTTPOFF:
418 case MCSymbolRefExpr::VK_INDNTPOFF:
419 case MCSymbolRefExpr::VK_NTPOFF:
420 case MCSymbolRefExpr::VK_GOTNTPOFF:
421 case MCSymbolRefExpr::VK_TLSLDM:
422 case MCSymbolRefExpr::VK_DTPOFF:
423 case MCSymbolRefExpr::VK_TLSLD:
428 ELFObjectWriter::~ELFObjectWriter()
431 // Emit the ELF header.
432 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
433 uint64_t SectionDataSize,
434 unsigned NumberOfSections) {
440 // emitWord method behaves differently for ELF32 and ELF64, writing
441 // 4 bytes in the former and 8 in the latter.
443 Write8(0x7f); // e_ident[EI_MAG0]
444 Write8('E'); // e_ident[EI_MAG1]
445 Write8('L'); // e_ident[EI_MAG2]
446 Write8('F'); // e_ident[EI_MAG3]
448 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
451 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
453 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
455 Write8(TargetObjectWriter->getOSABI());
456 Write8(0); // e_ident[EI_ABIVERSION]
458 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
460 Write16(ELF::ET_REL); // e_type
462 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
464 Write32(ELF::EV_CURRENT); // e_version
465 WriteWord(0); // e_entry, no entry point in .o file
466 WriteWord(0); // e_phoff, no program header for .o
467 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
468 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
470 // e_flags = whatever the target wants
471 Write32(Asm.getELFHeaderEFlags());
473 // e_ehsize = ELF header size
474 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
476 Write16(0); // e_phentsize = prog header entry size
477 Write16(0); // e_phnum = # prog header entries = 0
479 // e_shentsize = Section header entry size
480 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
482 // e_shnum = # of section header ents
483 if (NumberOfSections >= ELF::SHN_LORESERVE)
484 Write16(ELF::SHN_UNDEF);
486 Write16(NumberOfSections);
488 // e_shstrndx = Section # of '.shstrtab'
489 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
490 Write16(ELF::SHN_XINDEX);
492 Write16(ShstrtabIndex);
495 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
496 const MCAsmLayout &Layout) {
497 if (Data.isCommon() && Data.isExternal())
498 return Data.getCommonAlignment();
501 if (!Layout.getSymbolOffset(&Data, Res))
504 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
510 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
511 const MCAsmLayout &Layout) {
512 // The presence of symbol versions causes undefined symbols and
513 // versions declared with @@@ to be renamed.
515 for (MCSymbolData &OriginalData : Asm.symbols()) {
516 const MCSymbol &Alias = OriginalData.getSymbol();
519 if (!Alias.isVariable())
521 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
524 const MCSymbol &Symbol = Ref->getSymbol();
525 MCSymbolData &SD = Asm.getSymbolData(Symbol);
527 StringRef AliasName = Alias.getName();
528 size_t Pos = AliasName.find('@');
529 if (Pos == StringRef::npos)
532 // Aliases defined with .symvar copy the binding from the symbol they alias.
533 // This is the first place we are able to copy this information.
534 OriginalData.setExternal(SD.isExternal());
535 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
537 StringRef Rest = AliasName.substr(Pos);
538 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
541 // FIXME: produce a better error message.
542 if (Symbol.isUndefined() && Rest.startswith("@@") &&
543 !Rest.startswith("@@@"))
544 report_fatal_error("A @@ version cannot be undefined");
546 Renames.insert(std::make_pair(&Symbol, &Alias));
550 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
551 uint8_t Type = newType;
553 // Propagation rules:
554 // IFUNC > FUNC > OBJECT > NOTYPE
555 // TLS_OBJECT > OBJECT > NOTYPE
557 // dont let the new type degrade the old type
561 case ELF::STT_GNU_IFUNC:
562 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
563 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
564 Type = ELF::STT_GNU_IFUNC;
567 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
568 Type == ELF::STT_TLS)
569 Type = ELF::STT_FUNC;
571 case ELF::STT_OBJECT:
572 if (Type == ELF::STT_NOTYPE)
573 Type = ELF::STT_OBJECT;
576 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
577 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
585 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
586 const MCAsmLayout &Layout) {
587 MCSymbolData &OrigData = *MSD.SymbolData;
588 assert((!OrigData.getFragment() ||
589 (&OrigData.getFragment()->getParent()->getSection() ==
590 &OrigData.getSymbol().getSection())) &&
591 "The symbol's section doesn't match the fragment's symbol");
592 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
594 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
596 bool IsReserved = !Base || OrigData.isCommon();
598 // Binding and Type share the same byte as upper and lower nibbles
599 uint8_t Binding = MCELF::GetBinding(OrigData);
600 uint8_t Type = MCELF::GetType(OrigData);
601 MCSymbolData *BaseSD = nullptr;
603 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
604 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
606 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
608 // Other and Visibility share the same byte with Visibility using the lower
610 uint8_t Visibility = MCELF::GetVisibility(OrigData);
611 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
614 uint64_t Value = SymbolValue(OrigData, Layout);
617 const MCExpr *ESize = OrigData.getSize();
619 ESize = BaseSD->getSize();
623 if (!ESize->evaluateKnownAbsolute(Res, Layout))
624 report_fatal_error("Size expression must be absolute.");
628 // Write out the symbol table entry
629 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
630 MSD.SectionIndex, IsReserved);
633 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
635 const MCAsmLayout &Layout,
636 SectionIndexMapTy &SectionIndexMap) {
637 // The string table must be emitted first because we need the index
638 // into the string table for all the symbol names.
640 // FIXME: Make sure the start of the symbol table is aligned.
642 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
644 // The first entry is the undefined symbol entry.
645 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
647 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
648 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
649 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
652 // Write the symbol table entries.
653 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
655 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
656 ELFSymbolData &MSD = LocalSymbolData[i];
657 WriteSymbol(Writer, MSD, Layout);
660 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
661 ELFSymbolData &MSD = ExternalSymbolData[i];
662 MCSymbolData &Data = *MSD.SymbolData;
663 assert(((Data.getFlags() & ELF_STB_Global) ||
664 (Data.getFlags() & ELF_STB_Weak)) &&
665 "External symbol requires STB_GLOBAL or STB_WEAK flag");
666 WriteSymbol(Writer, MSD, Layout);
667 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
668 LastLocalSymbolIndex++;
671 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
672 ELFSymbolData &MSD = UndefinedSymbolData[i];
673 MCSymbolData &Data = *MSD.SymbolData;
674 WriteSymbol(Writer, MSD, Layout);
675 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
676 LastLocalSymbolIndex++;
680 // It is always valid to create a relocation with a symbol. It is preferable
681 // to use a relocation with a section if that is possible. Using the section
682 // allows us to omit some local symbols from the symbol table.
683 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
684 const MCSymbolRefExpr *RefA,
685 const MCSymbolData *SD,
687 unsigned Type) const {
688 // A PCRel relocation to an absolute value has no symbol (or section). We
689 // represent that with a relocation to a null section.
693 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
697 // The .odp creation emits a relocation against the symbol ".TOC." which
698 // create a R_PPC64_TOC relocation. However the relocation symbol name
699 // in final object creation should be NULL, since the symbol does not
700 // really exist, it is just the reference to TOC base for the current
701 // object file. Since the symbol is undefined, returning false results
702 // in a relocation with a null section which is the desired result.
703 case MCSymbolRefExpr::VK_PPC_TOCBASE:
706 // These VariantKind cause the relocation to refer to something other than
707 // the symbol itself, like a linker generated table. Since the address of
708 // symbol is not relevant, we cannot replace the symbol with the
709 // section and patch the difference in the addend.
710 case MCSymbolRefExpr::VK_GOT:
711 case MCSymbolRefExpr::VK_PLT:
712 case MCSymbolRefExpr::VK_GOTPCREL:
713 case MCSymbolRefExpr::VK_Mips_GOT:
714 case MCSymbolRefExpr::VK_PPC_GOT_LO:
715 case MCSymbolRefExpr::VK_PPC_GOT_HI:
716 case MCSymbolRefExpr::VK_PPC_GOT_HA:
720 // An undefined symbol is not in any section, so the relocation has to point
721 // to the symbol itself.
722 const MCSymbol &Sym = SD->getSymbol();
723 if (Sym.isUndefined())
726 unsigned Binding = MCELF::GetBinding(*SD);
729 llvm_unreachable("Invalid Binding");
733 // If the symbol is weak, it might be overridden by a symbol in another
734 // file. The relocation has to point to the symbol so that the linker
737 case ELF::STB_GLOBAL:
738 // Global ELF symbols can be preempted by the dynamic linker. The relocation
739 // has to point to the symbol for a reason analogous to the STB_WEAK case.
743 // If a relocation points to a mergeable section, we have to be careful.
744 // If the offset is zero, a relocation with the section will encode the
745 // same information. With a non-zero offset, the situation is different.
746 // For example, a relocation can point 42 bytes past the end of a string.
747 // If we change such a relocation to use the section, the linker would think
748 // that it pointed to another string and subtracting 42 at runtime will
749 // produce the wrong value.
750 auto &Sec = cast<MCSectionELF>(Sym.getSection());
751 unsigned Flags = Sec.getFlags();
752 if (Flags & ELF::SHF_MERGE) {
756 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
757 // only handle section relocations to mergeable sections if using RELA.
758 if (!hasRelocationAddend())
762 // Most TLS relocations use a got, so they need the symbol. Even those that
763 // are just an offset (@tpoff), require a symbol in gold versions before
764 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
765 // http://sourceware.org/PR16773.
766 if (Flags & ELF::SHF_TLS)
769 // If the symbol is a thumb function the final relocation must set the lowest
770 // bit. With a symbol that is done by just having the symbol have that bit
771 // set, so we would lose the bit if we relocated with the section.
772 // FIXME: We could use the section but add the bit to the relocation value.
773 if (Asm.isThumbFunc(&Sym))
776 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
781 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
782 const MCSymbol &Sym = Ref.getSymbol();
784 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
787 if (!Sym.isVariable())
790 const MCExpr *Expr = Sym.getVariableValue();
791 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
795 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
796 return &Inner->getSymbol();
800 static bool isWeak(const MCSymbolData &D) {
801 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
804 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
805 const MCAsmLayout &Layout,
806 const MCFragment *Fragment,
807 const MCFixup &Fixup, MCValue Target,
808 bool &IsPCRel, uint64_t &FixedValue) {
809 const MCSectionData *FixupSection = Fragment->getParent();
810 uint64_t C = Target.getConstant();
811 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
813 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
814 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
815 "Should not have constructed this");
817 // Let A, B and C being the components of Target and R be the location of
818 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
819 // If it is pcrel, we want to compute (A - B + C - R).
821 // In general, ELF has no relocations for -B. It can only represent (A + C)
822 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
823 // replace B to implement it: (A - R - K + C)
825 Asm.getContext().FatalError(
827 "No relocation available to represent this relative expression");
829 const MCSymbol &SymB = RefB->getSymbol();
831 if (SymB.isUndefined())
832 Asm.getContext().FatalError(
834 Twine("symbol '") + SymB.getName() +
835 "' can not be undefined in a subtraction expression");
837 assert(!SymB.isAbsolute() && "Should have been folded");
838 const MCSection &SecB = SymB.getSection();
839 if (&SecB != &FixupSection->getSection())
840 Asm.getContext().FatalError(
841 Fixup.getLoc(), "Cannot represent a difference across sections");
843 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
845 Asm.getContext().FatalError(
846 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
848 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
849 uint64_t K = SymBOffset - FixupOffset;
854 // We either rejected the fixup or folded B into C at this point.
855 const MCSymbolRefExpr *RefA = Target.getSymA();
856 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
857 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
859 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
860 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
861 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
862 C += Layout.getSymbolOffset(SymAD);
865 if (hasRelocationAddend()) {
872 // FIXME: What is this!?!?
873 MCSymbolRefExpr::VariantKind Modifier =
874 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
875 if (RelocNeedsGOT(Modifier))
878 if (!RelocateWithSymbol) {
879 const MCSection *SecA =
880 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
881 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
882 MCSymbol *SectionSymbol =
883 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
885 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
886 Relocations[FixupSection].push_back(Rec);
891 if (const MCSymbol *R = Renames.lookup(SymA))
894 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
895 WeakrefUsedInReloc.insert(WeakRef);
897 UsedInReloc.insert(SymA);
899 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
900 Relocations[FixupSection].push_back(Rec);
906 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
908 const MCSymbolData &SD = Asm.getSymbolData(*S);
909 return SD.getIndex();
912 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
913 const MCSymbolData &Data, bool Used,
915 const MCSymbol &Symbol = Data.getSymbol();
916 if (Symbol.isVariable()) {
917 const MCExpr *Expr = Symbol.getVariableValue();
918 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
919 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
930 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
933 if (Symbol.isVariable()) {
934 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
935 if (Base && Base->isUndefined())
939 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
940 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
943 if (Symbol.isTemporary())
949 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
950 if (Data.isExternal())
953 const MCSymbol &Symbol = Data.getSymbol();
954 if (Symbol.isDefined())
963 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
964 SectionIndexMapTy &SectionIndexMap) {
966 for (MCAssembler::iterator it = Asm.begin(),
967 ie = Asm.end(); it != ie; ++it) {
968 const MCSectionELF &Section =
969 static_cast<const MCSectionELF &>(it->getSection());
970 if (Section.getType() != ELF::SHT_GROUP)
972 SectionIndexMap[&Section] = Index++;
975 for (MCAssembler::iterator it = Asm.begin(),
976 ie = Asm.end(); it != ie; ++it) {
977 const MCSectionData &SD = *it;
978 const MCSectionELF &Section =
979 static_cast<const MCSectionELF &>(SD.getSection());
980 if (Section.getType() == ELF::SHT_GROUP ||
981 Section.getType() == ELF::SHT_REL ||
982 Section.getType() == ELF::SHT_RELA)
984 SectionIndexMap[&Section] = Index++;
985 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
986 const MCSectionELF *RelSection =
987 static_cast<const MCSectionELF *>(&RelSD->getSection());
988 SectionIndexMap[RelSection] = Index++;
994 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
995 const SectionIndexMapTy &SectionIndexMap,
996 const RevGroupMapTy &RevGroupMap,
997 unsigned NumRegularSections) {
998 // FIXME: Is this the correct place to do this?
999 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1001 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1002 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1003 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1004 Data.setExternal(true);
1005 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1008 // Add the data for the symbols.
1009 for (MCSymbolData &SD : Asm.symbols()) {
1010 const MCSymbol &Symbol = SD.getSymbol();
1012 bool Used = UsedInReloc.count(&Symbol);
1013 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1014 bool isSignature = RevGroupMap.count(&Symbol);
1016 if (!isInSymtab(Layout, SD,
1017 Used || WeakrefUsed || isSignature,
1018 Renames.count(&Symbol)))
1022 MSD.SymbolData = &SD;
1023 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1025 // Undefined symbols are global, but this is the first place we
1026 // are able to set it.
1027 bool Local = isLocal(SD, Used);
1028 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1030 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1031 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1032 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1036 MSD.SectionIndex = ELF::SHN_ABS;
1037 } else if (SD.isCommon()) {
1039 MSD.SectionIndex = ELF::SHN_COMMON;
1040 } else if (BaseSymbol->isUndefined()) {
1041 if (isSignature && !Used)
1042 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1044 MSD.SectionIndex = ELF::SHN_UNDEF;
1045 if (!Used && WeakrefUsed)
1046 MCELF::SetBinding(SD, ELF::STB_WEAK);
1048 const MCSectionELF &Section =
1049 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1050 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1051 assert(MSD.SectionIndex && "Invalid section index!");
1054 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1057 // FIXME: All name handling should be done before we get to the writer,
1058 // including dealing with GNU-style version suffixes. Fixing this isn't
1061 // We thus have to be careful to not perform the symbol version replacement
1064 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1065 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1066 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1067 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1068 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1069 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1070 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1071 // "__imp_?" or "__imp_@?".
1073 // It would have been interesting to perform the MS mangling prefix check
1074 // only when the target triple is of the form *-pc-windows-elf. But, it
1075 // seems that this information is not easily accessible from the
1077 StringRef Name = Symbol.getName();
1078 if (!Name.startswith("?") && !Name.startswith("@?") &&
1079 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1080 // This symbol isn't following the MSVC C++ name mangling convention. We
1081 // can thus safely interpret the @@@ in symbol names as specifying symbol
1083 SmallString<32> Buf;
1084 size_t Pos = Name.find("@@@");
1085 if (Pos != StringRef::npos) {
1086 Buf += Name.substr(0, Pos);
1087 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1088 Buf += Name.substr(Pos + Skip);
1093 // Sections have their own string table
1094 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1095 MSD.Name = StrTabBuilder.add(Name);
1097 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1098 UndefinedSymbolData.push_back(MSD);
1100 LocalSymbolData.push_back(MSD);
1102 ExternalSymbolData.push_back(MSD);
1105 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1106 StrTabBuilder.add(*i);
1108 StrTabBuilder.finalize(StringTableBuilder::ELF);
1110 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1111 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1113 for (ELFSymbolData &MSD : LocalSymbolData)
1114 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1116 : StrTabBuilder.getOffset(MSD.Name);
1117 for (ELFSymbolData &MSD : ExternalSymbolData)
1118 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1119 for (ELFSymbolData& MSD : UndefinedSymbolData)
1120 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1122 // Symbols are required to be in lexicographic order.
1123 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1124 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1125 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1127 // Set the symbol indices. Local symbols must come before all other
1128 // symbols with non-local bindings.
1129 unsigned Index = FileSymbolData.size() + 1;
1130 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1131 LocalSymbolData[i].SymbolData->setIndex(Index++);
1133 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1134 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1135 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1136 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1140 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1141 const MCSectionData &SD) {
1142 if (Relocations[&SD].empty())
1145 MCContext &Ctx = Asm.getContext();
1146 const MCSectionELF &Section =
1147 static_cast<const MCSectionELF &>(SD.getSection());
1149 const StringRef SectionName = Section.getSectionName();
1150 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1151 RelaSectionName += SectionName;
1154 if (hasRelocationAddend())
1155 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1157 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1160 if (Section.getFlags() & ELF::SHF_GROUP)
1161 Flags = ELF::SHF_GROUP;
1163 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1164 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1165 Flags, EntrySize, Section.getGroup(), &Section);
1166 return &Asm.getOrCreateSectionData(*RelaSection);
1169 static SmallVector<char, 128>
1170 getUncompressedData(MCAsmLayout &Layout,
1171 MCSectionData::FragmentListType &Fragments) {
1172 SmallVector<char, 128> UncompressedData;
1173 for (const MCFragment &F : Fragments) {
1174 const SmallVectorImpl<char> *Contents;
1175 switch (F.getKind()) {
1176 case MCFragment::FT_Data:
1177 Contents = &cast<MCDataFragment>(F).getContents();
1179 case MCFragment::FT_Dwarf:
1180 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1182 case MCFragment::FT_DwarfFrame:
1183 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1187 "Not expecting any other fragment types in a debug_* section");
1189 UncompressedData.append(Contents->begin(), Contents->end());
1191 return UncompressedData;
1194 // Include the debug info compression header:
1195 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1196 // useful for consumers to preallocate a buffer to decompress into.
1198 prependCompressionHeader(uint64_t Size,
1199 SmallVectorImpl<char> &CompressedContents) {
1200 const StringRef Magic = "ZLIB";
1201 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1203 if (sys::IsLittleEndianHost)
1204 sys::swapByteOrder(Size);
1205 CompressedContents.insert(CompressedContents.begin(),
1206 Magic.size() + sizeof(Size), 0);
1207 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1208 std::copy(reinterpret_cast<char *>(&Size),
1209 reinterpret_cast<char *>(&Size + 1),
1210 CompressedContents.begin() + Magic.size());
1214 // Return a single fragment containing the compressed contents of the whole
1215 // section. Null if the section was not compressed for any reason.
1216 static std::unique_ptr<MCDataFragment>
1217 getCompressedFragment(MCAsmLayout &Layout,
1218 MCSectionData::FragmentListType &Fragments) {
1219 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1221 // Gather the uncompressed data from all the fragments, recording the
1222 // alignment fragment, if seen, and any fixups.
1223 SmallVector<char, 128> UncompressedData =
1224 getUncompressedData(Layout, Fragments);
1226 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1228 zlib::Status Success = zlib::compress(
1229 StringRef(UncompressedData.data(), UncompressedData.size()),
1230 CompressedContents);
1231 if (Success != zlib::StatusOK)
1234 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1237 return CompressedFragment;
1240 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1243 static void UpdateSymbols(const MCAsmLayout &Layout,
1244 const std::vector<MCSymbolData *> &Symbols,
1245 MCFragment &NewFragment) {
1246 for (MCSymbolData *Sym : Symbols) {
1247 Sym->setOffset(Sym->getOffset() +
1248 Layout.getFragmentOffset(Sym->getFragment()));
1249 Sym->setFragment(&NewFragment);
1253 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1254 const DefiningSymbolMap &DefiningSymbols,
1255 const MCSectionELF &Section,
1256 MCSectionData &SD) {
1257 StringRef SectionName = Section.getSectionName();
1258 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1260 std::unique_ptr<MCDataFragment> CompressedFragment =
1261 getCompressedFragment(Layout, Fragments);
1263 // Leave the section as-is if the fragments could not be compressed.
1264 if (!CompressedFragment)
1267 // Update the fragment+offsets of any symbols referring to fragments in this
1268 // section to refer to the new fragment.
1269 auto I = DefiningSymbols.find(&SD);
1270 if (I != DefiningSymbols.end())
1271 UpdateSymbols(Layout, I->second, *CompressedFragment);
1273 // Invalidate the layout for the whole section since it will have new and
1274 // different fragments now.
1275 Layout.invalidateFragmentsFrom(&Fragments.front());
1278 // Complete the initialization of the new fragment
1279 CompressedFragment->setParent(&SD);
1280 CompressedFragment->setLayoutOrder(0);
1281 Fragments.push_back(CompressedFragment.release());
1283 // Rename from .debug_* to .zdebug_*
1284 Asm.getContext().renameELFSection(&Section,
1285 (".z" + SectionName.drop_front(1)).str());
1288 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1289 MCAsmLayout &Layout) {
1290 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1293 DefiningSymbolMap DefiningSymbols;
1295 for (MCSymbolData &SD : Asm.symbols())
1296 if (MCFragment *F = SD.getFragment())
1297 DefiningSymbols[F->getParent()].push_back(&SD);
1299 for (MCSectionData &SD : Asm) {
1300 const MCSectionELF &Section =
1301 static_cast<const MCSectionELF &>(SD.getSection());
1302 StringRef SectionName = Section.getSectionName();
1304 // Compressing debug_frame requires handling alignment fragments which is
1305 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1306 // for writing to arbitrary buffers) for little benefit.
1307 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1310 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1314 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1315 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1316 MCSectionData &RelSD = *it;
1317 const MCSectionELF &RelSection =
1318 static_cast<const MCSectionELF &>(RelSD.getSection());
1320 unsigned Type = RelSection.getType();
1321 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1324 const MCSectionELF *Section = RelSection.getAssociatedSection();
1325 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1326 RelSD.setAlignment(is64Bit() ? 8 : 4);
1328 MCDataFragment *F = new MCDataFragment(&RelSD);
1329 WriteRelocationsFragment(Asm, F, &SD);
1333 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1334 uint64_t Flags, uint64_t Address,
1335 uint64_t Offset, uint64_t Size,
1336 uint32_t Link, uint32_t Info,
1338 uint64_t EntrySize) {
1339 Write32(Name); // sh_name: index into string table
1340 Write32(Type); // sh_type
1341 WriteWord(Flags); // sh_flags
1342 WriteWord(Address); // sh_addr
1343 WriteWord(Offset); // sh_offset
1344 WriteWord(Size); // sh_size
1345 Write32(Link); // sh_link
1346 Write32(Info); // sh_info
1347 WriteWord(Alignment); // sh_addralign
1348 WriteWord(EntrySize); // sh_entsize
1351 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1352 // just to match gnu as for easier comparison. The use type is an arbitrary way
1353 // of making the sort deterministic.
1354 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1355 const ELFRelocationEntry &A = *AP;
1356 const ELFRelocationEntry &B = *BP;
1357 if (A.Offset != B.Offset)
1358 return B.Offset - A.Offset;
1359 if (B.Type != A.Type)
1360 return A.Type - B.Type;
1361 //llvm_unreachable("ELFRelocs might be unstable!");
1365 static void sortRelocs(const MCAssembler &Asm,
1366 std::vector<ELFRelocationEntry> &Relocs) {
1367 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1370 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1372 const MCSectionData *SD) {
1373 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1375 sortRelocs(Asm, Relocs);
1377 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1378 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1380 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1383 write(*F, Entry.Offset);
1384 if (TargetObjectWriter->isN64()) {
1385 write(*F, uint32_t(Index));
1387 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1388 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1389 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1390 write(*F, TargetObjectWriter->getRType(Entry.Type));
1392 struct ELF::Elf64_Rela ERE64;
1393 ERE64.setSymbolAndType(Index, Entry.Type);
1394 write(*F, ERE64.r_info);
1396 if (hasRelocationAddend())
1397 write(*F, Entry.Addend);
1399 write(*F, uint32_t(Entry.Offset));
1401 struct ELF::Elf32_Rela ERE32;
1402 ERE32.setSymbolAndType(Index, Entry.Type);
1403 write(*F, ERE32.r_info);
1405 if (hasRelocationAddend())
1406 write(*F, uint32_t(Entry.Addend));
1411 void ELFObjectWriter::CreateMetadataSections(
1412 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1413 MCContext &Ctx = Asm.getContext();
1416 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1418 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1419 const MCSectionELF *ShstrtabSection =
1420 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1421 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1422 ShstrtabSD.setAlignment(1);
1423 ShstrtabIndex = SectionIndexMap.size() + 1;
1424 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1426 const MCSectionELF *SymtabSection =
1427 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1429 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1430 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1431 SymbolTableIndex = SectionIndexMap.size() + 1;
1432 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1434 const MCSectionELF *StrtabSection;
1435 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1436 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1437 StrtabSD.setAlignment(1);
1438 StringTableIndex = SectionIndexMap.size() + 1;
1439 SectionIndexMap[StrtabSection] = StringTableIndex;
1442 F = new MCDataFragment(&SymtabSD);
1443 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1445 F = new MCDataFragment(&StrtabSD);
1446 F->getContents().append(StrTabBuilder.data().begin(),
1447 StrTabBuilder.data().end());
1449 F = new MCDataFragment(&ShstrtabSD);
1451 // Section header string table.
1452 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF&>(it->getSection());
1455 ShStrTabBuilder.add(Section.getSectionName());
1457 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1458 F->getContents().append(ShStrTabBuilder.data().begin(),
1459 ShStrTabBuilder.data().end());
1462 void ELFObjectWriter::createIndexedSections(
1463 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1464 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1465 MCContext &Ctx = Asm.getContext();
1468 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1470 const MCSectionELF &Section =
1471 static_cast<const MCSectionELF&>(it->getSection());
1472 if (!(Section.getFlags() & ELF::SHF_GROUP))
1475 const MCSymbol *SignatureSymbol = Section.getGroup();
1476 Asm.getOrCreateSymbolData(*SignatureSymbol);
1477 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1479 Group = Ctx.CreateELFGroupSection();
1480 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1481 Data.setAlignment(4);
1482 MCDataFragment *F = new MCDataFragment(&Data);
1483 write(*F, uint32_t(ELF::GRP_COMDAT));
1485 GroupMap[Group] = SignatureSymbol;
1488 computeIndexMap(Asm, SectionIndexMap);
1490 // Add sections to the groups
1491 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1493 const MCSectionELF &Section =
1494 static_cast<const MCSectionELF&>(it->getSection());
1495 if (!(Section.getFlags() & ELF::SHF_GROUP))
1497 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1498 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1499 // FIXME: we could use the previous fragment
1500 MCDataFragment *F = new MCDataFragment(&Data);
1501 uint32_t Index = SectionIndexMap.lookup(&Section);
1506 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1507 const SectionIndexMapTy &SectionIndexMap,
1508 uint32_t GroupSymbolIndex,
1509 uint64_t Offset, uint64_t Size,
1511 const MCSectionELF &Section) {
1512 uint64_t sh_link = 0;
1513 uint64_t sh_info = 0;
1515 switch(Section.getType()) {
1520 case ELF::SHT_DYNAMIC:
1521 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1525 case ELF::SHT_RELA: {
1526 sh_link = SymbolTableIndex;
1527 assert(sh_link && ".symtab not found");
1528 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1529 sh_info = SectionIndexMap.lookup(InfoSection);
1533 case ELF::SHT_SYMTAB:
1534 case ELF::SHT_DYNSYM:
1535 sh_link = StringTableIndex;
1536 sh_info = LastLocalSymbolIndex;
1539 case ELF::SHT_SYMTAB_SHNDX:
1540 sh_link = SymbolTableIndex;
1543 case ELF::SHT_GROUP:
1544 sh_link = SymbolTableIndex;
1545 sh_info = GroupSymbolIndex;
1549 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1550 Section.getType() == ELF::SHT_ARM_EXIDX)
1551 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1553 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1555 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1556 Alignment, Section.getEntrySize());
1559 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1560 return SD.getOrdinal() == ~UINT32_C(0) &&
1561 !SD.getSection().isVirtualSection();
1564 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1566 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1568 const MCFragment &F = *i;
1569 assert(F.getKind() == MCFragment::FT_Data);
1570 Ret += cast<MCDataFragment>(F).getContents().size();
1575 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1576 const MCSectionData &SD) {
1577 if (IsELFMetaDataSection(SD))
1578 return DataSectionSize(SD);
1579 return Layout.getSectionFileSize(&SD);
1582 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1583 const MCSectionData &SD) {
1584 if (IsELFMetaDataSection(SD))
1585 return DataSectionSize(SD);
1586 return Layout.getSectionAddressSize(&SD);
1589 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1590 const MCAsmLayout &Layout,
1591 const MCSectionELF &Section) {
1592 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1594 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1595 WriteZeros(Padding);
1597 if (IsELFMetaDataSection(SD)) {
1598 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1600 const MCFragment &F = *i;
1601 assert(F.getKind() == MCFragment::FT_Data);
1602 WriteBytes(cast<MCDataFragment>(F).getContents());
1605 Asm.writeSectionData(&SD, Layout);
1609 void ELFObjectWriter::writeSectionHeader(
1610 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1611 const SectionIndexMapTy &SectionIndexMap,
1612 const SectionOffsetMapTy &SectionOffsetMap) {
1613 const unsigned NumSections = Asm.size() + 1;
1615 std::vector<const MCSectionELF*> Sections;
1616 Sections.resize(NumSections - 1);
1618 for (SectionIndexMapTy::const_iterator i=
1619 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1620 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1621 Sections[p.second - 1] = p.first;
1624 // Null section first.
1625 uint64_t FirstSectionSize =
1626 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1627 uint32_t FirstSectionLink =
1628 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1629 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1631 for (unsigned i = 0; i < NumSections - 1; ++i) {
1632 const MCSectionELF &Section = *Sections[i];
1633 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1634 uint32_t GroupSymbolIndex;
1635 if (Section.getType() != ELF::SHT_GROUP)
1636 GroupSymbolIndex = 0;
1638 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1639 GroupMap.lookup(&Section));
1641 uint64_t Size = GetSectionAddressSize(Layout, SD);
1643 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1644 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1649 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1650 std::vector<const MCSectionELF*> &Sections) {
1651 for (MCAssembler::iterator it = Asm.begin(),
1652 ie = Asm.end(); it != ie; ++it) {
1653 const MCSectionELF &Section =
1654 static_cast<const MCSectionELF &>(it->getSection());
1655 if (Section.getType() == ELF::SHT_GROUP)
1656 Sections.push_back(&Section);
1659 for (MCAssembler::iterator it = Asm.begin(),
1660 ie = Asm.end(); it != ie; ++it) {
1661 const MCSectionELF &Section =
1662 static_cast<const MCSectionELF &>(it->getSection());
1663 if (Section.getType() != ELF::SHT_GROUP &&
1664 Section.getType() != ELF::SHT_REL &&
1665 Section.getType() != ELF::SHT_RELA)
1666 Sections.push_back(&Section);
1669 for (MCAssembler::iterator it = Asm.begin(),
1670 ie = Asm.end(); it != ie; ++it) {
1671 const MCSectionELF &Section =
1672 static_cast<const MCSectionELF &>(it->getSection());
1673 if (Section.getType() == ELF::SHT_REL ||
1674 Section.getType() == ELF::SHT_RELA)
1675 Sections.push_back(&Section);
1679 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1680 const MCAsmLayout &Layout) {
1681 GroupMapTy GroupMap;
1682 RevGroupMapTy RevGroupMap;
1683 SectionIndexMapTy SectionIndexMap;
1685 unsigned NumUserSections = Asm.size();
1687 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1689 const unsigned NumUserAndRelocSections = Asm.size();
1690 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1691 RevGroupMap, SectionIndexMap);
1692 const unsigned AllSections = Asm.size();
1693 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1695 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1697 // Compute symbol table information.
1698 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1699 NumRegularSections);
1701 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1703 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1704 const_cast<MCAsmLayout&>(Layout),
1707 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1708 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1709 sizeof(ELF::Elf32_Ehdr);
1710 uint64_t FileOff = HeaderSize;
1712 std::vector<const MCSectionELF*> Sections;
1713 ComputeSectionOrder(Asm, Sections);
1714 unsigned NumSections = Sections.size();
1715 SectionOffsetMapTy SectionOffsetMap;
1716 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1717 const MCSectionELF &Section = *Sections[i];
1718 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1720 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1722 // Remember the offset into the file for this section.
1723 SectionOffsetMap[&Section] = FileOff;
1725 // Get the size of the section in the output file (including padding).
1726 FileOff += GetSectionFileSize(Layout, SD);
1729 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1731 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1733 uint64_t SectionHeaderEntrySize = is64Bit() ?
1734 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1735 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1737 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1738 const MCSectionELF &Section = *Sections[i];
1739 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1741 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1743 // Remember the offset into the file for this section.
1744 SectionOffsetMap[&Section] = FileOff;
1746 // Get the size of the section in the output file (including padding).
1747 FileOff += GetSectionFileSize(Layout, SD);
1750 // Write out the ELF header ...
1751 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1753 // ... then the regular sections ...
1754 // + because of .shstrtab
1755 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1756 WriteDataSectionData(Asm, Layout, *Sections[i]);
1758 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1759 WriteZeros(Padding);
1761 // ... then the section header table ...
1762 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1764 // ... and then the remaining sections ...
1765 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1766 WriteDataSectionData(Asm, Layout, *Sections[i]);
1769 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1770 const MCAssembler &Asm, const MCSymbolData &DataA,
1771 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1772 bool IsPCRel) const {
1773 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1775 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1776 Asm, DataA, DataB, FB, InSet, IsPCRel);
1779 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1780 return ::isWeak(SD);
1783 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1785 bool IsLittleEndian) {
1786 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);