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 /// \param NumRegularSections - Number of non-relocation sections.
251 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
252 const SectionIndexMapTy &SectionIndexMap,
253 const RevGroupMapTy &RevGroupMap);
255 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
257 MCSectionData *createRelocationSection(MCAssembler &Asm,
258 const MCSectionData &SD);
260 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
262 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
264 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
265 SectionIndexMapTy &SectionIndexMap);
267 // Create the sections that show up in the symbol table. Currently
268 // those are the .note.GNU-stack section and the group sections.
269 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
270 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
271 SectionIndexMapTy &SectionIndexMap);
273 void ExecutePostLayoutBinding(MCAssembler &Asm,
274 const MCAsmLayout &Layout) override;
276 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
277 const MCAsmLayout &Layout,
278 const SectionIndexMapTy &SectionIndexMap,
279 const SectionOffsetMapTy &SectionOffsetMap);
281 void ComputeSectionOrder(MCAssembler &Asm,
282 std::vector<const MCSectionELF*> &Sections);
284 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
285 uint64_t Address, uint64_t Offset,
286 uint64_t Size, uint32_t Link, uint32_t Info,
287 uint64_t Alignment, uint64_t EntrySize);
289 void WriteRelocationsFragment(const MCAssembler &Asm,
291 const MCSectionData *SD);
294 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
295 const MCSymbolData &DataA,
296 const MCSymbolData *DataB,
297 const MCFragment &FB,
299 bool IsPCRel) const override;
301 bool isWeak(const MCSymbolData &SD) const override;
303 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
304 void writeSection(MCAssembler &Asm,
305 const SectionIndexMapTy &SectionIndexMap,
306 uint32_t GroupSymbolIndex,
307 uint64_t Offset, uint64_t Size, uint64_t Alignment,
308 const MCSectionELF &Section);
312 FragmentWriter::FragmentWriter(bool IsLittleEndian)
313 : IsLittleEndian(IsLittleEndian) {}
315 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
317 Val = support::endian::byte_swap<T, support::little>(Val);
319 Val = support::endian::byte_swap<T, support::big>(Val);
320 const char *Start = (const char *)&Val;
321 F.getContents().append(Start, Start + sizeof(T));
324 void SymbolTableWriter::createSymtabShndx() {
328 MCContext &Ctx = Asm.getContext();
329 const MCSectionELF *SymtabShndxSection =
330 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
331 MCSectionData *SymtabShndxSD =
332 &Asm.getOrCreateSectionData(*SymtabShndxSection);
333 SymtabShndxSD->setAlignment(4);
334 ShndxF = new MCDataFragment(SymtabShndxSD);
335 unsigned Index = SectionIndexMap.size() + 1;
336 SectionIndexMap[SymtabShndxSection] = Index;
338 for (unsigned I = 0; I < NumWritten; ++I)
339 write(*ShndxF, uint32_t(0));
342 template <typename T>
343 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
344 FWriter.write(F, Value);
347 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
349 SectionIndexMapTy &SectionIndexMap,
350 MCDataFragment *SymtabF)
351 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
352 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
355 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
356 uint64_t size, uint8_t other,
357 uint32_t shndx, bool Reserved) {
358 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
365 write(*ShndxF, shndx);
367 write(*ShndxF, uint32_t(0));
370 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
372 raw_svector_ostream OS(SymtabF->getContents());
375 write(*SymtabF, name); // st_name
376 write(*SymtabF, info); // st_info
377 write(*SymtabF, other); // st_other
378 write(*SymtabF, Index); // st_shndx
379 write(*SymtabF, value); // st_value
380 write(*SymtabF, size); // st_size
382 write(*SymtabF, name); // st_name
383 write(*SymtabF, uint32_t(value)); // st_value
384 write(*SymtabF, uint32_t(size)); // st_size
385 write(*SymtabF, info); // st_info
386 write(*SymtabF, other); // st_other
387 write(*SymtabF, Index); // st_shndx
393 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
394 const MCFixupKindInfo &FKI =
395 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
397 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
400 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
404 case MCSymbolRefExpr::VK_GOT:
405 case MCSymbolRefExpr::VK_PLT:
406 case MCSymbolRefExpr::VK_GOTPCREL:
407 case MCSymbolRefExpr::VK_GOTOFF:
408 case MCSymbolRefExpr::VK_TPOFF:
409 case MCSymbolRefExpr::VK_TLSGD:
410 case MCSymbolRefExpr::VK_GOTTPOFF:
411 case MCSymbolRefExpr::VK_INDNTPOFF:
412 case MCSymbolRefExpr::VK_NTPOFF:
413 case MCSymbolRefExpr::VK_GOTNTPOFF:
414 case MCSymbolRefExpr::VK_TLSLDM:
415 case MCSymbolRefExpr::VK_DTPOFF:
416 case MCSymbolRefExpr::VK_TLSLD:
421 ELFObjectWriter::~ELFObjectWriter()
424 // Emit the ELF header.
425 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
426 uint64_t SectionHeaderOffset,
427 unsigned NumberOfSections) {
433 // emitWord method behaves differently for ELF32 and ELF64, writing
434 // 4 bytes in the former and 8 in the latter.
436 Write8(0x7f); // e_ident[EI_MAG0]
437 Write8('E'); // e_ident[EI_MAG1]
438 Write8('L'); // e_ident[EI_MAG2]
439 Write8('F'); // e_ident[EI_MAG3]
441 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
444 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
446 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
448 Write8(TargetObjectWriter->getOSABI());
449 Write8(0); // e_ident[EI_ABIVERSION]
451 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
453 Write16(ELF::ET_REL); // e_type
455 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
457 Write32(ELF::EV_CURRENT); // e_version
458 WriteWord(0); // e_entry, no entry point in .o file
459 WriteWord(0); // e_phoff, no program header for .o
460 WriteWord(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
462 // e_flags = whatever the target wants
463 Write32(Asm.getELFHeaderEFlags());
465 // e_ehsize = ELF header size
466 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
468 Write16(0); // e_phentsize = prog header entry size
469 Write16(0); // e_phnum = # prog header entries = 0
471 // e_shentsize = Section header entry size
472 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
474 // e_shnum = # of section header ents
475 if (NumberOfSections >= ELF::SHN_LORESERVE)
476 Write16(ELF::SHN_UNDEF);
478 Write16(NumberOfSections);
480 // e_shstrndx = Section # of '.shstrtab'
481 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
482 Write16(ELF::SHN_XINDEX);
484 Write16(ShstrtabIndex);
487 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
488 const MCAsmLayout &Layout) {
489 if (Data.isCommon() && Data.isExternal())
490 return Data.getCommonAlignment();
493 if (!Layout.getSymbolOffset(&Data, Res))
496 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
502 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
503 const MCAsmLayout &Layout) {
504 // The presence of symbol versions causes undefined symbols and
505 // versions declared with @@@ to be renamed.
507 for (MCSymbolData &OriginalData : Asm.symbols()) {
508 const MCSymbol &Alias = OriginalData.getSymbol();
511 if (!Alias.isVariable())
513 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
516 const MCSymbol &Symbol = Ref->getSymbol();
517 MCSymbolData &SD = Asm.getSymbolData(Symbol);
519 StringRef AliasName = Alias.getName();
520 size_t Pos = AliasName.find('@');
521 if (Pos == StringRef::npos)
524 // Aliases defined with .symvar copy the binding from the symbol they alias.
525 // This is the first place we are able to copy this information.
526 OriginalData.setExternal(SD.isExternal());
527 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
529 StringRef Rest = AliasName.substr(Pos);
530 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
533 // FIXME: produce a better error message.
534 if (Symbol.isUndefined() && Rest.startswith("@@") &&
535 !Rest.startswith("@@@"))
536 report_fatal_error("A @@ version cannot be undefined");
538 Renames.insert(std::make_pair(&Symbol, &Alias));
542 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
543 uint8_t Type = newType;
545 // Propagation rules:
546 // IFUNC > FUNC > OBJECT > NOTYPE
547 // TLS_OBJECT > OBJECT > NOTYPE
549 // dont let the new type degrade the old type
553 case ELF::STT_GNU_IFUNC:
554 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
555 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
556 Type = ELF::STT_GNU_IFUNC;
559 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
560 Type == ELF::STT_TLS)
561 Type = ELF::STT_FUNC;
563 case ELF::STT_OBJECT:
564 if (Type == ELF::STT_NOTYPE)
565 Type = ELF::STT_OBJECT;
568 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
569 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
577 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
578 const MCAsmLayout &Layout) {
579 MCSymbolData &OrigData = *MSD.SymbolData;
580 assert((!OrigData.getFragment() ||
581 (&OrigData.getFragment()->getParent()->getSection() ==
582 &OrigData.getSymbol().getSection())) &&
583 "The symbol's section doesn't match the fragment's symbol");
584 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
586 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
588 bool IsReserved = !Base || OrigData.isCommon();
590 // Binding and Type share the same byte as upper and lower nibbles
591 uint8_t Binding = MCELF::GetBinding(OrigData);
592 uint8_t Type = MCELF::GetType(OrigData);
593 MCSymbolData *BaseSD = nullptr;
595 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
596 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
598 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
600 // Other and Visibility share the same byte with Visibility using the lower
602 uint8_t Visibility = MCELF::GetVisibility(OrigData);
603 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
606 uint64_t Value = SymbolValue(OrigData, Layout);
609 const MCExpr *ESize = OrigData.getSize();
611 ESize = BaseSD->getSize();
615 if (!ESize->evaluateKnownAbsolute(Res, Layout))
616 report_fatal_error("Size expression must be absolute.");
620 // Write out the symbol table entry
621 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
622 MSD.SectionIndex, IsReserved);
625 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
627 const MCAsmLayout &Layout,
628 SectionIndexMapTy &SectionIndexMap) {
629 // The string table must be emitted first because we need the index
630 // into the string table for all the symbol names.
632 // FIXME: Make sure the start of the symbol table is aligned.
634 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
636 // The first entry is the undefined symbol entry.
637 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
639 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
640 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
641 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
644 // Write the symbol table entries.
645 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
647 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
648 ELFSymbolData &MSD = LocalSymbolData[i];
649 WriteSymbol(Writer, MSD, Layout);
652 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
653 ELFSymbolData &MSD = ExternalSymbolData[i];
654 MCSymbolData &Data = *MSD.SymbolData;
655 assert(((Data.getFlags() & ELF_STB_Global) ||
656 (Data.getFlags() & ELF_STB_Weak)) &&
657 "External symbol requires STB_GLOBAL or STB_WEAK flag");
658 WriteSymbol(Writer, MSD, Layout);
659 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
660 LastLocalSymbolIndex++;
663 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
664 ELFSymbolData &MSD = UndefinedSymbolData[i];
665 MCSymbolData &Data = *MSD.SymbolData;
666 WriteSymbol(Writer, MSD, Layout);
667 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
668 LastLocalSymbolIndex++;
672 // It is always valid to create a relocation with a symbol. It is preferable
673 // to use a relocation with a section if that is possible. Using the section
674 // allows us to omit some local symbols from the symbol table.
675 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
676 const MCSymbolRefExpr *RefA,
677 const MCSymbolData *SD,
679 unsigned Type) const {
680 // A PCRel relocation to an absolute value has no symbol (or section). We
681 // represent that with a relocation to a null section.
685 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
689 // The .odp creation emits a relocation against the symbol ".TOC." which
690 // create a R_PPC64_TOC relocation. However the relocation symbol name
691 // in final object creation should be NULL, since the symbol does not
692 // really exist, it is just the reference to TOC base for the current
693 // object file. Since the symbol is undefined, returning false results
694 // in a relocation with a null section which is the desired result.
695 case MCSymbolRefExpr::VK_PPC_TOCBASE:
698 // These VariantKind cause the relocation to refer to something other than
699 // the symbol itself, like a linker generated table. Since the address of
700 // symbol is not relevant, we cannot replace the symbol with the
701 // section and patch the difference in the addend.
702 case MCSymbolRefExpr::VK_GOT:
703 case MCSymbolRefExpr::VK_PLT:
704 case MCSymbolRefExpr::VK_GOTPCREL:
705 case MCSymbolRefExpr::VK_Mips_GOT:
706 case MCSymbolRefExpr::VK_PPC_GOT_LO:
707 case MCSymbolRefExpr::VK_PPC_GOT_HI:
708 case MCSymbolRefExpr::VK_PPC_GOT_HA:
712 // An undefined symbol is not in any section, so the relocation has to point
713 // to the symbol itself.
714 const MCSymbol &Sym = SD->getSymbol();
715 if (Sym.isUndefined())
718 unsigned Binding = MCELF::GetBinding(*SD);
721 llvm_unreachable("Invalid Binding");
725 // If the symbol is weak, it might be overridden by a symbol in another
726 // file. The relocation has to point to the symbol so that the linker
729 case ELF::STB_GLOBAL:
730 // Global ELF symbols can be preempted by the dynamic linker. The relocation
731 // has to point to the symbol for a reason analogous to the STB_WEAK case.
735 // If a relocation points to a mergeable section, we have to be careful.
736 // If the offset is zero, a relocation with the section will encode the
737 // same information. With a non-zero offset, the situation is different.
738 // For example, a relocation can point 42 bytes past the end of a string.
739 // If we change such a relocation to use the section, the linker would think
740 // that it pointed to another string and subtracting 42 at runtime will
741 // produce the wrong value.
742 auto &Sec = cast<MCSectionELF>(Sym.getSection());
743 unsigned Flags = Sec.getFlags();
744 if (Flags & ELF::SHF_MERGE) {
748 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
749 // only handle section relocations to mergeable sections if using RELA.
750 if (!hasRelocationAddend())
754 // Most TLS relocations use a got, so they need the symbol. Even those that
755 // are just an offset (@tpoff), require a symbol in gold versions before
756 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
757 // http://sourceware.org/PR16773.
758 if (Flags & ELF::SHF_TLS)
761 // If the symbol is a thumb function the final relocation must set the lowest
762 // bit. With a symbol that is done by just having the symbol have that bit
763 // set, so we would lose the bit if we relocated with the section.
764 // FIXME: We could use the section but add the bit to the relocation value.
765 if (Asm.isThumbFunc(&Sym))
768 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
773 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
774 const MCSymbol &Sym = Ref.getSymbol();
776 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
779 if (!Sym.isVariable())
782 const MCExpr *Expr = Sym.getVariableValue();
783 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
787 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
788 return &Inner->getSymbol();
792 static bool isWeak(const MCSymbolData &D) {
793 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
796 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
797 const MCAsmLayout &Layout,
798 const MCFragment *Fragment,
799 const MCFixup &Fixup, MCValue Target,
800 bool &IsPCRel, uint64_t &FixedValue) {
801 const MCSectionData *FixupSection = Fragment->getParent();
802 uint64_t C = Target.getConstant();
803 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
805 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
806 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
807 "Should not have constructed this");
809 // Let A, B and C being the components of Target and R be the location of
810 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
811 // If it is pcrel, we want to compute (A - B + C - R).
813 // In general, ELF has no relocations for -B. It can only represent (A + C)
814 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
815 // replace B to implement it: (A - R - K + C)
817 Asm.getContext().FatalError(
819 "No relocation available to represent this relative expression");
821 const MCSymbol &SymB = RefB->getSymbol();
823 if (SymB.isUndefined())
824 Asm.getContext().FatalError(
826 Twine("symbol '") + SymB.getName() +
827 "' can not be undefined in a subtraction expression");
829 assert(!SymB.isAbsolute() && "Should have been folded");
830 const MCSection &SecB = SymB.getSection();
831 if (&SecB != &FixupSection->getSection())
832 Asm.getContext().FatalError(
833 Fixup.getLoc(), "Cannot represent a difference across sections");
835 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
837 Asm.getContext().FatalError(
838 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
840 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
841 uint64_t K = SymBOffset - FixupOffset;
846 // We either rejected the fixup or folded B into C at this point.
847 const MCSymbolRefExpr *RefA = Target.getSymA();
848 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
849 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
851 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
852 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
853 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
854 C += Layout.getSymbolOffset(SymAD);
857 if (hasRelocationAddend()) {
864 // FIXME: What is this!?!?
865 MCSymbolRefExpr::VariantKind Modifier =
866 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
867 if (RelocNeedsGOT(Modifier))
870 if (!RelocateWithSymbol) {
871 const MCSection *SecA =
872 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
873 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
874 MCSymbol *SectionSymbol =
875 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
877 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
878 Relocations[FixupSection].push_back(Rec);
883 if (const MCSymbol *R = Renames.lookup(SymA))
886 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
887 WeakrefUsedInReloc.insert(WeakRef);
889 UsedInReloc.insert(SymA);
891 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
892 Relocations[FixupSection].push_back(Rec);
898 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
900 const MCSymbolData &SD = Asm.getSymbolData(*S);
901 return SD.getIndex();
904 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
905 const MCSymbolData &Data, bool Used,
907 const MCSymbol &Symbol = Data.getSymbol();
908 if (Symbol.isVariable()) {
909 const MCExpr *Expr = Symbol.getVariableValue();
910 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
911 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
922 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
925 if (Symbol.isVariable()) {
926 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
927 if (Base && Base->isUndefined())
931 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
932 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
935 if (Symbol.isTemporary())
941 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
942 if (Data.isExternal())
945 const MCSymbol &Symbol = Data.getSymbol();
946 if (Symbol.isDefined())
955 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
956 SectionIndexMapTy &SectionIndexMap) {
958 for (MCAssembler::iterator it = Asm.begin(),
959 ie = Asm.end(); it != ie; ++it) {
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF &>(it->getSection());
962 if (Section.getType() != ELF::SHT_GROUP)
964 SectionIndexMap[&Section] = Index++;
967 for (MCAssembler::iterator it = Asm.begin(),
968 ie = Asm.end(); it != ie; ++it) {
969 const MCSectionData &SD = *it;
970 const MCSectionELF &Section =
971 static_cast<const MCSectionELF &>(SD.getSection());
972 if (Section.getType() == ELF::SHT_GROUP ||
973 Section.getType() == ELF::SHT_REL ||
974 Section.getType() == ELF::SHT_RELA)
976 SectionIndexMap[&Section] = Index++;
977 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
978 const MCSectionELF *RelSection =
979 static_cast<const MCSectionELF *>(&RelSD->getSection());
980 SectionIndexMap[RelSection] = Index++;
985 void ELFObjectWriter::computeSymbolTable(
986 MCAssembler &Asm, const MCAsmLayout &Layout,
987 const SectionIndexMapTy &SectionIndexMap,
988 const RevGroupMapTy &RevGroupMap) {
989 // FIXME: Is this the correct place to do this?
990 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
992 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
993 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
994 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
995 Data.setExternal(true);
996 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
999 // Add the data for the symbols.
1000 for (MCSymbolData &SD : Asm.symbols()) {
1001 const MCSymbol &Symbol = SD.getSymbol();
1003 bool Used = UsedInReloc.count(&Symbol);
1004 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1005 bool isSignature = RevGroupMap.count(&Symbol);
1007 if (!isInSymtab(Layout, SD,
1008 Used || WeakrefUsed || isSignature,
1009 Renames.count(&Symbol)))
1013 MSD.SymbolData = &SD;
1014 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1016 // Undefined symbols are global, but this is the first place we
1017 // are able to set it.
1018 bool Local = isLocal(SD, Used);
1019 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1021 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1022 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1023 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1027 MSD.SectionIndex = ELF::SHN_ABS;
1028 } else if (SD.isCommon()) {
1030 MSD.SectionIndex = ELF::SHN_COMMON;
1031 } else if (BaseSymbol->isUndefined()) {
1032 if (isSignature && !Used)
1033 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1035 MSD.SectionIndex = ELF::SHN_UNDEF;
1036 if (!Used && WeakrefUsed)
1037 MCELF::SetBinding(SD, ELF::STB_WEAK);
1039 const MCSectionELF &Section =
1040 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1041 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1042 assert(MSD.SectionIndex && "Invalid section index!");
1045 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1048 // FIXME: All name handling should be done before we get to the writer,
1049 // including dealing with GNU-style version suffixes. Fixing this isn't
1052 // We thus have to be careful to not perform the symbol version replacement
1055 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1056 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1057 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1058 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1059 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1060 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1061 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1062 // "__imp_?" or "__imp_@?".
1064 // It would have been interesting to perform the MS mangling prefix check
1065 // only when the target triple is of the form *-pc-windows-elf. But, it
1066 // seems that this information is not easily accessible from the
1068 StringRef Name = Symbol.getName();
1069 if (!Name.startswith("?") && !Name.startswith("@?") &&
1070 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1071 // This symbol isn't following the MSVC C++ name mangling convention. We
1072 // can thus safely interpret the @@@ in symbol names as specifying symbol
1074 SmallString<32> Buf;
1075 size_t Pos = Name.find("@@@");
1076 if (Pos != StringRef::npos) {
1077 Buf += Name.substr(0, Pos);
1078 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1079 Buf += Name.substr(Pos + Skip);
1084 // Sections have their own string table
1085 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1086 MSD.Name = StrTabBuilder.add(Name);
1088 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1089 UndefinedSymbolData.push_back(MSD);
1091 LocalSymbolData.push_back(MSD);
1093 ExternalSymbolData.push_back(MSD);
1096 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1097 StrTabBuilder.add(*i);
1099 StrTabBuilder.finalize(StringTableBuilder::ELF);
1101 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1102 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1104 for (ELFSymbolData &MSD : LocalSymbolData)
1105 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1107 : StrTabBuilder.getOffset(MSD.Name);
1108 for (ELFSymbolData &MSD : ExternalSymbolData)
1109 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1110 for (ELFSymbolData& MSD : UndefinedSymbolData)
1111 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1113 // Symbols are required to be in lexicographic order.
1114 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1115 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1116 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1118 // Set the symbol indices. Local symbols must come before all other
1119 // symbols with non-local bindings.
1120 unsigned Index = FileSymbolData.size() + 1;
1121 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1122 LocalSymbolData[i].SymbolData->setIndex(Index++);
1124 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1125 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1126 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1127 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1131 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1132 const MCSectionData &SD) {
1133 if (Relocations[&SD].empty())
1136 MCContext &Ctx = Asm.getContext();
1137 const MCSectionELF &Section =
1138 static_cast<const MCSectionELF &>(SD.getSection());
1140 const StringRef SectionName = Section.getSectionName();
1141 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1142 RelaSectionName += SectionName;
1145 if (hasRelocationAddend())
1146 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1148 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1151 if (Section.getFlags() & ELF::SHF_GROUP)
1152 Flags = ELF::SHF_GROUP;
1154 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1155 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1156 Flags, EntrySize, Section.getGroup(), &Section);
1157 return &Asm.getOrCreateSectionData(*RelaSection);
1160 static SmallVector<char, 128>
1161 getUncompressedData(MCAsmLayout &Layout,
1162 MCSectionData::FragmentListType &Fragments) {
1163 SmallVector<char, 128> UncompressedData;
1164 for (const MCFragment &F : Fragments) {
1165 const SmallVectorImpl<char> *Contents;
1166 switch (F.getKind()) {
1167 case MCFragment::FT_Data:
1168 Contents = &cast<MCDataFragment>(F).getContents();
1170 case MCFragment::FT_Dwarf:
1171 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1173 case MCFragment::FT_DwarfFrame:
1174 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1178 "Not expecting any other fragment types in a debug_* section");
1180 UncompressedData.append(Contents->begin(), Contents->end());
1182 return UncompressedData;
1185 // Include the debug info compression header:
1186 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1187 // useful for consumers to preallocate a buffer to decompress into.
1189 prependCompressionHeader(uint64_t Size,
1190 SmallVectorImpl<char> &CompressedContents) {
1191 const StringRef Magic = "ZLIB";
1192 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1194 if (sys::IsLittleEndianHost)
1195 sys::swapByteOrder(Size);
1196 CompressedContents.insert(CompressedContents.begin(),
1197 Magic.size() + sizeof(Size), 0);
1198 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1199 std::copy(reinterpret_cast<char *>(&Size),
1200 reinterpret_cast<char *>(&Size + 1),
1201 CompressedContents.begin() + Magic.size());
1205 // Return a single fragment containing the compressed contents of the whole
1206 // section. Null if the section was not compressed for any reason.
1207 static std::unique_ptr<MCDataFragment>
1208 getCompressedFragment(MCAsmLayout &Layout,
1209 MCSectionData::FragmentListType &Fragments) {
1210 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1212 // Gather the uncompressed data from all the fragments, recording the
1213 // alignment fragment, if seen, and any fixups.
1214 SmallVector<char, 128> UncompressedData =
1215 getUncompressedData(Layout, Fragments);
1217 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1219 zlib::Status Success = zlib::compress(
1220 StringRef(UncompressedData.data(), UncompressedData.size()),
1221 CompressedContents);
1222 if (Success != zlib::StatusOK)
1225 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1228 return CompressedFragment;
1231 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1234 static void UpdateSymbols(const MCAsmLayout &Layout,
1235 const std::vector<MCSymbolData *> &Symbols,
1236 MCFragment &NewFragment) {
1237 for (MCSymbolData *Sym : Symbols) {
1238 Sym->setOffset(Sym->getOffset() +
1239 Layout.getFragmentOffset(Sym->getFragment()));
1240 Sym->setFragment(&NewFragment);
1244 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1245 const DefiningSymbolMap &DefiningSymbols,
1246 const MCSectionELF &Section,
1247 MCSectionData &SD) {
1248 StringRef SectionName = Section.getSectionName();
1249 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1251 std::unique_ptr<MCDataFragment> CompressedFragment =
1252 getCompressedFragment(Layout, Fragments);
1254 // Leave the section as-is if the fragments could not be compressed.
1255 if (!CompressedFragment)
1258 // Update the fragment+offsets of any symbols referring to fragments in this
1259 // section to refer to the new fragment.
1260 auto I = DefiningSymbols.find(&SD);
1261 if (I != DefiningSymbols.end())
1262 UpdateSymbols(Layout, I->second, *CompressedFragment);
1264 // Invalidate the layout for the whole section since it will have new and
1265 // different fragments now.
1266 Layout.invalidateFragmentsFrom(&Fragments.front());
1269 // Complete the initialization of the new fragment
1270 CompressedFragment->setParent(&SD);
1271 CompressedFragment->setLayoutOrder(0);
1272 Fragments.push_back(CompressedFragment.release());
1274 // Rename from .debug_* to .zdebug_*
1275 Asm.getContext().renameELFSection(&Section,
1276 (".z" + SectionName.drop_front(1)).str());
1279 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1280 MCAsmLayout &Layout) {
1281 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1284 DefiningSymbolMap DefiningSymbols;
1286 for (MCSymbolData &SD : Asm.symbols())
1287 if (MCFragment *F = SD.getFragment())
1288 DefiningSymbols[F->getParent()].push_back(&SD);
1290 for (MCSectionData &SD : Asm) {
1291 const MCSectionELF &Section =
1292 static_cast<const MCSectionELF &>(SD.getSection());
1293 StringRef SectionName = Section.getSectionName();
1295 // Compressing debug_frame requires handling alignment fragments which is
1296 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1297 // for writing to arbitrary buffers) for little benefit.
1298 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1301 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1305 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1306 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1307 MCSectionData &RelSD = *it;
1308 const MCSectionELF &RelSection =
1309 static_cast<const MCSectionELF &>(RelSD.getSection());
1311 unsigned Type = RelSection.getType();
1312 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1315 const MCSectionELF *Section = RelSection.getAssociatedSection();
1316 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1317 RelSD.setAlignment(is64Bit() ? 8 : 4);
1319 MCDataFragment *F = new MCDataFragment(&RelSD);
1320 WriteRelocationsFragment(Asm, F, &SD);
1324 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1325 uint64_t Flags, uint64_t Address,
1326 uint64_t Offset, uint64_t Size,
1327 uint32_t Link, uint32_t Info,
1329 uint64_t EntrySize) {
1330 Write32(Name); // sh_name: index into string table
1331 Write32(Type); // sh_type
1332 WriteWord(Flags); // sh_flags
1333 WriteWord(Address); // sh_addr
1334 WriteWord(Offset); // sh_offset
1335 WriteWord(Size); // sh_size
1336 Write32(Link); // sh_link
1337 Write32(Info); // sh_info
1338 WriteWord(Alignment); // sh_addralign
1339 WriteWord(EntrySize); // sh_entsize
1342 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1343 // just to match gnu as for easier comparison. The use type is an arbitrary way
1344 // of making the sort deterministic.
1345 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1346 const ELFRelocationEntry &A = *AP;
1347 const ELFRelocationEntry &B = *BP;
1348 if (A.Offset != B.Offset)
1349 return B.Offset - A.Offset;
1350 if (B.Type != A.Type)
1351 return A.Type - B.Type;
1352 //llvm_unreachable("ELFRelocs might be unstable!");
1356 static void sortRelocs(const MCAssembler &Asm,
1357 std::vector<ELFRelocationEntry> &Relocs) {
1358 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1361 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1363 const MCSectionData *SD) {
1364 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1366 sortRelocs(Asm, Relocs);
1368 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1369 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1371 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1374 write(*F, Entry.Offset);
1375 if (TargetObjectWriter->isN64()) {
1376 write(*F, uint32_t(Index));
1378 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1379 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1380 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1381 write(*F, TargetObjectWriter->getRType(Entry.Type));
1383 struct ELF::Elf64_Rela ERE64;
1384 ERE64.setSymbolAndType(Index, Entry.Type);
1385 write(*F, ERE64.r_info);
1387 if (hasRelocationAddend())
1388 write(*F, Entry.Addend);
1390 write(*F, uint32_t(Entry.Offset));
1392 struct ELF::Elf32_Rela ERE32;
1393 ERE32.setSymbolAndType(Index, Entry.Type);
1394 write(*F, ERE32.r_info);
1396 if (hasRelocationAddend())
1397 write(*F, uint32_t(Entry.Addend));
1402 void ELFObjectWriter::CreateMetadataSections(
1403 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1404 MCContext &Ctx = Asm.getContext();
1407 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1409 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1410 const MCSectionELF *ShstrtabSection =
1411 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1412 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1413 ShstrtabSD.setAlignment(1);
1414 ShstrtabIndex = SectionIndexMap.size() + 1;
1415 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1417 const MCSectionELF *SymtabSection =
1418 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1420 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1421 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1422 SymbolTableIndex = SectionIndexMap.size() + 1;
1423 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1425 const MCSectionELF *StrtabSection;
1426 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1427 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1428 StrtabSD.setAlignment(1);
1429 StringTableIndex = SectionIndexMap.size() + 1;
1430 SectionIndexMap[StrtabSection] = StringTableIndex;
1433 F = new MCDataFragment(&SymtabSD);
1434 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1436 F = new MCDataFragment(&StrtabSD);
1437 F->getContents().append(StrTabBuilder.data().begin(),
1438 StrTabBuilder.data().end());
1440 F = new MCDataFragment(&ShstrtabSD);
1442 // Section header string table.
1443 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1444 const MCSectionELF &Section =
1445 static_cast<const MCSectionELF&>(it->getSection());
1446 ShStrTabBuilder.add(Section.getSectionName());
1448 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1449 F->getContents().append(ShStrTabBuilder.data().begin(),
1450 ShStrTabBuilder.data().end());
1453 void ELFObjectWriter::createIndexedSections(
1454 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1455 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1456 MCContext &Ctx = Asm.getContext();
1459 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1461 const MCSectionELF &Section =
1462 static_cast<const MCSectionELF&>(it->getSection());
1463 if (!(Section.getFlags() & ELF::SHF_GROUP))
1466 const MCSymbol *SignatureSymbol = Section.getGroup();
1467 Asm.getOrCreateSymbolData(*SignatureSymbol);
1468 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1470 Group = Ctx.CreateELFGroupSection();
1471 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1472 Data.setAlignment(4);
1473 MCDataFragment *F = new MCDataFragment(&Data);
1474 write(*F, uint32_t(ELF::GRP_COMDAT));
1476 GroupMap[Group] = SignatureSymbol;
1479 computeIndexMap(Asm, SectionIndexMap);
1481 // Add sections to the groups
1482 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1484 const MCSectionELF &Section =
1485 static_cast<const MCSectionELF&>(it->getSection());
1486 if (!(Section.getFlags() & ELF::SHF_GROUP))
1488 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1489 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1490 // FIXME: we could use the previous fragment
1491 MCDataFragment *F = new MCDataFragment(&Data);
1492 uint32_t Index = SectionIndexMap.lookup(&Section);
1497 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1498 const SectionIndexMapTy &SectionIndexMap,
1499 uint32_t GroupSymbolIndex,
1500 uint64_t Offset, uint64_t Size,
1502 const MCSectionELF &Section) {
1503 uint64_t sh_link = 0;
1504 uint64_t sh_info = 0;
1506 switch(Section.getType()) {
1511 case ELF::SHT_DYNAMIC:
1512 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1516 case ELF::SHT_RELA: {
1517 sh_link = SymbolTableIndex;
1518 assert(sh_link && ".symtab not found");
1519 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1520 sh_info = SectionIndexMap.lookup(InfoSection);
1524 case ELF::SHT_SYMTAB:
1525 case ELF::SHT_DYNSYM:
1526 sh_link = StringTableIndex;
1527 sh_info = LastLocalSymbolIndex;
1530 case ELF::SHT_SYMTAB_SHNDX:
1531 sh_link = SymbolTableIndex;
1534 case ELF::SHT_GROUP:
1535 sh_link = SymbolTableIndex;
1536 sh_info = GroupSymbolIndex;
1540 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1541 Section.getType() == ELF::SHT_ARM_EXIDX)
1542 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1544 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1546 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1547 Alignment, Section.getEntrySize());
1550 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1551 return SD.getOrdinal() == ~UINT32_C(0) &&
1552 !SD.getSection().isVirtualSection();
1555 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1557 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1559 const MCFragment &F = *i;
1560 assert(F.getKind() == MCFragment::FT_Data);
1561 Ret += cast<MCDataFragment>(F).getContents().size();
1566 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1567 const MCSectionData &SD) {
1568 if (IsELFMetaDataSection(SD))
1569 return DataSectionSize(SD);
1570 return Layout.getSectionFileSize(&SD);
1573 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1574 const MCSectionData &SD) {
1575 if (IsELFMetaDataSection(SD))
1576 return DataSectionSize(SD);
1577 return Layout.getSectionAddressSize(&SD);
1580 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1581 const MCAsmLayout &Layout,
1582 const MCSectionELF &Section) {
1583 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1585 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1586 WriteZeros(Padding);
1588 if (IsELFMetaDataSection(SD)) {
1589 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1591 const MCFragment &F = *i;
1592 assert(F.getKind() == MCFragment::FT_Data);
1593 WriteBytes(cast<MCDataFragment>(F).getContents());
1596 Asm.writeSectionData(&SD, Layout);
1600 void ELFObjectWriter::writeSectionHeader(
1601 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1602 const SectionIndexMapTy &SectionIndexMap,
1603 const SectionOffsetMapTy &SectionOffsetMap) {
1604 const unsigned NumSections = Asm.size() + 1;
1606 std::vector<const MCSectionELF*> Sections;
1607 Sections.resize(NumSections - 1);
1609 for (SectionIndexMapTy::const_iterator i=
1610 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1611 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1612 Sections[p.second - 1] = p.first;
1615 // Null section first.
1616 uint64_t FirstSectionSize =
1617 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1618 uint32_t FirstSectionLink =
1619 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1620 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1622 for (unsigned i = 0; i < NumSections - 1; ++i) {
1623 const MCSectionELF &Section = *Sections[i];
1624 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1625 uint32_t GroupSymbolIndex;
1626 if (Section.getType() != ELF::SHT_GROUP)
1627 GroupSymbolIndex = 0;
1629 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1630 GroupMap.lookup(&Section));
1632 uint64_t Size = GetSectionAddressSize(Layout, SD);
1634 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1635 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1640 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1641 std::vector<const MCSectionELF*> &Sections) {
1642 for (MCAssembler::iterator it = Asm.begin(),
1643 ie = Asm.end(); it != ie; ++it) {
1644 const MCSectionELF &Section =
1645 static_cast<const MCSectionELF &>(it->getSection());
1646 if (Section.getType() == ELF::SHT_GROUP)
1647 Sections.push_back(&Section);
1650 for (MCAssembler::iterator it = Asm.begin(),
1651 ie = Asm.end(); it != ie; ++it) {
1652 const MCSectionELF &Section =
1653 static_cast<const MCSectionELF &>(it->getSection());
1654 if (Section.getType() != ELF::SHT_GROUP &&
1655 Section.getType() != ELF::SHT_REL &&
1656 Section.getType() != ELF::SHT_RELA)
1657 Sections.push_back(&Section);
1660 for (MCAssembler::iterator it = Asm.begin(),
1661 ie = Asm.end(); it != ie; ++it) {
1662 const MCSectionELF &Section =
1663 static_cast<const MCSectionELF &>(it->getSection());
1664 if (Section.getType() == ELF::SHT_REL ||
1665 Section.getType() == ELF::SHT_RELA)
1666 Sections.push_back(&Section);
1670 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1671 const MCAsmLayout &Layout) {
1672 GroupMapTy GroupMap;
1673 RevGroupMapTy RevGroupMap;
1674 SectionIndexMapTy SectionIndexMap;
1676 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1677 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1678 RevGroupMap, SectionIndexMap);
1680 unsigned NumRegularSections = Asm.size();
1682 // Compute symbol table information.
1683 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1685 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1687 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1688 const_cast<MCAsmLayout&>(Layout),
1691 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1692 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1693 sizeof(ELF::Elf32_Ehdr);
1694 uint64_t FileOff = HeaderSize;
1696 std::vector<const MCSectionELF*> Sections;
1697 ComputeSectionOrder(Asm, Sections);
1698 unsigned NumSections = Sections.size();
1699 SectionOffsetMapTy SectionOffsetMap;
1700 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1701 const MCSectionELF &Section = *Sections[i];
1702 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1704 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1706 // Remember the offset into the file for this section.
1707 SectionOffsetMap[&Section] = FileOff;
1709 // Get the size of the section in the output file (including padding).
1710 FileOff += GetSectionFileSize(Layout, SD);
1713 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1715 const unsigned SectionHeaderOffset = FileOff;
1717 uint64_t SectionHeaderEntrySize = is64Bit() ?
1718 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1719 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1721 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1722 const MCSectionELF &Section = *Sections[i];
1723 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1725 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1727 // Remember the offset into the file for this section.
1728 SectionOffsetMap[&Section] = FileOff;
1730 // Get the size of the section in the output file (including padding).
1731 FileOff += GetSectionFileSize(Layout, SD);
1734 // Write out the ELF header ...
1735 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1737 // ... then the regular sections ...
1738 // + because of .shstrtab
1739 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1740 WriteDataSectionData(Asm, Layout, *Sections[i]);
1742 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1743 WriteZeros(Padding);
1745 // ... then the section header table ...
1746 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1748 // ... and then the remaining sections ...
1749 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1750 WriteDataSectionData(Asm, Layout, *Sections[i]);
1753 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1754 const MCAssembler &Asm, const MCSymbolData &DataA,
1755 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1756 bool IsPCRel) const {
1757 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1759 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1760 Asm, DataA, DataB, FB, InSet, IsPCRel);
1763 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1764 return ::isWeak(SD);
1767 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1769 bool IsLittleEndian) {
1770 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);