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 /// Helper struct for containing some precomputed information on symbols.
116 struct ELFSymbolData {
117 MCSymbolData *SymbolData;
118 uint64_t StringIndex;
119 uint32_t SectionIndex;
122 // Support lexicographic sorting.
123 bool operator<(const ELFSymbolData &RHS) const {
124 unsigned LHSType = MCELF::GetType(*SymbolData);
125 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
126 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
128 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
130 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
131 return SectionIndex < RHS.SectionIndex;
132 return Name < RHS.Name;
136 /// The target specific ELF writer instance.
137 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
139 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
140 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
141 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
143 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
145 StringTableBuilder ShStrTabBuilder;
148 /// @name Symbol Table Data
151 StringTableBuilder StrTabBuilder;
152 std::vector<uint64_t> FileSymbolData;
153 std::vector<ELFSymbolData> LocalSymbolData;
154 std::vector<ELFSymbolData> ExternalSymbolData;
155 std::vector<ELFSymbolData> UndefinedSymbolData;
161 // This holds the symbol table index of the last local symbol.
162 unsigned LastLocalSymbolIndex;
163 // This holds the .strtab section index.
164 unsigned StringTableIndex;
165 // This holds the .symtab section index.
166 unsigned SymbolTableIndex;
168 unsigned ShstrtabIndex;
171 // TargetObjectWriter wrappers.
172 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
173 bool hasRelocationAddend() const {
174 return TargetObjectWriter->hasRelocationAddend();
176 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
177 bool IsPCRel) const {
178 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
182 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
184 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
185 TargetObjectWriter(MOTW), NeedsGOT(false) {}
187 void reset() override {
189 WeakrefUsedInReloc.clear();
192 ShStrTabBuilder.clear();
193 StrTabBuilder.clear();
194 FileSymbolData.clear();
195 LocalSymbolData.clear();
196 ExternalSymbolData.clear();
197 UndefinedSymbolData.clear();
198 MCObjectWriter::reset();
201 virtual ~ELFObjectWriter();
203 void WriteWord(uint64_t W) {
210 template <typename T> void write(MCDataFragment &F, T Value) {
211 FWriter.write(F, Value);
214 void WriteHeader(const MCAssembler &Asm,
215 uint64_t SectionHeaderOffset,
216 unsigned NumberOfSections);
218 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
219 const MCAsmLayout &Layout);
221 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
222 const MCAsmLayout &Layout,
223 SectionIndexMapTy &SectionIndexMap);
225 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
226 const MCSymbolRefExpr *RefA,
227 const MCSymbolData *SD, uint64_t C,
228 unsigned Type) const;
230 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
231 const MCFragment *Fragment, const MCFixup &Fixup,
232 MCValue Target, bool &IsPCRel,
233 uint64_t &FixedValue) override;
235 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
238 // Map from a group section to the signature symbol
239 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
240 // Map from a signature symbol to the group section
241 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
242 // Map from a section to its offset
243 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
245 /// Compute the symbol table data
247 /// \param Asm - The assembler.
248 /// \param SectionIndexMap - Maps a section to its index.
249 /// \param RevGroupMap - Maps a signature symbol to the group section.
250 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
251 const SectionIndexMapTy &SectionIndexMap,
252 const RevGroupMapTy &RevGroupMap);
254 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
256 MCSectionData *createRelocationSection(MCAssembler &Asm,
257 const MCSectionData &SD);
259 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
261 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
263 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
264 SectionIndexMapTy &SectionIndexMap);
266 // Create the sections that show up in the symbol table. Currently
267 // those are the .note.GNU-stack section and the group sections.
268 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
269 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
270 SectionIndexMapTy &SectionIndexMap);
272 void ExecutePostLayoutBinding(MCAssembler &Asm,
273 const MCAsmLayout &Layout) override;
275 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
276 const MCAsmLayout &Layout,
277 const SectionIndexMapTy &SectionIndexMap,
278 const SectionOffsetMapTy &SectionOffsetMap);
280 void ComputeSectionOrder(MCAssembler &Asm,
281 std::vector<const MCSectionELF*> &Sections);
283 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
284 uint64_t Address, uint64_t Offset,
285 uint64_t Size, uint32_t Link, uint32_t Info,
286 uint64_t Alignment, uint64_t EntrySize);
288 void WriteRelocationsFragment(const MCAssembler &Asm,
290 const MCSectionData *SD);
293 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
294 const MCSymbolData &DataA,
295 const MCSymbolData *DataB,
296 const MCFragment &FB,
298 bool IsPCRel) const override;
300 bool isWeak(const MCSymbolData &SD) const override;
302 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
303 void writeSection(MCAssembler &Asm,
304 const SectionIndexMapTy &SectionIndexMap,
305 uint32_t GroupSymbolIndex,
306 uint64_t Offset, uint64_t Size, uint64_t Alignment,
307 const MCSectionELF &Section);
311 FragmentWriter::FragmentWriter(bool IsLittleEndian)
312 : IsLittleEndian(IsLittleEndian) {}
314 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
316 Val = support::endian::byte_swap<T, support::little>(Val);
318 Val = support::endian::byte_swap<T, support::big>(Val);
319 const char *Start = (const char *)&Val;
320 F.getContents().append(Start, Start + sizeof(T));
323 void SymbolTableWriter::createSymtabShndx() {
327 MCContext &Ctx = Asm.getContext();
328 const MCSectionELF *SymtabShndxSection =
329 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
330 MCSectionData *SymtabShndxSD =
331 &Asm.getOrCreateSectionData(*SymtabShndxSection);
332 SymtabShndxSD->setAlignment(4);
333 ShndxF = new MCDataFragment(SymtabShndxSD);
334 unsigned Index = SectionIndexMap.size() + 1;
335 SectionIndexMap[SymtabShndxSection] = Index;
337 for (unsigned I = 0; I < NumWritten; ++I)
338 write(*ShndxF, uint32_t(0));
341 template <typename T>
342 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
343 FWriter.write(F, Value);
346 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
348 SectionIndexMapTy &SectionIndexMap,
349 MCDataFragment *SymtabF)
350 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
351 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
354 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
355 uint64_t size, uint8_t other,
356 uint32_t shndx, bool Reserved) {
357 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
364 write(*ShndxF, shndx);
366 write(*ShndxF, uint32_t(0));
369 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
371 raw_svector_ostream OS(SymtabF->getContents());
374 write(*SymtabF, name); // st_name
375 write(*SymtabF, info); // st_info
376 write(*SymtabF, other); // st_other
377 write(*SymtabF, Index); // st_shndx
378 write(*SymtabF, value); // st_value
379 write(*SymtabF, size); // st_size
381 write(*SymtabF, name); // st_name
382 write(*SymtabF, uint32_t(value)); // st_value
383 write(*SymtabF, uint32_t(size)); // st_size
384 write(*SymtabF, info); // st_info
385 write(*SymtabF, other); // st_other
386 write(*SymtabF, Index); // st_shndx
392 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
393 const MCFixupKindInfo &FKI =
394 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
396 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
399 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
403 case MCSymbolRefExpr::VK_GOT:
404 case MCSymbolRefExpr::VK_PLT:
405 case MCSymbolRefExpr::VK_GOTPCREL:
406 case MCSymbolRefExpr::VK_GOTOFF:
407 case MCSymbolRefExpr::VK_TPOFF:
408 case MCSymbolRefExpr::VK_TLSGD:
409 case MCSymbolRefExpr::VK_GOTTPOFF:
410 case MCSymbolRefExpr::VK_INDNTPOFF:
411 case MCSymbolRefExpr::VK_NTPOFF:
412 case MCSymbolRefExpr::VK_GOTNTPOFF:
413 case MCSymbolRefExpr::VK_TLSLDM:
414 case MCSymbolRefExpr::VK_DTPOFF:
415 case MCSymbolRefExpr::VK_TLSLD:
420 ELFObjectWriter::~ELFObjectWriter()
423 // Emit the ELF header.
424 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
425 uint64_t SectionHeaderOffset,
426 unsigned NumberOfSections) {
432 // emitWord method behaves differently for ELF32 and ELF64, writing
433 // 4 bytes in the former and 8 in the latter.
435 Write8(0x7f); // e_ident[EI_MAG0]
436 Write8('E'); // e_ident[EI_MAG1]
437 Write8('L'); // e_ident[EI_MAG2]
438 Write8('F'); // e_ident[EI_MAG3]
440 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
443 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
445 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
447 Write8(TargetObjectWriter->getOSABI());
448 Write8(0); // e_ident[EI_ABIVERSION]
450 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
452 Write16(ELF::ET_REL); // e_type
454 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
456 Write32(ELF::EV_CURRENT); // e_version
457 WriteWord(0); // e_entry, no entry point in .o file
458 WriteWord(0); // e_phoff, no program header for .o
459 WriteWord(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
461 // e_flags = whatever the target wants
462 Write32(Asm.getELFHeaderEFlags());
464 // e_ehsize = ELF header size
465 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
467 Write16(0); // e_phentsize = prog header entry size
468 Write16(0); // e_phnum = # prog header entries = 0
470 // e_shentsize = Section header entry size
471 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
473 // e_shnum = # of section header ents
474 if (NumberOfSections >= ELF::SHN_LORESERVE)
475 Write16(ELF::SHN_UNDEF);
477 Write16(NumberOfSections);
479 // e_shstrndx = Section # of '.shstrtab'
480 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
481 Write16(ELF::SHN_XINDEX);
483 Write16(ShstrtabIndex);
486 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
487 const MCAsmLayout &Layout) {
488 if (Data.isCommon() && Data.isExternal())
489 return Data.getCommonAlignment();
492 if (!Layout.getSymbolOffset(&Data, Res))
495 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
501 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
502 const MCAsmLayout &Layout) {
503 // The presence of symbol versions causes undefined symbols and
504 // versions declared with @@@ to be renamed.
506 for (MCSymbolData &OriginalData : Asm.symbols()) {
507 const MCSymbol &Alias = OriginalData.getSymbol();
510 if (!Alias.isVariable())
512 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
515 const MCSymbol &Symbol = Ref->getSymbol();
516 MCSymbolData &SD = Asm.getSymbolData(Symbol);
518 StringRef AliasName = Alias.getName();
519 size_t Pos = AliasName.find('@');
520 if (Pos == StringRef::npos)
523 // Aliases defined with .symvar copy the binding from the symbol they alias.
524 // This is the first place we are able to copy this information.
525 OriginalData.setExternal(SD.isExternal());
526 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
528 StringRef Rest = AliasName.substr(Pos);
529 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
532 // FIXME: produce a better error message.
533 if (Symbol.isUndefined() && Rest.startswith("@@") &&
534 !Rest.startswith("@@@"))
535 report_fatal_error("A @@ version cannot be undefined");
537 Renames.insert(std::make_pair(&Symbol, &Alias));
541 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
542 uint8_t Type = newType;
544 // Propagation rules:
545 // IFUNC > FUNC > OBJECT > NOTYPE
546 // TLS_OBJECT > OBJECT > NOTYPE
548 // dont let the new type degrade the old type
552 case ELF::STT_GNU_IFUNC:
553 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
554 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
555 Type = ELF::STT_GNU_IFUNC;
558 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
559 Type == ELF::STT_TLS)
560 Type = ELF::STT_FUNC;
562 case ELF::STT_OBJECT:
563 if (Type == ELF::STT_NOTYPE)
564 Type = ELF::STT_OBJECT;
567 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
568 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
576 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
577 const MCAsmLayout &Layout) {
578 MCSymbolData &OrigData = *MSD.SymbolData;
579 assert((!OrigData.getFragment() ||
580 (&OrigData.getFragment()->getParent()->getSection() ==
581 &OrigData.getSymbol().getSection())) &&
582 "The symbol's section doesn't match the fragment's symbol");
583 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
585 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
587 bool IsReserved = !Base || OrigData.isCommon();
589 // Binding and Type share the same byte as upper and lower nibbles
590 uint8_t Binding = MCELF::GetBinding(OrigData);
591 uint8_t Type = MCELF::GetType(OrigData);
592 MCSymbolData *BaseSD = nullptr;
594 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
595 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
597 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
599 // Other and Visibility share the same byte with Visibility using the lower
601 uint8_t Visibility = MCELF::GetVisibility(OrigData);
602 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
605 uint64_t Value = SymbolValue(OrigData, Layout);
608 const MCExpr *ESize = OrigData.getSize();
610 ESize = BaseSD->getSize();
614 if (!ESize->evaluateKnownAbsolute(Res, Layout))
615 report_fatal_error("Size expression must be absolute.");
619 // Write out the symbol table entry
620 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
621 MSD.SectionIndex, IsReserved);
624 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
626 const MCAsmLayout &Layout,
627 SectionIndexMapTy &SectionIndexMap) {
628 // The string table must be emitted first because we need the index
629 // into the string table for all the symbol names.
631 // FIXME: Make sure the start of the symbol table is aligned.
633 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
635 // The first entry is the undefined symbol entry.
636 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
638 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
639 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
640 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
643 // Write the symbol table entries.
644 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
646 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
647 ELFSymbolData &MSD = LocalSymbolData[i];
648 WriteSymbol(Writer, MSD, Layout);
651 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
652 ELFSymbolData &MSD = ExternalSymbolData[i];
653 MCSymbolData &Data = *MSD.SymbolData;
654 assert(((Data.getFlags() & ELF_STB_Global) ||
655 (Data.getFlags() & ELF_STB_Weak)) &&
656 "External symbol requires STB_GLOBAL or STB_WEAK flag");
657 WriteSymbol(Writer, MSD, Layout);
658 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
659 LastLocalSymbolIndex++;
662 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
663 ELFSymbolData &MSD = UndefinedSymbolData[i];
664 MCSymbolData &Data = *MSD.SymbolData;
665 WriteSymbol(Writer, MSD, Layout);
666 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
667 LastLocalSymbolIndex++;
671 // It is always valid to create a relocation with a symbol. It is preferable
672 // to use a relocation with a section if that is possible. Using the section
673 // allows us to omit some local symbols from the symbol table.
674 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
675 const MCSymbolRefExpr *RefA,
676 const MCSymbolData *SD,
678 unsigned Type) const {
679 // A PCRel relocation to an absolute value has no symbol (or section). We
680 // represent that with a relocation to a null section.
684 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
688 // The .odp creation emits a relocation against the symbol ".TOC." which
689 // create a R_PPC64_TOC relocation. However the relocation symbol name
690 // in final object creation should be NULL, since the symbol does not
691 // really exist, it is just the reference to TOC base for the current
692 // object file. Since the symbol is undefined, returning false results
693 // in a relocation with a null section which is the desired result.
694 case MCSymbolRefExpr::VK_PPC_TOCBASE:
697 // These VariantKind cause the relocation to refer to something other than
698 // the symbol itself, like a linker generated table. Since the address of
699 // symbol is not relevant, we cannot replace the symbol with the
700 // section and patch the difference in the addend.
701 case MCSymbolRefExpr::VK_GOT:
702 case MCSymbolRefExpr::VK_PLT:
703 case MCSymbolRefExpr::VK_GOTPCREL:
704 case MCSymbolRefExpr::VK_Mips_GOT:
705 case MCSymbolRefExpr::VK_PPC_GOT_LO:
706 case MCSymbolRefExpr::VK_PPC_GOT_HI:
707 case MCSymbolRefExpr::VK_PPC_GOT_HA:
711 // An undefined symbol is not in any section, so the relocation has to point
712 // to the symbol itself.
713 const MCSymbol &Sym = SD->getSymbol();
714 if (Sym.isUndefined())
717 unsigned Binding = MCELF::GetBinding(*SD);
720 llvm_unreachable("Invalid Binding");
724 // If the symbol is weak, it might be overridden by a symbol in another
725 // file. The relocation has to point to the symbol so that the linker
728 case ELF::STB_GLOBAL:
729 // Global ELF symbols can be preempted by the dynamic linker. The relocation
730 // has to point to the symbol for a reason analogous to the STB_WEAK case.
734 // If a relocation points to a mergeable section, we have to be careful.
735 // If the offset is zero, a relocation with the section will encode the
736 // same information. With a non-zero offset, the situation is different.
737 // For example, a relocation can point 42 bytes past the end of a string.
738 // If we change such a relocation to use the section, the linker would think
739 // that it pointed to another string and subtracting 42 at runtime will
740 // produce the wrong value.
741 auto &Sec = cast<MCSectionELF>(Sym.getSection());
742 unsigned Flags = Sec.getFlags();
743 if (Flags & ELF::SHF_MERGE) {
747 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
748 // only handle section relocations to mergeable sections if using RELA.
749 if (!hasRelocationAddend())
753 // Most TLS relocations use a got, so they need the symbol. Even those that
754 // are just an offset (@tpoff), require a symbol in gold versions before
755 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
756 // http://sourceware.org/PR16773.
757 if (Flags & ELF::SHF_TLS)
760 // If the symbol is a thumb function the final relocation must set the lowest
761 // bit. With a symbol that is done by just having the symbol have that bit
762 // set, so we would lose the bit if we relocated with the section.
763 // FIXME: We could use the section but add the bit to the relocation value.
764 if (Asm.isThumbFunc(&Sym))
767 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
772 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
773 const MCSymbol &Sym = Ref.getSymbol();
775 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
778 if (!Sym.isVariable())
781 const MCExpr *Expr = Sym.getVariableValue();
782 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
786 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
787 return &Inner->getSymbol();
791 static bool isWeak(const MCSymbolData &D) {
792 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
795 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
796 const MCAsmLayout &Layout,
797 const MCFragment *Fragment,
798 const MCFixup &Fixup, MCValue Target,
799 bool &IsPCRel, uint64_t &FixedValue) {
800 const MCSectionData *FixupSection = Fragment->getParent();
801 uint64_t C = Target.getConstant();
802 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
804 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
805 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
806 "Should not have constructed this");
808 // Let A, B and C being the components of Target and R be the location of
809 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
810 // If it is pcrel, we want to compute (A - B + C - R).
812 // In general, ELF has no relocations for -B. It can only represent (A + C)
813 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
814 // replace B to implement it: (A - R - K + C)
816 Asm.getContext().FatalError(
818 "No relocation available to represent this relative expression");
820 const MCSymbol &SymB = RefB->getSymbol();
822 if (SymB.isUndefined())
823 Asm.getContext().FatalError(
825 Twine("symbol '") + SymB.getName() +
826 "' can not be undefined in a subtraction expression");
828 assert(!SymB.isAbsolute() && "Should have been folded");
829 const MCSection &SecB = SymB.getSection();
830 if (&SecB != &FixupSection->getSection())
831 Asm.getContext().FatalError(
832 Fixup.getLoc(), "Cannot represent a difference across sections");
834 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
836 Asm.getContext().FatalError(
837 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
839 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
840 uint64_t K = SymBOffset - FixupOffset;
845 // We either rejected the fixup or folded B into C at this point.
846 const MCSymbolRefExpr *RefA = Target.getSymA();
847 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
848 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
850 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
851 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
852 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
853 C += Layout.getSymbolOffset(SymAD);
856 if (hasRelocationAddend()) {
863 // FIXME: What is this!?!?
864 MCSymbolRefExpr::VariantKind Modifier =
865 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
866 if (RelocNeedsGOT(Modifier))
869 if (!RelocateWithSymbol) {
870 const MCSection *SecA =
871 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
872 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
873 MCSymbol *SectionSymbol =
874 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
876 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
877 Relocations[FixupSection].push_back(Rec);
882 if (const MCSymbol *R = Renames.lookup(SymA))
885 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
886 WeakrefUsedInReloc.insert(WeakRef);
888 UsedInReloc.insert(SymA);
890 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
891 Relocations[FixupSection].push_back(Rec);
897 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
899 const MCSymbolData &SD = Asm.getSymbolData(*S);
900 return SD.getIndex();
903 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
904 const MCSymbolData &Data, bool Used,
906 const MCSymbol &Symbol = Data.getSymbol();
907 if (Symbol.isVariable()) {
908 const MCExpr *Expr = Symbol.getVariableValue();
909 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
910 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
921 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
924 if (Symbol.isVariable()) {
925 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
926 if (Base && Base->isUndefined())
930 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
931 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
934 if (Symbol.isTemporary())
940 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
941 if (Data.isExternal())
944 const MCSymbol &Symbol = Data.getSymbol();
945 if (Symbol.isDefined())
954 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
955 SectionIndexMapTy &SectionIndexMap) {
957 for (MCAssembler::iterator it = Asm.begin(),
958 ie = Asm.end(); it != ie; ++it) {
959 const MCSectionELF &Section =
960 static_cast<const MCSectionELF &>(it->getSection());
961 if (Section.getType() != ELF::SHT_GROUP)
963 SectionIndexMap[&Section] = Index++;
966 for (MCAssembler::iterator it = Asm.begin(),
967 ie = Asm.end(); it != ie; ++it) {
968 const MCSectionData &SD = *it;
969 const MCSectionELF &Section =
970 static_cast<const MCSectionELF &>(SD.getSection());
971 if (Section.getType() == ELF::SHT_GROUP ||
972 Section.getType() == ELF::SHT_REL ||
973 Section.getType() == ELF::SHT_RELA)
975 SectionIndexMap[&Section] = Index++;
976 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
977 const MCSectionELF *RelSection =
978 static_cast<const MCSectionELF *>(&RelSD->getSection());
979 SectionIndexMap[RelSection] = Index++;
984 void ELFObjectWriter::computeSymbolTable(
985 MCAssembler &Asm, const MCAsmLayout &Layout,
986 const SectionIndexMapTy &SectionIndexMap,
987 const RevGroupMapTy &RevGroupMap) {
988 // FIXME: Is this the correct place to do this?
989 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
991 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
992 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
993 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
994 Data.setExternal(true);
995 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
998 // Add the data for the symbols.
999 for (MCSymbolData &SD : Asm.symbols()) {
1000 const MCSymbol &Symbol = SD.getSymbol();
1002 bool Used = UsedInReloc.count(&Symbol);
1003 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1004 bool isSignature = RevGroupMap.count(&Symbol);
1006 if (!isInSymtab(Layout, SD,
1007 Used || WeakrefUsed || isSignature,
1008 Renames.count(&Symbol)))
1012 MSD.SymbolData = &SD;
1013 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1015 // Undefined symbols are global, but this is the first place we
1016 // are able to set it.
1017 bool Local = isLocal(SD, Used);
1018 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1020 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1021 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1022 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1026 MSD.SectionIndex = ELF::SHN_ABS;
1027 } else if (SD.isCommon()) {
1029 MSD.SectionIndex = ELF::SHN_COMMON;
1030 } else if (BaseSymbol->isUndefined()) {
1031 if (isSignature && !Used)
1032 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1034 MSD.SectionIndex = ELF::SHN_UNDEF;
1035 if (!Used && WeakrefUsed)
1036 MCELF::SetBinding(SD, ELF::STB_WEAK);
1038 const MCSectionELF &Section =
1039 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1040 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1041 assert(MSD.SectionIndex && "Invalid section index!");
1044 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1047 // FIXME: All name handling should be done before we get to the writer,
1048 // including dealing with GNU-style version suffixes. Fixing this isn't
1051 // We thus have to be careful to not perform the symbol version replacement
1054 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1055 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1056 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1057 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1058 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1059 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1060 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1061 // "__imp_?" or "__imp_@?".
1063 // It would have been interesting to perform the MS mangling prefix check
1064 // only when the target triple is of the form *-pc-windows-elf. But, it
1065 // seems that this information is not easily accessible from the
1067 StringRef Name = Symbol.getName();
1068 if (!Name.startswith("?") && !Name.startswith("@?") &&
1069 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1070 // This symbol isn't following the MSVC C++ name mangling convention. We
1071 // can thus safely interpret the @@@ in symbol names as specifying symbol
1073 SmallString<32> Buf;
1074 size_t Pos = Name.find("@@@");
1075 if (Pos != StringRef::npos) {
1076 Buf += Name.substr(0, Pos);
1077 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1078 Buf += Name.substr(Pos + Skip);
1083 // Sections have their own string table
1084 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1085 MSD.Name = StrTabBuilder.add(Name);
1087 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1088 UndefinedSymbolData.push_back(MSD);
1090 LocalSymbolData.push_back(MSD);
1092 ExternalSymbolData.push_back(MSD);
1095 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1096 StrTabBuilder.add(*i);
1098 StrTabBuilder.finalize(StringTableBuilder::ELF);
1100 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1101 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1103 for (ELFSymbolData &MSD : LocalSymbolData)
1104 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1106 : StrTabBuilder.getOffset(MSD.Name);
1107 for (ELFSymbolData &MSD : ExternalSymbolData)
1108 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1109 for (ELFSymbolData& MSD : UndefinedSymbolData)
1110 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1112 // Symbols are required to be in lexicographic order.
1113 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1114 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1115 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1117 // Set the symbol indices. Local symbols must come before all other
1118 // symbols with non-local bindings.
1119 unsigned Index = FileSymbolData.size() + 1;
1120 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1121 LocalSymbolData[i].SymbolData->setIndex(Index++);
1123 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1124 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1125 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1126 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1130 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1131 const MCSectionData &SD) {
1132 if (Relocations[&SD].empty())
1135 MCContext &Ctx = Asm.getContext();
1136 const MCSectionELF &Section =
1137 static_cast<const MCSectionELF &>(SD.getSection());
1139 const StringRef SectionName = Section.getSectionName();
1140 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1141 RelaSectionName += SectionName;
1144 if (hasRelocationAddend())
1145 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1147 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1150 if (Section.getFlags() & ELF::SHF_GROUP)
1151 Flags = ELF::SHF_GROUP;
1153 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1154 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1155 Flags, EntrySize, Section.getGroup(), &Section);
1156 return &Asm.getOrCreateSectionData(*RelaSection);
1159 static SmallVector<char, 128>
1160 getUncompressedData(MCAsmLayout &Layout,
1161 MCSectionData::FragmentListType &Fragments) {
1162 SmallVector<char, 128> UncompressedData;
1163 for (const MCFragment &F : Fragments) {
1164 const SmallVectorImpl<char> *Contents;
1165 switch (F.getKind()) {
1166 case MCFragment::FT_Data:
1167 Contents = &cast<MCDataFragment>(F).getContents();
1169 case MCFragment::FT_Dwarf:
1170 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1172 case MCFragment::FT_DwarfFrame:
1173 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1177 "Not expecting any other fragment types in a debug_* section");
1179 UncompressedData.append(Contents->begin(), Contents->end());
1181 return UncompressedData;
1184 // Include the debug info compression header:
1185 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1186 // useful for consumers to preallocate a buffer to decompress into.
1188 prependCompressionHeader(uint64_t Size,
1189 SmallVectorImpl<char> &CompressedContents) {
1190 const StringRef Magic = "ZLIB";
1191 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1193 if (sys::IsLittleEndianHost)
1194 sys::swapByteOrder(Size);
1195 CompressedContents.insert(CompressedContents.begin(),
1196 Magic.size() + sizeof(Size), 0);
1197 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1198 std::copy(reinterpret_cast<char *>(&Size),
1199 reinterpret_cast<char *>(&Size + 1),
1200 CompressedContents.begin() + Magic.size());
1204 // Return a single fragment containing the compressed contents of the whole
1205 // section. Null if the section was not compressed for any reason.
1206 static std::unique_ptr<MCDataFragment>
1207 getCompressedFragment(MCAsmLayout &Layout,
1208 MCSectionData::FragmentListType &Fragments) {
1209 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1211 // Gather the uncompressed data from all the fragments, recording the
1212 // alignment fragment, if seen, and any fixups.
1213 SmallVector<char, 128> UncompressedData =
1214 getUncompressedData(Layout, Fragments);
1216 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1218 zlib::Status Success = zlib::compress(
1219 StringRef(UncompressedData.data(), UncompressedData.size()),
1220 CompressedContents);
1221 if (Success != zlib::StatusOK)
1224 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1227 return CompressedFragment;
1230 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1233 static void UpdateSymbols(const MCAsmLayout &Layout,
1234 const std::vector<MCSymbolData *> &Symbols,
1235 MCFragment &NewFragment) {
1236 for (MCSymbolData *Sym : Symbols) {
1237 Sym->setOffset(Sym->getOffset() +
1238 Layout.getFragmentOffset(Sym->getFragment()));
1239 Sym->setFragment(&NewFragment);
1243 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1244 const DefiningSymbolMap &DefiningSymbols,
1245 const MCSectionELF &Section,
1246 MCSectionData &SD) {
1247 StringRef SectionName = Section.getSectionName();
1248 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1250 std::unique_ptr<MCDataFragment> CompressedFragment =
1251 getCompressedFragment(Layout, Fragments);
1253 // Leave the section as-is if the fragments could not be compressed.
1254 if (!CompressedFragment)
1257 // Update the fragment+offsets of any symbols referring to fragments in this
1258 // section to refer to the new fragment.
1259 auto I = DefiningSymbols.find(&SD);
1260 if (I != DefiningSymbols.end())
1261 UpdateSymbols(Layout, I->second, *CompressedFragment);
1263 // Invalidate the layout for the whole section since it will have new and
1264 // different fragments now.
1265 Layout.invalidateFragmentsFrom(&Fragments.front());
1268 // Complete the initialization of the new fragment
1269 CompressedFragment->setParent(&SD);
1270 CompressedFragment->setLayoutOrder(0);
1271 Fragments.push_back(CompressedFragment.release());
1273 // Rename from .debug_* to .zdebug_*
1274 Asm.getContext().renameELFSection(&Section,
1275 (".z" + SectionName.drop_front(1)).str());
1278 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1279 MCAsmLayout &Layout) {
1280 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1283 DefiningSymbolMap DefiningSymbols;
1285 for (MCSymbolData &SD : Asm.symbols())
1286 if (MCFragment *F = SD.getFragment())
1287 DefiningSymbols[F->getParent()].push_back(&SD);
1289 for (MCSectionData &SD : Asm) {
1290 const MCSectionELF &Section =
1291 static_cast<const MCSectionELF &>(SD.getSection());
1292 StringRef SectionName = Section.getSectionName();
1294 // Compressing debug_frame requires handling alignment fragments which is
1295 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1296 // for writing to arbitrary buffers) for little benefit.
1297 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1300 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1304 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1305 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1306 MCSectionData &RelSD = *it;
1307 const MCSectionELF &RelSection =
1308 static_cast<const MCSectionELF &>(RelSD.getSection());
1310 unsigned Type = RelSection.getType();
1311 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1314 const MCSectionELF *Section = RelSection.getAssociatedSection();
1315 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1316 RelSD.setAlignment(is64Bit() ? 8 : 4);
1318 MCDataFragment *F = new MCDataFragment(&RelSD);
1319 WriteRelocationsFragment(Asm, F, &SD);
1323 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1324 uint64_t Flags, uint64_t Address,
1325 uint64_t Offset, uint64_t Size,
1326 uint32_t Link, uint32_t Info,
1328 uint64_t EntrySize) {
1329 Write32(Name); // sh_name: index into string table
1330 Write32(Type); // sh_type
1331 WriteWord(Flags); // sh_flags
1332 WriteWord(Address); // sh_addr
1333 WriteWord(Offset); // sh_offset
1334 WriteWord(Size); // sh_size
1335 Write32(Link); // sh_link
1336 Write32(Info); // sh_info
1337 WriteWord(Alignment); // sh_addralign
1338 WriteWord(EntrySize); // sh_entsize
1341 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1342 // just to match gnu as for easier comparison. The use type is an arbitrary way
1343 // of making the sort deterministic.
1344 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1345 const ELFRelocationEntry &A = *AP;
1346 const ELFRelocationEntry &B = *BP;
1347 if (A.Offset != B.Offset)
1348 return B.Offset - A.Offset;
1349 if (B.Type != A.Type)
1350 return A.Type - B.Type;
1351 //llvm_unreachable("ELFRelocs might be unstable!");
1355 static void sortRelocs(const MCAssembler &Asm,
1356 std::vector<ELFRelocationEntry> &Relocs) {
1357 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1360 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1362 const MCSectionData *SD) {
1363 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1365 sortRelocs(Asm, Relocs);
1367 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1368 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1370 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1373 write(*F, Entry.Offset);
1374 if (TargetObjectWriter->isN64()) {
1375 write(*F, uint32_t(Index));
1377 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1378 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1379 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1380 write(*F, TargetObjectWriter->getRType(Entry.Type));
1382 struct ELF::Elf64_Rela ERE64;
1383 ERE64.setSymbolAndType(Index, Entry.Type);
1384 write(*F, ERE64.r_info);
1386 if (hasRelocationAddend())
1387 write(*F, Entry.Addend);
1389 write(*F, uint32_t(Entry.Offset));
1391 struct ELF::Elf32_Rela ERE32;
1392 ERE32.setSymbolAndType(Index, Entry.Type);
1393 write(*F, ERE32.r_info);
1395 if (hasRelocationAddend())
1396 write(*F, uint32_t(Entry.Addend));
1401 void ELFObjectWriter::CreateMetadataSections(
1402 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1403 MCContext &Ctx = Asm.getContext();
1406 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1408 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1409 const MCSectionELF *ShstrtabSection =
1410 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1411 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1412 ShstrtabSD.setAlignment(1);
1413 ShstrtabIndex = SectionIndexMap.size() + 1;
1414 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1416 const MCSectionELF *SymtabSection =
1417 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1419 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1420 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1421 SymbolTableIndex = SectionIndexMap.size() + 1;
1422 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1424 const MCSectionELF *StrtabSection;
1425 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1426 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1427 StrtabSD.setAlignment(1);
1428 StringTableIndex = SectionIndexMap.size() + 1;
1429 SectionIndexMap[StrtabSection] = StringTableIndex;
1432 F = new MCDataFragment(&SymtabSD);
1433 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1435 F = new MCDataFragment(&StrtabSD);
1436 F->getContents().append(StrTabBuilder.data().begin(),
1437 StrTabBuilder.data().end());
1439 F = new MCDataFragment(&ShstrtabSD);
1441 // Section header string table.
1442 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1443 const MCSectionELF &Section =
1444 static_cast<const MCSectionELF&>(it->getSection());
1445 ShStrTabBuilder.add(Section.getSectionName());
1447 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1448 F->getContents().append(ShStrTabBuilder.data().begin(),
1449 ShStrTabBuilder.data().end());
1452 void ELFObjectWriter::createIndexedSections(
1453 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1454 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1455 MCContext &Ctx = Asm.getContext();
1458 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1460 const MCSectionELF &Section =
1461 static_cast<const MCSectionELF&>(it->getSection());
1462 if (!(Section.getFlags() & ELF::SHF_GROUP))
1465 const MCSymbol *SignatureSymbol = Section.getGroup();
1466 Asm.getOrCreateSymbolData(*SignatureSymbol);
1467 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1469 Group = Ctx.CreateELFGroupSection();
1470 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1471 Data.setAlignment(4);
1472 MCDataFragment *F = new MCDataFragment(&Data);
1473 write(*F, uint32_t(ELF::GRP_COMDAT));
1475 GroupMap[Group] = SignatureSymbol;
1478 computeIndexMap(Asm, SectionIndexMap);
1480 // Add sections to the groups
1481 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1483 const MCSectionELF &Section =
1484 static_cast<const MCSectionELF&>(it->getSection());
1485 if (!(Section.getFlags() & ELF::SHF_GROUP))
1487 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1488 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1489 // FIXME: we could use the previous fragment
1490 MCDataFragment *F = new MCDataFragment(&Data);
1491 uint32_t Index = SectionIndexMap.lookup(&Section);
1496 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1497 const SectionIndexMapTy &SectionIndexMap,
1498 uint32_t GroupSymbolIndex,
1499 uint64_t Offset, uint64_t Size,
1501 const MCSectionELF &Section) {
1502 uint64_t sh_link = 0;
1503 uint64_t sh_info = 0;
1505 switch(Section.getType()) {
1510 case ELF::SHT_DYNAMIC:
1511 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1515 case ELF::SHT_RELA: {
1516 sh_link = SymbolTableIndex;
1517 assert(sh_link && ".symtab not found");
1518 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1519 sh_info = SectionIndexMap.lookup(InfoSection);
1523 case ELF::SHT_SYMTAB:
1524 case ELF::SHT_DYNSYM:
1525 sh_link = StringTableIndex;
1526 sh_info = LastLocalSymbolIndex;
1529 case ELF::SHT_SYMTAB_SHNDX:
1530 sh_link = SymbolTableIndex;
1533 case ELF::SHT_GROUP:
1534 sh_link = SymbolTableIndex;
1535 sh_info = GroupSymbolIndex;
1539 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1540 Section.getType() == ELF::SHT_ARM_EXIDX)
1541 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1543 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1545 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1546 Alignment, Section.getEntrySize());
1549 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1550 return SD.getOrdinal() == ~UINT32_C(0) &&
1551 !SD.getSection().isVirtualSection();
1554 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1556 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1558 const MCFragment &F = *i;
1559 assert(F.getKind() == MCFragment::FT_Data);
1560 Ret += cast<MCDataFragment>(F).getContents().size();
1565 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1566 const MCSectionData &SD) {
1567 if (IsELFMetaDataSection(SD))
1568 return DataSectionSize(SD);
1569 return Layout.getSectionFileSize(&SD);
1572 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1573 const MCSectionData &SD) {
1574 if (IsELFMetaDataSection(SD))
1575 return DataSectionSize(SD);
1576 return Layout.getSectionAddressSize(&SD);
1579 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1580 const MCAsmLayout &Layout,
1581 const MCSectionELF &Section) {
1582 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1584 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1585 WriteZeros(Padding);
1587 if (IsELFMetaDataSection(SD)) {
1588 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1590 const MCFragment &F = *i;
1591 assert(F.getKind() == MCFragment::FT_Data);
1592 WriteBytes(cast<MCDataFragment>(F).getContents());
1595 Asm.writeSectionData(&SD, Layout);
1599 void ELFObjectWriter::writeSectionHeader(
1600 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1601 const SectionIndexMapTy &SectionIndexMap,
1602 const SectionOffsetMapTy &SectionOffsetMap) {
1603 const unsigned NumSections = Asm.size() + 1;
1605 std::vector<const MCSectionELF*> Sections;
1606 Sections.resize(NumSections - 1);
1608 for (SectionIndexMapTy::const_iterator i=
1609 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1610 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1611 Sections[p.second - 1] = p.first;
1614 // Null section first.
1615 uint64_t FirstSectionSize =
1616 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1617 uint32_t FirstSectionLink =
1618 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1619 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1621 for (unsigned i = 0; i < NumSections - 1; ++i) {
1622 const MCSectionELF &Section = *Sections[i];
1623 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1624 uint32_t GroupSymbolIndex;
1625 if (Section.getType() != ELF::SHT_GROUP)
1626 GroupSymbolIndex = 0;
1628 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1629 GroupMap.lookup(&Section));
1631 uint64_t Size = GetSectionAddressSize(Layout, SD);
1633 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1634 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1639 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1640 std::vector<const MCSectionELF*> &Sections) {
1641 for (MCAssembler::iterator it = Asm.begin(),
1642 ie = Asm.end(); it != ie; ++it) {
1643 const MCSectionELF &Section =
1644 static_cast<const MCSectionELF &>(it->getSection());
1645 if (Section.getType() == ELF::SHT_GROUP)
1646 Sections.push_back(&Section);
1649 for (MCAssembler::iterator it = Asm.begin(),
1650 ie = Asm.end(); it != ie; ++it) {
1651 const MCSectionELF &Section =
1652 static_cast<const MCSectionELF &>(it->getSection());
1653 if (Section.getType() != ELF::SHT_GROUP &&
1654 Section.getType() != ELF::SHT_REL &&
1655 Section.getType() != ELF::SHT_RELA)
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_REL ||
1664 Section.getType() == ELF::SHT_RELA)
1665 Sections.push_back(&Section);
1669 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1670 const MCAsmLayout &Layout) {
1671 GroupMapTy GroupMap;
1672 RevGroupMapTy RevGroupMap;
1673 SectionIndexMapTy SectionIndexMap;
1675 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1676 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1677 RevGroupMap, SectionIndexMap);
1679 unsigned NumRegularSections = Asm.size();
1681 // Compute symbol table information.
1682 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1684 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1686 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1687 const_cast<MCAsmLayout&>(Layout),
1690 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1691 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1692 sizeof(ELF::Elf32_Ehdr);
1693 uint64_t FileOff = HeaderSize;
1695 std::vector<const MCSectionELF*> Sections;
1696 ComputeSectionOrder(Asm, Sections);
1697 unsigned NumSections = Sections.size();
1698 SectionOffsetMapTy SectionOffsetMap;
1699 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1700 const MCSectionELF &Section = *Sections[i];
1701 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1703 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1705 // Remember the offset into the file for this section.
1706 SectionOffsetMap[&Section] = FileOff;
1708 // Get the size of the section in the output file (including padding).
1709 FileOff += GetSectionFileSize(Layout, SD);
1712 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1714 const unsigned SectionHeaderOffset = FileOff;
1716 uint64_t SectionHeaderEntrySize = is64Bit() ?
1717 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1718 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1720 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1721 const MCSectionELF &Section = *Sections[i];
1722 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1724 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1726 // Remember the offset into the file for this section.
1727 SectionOffsetMap[&Section] = FileOff;
1729 // Get the size of the section in the output file (including padding).
1730 FileOff += GetSectionFileSize(Layout, SD);
1733 // Write out the ELF header ...
1734 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1736 // ... then the regular sections ...
1737 // + because of .shstrtab
1738 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1739 WriteDataSectionData(Asm, Layout, *Sections[i]);
1741 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1742 WriteZeros(Padding);
1744 // ... then the section header table ...
1745 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1747 // ... and then the remaining sections ...
1748 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1749 WriteDataSectionData(Asm, Layout, *Sections[i]);
1752 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1753 const MCAssembler &Asm, const MCSymbolData &DataA,
1754 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1755 bool IsPCRel) const {
1756 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1758 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1759 Asm, DataA, DataB, FB, InSet, IsPCRel);
1762 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1763 return ::isWeak(SD);
1766 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1768 bool IsLittleEndian) {
1769 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);