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 SectionHeaderOffset,
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 SectionHeaderOffset,
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(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
468 // e_flags = whatever the target wants
469 Write32(Asm.getELFHeaderEFlags());
471 // e_ehsize = ELF header size
472 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
474 Write16(0); // e_phentsize = prog header entry size
475 Write16(0); // e_phnum = # prog header entries = 0
477 // e_shentsize = Section header entry size
478 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
480 // e_shnum = # of section header ents
481 if (NumberOfSections >= ELF::SHN_LORESERVE)
482 Write16(ELF::SHN_UNDEF);
484 Write16(NumberOfSections);
486 // e_shstrndx = Section # of '.shstrtab'
487 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
488 Write16(ELF::SHN_XINDEX);
490 Write16(ShstrtabIndex);
493 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
494 const MCAsmLayout &Layout) {
495 if (Data.isCommon() && Data.isExternal())
496 return Data.getCommonAlignment();
499 if (!Layout.getSymbolOffset(&Data, Res))
502 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
508 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
509 const MCAsmLayout &Layout) {
510 // The presence of symbol versions causes undefined symbols and
511 // versions declared with @@@ to be renamed.
513 for (MCSymbolData &OriginalData : Asm.symbols()) {
514 const MCSymbol &Alias = OriginalData.getSymbol();
517 if (!Alias.isVariable())
519 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
522 const MCSymbol &Symbol = Ref->getSymbol();
523 MCSymbolData &SD = Asm.getSymbolData(Symbol);
525 StringRef AliasName = Alias.getName();
526 size_t Pos = AliasName.find('@');
527 if (Pos == StringRef::npos)
530 // Aliases defined with .symvar copy the binding from the symbol they alias.
531 // This is the first place we are able to copy this information.
532 OriginalData.setExternal(SD.isExternal());
533 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
535 StringRef Rest = AliasName.substr(Pos);
536 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
539 // FIXME: produce a better error message.
540 if (Symbol.isUndefined() && Rest.startswith("@@") &&
541 !Rest.startswith("@@@"))
542 report_fatal_error("A @@ version cannot be undefined");
544 Renames.insert(std::make_pair(&Symbol, &Alias));
548 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
549 uint8_t Type = newType;
551 // Propagation rules:
552 // IFUNC > FUNC > OBJECT > NOTYPE
553 // TLS_OBJECT > OBJECT > NOTYPE
555 // dont let the new type degrade the old type
559 case ELF::STT_GNU_IFUNC:
560 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
561 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
562 Type = ELF::STT_GNU_IFUNC;
565 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
566 Type == ELF::STT_TLS)
567 Type = ELF::STT_FUNC;
569 case ELF::STT_OBJECT:
570 if (Type == ELF::STT_NOTYPE)
571 Type = ELF::STT_OBJECT;
574 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
575 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
583 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
584 const MCAsmLayout &Layout) {
585 MCSymbolData &OrigData = *MSD.SymbolData;
586 assert((!OrigData.getFragment() ||
587 (&OrigData.getFragment()->getParent()->getSection() ==
588 &OrigData.getSymbol().getSection())) &&
589 "The symbol's section doesn't match the fragment's symbol");
590 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
592 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
594 bool IsReserved = !Base || OrigData.isCommon();
596 // Binding and Type share the same byte as upper and lower nibbles
597 uint8_t Binding = MCELF::GetBinding(OrigData);
598 uint8_t Type = MCELF::GetType(OrigData);
599 MCSymbolData *BaseSD = nullptr;
601 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
602 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
604 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
606 // Other and Visibility share the same byte with Visibility using the lower
608 uint8_t Visibility = MCELF::GetVisibility(OrigData);
609 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
612 uint64_t Value = SymbolValue(OrigData, Layout);
615 const MCExpr *ESize = OrigData.getSize();
617 ESize = BaseSD->getSize();
621 if (!ESize->evaluateKnownAbsolute(Res, Layout))
622 report_fatal_error("Size expression must be absolute.");
626 // Write out the symbol table entry
627 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
628 MSD.SectionIndex, IsReserved);
631 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
633 const MCAsmLayout &Layout,
634 SectionIndexMapTy &SectionIndexMap) {
635 // The string table must be emitted first because we need the index
636 // into the string table for all the symbol names.
638 // FIXME: Make sure the start of the symbol table is aligned.
640 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
642 // The first entry is the undefined symbol entry.
643 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
645 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
646 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
647 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
650 // Write the symbol table entries.
651 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
653 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
654 ELFSymbolData &MSD = LocalSymbolData[i];
655 WriteSymbol(Writer, MSD, Layout);
658 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
659 ELFSymbolData &MSD = ExternalSymbolData[i];
660 MCSymbolData &Data = *MSD.SymbolData;
661 assert(((Data.getFlags() & ELF_STB_Global) ||
662 (Data.getFlags() & ELF_STB_Weak)) &&
663 "External symbol requires STB_GLOBAL or STB_WEAK flag");
664 WriteSymbol(Writer, MSD, Layout);
665 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
666 LastLocalSymbolIndex++;
669 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
670 ELFSymbolData &MSD = UndefinedSymbolData[i];
671 MCSymbolData &Data = *MSD.SymbolData;
672 WriteSymbol(Writer, MSD, Layout);
673 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
674 LastLocalSymbolIndex++;
678 // It is always valid to create a relocation with a symbol. It is preferable
679 // to use a relocation with a section if that is possible. Using the section
680 // allows us to omit some local symbols from the symbol table.
681 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
682 const MCSymbolRefExpr *RefA,
683 const MCSymbolData *SD,
685 unsigned Type) const {
686 // A PCRel relocation to an absolute value has no symbol (or section). We
687 // represent that with a relocation to a null section.
691 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
695 // The .odp creation emits a relocation against the symbol ".TOC." which
696 // create a R_PPC64_TOC relocation. However the relocation symbol name
697 // in final object creation should be NULL, since the symbol does not
698 // really exist, it is just the reference to TOC base for the current
699 // object file. Since the symbol is undefined, returning false results
700 // in a relocation with a null section which is the desired result.
701 case MCSymbolRefExpr::VK_PPC_TOCBASE:
704 // These VariantKind cause the relocation to refer to something other than
705 // the symbol itself, like a linker generated table. Since the address of
706 // symbol is not relevant, we cannot replace the symbol with the
707 // section and patch the difference in the addend.
708 case MCSymbolRefExpr::VK_GOT:
709 case MCSymbolRefExpr::VK_PLT:
710 case MCSymbolRefExpr::VK_GOTPCREL:
711 case MCSymbolRefExpr::VK_Mips_GOT:
712 case MCSymbolRefExpr::VK_PPC_GOT_LO:
713 case MCSymbolRefExpr::VK_PPC_GOT_HI:
714 case MCSymbolRefExpr::VK_PPC_GOT_HA:
718 // An undefined symbol is not in any section, so the relocation has to point
719 // to the symbol itself.
720 const MCSymbol &Sym = SD->getSymbol();
721 if (Sym.isUndefined())
724 unsigned Binding = MCELF::GetBinding(*SD);
727 llvm_unreachable("Invalid Binding");
731 // If the symbol is weak, it might be overridden by a symbol in another
732 // file. The relocation has to point to the symbol so that the linker
735 case ELF::STB_GLOBAL:
736 // Global ELF symbols can be preempted by the dynamic linker. The relocation
737 // has to point to the symbol for a reason analogous to the STB_WEAK case.
741 // If a relocation points to a mergeable section, we have to be careful.
742 // If the offset is zero, a relocation with the section will encode the
743 // same information. With a non-zero offset, the situation is different.
744 // For example, a relocation can point 42 bytes past the end of a string.
745 // If we change such a relocation to use the section, the linker would think
746 // that it pointed to another string and subtracting 42 at runtime will
747 // produce the wrong value.
748 auto &Sec = cast<MCSectionELF>(Sym.getSection());
749 unsigned Flags = Sec.getFlags();
750 if (Flags & ELF::SHF_MERGE) {
754 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
755 // only handle section relocations to mergeable sections if using RELA.
756 if (!hasRelocationAddend())
760 // Most TLS relocations use a got, so they need the symbol. Even those that
761 // are just an offset (@tpoff), require a symbol in gold versions before
762 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
763 // http://sourceware.org/PR16773.
764 if (Flags & ELF::SHF_TLS)
767 // If the symbol is a thumb function the final relocation must set the lowest
768 // bit. With a symbol that is done by just having the symbol have that bit
769 // set, so we would lose the bit if we relocated with the section.
770 // FIXME: We could use the section but add the bit to the relocation value.
771 if (Asm.isThumbFunc(&Sym))
774 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
779 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
780 const MCSymbol &Sym = Ref.getSymbol();
782 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
785 if (!Sym.isVariable())
788 const MCExpr *Expr = Sym.getVariableValue();
789 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
793 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
794 return &Inner->getSymbol();
798 static bool isWeak(const MCSymbolData &D) {
799 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
802 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
803 const MCAsmLayout &Layout,
804 const MCFragment *Fragment,
805 const MCFixup &Fixup, MCValue Target,
806 bool &IsPCRel, uint64_t &FixedValue) {
807 const MCSectionData *FixupSection = Fragment->getParent();
808 uint64_t C = Target.getConstant();
809 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
811 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
812 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
813 "Should not have constructed this");
815 // Let A, B and C being the components of Target and R be the location of
816 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
817 // If it is pcrel, we want to compute (A - B + C - R).
819 // In general, ELF has no relocations for -B. It can only represent (A + C)
820 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
821 // replace B to implement it: (A - R - K + C)
823 Asm.getContext().FatalError(
825 "No relocation available to represent this relative expression");
827 const MCSymbol &SymB = RefB->getSymbol();
829 if (SymB.isUndefined())
830 Asm.getContext().FatalError(
832 Twine("symbol '") + SymB.getName() +
833 "' can not be undefined in a subtraction expression");
835 assert(!SymB.isAbsolute() && "Should have been folded");
836 const MCSection &SecB = SymB.getSection();
837 if (&SecB != &FixupSection->getSection())
838 Asm.getContext().FatalError(
839 Fixup.getLoc(), "Cannot represent a difference across sections");
841 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
843 Asm.getContext().FatalError(
844 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
846 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
847 uint64_t K = SymBOffset - FixupOffset;
852 // We either rejected the fixup or folded B into C at this point.
853 const MCSymbolRefExpr *RefA = Target.getSymA();
854 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
855 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
857 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
858 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
859 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
860 C += Layout.getSymbolOffset(SymAD);
863 if (hasRelocationAddend()) {
870 // FIXME: What is this!?!?
871 MCSymbolRefExpr::VariantKind Modifier =
872 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
873 if (RelocNeedsGOT(Modifier))
876 if (!RelocateWithSymbol) {
877 const MCSection *SecA =
878 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
879 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
880 MCSymbol *SectionSymbol =
881 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
883 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
884 Relocations[FixupSection].push_back(Rec);
889 if (const MCSymbol *R = Renames.lookup(SymA))
892 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
893 WeakrefUsedInReloc.insert(WeakRef);
895 UsedInReloc.insert(SymA);
897 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
898 Relocations[FixupSection].push_back(Rec);
904 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
906 const MCSymbolData &SD = Asm.getSymbolData(*S);
907 return SD.getIndex();
910 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
911 const MCSymbolData &Data, bool Used,
913 const MCSymbol &Symbol = Data.getSymbol();
914 if (Symbol.isVariable()) {
915 const MCExpr *Expr = Symbol.getVariableValue();
916 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
917 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
928 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
931 if (Symbol.isVariable()) {
932 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
933 if (Base && Base->isUndefined())
937 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
938 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
941 if (Symbol.isTemporary())
947 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
948 if (Data.isExternal())
951 const MCSymbol &Symbol = Data.getSymbol();
952 if (Symbol.isDefined())
961 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
962 SectionIndexMapTy &SectionIndexMap) {
964 for (MCAssembler::iterator it = Asm.begin(),
965 ie = Asm.end(); it != ie; ++it) {
966 const MCSectionELF &Section =
967 static_cast<const MCSectionELF &>(it->getSection());
968 if (Section.getType() != ELF::SHT_GROUP)
970 SectionIndexMap[&Section] = Index++;
973 for (MCAssembler::iterator it = Asm.begin(),
974 ie = Asm.end(); it != ie; ++it) {
975 const MCSectionData &SD = *it;
976 const MCSectionELF &Section =
977 static_cast<const MCSectionELF &>(SD.getSection());
978 if (Section.getType() == ELF::SHT_GROUP ||
979 Section.getType() == ELF::SHT_REL ||
980 Section.getType() == ELF::SHT_RELA)
982 SectionIndexMap[&Section] = Index++;
983 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
984 const MCSectionELF *RelSection =
985 static_cast<const MCSectionELF *>(&RelSD->getSection());
986 SectionIndexMap[RelSection] = Index++;
991 void ELFObjectWriter::computeSymbolTable(
992 MCAssembler &Asm, const MCAsmLayout &Layout,
993 const SectionIndexMapTy &SectionIndexMap,
994 const RevGroupMapTy &RevGroupMap) {
995 // FIXME: Is this the correct place to do this?
996 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
998 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
999 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1000 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1001 Data.setExternal(true);
1002 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1005 // Add the data for the symbols.
1006 for (MCSymbolData &SD : Asm.symbols()) {
1007 const MCSymbol &Symbol = SD.getSymbol();
1009 bool Used = UsedInReloc.count(&Symbol);
1010 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1011 bool isSignature = RevGroupMap.count(&Symbol);
1013 if (!isInSymtab(Layout, SD,
1014 Used || WeakrefUsed || isSignature,
1015 Renames.count(&Symbol)))
1019 MSD.SymbolData = &SD;
1020 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1022 // Undefined symbols are global, but this is the first place we
1023 // are able to set it.
1024 bool Local = isLocal(SD, Used);
1025 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1027 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1028 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1029 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1033 MSD.SectionIndex = ELF::SHN_ABS;
1034 } else if (SD.isCommon()) {
1036 MSD.SectionIndex = ELF::SHN_COMMON;
1037 } else if (BaseSymbol->isUndefined()) {
1038 if (isSignature && !Used)
1039 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1041 MSD.SectionIndex = ELF::SHN_UNDEF;
1042 if (!Used && WeakrefUsed)
1043 MCELF::SetBinding(SD, ELF::STB_WEAK);
1045 const MCSectionELF &Section =
1046 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1047 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1048 assert(MSD.SectionIndex && "Invalid section index!");
1051 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1054 // FIXME: All name handling should be done before we get to the writer,
1055 // including dealing with GNU-style version suffixes. Fixing this isn't
1058 // We thus have to be careful to not perform the symbol version replacement
1061 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1062 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1063 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1064 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1065 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1066 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1067 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1068 // "__imp_?" or "__imp_@?".
1070 // It would have been interesting to perform the MS mangling prefix check
1071 // only when the target triple is of the form *-pc-windows-elf. But, it
1072 // seems that this information is not easily accessible from the
1074 StringRef Name = Symbol.getName();
1075 if (!Name.startswith("?") && !Name.startswith("@?") &&
1076 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1077 // This symbol isn't following the MSVC C++ name mangling convention. We
1078 // can thus safely interpret the @@@ in symbol names as specifying symbol
1080 SmallString<32> Buf;
1081 size_t Pos = Name.find("@@@");
1082 if (Pos != StringRef::npos) {
1083 Buf += Name.substr(0, Pos);
1084 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1085 Buf += Name.substr(Pos + Skip);
1090 // Sections have their own string table
1091 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1092 MSD.Name = StrTabBuilder.add(Name);
1094 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1095 UndefinedSymbolData.push_back(MSD);
1097 LocalSymbolData.push_back(MSD);
1099 ExternalSymbolData.push_back(MSD);
1102 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1103 StrTabBuilder.add(*i);
1105 StrTabBuilder.finalize(StringTableBuilder::ELF);
1107 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1108 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1110 for (ELFSymbolData &MSD : LocalSymbolData)
1111 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1113 : StrTabBuilder.getOffset(MSD.Name);
1114 for (ELFSymbolData &MSD : ExternalSymbolData)
1115 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1116 for (ELFSymbolData& MSD : UndefinedSymbolData)
1117 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1119 // Symbols are required to be in lexicographic order.
1120 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1121 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1122 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1124 // Set the symbol indices. Local symbols must come before all other
1125 // symbols with non-local bindings.
1126 unsigned Index = FileSymbolData.size() + 1;
1127 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1128 LocalSymbolData[i].SymbolData->setIndex(Index++);
1130 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1131 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1132 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1133 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1137 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1138 const MCSectionData &SD) {
1139 if (Relocations[&SD].empty())
1142 MCContext &Ctx = Asm.getContext();
1143 const MCSectionELF &Section =
1144 static_cast<const MCSectionELF &>(SD.getSection());
1146 const StringRef SectionName = Section.getSectionName();
1147 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1148 RelaSectionName += SectionName;
1151 if (hasRelocationAddend())
1152 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1154 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1157 if (Section.getFlags() & ELF::SHF_GROUP)
1158 Flags = ELF::SHF_GROUP;
1160 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1161 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1162 Flags, EntrySize, Section.getGroup(), &Section);
1163 return &Asm.getOrCreateSectionData(*RelaSection);
1166 static SmallVector<char, 128>
1167 getUncompressedData(MCAsmLayout &Layout,
1168 MCSectionData::FragmentListType &Fragments) {
1169 SmallVector<char, 128> UncompressedData;
1170 for (const MCFragment &F : Fragments) {
1171 const SmallVectorImpl<char> *Contents;
1172 switch (F.getKind()) {
1173 case MCFragment::FT_Data:
1174 Contents = &cast<MCDataFragment>(F).getContents();
1176 case MCFragment::FT_Dwarf:
1177 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1179 case MCFragment::FT_DwarfFrame:
1180 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1184 "Not expecting any other fragment types in a debug_* section");
1186 UncompressedData.append(Contents->begin(), Contents->end());
1188 return UncompressedData;
1191 // Include the debug info compression header:
1192 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1193 // useful for consumers to preallocate a buffer to decompress into.
1195 prependCompressionHeader(uint64_t Size,
1196 SmallVectorImpl<char> &CompressedContents) {
1197 const StringRef Magic = "ZLIB";
1198 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1200 if (sys::IsLittleEndianHost)
1201 sys::swapByteOrder(Size);
1202 CompressedContents.insert(CompressedContents.begin(),
1203 Magic.size() + sizeof(Size), 0);
1204 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1205 std::copy(reinterpret_cast<char *>(&Size),
1206 reinterpret_cast<char *>(&Size + 1),
1207 CompressedContents.begin() + Magic.size());
1211 // Return a single fragment containing the compressed contents of the whole
1212 // section. Null if the section was not compressed for any reason.
1213 static std::unique_ptr<MCDataFragment>
1214 getCompressedFragment(MCAsmLayout &Layout,
1215 MCSectionData::FragmentListType &Fragments) {
1216 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1218 // Gather the uncompressed data from all the fragments, recording the
1219 // alignment fragment, if seen, and any fixups.
1220 SmallVector<char, 128> UncompressedData =
1221 getUncompressedData(Layout, Fragments);
1223 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1225 zlib::Status Success = zlib::compress(
1226 StringRef(UncompressedData.data(), UncompressedData.size()),
1227 CompressedContents);
1228 if (Success != zlib::StatusOK)
1231 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1234 return CompressedFragment;
1237 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1240 static void UpdateSymbols(const MCAsmLayout &Layout,
1241 const std::vector<MCSymbolData *> &Symbols,
1242 MCFragment &NewFragment) {
1243 for (MCSymbolData *Sym : Symbols) {
1244 Sym->setOffset(Sym->getOffset() +
1245 Layout.getFragmentOffset(Sym->getFragment()));
1246 Sym->setFragment(&NewFragment);
1250 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1251 const DefiningSymbolMap &DefiningSymbols,
1252 const MCSectionELF &Section,
1253 MCSectionData &SD) {
1254 StringRef SectionName = Section.getSectionName();
1255 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1257 std::unique_ptr<MCDataFragment> CompressedFragment =
1258 getCompressedFragment(Layout, Fragments);
1260 // Leave the section as-is if the fragments could not be compressed.
1261 if (!CompressedFragment)
1264 // Update the fragment+offsets of any symbols referring to fragments in this
1265 // section to refer to the new fragment.
1266 auto I = DefiningSymbols.find(&SD);
1267 if (I != DefiningSymbols.end())
1268 UpdateSymbols(Layout, I->second, *CompressedFragment);
1270 // Invalidate the layout for the whole section since it will have new and
1271 // different fragments now.
1272 Layout.invalidateFragmentsFrom(&Fragments.front());
1275 // Complete the initialization of the new fragment
1276 CompressedFragment->setParent(&SD);
1277 CompressedFragment->setLayoutOrder(0);
1278 Fragments.push_back(CompressedFragment.release());
1280 // Rename from .debug_* to .zdebug_*
1281 Asm.getContext().renameELFSection(&Section,
1282 (".z" + SectionName.drop_front(1)).str());
1285 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1286 MCAsmLayout &Layout) {
1287 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1290 DefiningSymbolMap DefiningSymbols;
1292 for (MCSymbolData &SD : Asm.symbols())
1293 if (MCFragment *F = SD.getFragment())
1294 DefiningSymbols[F->getParent()].push_back(&SD);
1296 for (MCSectionData &SD : Asm) {
1297 const MCSectionELF &Section =
1298 static_cast<const MCSectionELF &>(SD.getSection());
1299 StringRef SectionName = Section.getSectionName();
1301 // Compressing debug_frame requires handling alignment fragments which is
1302 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1303 // for writing to arbitrary buffers) for little benefit.
1304 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1307 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1311 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1312 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1313 MCSectionData &RelSD = *it;
1314 const MCSectionELF &RelSection =
1315 static_cast<const MCSectionELF &>(RelSD.getSection());
1317 unsigned Type = RelSection.getType();
1318 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1321 const MCSectionELF *Section = RelSection.getAssociatedSection();
1322 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1323 RelSD.setAlignment(is64Bit() ? 8 : 4);
1325 MCDataFragment *F = new MCDataFragment(&RelSD);
1326 WriteRelocationsFragment(Asm, F, &SD);
1330 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1331 uint64_t Flags, uint64_t Address,
1332 uint64_t Offset, uint64_t Size,
1333 uint32_t Link, uint32_t Info,
1335 uint64_t EntrySize) {
1336 Write32(Name); // sh_name: index into string table
1337 Write32(Type); // sh_type
1338 WriteWord(Flags); // sh_flags
1339 WriteWord(Address); // sh_addr
1340 WriteWord(Offset); // sh_offset
1341 WriteWord(Size); // sh_size
1342 Write32(Link); // sh_link
1343 Write32(Info); // sh_info
1344 WriteWord(Alignment); // sh_addralign
1345 WriteWord(EntrySize); // sh_entsize
1348 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1349 // just to match gnu as for easier comparison. The use type is an arbitrary way
1350 // of making the sort deterministic.
1351 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1352 const ELFRelocationEntry &A = *AP;
1353 const ELFRelocationEntry &B = *BP;
1354 if (A.Offset != B.Offset)
1355 return B.Offset - A.Offset;
1356 if (B.Type != A.Type)
1357 return A.Type - B.Type;
1358 //llvm_unreachable("ELFRelocs might be unstable!");
1362 static void sortRelocs(const MCAssembler &Asm,
1363 std::vector<ELFRelocationEntry> &Relocs) {
1364 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1367 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1369 const MCSectionData *SD) {
1370 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1372 sortRelocs(Asm, Relocs);
1374 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1375 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1377 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1380 write(*F, Entry.Offset);
1381 if (TargetObjectWriter->isN64()) {
1382 write(*F, uint32_t(Index));
1384 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1385 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1386 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1387 write(*F, TargetObjectWriter->getRType(Entry.Type));
1389 struct ELF::Elf64_Rela ERE64;
1390 ERE64.setSymbolAndType(Index, Entry.Type);
1391 write(*F, ERE64.r_info);
1393 if (hasRelocationAddend())
1394 write(*F, Entry.Addend);
1396 write(*F, uint32_t(Entry.Offset));
1398 struct ELF::Elf32_Rela ERE32;
1399 ERE32.setSymbolAndType(Index, Entry.Type);
1400 write(*F, ERE32.r_info);
1402 if (hasRelocationAddend())
1403 write(*F, uint32_t(Entry.Addend));
1408 void ELFObjectWriter::CreateMetadataSections(
1409 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1410 MCContext &Ctx = Asm.getContext();
1413 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1415 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1416 const MCSectionELF *ShstrtabSection =
1417 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1418 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1419 ShstrtabSD.setAlignment(1);
1420 ShstrtabIndex = SectionIndexMap.size() + 1;
1421 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1423 const MCSectionELF *SymtabSection =
1424 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1426 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1427 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1428 SymbolTableIndex = SectionIndexMap.size() + 1;
1429 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1431 const MCSectionELF *StrtabSection;
1432 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1433 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1434 StrtabSD.setAlignment(1);
1435 StringTableIndex = SectionIndexMap.size() + 1;
1436 SectionIndexMap[StrtabSection] = StringTableIndex;
1439 F = new MCDataFragment(&SymtabSD);
1440 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1442 F = new MCDataFragment(&StrtabSD);
1443 F->getContents().append(StrTabBuilder.data().begin(),
1444 StrTabBuilder.data().end());
1446 F = new MCDataFragment(&ShstrtabSD);
1448 // Section header string table.
1449 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1450 const MCSectionELF &Section =
1451 static_cast<const MCSectionELF&>(it->getSection());
1452 ShStrTabBuilder.add(Section.getSectionName());
1454 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1455 F->getContents().append(ShStrTabBuilder.data().begin(),
1456 ShStrTabBuilder.data().end());
1459 void ELFObjectWriter::createIndexedSections(
1460 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1461 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1462 MCContext &Ctx = Asm.getContext();
1465 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1467 const MCSectionELF &Section =
1468 static_cast<const MCSectionELF&>(it->getSection());
1469 if (!(Section.getFlags() & ELF::SHF_GROUP))
1472 const MCSymbol *SignatureSymbol = Section.getGroup();
1473 Asm.getOrCreateSymbolData(*SignatureSymbol);
1474 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1476 Group = Ctx.CreateELFGroupSection();
1477 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1478 Data.setAlignment(4);
1479 MCDataFragment *F = new MCDataFragment(&Data);
1480 write(*F, uint32_t(ELF::GRP_COMDAT));
1482 GroupMap[Group] = SignatureSymbol;
1485 computeIndexMap(Asm, SectionIndexMap);
1487 // Add sections to the groups
1488 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1490 const MCSectionELF &Section =
1491 static_cast<const MCSectionELF&>(it->getSection());
1492 if (!(Section.getFlags() & ELF::SHF_GROUP))
1494 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1495 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1496 // FIXME: we could use the previous fragment
1497 MCDataFragment *F = new MCDataFragment(&Data);
1498 uint32_t Index = SectionIndexMap.lookup(&Section);
1503 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1504 const SectionIndexMapTy &SectionIndexMap,
1505 uint32_t GroupSymbolIndex,
1506 uint64_t Offset, uint64_t Size,
1508 const MCSectionELF &Section) {
1509 uint64_t sh_link = 0;
1510 uint64_t sh_info = 0;
1512 switch(Section.getType()) {
1517 case ELF::SHT_DYNAMIC:
1518 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1522 case ELF::SHT_RELA: {
1523 sh_link = SymbolTableIndex;
1524 assert(sh_link && ".symtab not found");
1525 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1526 sh_info = SectionIndexMap.lookup(InfoSection);
1530 case ELF::SHT_SYMTAB:
1531 case ELF::SHT_DYNSYM:
1532 sh_link = StringTableIndex;
1533 sh_info = LastLocalSymbolIndex;
1536 case ELF::SHT_SYMTAB_SHNDX:
1537 sh_link = SymbolTableIndex;
1540 case ELF::SHT_GROUP:
1541 sh_link = SymbolTableIndex;
1542 sh_info = GroupSymbolIndex;
1546 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1547 Section.getType() == ELF::SHT_ARM_EXIDX)
1548 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1550 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1552 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1553 Alignment, Section.getEntrySize());
1556 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1557 return SD.getOrdinal() == ~UINT32_C(0) &&
1558 !SD.getSection().isVirtualSection();
1561 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1563 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1565 const MCFragment &F = *i;
1566 assert(F.getKind() == MCFragment::FT_Data);
1567 Ret += cast<MCDataFragment>(F).getContents().size();
1572 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1573 const MCSectionData &SD) {
1574 if (IsELFMetaDataSection(SD))
1575 return DataSectionSize(SD);
1576 return Layout.getSectionFileSize(&SD);
1579 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1580 const MCSectionData &SD) {
1581 if (IsELFMetaDataSection(SD))
1582 return DataSectionSize(SD);
1583 return Layout.getSectionAddressSize(&SD);
1586 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1587 const MCAsmLayout &Layout,
1588 const MCSectionELF &Section) {
1589 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1591 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1592 WriteZeros(Padding);
1594 if (IsELFMetaDataSection(SD)) {
1595 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1597 const MCFragment &F = *i;
1598 assert(F.getKind() == MCFragment::FT_Data);
1599 WriteBytes(cast<MCDataFragment>(F).getContents());
1602 Asm.writeSectionData(&SD, Layout);
1606 void ELFObjectWriter::writeSectionHeader(
1607 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1608 const SectionIndexMapTy &SectionIndexMap,
1609 const SectionOffsetMapTy &SectionOffsetMap) {
1610 const unsigned NumSections = Asm.size() + 1;
1612 std::vector<const MCSectionELF*> Sections;
1613 Sections.resize(NumSections - 1);
1615 for (SectionIndexMapTy::const_iterator i=
1616 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1617 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1618 Sections[p.second - 1] = p.first;
1621 // Null section first.
1622 uint64_t FirstSectionSize =
1623 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1624 uint32_t FirstSectionLink =
1625 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1626 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1628 for (unsigned i = 0; i < NumSections - 1; ++i) {
1629 const MCSectionELF &Section = *Sections[i];
1630 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1631 uint32_t GroupSymbolIndex;
1632 if (Section.getType() != ELF::SHT_GROUP)
1633 GroupSymbolIndex = 0;
1635 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1636 GroupMap.lookup(&Section));
1638 uint64_t Size = GetSectionAddressSize(Layout, SD);
1640 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1641 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1646 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1647 std::vector<const MCSectionELF*> &Sections) {
1648 for (MCAssembler::iterator it = Asm.begin(),
1649 ie = Asm.end(); it != ie; ++it) {
1650 const MCSectionELF &Section =
1651 static_cast<const MCSectionELF &>(it->getSection());
1652 if (Section.getType() == ELF::SHT_GROUP)
1653 Sections.push_back(&Section);
1656 for (MCAssembler::iterator it = Asm.begin(),
1657 ie = Asm.end(); it != ie; ++it) {
1658 const MCSectionELF &Section =
1659 static_cast<const MCSectionELF &>(it->getSection());
1660 if (Section.getType() != ELF::SHT_GROUP &&
1661 Section.getType() != ELF::SHT_REL &&
1662 Section.getType() != ELF::SHT_RELA)
1663 Sections.push_back(&Section);
1666 for (MCAssembler::iterator it = Asm.begin(),
1667 ie = Asm.end(); it != ie; ++it) {
1668 const MCSectionELF &Section =
1669 static_cast<const MCSectionELF &>(it->getSection());
1670 if (Section.getType() == ELF::SHT_REL ||
1671 Section.getType() == ELF::SHT_RELA)
1672 Sections.push_back(&Section);
1676 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1677 const MCAsmLayout &Layout) {
1678 GroupMapTy GroupMap;
1679 RevGroupMapTy RevGroupMap;
1680 SectionIndexMapTy SectionIndexMap;
1682 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1683 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1684 RevGroupMap, SectionIndexMap);
1686 unsigned NumRegularSections = Asm.size();
1688 // Compute symbol table information.
1689 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1691 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1693 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1694 const_cast<MCAsmLayout&>(Layout),
1697 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1698 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1699 sizeof(ELF::Elf32_Ehdr);
1700 uint64_t FileOff = HeaderSize;
1702 std::vector<const MCSectionELF*> Sections;
1703 ComputeSectionOrder(Asm, Sections);
1704 unsigned NumSections = Sections.size();
1705 SectionOffsetMapTy SectionOffsetMap;
1706 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1707 const MCSectionELF &Section = *Sections[i];
1708 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1710 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1712 // Remember the offset into the file for this section.
1713 SectionOffsetMap[&Section] = FileOff;
1715 // Get the size of the section in the output file (including padding).
1716 FileOff += GetSectionFileSize(Layout, SD);
1719 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1721 const unsigned SectionHeaderOffset = FileOff;
1723 uint64_t SectionHeaderEntrySize = is64Bit() ?
1724 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1725 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1727 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1728 const MCSectionELF &Section = *Sections[i];
1729 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1731 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1733 // Remember the offset into the file for this section.
1734 SectionOffsetMap[&Section] = FileOff;
1736 // Get the size of the section in the output file (including padding).
1737 FileOff += GetSectionFileSize(Layout, SD);
1740 // Write out the ELF header ...
1741 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1743 // ... then the regular sections ...
1744 // + because of .shstrtab
1745 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1746 WriteDataSectionData(Asm, Layout, *Sections[i]);
1748 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1749 WriteZeros(Padding);
1751 // ... then the section header table ...
1752 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1754 // ... and then the remaining sections ...
1755 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1756 WriteDataSectionData(Asm, Layout, *Sections[i]);
1759 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1760 const MCAssembler &Asm, const MCSymbolData &DataA,
1761 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1762 bool IsPCRel) const {
1763 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1765 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1766 Asm, DataA, DataB, FB, InSet, IsPCRel);
1769 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1770 return ::isWeak(SD);
1773 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1775 bool IsLittleEndian) {
1776 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);