1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
41 #define DEBUG_TYPE "reloc-info"
44 class FragmentWriter {
48 FragmentWriter(bool IsLittleEndian);
49 template <typename T> void write(MCDataFragment &F, T Val);
52 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
54 class SymbolTableWriter {
56 FragmentWriter &FWriter;
58 SectionIndexMapTy &SectionIndexMap;
60 // The symbol .symtab fragment we are writting to.
61 MCDataFragment *SymtabF;
63 // .symtab_shndx fragment we are writting to.
64 MCDataFragment *ShndxF;
66 // The numbel of symbols written so far.
69 void createSymtabShndx();
71 template <typename T> void write(MCDataFragment &F, T Value);
74 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75 SectionIndexMapTy &SectionIndexMap,
76 MCDataFragment *SymtabF);
78 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79 uint8_t other, uint32_t shndx, bool Reserved);
82 struct ELFRelocationEntry {
83 uint64_t Offset; // Where is the relocation.
84 const MCSymbol *Symbol; // The symbol to relocate with.
85 unsigned Type; // The type of the relocation.
86 uint64_t Addend; // The addend to use.
88 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
90 : Offset(Offset), Symbol(Symbol), Type(Type), Addend(Addend) {}
93 class ELFObjectWriter : public MCObjectWriter {
94 FragmentWriter FWriter;
98 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
99 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
100 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
101 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
102 bool Used, bool Renamed);
103 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
104 static bool IsELFMetaDataSection(const MCSectionData &SD);
105 static uint64_t DataSectionSize(const MCSectionData &SD);
106 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
107 const MCSectionData &SD);
108 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
109 const MCSectionData &SD);
111 void WriteDataSectionData(MCAssembler &Asm,
112 const MCAsmLayout &Layout,
113 const MCSectionELF &Section);
115 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
116 return Kind == X86::reloc_riprel_4byte ||
117 Kind == X86::reloc_riprel_4byte_movq_load;
120 /// ELFSymbolData - Helper struct for containing some precomputed
121 /// information on symbols.
122 struct ELFSymbolData {
123 MCSymbolData *SymbolData;
124 uint64_t StringIndex;
125 uint32_t SectionIndex;
128 // Support lexicographic sorting.
129 bool operator<(const ELFSymbolData &RHS) const {
130 unsigned LHSType = MCELF::GetType(*SymbolData);
131 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
132 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
134 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
136 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
137 return SectionIndex < RHS.SectionIndex;
138 return Name < RHS.Name;
142 /// The target specific ELF writer instance.
143 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
149 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
151 StringTableBuilder ShStrTabBuilder;
154 /// @name Symbol Table Data
157 StringTableBuilder StrTabBuilder;
158 std::vector<uint64_t> FileSymbolData;
159 std::vector<ELFSymbolData> LocalSymbolData;
160 std::vector<ELFSymbolData> ExternalSymbolData;
161 std::vector<ELFSymbolData> UndefinedSymbolData;
167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
171 // This holds the .symtab section index.
172 unsigned SymbolTableIndex;
174 unsigned ShstrtabIndex;
177 // TargetObjectWriter wrappers.
178 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
179 bool hasRelocationAddend() const {
180 return TargetObjectWriter->hasRelocationAddend();
182 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
183 bool IsPCRel) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
188 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
190 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
191 TargetObjectWriter(MOTW), NeedsGOT(false) {}
193 void reset() override {
195 WeakrefUsedInReloc.clear();
198 ShStrTabBuilder.clear();
199 StrTabBuilder.clear();
200 FileSymbolData.clear();
201 LocalSymbolData.clear();
202 ExternalSymbolData.clear();
203 UndefinedSymbolData.clear();
204 MCObjectWriter::reset();
207 virtual ~ELFObjectWriter();
209 void WriteWord(uint64_t W) {
216 template <typename T> void write(MCDataFragment &F, T Value) {
217 FWriter.write(F, Value);
220 void WriteHeader(const MCAssembler &Asm,
221 uint64_t SectionDataSize,
222 unsigned NumberOfSections);
224 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
225 const MCAsmLayout &Layout);
227 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
228 const MCAsmLayout &Layout,
229 SectionIndexMapTy &SectionIndexMap);
231 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
232 const MCSymbolRefExpr *RefA,
233 const MCSymbolData *SD, uint64_t C,
234 unsigned Type) const;
236 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
237 const MCFragment *Fragment, const MCFixup &Fixup,
238 MCValue Target, bool &IsPCRel,
239 uint64_t &FixedValue) override;
241 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
244 // Map from a group section to the signature symbol
245 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
246 // Map from a signature symbol to the group section
247 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
248 // Map from a section to the section with the relocations
249 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
250 // Map from a section to its offset
251 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
253 /// Compute the symbol table data
255 /// \param Asm - The assembler.
256 /// \param SectionIndexMap - Maps a section to its index.
257 /// \param RevGroupMap - Maps a signature symbol to the group section.
258 /// \param NumRegularSections - Number of non-relocation sections.
259 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
260 const SectionIndexMapTy &SectionIndexMap,
261 const RevGroupMapTy &RevGroupMap,
262 unsigned NumRegularSections);
264 void computeIndexMap(MCAssembler &Asm,
265 SectionIndexMapTy &SectionIndexMap,
268 MCSectionData *createRelocationSection(MCAssembler &Asm,
269 const MCSectionData &SD);
271 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
273 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
274 const RelMapTy &RelMap);
276 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
277 SectionIndexMapTy &SectionIndexMap);
279 // Create the sections that show up in the symbol table. Currently
280 // those are the .note.GNU-stack section and the group sections.
281 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
282 GroupMapTy &GroupMap,
283 RevGroupMapTy &RevGroupMap,
284 SectionIndexMapTy &SectionIndexMap,
287 void ExecutePostLayoutBinding(MCAssembler &Asm,
288 const MCAsmLayout &Layout) override;
290 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
291 const MCAsmLayout &Layout,
292 const SectionIndexMapTy &SectionIndexMap,
293 const RelMapTy &RelMap,
294 const SectionOffsetMapTy &SectionOffsetMap);
296 void ComputeSectionOrder(MCAssembler &Asm,
297 std::vector<const MCSectionELF*> &Sections);
299 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
300 uint64_t Address, uint64_t Offset,
301 uint64_t Size, uint32_t Link, uint32_t Info,
302 uint64_t Alignment, uint64_t EntrySize);
304 void WriteRelocationsFragment(const MCAssembler &Asm,
306 const MCSectionData *SD);
309 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
310 const MCSymbolData &DataA,
311 const MCFragment &FB,
313 bool IsPCRel) const override;
315 bool isWeak(const MCSymbolData &SD) const override;
317 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
318 void writeSection(MCAssembler &Asm,
319 const SectionIndexMapTy &SectionIndexMap,
320 const RelMapTy &RelMap,
321 uint32_t GroupSymbolIndex,
322 uint64_t Offset, uint64_t Size, uint64_t Alignment,
323 const MCSectionELF &Section);
327 FragmentWriter::FragmentWriter(bool IsLittleEndian)
328 : IsLittleEndian(IsLittleEndian) {}
330 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
332 Val = support::endian::byte_swap<T, support::little>(Val);
334 Val = support::endian::byte_swap<T, support::big>(Val);
335 const char *Start = (const char *)&Val;
336 F.getContents().append(Start, Start + sizeof(T));
339 void SymbolTableWriter::createSymtabShndx() {
343 MCContext &Ctx = Asm.getContext();
344 const MCSectionELF *SymtabShndxSection =
345 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
346 MCSectionData *SymtabShndxSD =
347 &Asm.getOrCreateSectionData(*SymtabShndxSection);
348 SymtabShndxSD->setAlignment(4);
349 ShndxF = new MCDataFragment(SymtabShndxSD);
350 unsigned Index = SectionIndexMap.size() + 1;
351 SectionIndexMap[SymtabShndxSection] = Index;
353 for (unsigned I = 0; I < NumWritten; ++I)
354 write(*ShndxF, uint32_t(0));
357 template <typename T>
358 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
359 FWriter.write(F, Value);
362 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
364 SectionIndexMapTy &SectionIndexMap,
365 MCDataFragment *SymtabF)
366 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
367 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
370 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
371 uint64_t size, uint8_t other,
372 uint32_t shndx, bool Reserved) {
373 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
380 write(*ShndxF, shndx);
382 write(*ShndxF, uint32_t(0));
385 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
387 raw_svector_ostream OS(SymtabF->getContents());
390 write(*SymtabF, name); // st_name
391 write(*SymtabF, info); // st_info
392 write(*SymtabF, other); // st_other
393 write(*SymtabF, Index); // st_shndx
394 write(*SymtabF, value); // st_value
395 write(*SymtabF, size); // st_size
397 write(*SymtabF, name); // st_name
398 write(*SymtabF, uint32_t(value)); // st_value
399 write(*SymtabF, uint32_t(size)); // st_size
400 write(*SymtabF, info); // st_info
401 write(*SymtabF, other); // st_other
402 write(*SymtabF, Index); // st_shndx
408 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
409 const MCFixupKindInfo &FKI =
410 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
412 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
415 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
419 case MCSymbolRefExpr::VK_GOT:
420 case MCSymbolRefExpr::VK_PLT:
421 case MCSymbolRefExpr::VK_GOTPCREL:
422 case MCSymbolRefExpr::VK_GOTOFF:
423 case MCSymbolRefExpr::VK_TPOFF:
424 case MCSymbolRefExpr::VK_TLSGD:
425 case MCSymbolRefExpr::VK_GOTTPOFF:
426 case MCSymbolRefExpr::VK_INDNTPOFF:
427 case MCSymbolRefExpr::VK_NTPOFF:
428 case MCSymbolRefExpr::VK_GOTNTPOFF:
429 case MCSymbolRefExpr::VK_TLSLDM:
430 case MCSymbolRefExpr::VK_DTPOFF:
431 case MCSymbolRefExpr::VK_TLSLD:
436 ELFObjectWriter::~ELFObjectWriter()
439 // Emit the ELF header.
440 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
441 uint64_t SectionDataSize,
442 unsigned NumberOfSections) {
448 // emitWord method behaves differently for ELF32 and ELF64, writing
449 // 4 bytes in the former and 8 in the latter.
451 Write8(0x7f); // e_ident[EI_MAG0]
452 Write8('E'); // e_ident[EI_MAG1]
453 Write8('L'); // e_ident[EI_MAG2]
454 Write8('F'); // e_ident[EI_MAG3]
456 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
459 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
461 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
463 Write8(TargetObjectWriter->getOSABI());
464 Write8(0); // e_ident[EI_ABIVERSION]
466 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
468 Write16(ELF::ET_REL); // e_type
470 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
472 Write32(ELF::EV_CURRENT); // e_version
473 WriteWord(0); // e_entry, no entry point in .o file
474 WriteWord(0); // e_phoff, no program header for .o
475 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
476 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
478 // e_flags = whatever the target wants
479 Write32(Asm.getELFHeaderEFlags());
481 // e_ehsize = ELF header size
482 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
484 Write16(0); // e_phentsize = prog header entry size
485 Write16(0); // e_phnum = # prog header entries = 0
487 // e_shentsize = Section header entry size
488 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
490 // e_shnum = # of section header ents
491 if (NumberOfSections >= ELF::SHN_LORESERVE)
492 Write16(ELF::SHN_UNDEF);
494 Write16(NumberOfSections);
496 // e_shstrndx = Section # of '.shstrtab'
497 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
498 Write16(ELF::SHN_XINDEX);
500 Write16(ShstrtabIndex);
503 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
504 const MCAsmLayout &Layout) {
505 if (Data.isCommon() && Data.isExternal())
506 return Data.getCommonAlignment();
509 if (!Layout.getSymbolOffset(&Data, Res))
512 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
518 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
519 const MCAsmLayout &Layout) {
520 // The presence of symbol versions causes undefined symbols and
521 // versions declared with @@@ to be renamed.
523 for (MCSymbolData &OriginalData : Asm.symbols()) {
524 const MCSymbol &Alias = OriginalData.getSymbol();
527 if (!Alias.isVariable())
529 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
532 const MCSymbol &Symbol = Ref->getSymbol();
533 MCSymbolData &SD = Asm.getSymbolData(Symbol);
535 StringRef AliasName = Alias.getName();
536 size_t Pos = AliasName.find('@');
537 if (Pos == StringRef::npos)
540 // Aliases defined with .symvar copy the binding from the symbol they alias.
541 // This is the first place we are able to copy this information.
542 OriginalData.setExternal(SD.isExternal());
543 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
545 StringRef Rest = AliasName.substr(Pos);
546 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
549 // FIXME: produce a better error message.
550 if (Symbol.isUndefined() && Rest.startswith("@@") &&
551 !Rest.startswith("@@@"))
552 report_fatal_error("A @@ version cannot be undefined");
554 Renames.insert(std::make_pair(&Symbol, &Alias));
558 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
559 uint8_t Type = newType;
561 // Propagation rules:
562 // IFUNC > FUNC > OBJECT > NOTYPE
563 // TLS_OBJECT > OBJECT > NOTYPE
565 // dont let the new type degrade the old type
569 case ELF::STT_GNU_IFUNC:
570 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
571 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
572 Type = ELF::STT_GNU_IFUNC;
575 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
576 Type == ELF::STT_TLS)
577 Type = ELF::STT_FUNC;
579 case ELF::STT_OBJECT:
580 if (Type == ELF::STT_NOTYPE)
581 Type = ELF::STT_OBJECT;
584 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
585 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
593 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
594 const MCAsmLayout &Layout) {
595 MCSymbolData &OrigData = *MSD.SymbolData;
596 assert((!OrigData.getFragment() ||
597 (&OrigData.getFragment()->getParent()->getSection() ==
598 &OrigData.getSymbol().getSection())) &&
599 "The symbol's section doesn't match the fragment's symbol");
600 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
602 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
604 bool IsReserved = !Base || OrigData.isCommon();
606 // Binding and Type share the same byte as upper and lower nibbles
607 uint8_t Binding = MCELF::GetBinding(OrigData);
608 uint8_t Type = MCELF::GetType(OrigData);
609 MCSymbolData *BaseSD = nullptr;
611 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
612 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
614 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
616 // Other and Visibility share the same byte with Visibility using the lower
618 uint8_t Visibility = MCELF::GetVisibility(OrigData);
619 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
622 uint64_t Value = SymbolValue(OrigData, Layout);
625 const MCExpr *ESize = OrigData.getSize();
627 ESize = BaseSD->getSize();
631 if (!ESize->EvaluateAsAbsolute(Res, Layout))
632 report_fatal_error("Size expression must be absolute.");
636 // Write out the symbol table entry
637 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
638 MSD.SectionIndex, IsReserved);
641 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
643 const MCAsmLayout &Layout,
644 SectionIndexMapTy &SectionIndexMap) {
645 // The string table must be emitted first because we need the index
646 // into the string table for all the symbol names.
648 // FIXME: Make sure the start of the symbol table is aligned.
650 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
652 // The first entry is the undefined symbol entry.
653 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
655 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
656 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
657 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
660 // Write the symbol table entries.
661 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
663 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
664 ELFSymbolData &MSD = LocalSymbolData[i];
665 WriteSymbol(Writer, MSD, Layout);
668 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
669 ELFSymbolData &MSD = ExternalSymbolData[i];
670 MCSymbolData &Data = *MSD.SymbolData;
671 assert(((Data.getFlags() & ELF_STB_Global) ||
672 (Data.getFlags() & ELF_STB_Weak)) &&
673 "External symbol requires STB_GLOBAL or STB_WEAK flag");
674 WriteSymbol(Writer, MSD, Layout);
675 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
676 LastLocalSymbolIndex++;
679 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
680 ELFSymbolData &MSD = UndefinedSymbolData[i];
681 MCSymbolData &Data = *MSD.SymbolData;
682 WriteSymbol(Writer, MSD, Layout);
683 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
684 LastLocalSymbolIndex++;
688 // It is always valid to create a relocation with a symbol. It is preferable
689 // to use a relocation with a section if that is possible. Using the section
690 // allows us to omit some local symbols from the symbol table.
691 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
692 const MCSymbolRefExpr *RefA,
693 const MCSymbolData *SD,
695 unsigned Type) const {
696 // A PCRel relocation to an absolute value has no symbol (or section). We
697 // represent that with a relocation to a null section.
701 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
705 // The .odp creation emits a relocation against the symbol ".TOC." which
706 // create a R_PPC64_TOC relocation. However the relocation symbol name
707 // in final object creation should be NULL, since the symbol does not
708 // really exist, it is just the reference to TOC base for the current
709 // object file. Since the symbol is undefined, returning false results
710 // in a relocation with a null section which is the desired result.
711 case MCSymbolRefExpr::VK_PPC_TOCBASE:
714 // These VariantKind cause the relocation to refer to something other than
715 // the symbol itself, like a linker generated table. Since the address of
716 // symbol is not relevant, we cannot replace the symbol with the
717 // section and patch the difference in the addend.
718 case MCSymbolRefExpr::VK_GOT:
719 case MCSymbolRefExpr::VK_PLT:
720 case MCSymbolRefExpr::VK_GOTPCREL:
721 case MCSymbolRefExpr::VK_Mips_GOT:
722 case MCSymbolRefExpr::VK_PPC_GOT_LO:
723 case MCSymbolRefExpr::VK_PPC_GOT_HI:
724 case MCSymbolRefExpr::VK_PPC_GOT_HA:
728 // An undefined symbol is not in any section, so the relocation has to point
729 // to the symbol itself.
730 const MCSymbol &Sym = SD->getSymbol();
731 if (Sym.isUndefined())
734 unsigned Binding = MCELF::GetBinding(*SD);
737 llvm_unreachable("Invalid Binding");
741 // If the symbol is weak, it might be overridden by a symbol in another
742 // file. The relocation has to point to the symbol so that the linker
745 case ELF::STB_GLOBAL:
746 // Global ELF symbols can be preempted by the dynamic linker. The relocation
747 // has to point to the symbol for a reason analogous to the STB_WEAK case.
751 // If a relocation points to a mergeable section, we have to be careful.
752 // If the offset is zero, a relocation with the section will encode the
753 // same information. With a non-zero offset, the situation is different.
754 // For example, a relocation can point 42 bytes past the end of a string.
755 // If we change such a relocation to use the section, the linker would think
756 // that it pointed to another string and subtracting 42 at runtime will
757 // produce the wrong value.
758 auto &Sec = cast<MCSectionELF>(Sym.getSection());
759 unsigned Flags = Sec.getFlags();
760 if (Flags & ELF::SHF_MERGE) {
764 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
765 // only handle section relocations to mergeable sections if using RELA.
766 if (!hasRelocationAddend())
770 // Most TLS relocations use a got, so they need the symbol. Even those that
771 // are just an offset (@tpoff), require a symbol in gold versions before
772 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
773 // http://sourceware.org/PR16773.
774 if (Flags & ELF::SHF_TLS)
777 // If the symbol is a thumb function the final relocation must set the lowest
778 // bit. With a symbol that is done by just having the symbol have that bit
779 // set, so we would lose the bit if we relocated with the section.
780 // FIXME: We could use the section but add the bit to the relocation value.
781 if (Asm.isThumbFunc(&Sym))
784 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
789 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
790 const MCSymbol &Sym = Ref.getSymbol();
792 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
795 if (!Sym.isVariable())
798 const MCExpr *Expr = Sym.getVariableValue();
799 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
803 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
804 return &Inner->getSymbol();
808 static bool isWeak(const MCSymbolData &D) {
809 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
812 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
813 const MCAsmLayout &Layout,
814 const MCFragment *Fragment,
815 const MCFixup &Fixup, MCValue Target,
816 bool &IsPCRel, uint64_t &FixedValue) {
817 const MCSectionData *FixupSection = Fragment->getParent();
818 uint64_t C = Target.getConstant();
819 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
821 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
822 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
823 "Should not have constructed this");
825 // Let A, B and C being the components of Target and R be the location of
826 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
827 // If it is pcrel, we want to compute (A - B + C - R).
829 // In general, ELF has no relocations for -B. It can only represent (A + C)
830 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
831 // replace B to implement it: (A - R - K + C)
833 Asm.getContext().FatalError(
835 "No relocation available to represent this relative expression");
837 const MCSymbol &SymB = RefB->getSymbol();
839 if (SymB.isUndefined())
840 Asm.getContext().FatalError(
842 Twine("symbol '") + SymB.getName() +
843 "' can not be undefined in a subtraction expression");
845 assert(!SymB.isAbsolute() && "Should have been folded");
846 const MCSection &SecB = SymB.getSection();
847 if (&SecB != &FixupSection->getSection())
848 Asm.getContext().FatalError(
849 Fixup.getLoc(), "Cannot represent a difference across sections");
851 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
853 Asm.getContext().FatalError(
854 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
856 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
857 uint64_t K = SymBOffset - FixupOffset;
862 // We either rejected the fixup or folded B into C at this point.
863 const MCSymbolRefExpr *RefA = Target.getSymA();
864 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
865 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
867 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
868 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
869 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
870 C += Layout.getSymbolOffset(SymAD);
873 if (hasRelocationAddend()) {
880 // FIXME: What is this!?!?
881 MCSymbolRefExpr::VariantKind Modifier =
882 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
883 if (RelocNeedsGOT(Modifier))
886 if (!RelocateWithSymbol) {
887 const MCSection *SecA =
888 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
889 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
890 MCSymbol *SectionSymbol =
891 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
893 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
894 Relocations[FixupSection].push_back(Rec);
899 if (const MCSymbol *R = Renames.lookup(SymA))
902 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
903 WeakrefUsedInReloc.insert(WeakRef);
905 UsedInReloc.insert(SymA);
907 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
908 Relocations[FixupSection].push_back(Rec);
914 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
916 const MCSymbolData &SD = Asm.getSymbolData(*S);
917 return SD.getIndex();
920 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
921 const MCSymbolData &Data, bool Used,
923 const MCSymbol &Symbol = Data.getSymbol();
924 if (Symbol.isVariable()) {
925 const MCExpr *Expr = Symbol.getVariableValue();
926 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
927 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
938 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
941 if (Symbol.isVariable()) {
942 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
943 if (Base && Base->isUndefined())
947 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
948 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
951 if (Symbol.isTemporary())
957 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
958 if (Data.isExternal())
961 const MCSymbol &Symbol = Data.getSymbol();
962 if (Symbol.isDefined())
971 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
972 SectionIndexMapTy &SectionIndexMap,
975 for (MCAssembler::iterator it = Asm.begin(),
976 ie = Asm.end(); it != ie; ++it) {
977 const MCSectionELF &Section =
978 static_cast<const MCSectionELF &>(it->getSection());
979 if (Section.getType() != ELF::SHT_GROUP)
981 SectionIndexMap[&Section] = Index++;
984 for (MCAssembler::iterator it = Asm.begin(),
985 ie = Asm.end(); it != ie; ++it) {
986 const MCSectionData &SD = *it;
987 const MCSectionELF &Section =
988 static_cast<const MCSectionELF &>(SD.getSection());
989 if (Section.getType() == ELF::SHT_GROUP ||
990 Section.getType() == ELF::SHT_REL ||
991 Section.getType() == ELF::SHT_RELA)
993 SectionIndexMap[&Section] = Index++;
994 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
995 const MCSectionELF *RelSection =
996 static_cast<const MCSectionELF *>(&RelSD->getSection());
997 RelMap[RelSection] = &Section;
998 SectionIndexMap[RelSection] = Index++;
1004 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1005 const SectionIndexMapTy &SectionIndexMap,
1006 const RevGroupMapTy &RevGroupMap,
1007 unsigned NumRegularSections) {
1008 // FIXME: Is this the correct place to do this?
1009 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1011 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1012 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1013 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1014 Data.setExternal(true);
1015 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1018 // Add the data for the symbols.
1019 for (MCSymbolData &SD : Asm.symbols()) {
1020 const MCSymbol &Symbol = SD.getSymbol();
1022 bool Used = UsedInReloc.count(&Symbol);
1023 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1024 bool isSignature = RevGroupMap.count(&Symbol);
1026 if (!isInSymtab(Layout, SD,
1027 Used || WeakrefUsed || isSignature,
1028 Renames.count(&Symbol)))
1032 MSD.SymbolData = &SD;
1033 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1035 // Undefined symbols are global, but this is the first place we
1036 // are able to set it.
1037 bool Local = isLocal(SD, Used);
1038 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1040 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1041 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1042 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1046 MSD.SectionIndex = ELF::SHN_ABS;
1047 } else if (SD.isCommon()) {
1049 MSD.SectionIndex = ELF::SHN_COMMON;
1050 } else if (BaseSymbol->isUndefined()) {
1051 if (isSignature && !Used)
1052 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1054 MSD.SectionIndex = ELF::SHN_UNDEF;
1055 if (!Used && WeakrefUsed)
1056 MCELF::SetBinding(SD, ELF::STB_WEAK);
1058 const MCSectionELF &Section =
1059 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1060 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1061 assert(MSD.SectionIndex && "Invalid section index!");
1064 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1067 // FIXME: All name handling should be done before we get to the writer,
1068 // including dealing with GNU-style version suffixes. Fixing this isn't
1071 // We thus have to be careful to not perform the symbol version replacement
1074 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1075 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1076 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1077 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1078 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1079 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1080 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1081 // "__imp_?" or "__imp_@?".
1083 // It would have been interesting to perform the MS mangling prefix check
1084 // only when the target triple is of the form *-pc-windows-elf. But, it
1085 // seems that this information is not easily accessible from the
1087 StringRef Name = Symbol.getName();
1088 if (!Name.startswith("?") && !Name.startswith("@?") &&
1089 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1090 // This symbol isn't following the MSVC C++ name mangling convention. We
1091 // can thus safely interpret the @@@ in symbol names as specifying symbol
1093 SmallString<32> Buf;
1094 size_t Pos = Name.find("@@@");
1095 if (Pos != StringRef::npos) {
1096 Buf += Name.substr(0, Pos);
1097 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1098 Buf += Name.substr(Pos + Skip);
1103 // Sections have their own string table
1104 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1105 MSD.Name = StrTabBuilder.add(Name);
1107 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1108 UndefinedSymbolData.push_back(MSD);
1110 LocalSymbolData.push_back(MSD);
1112 ExternalSymbolData.push_back(MSD);
1115 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1116 StrTabBuilder.add(*i);
1118 StrTabBuilder.finalize(StringTableBuilder::ELF);
1120 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1121 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1123 for (ELFSymbolData &MSD : LocalSymbolData)
1124 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1126 : StrTabBuilder.getOffset(MSD.Name);
1127 for (ELFSymbolData &MSD : ExternalSymbolData)
1128 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1129 for (ELFSymbolData& MSD : UndefinedSymbolData)
1130 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1132 // Symbols are required to be in lexicographic order.
1133 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1134 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1135 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1137 // Set the symbol indices. Local symbols must come before all other
1138 // symbols with non-local bindings.
1139 unsigned Index = FileSymbolData.size() + 1;
1140 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1141 LocalSymbolData[i].SymbolData->setIndex(Index++);
1143 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1144 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1145 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1146 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1150 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1151 const MCSectionData &SD) {
1152 if (Relocations[&SD].empty())
1155 MCContext &Ctx = Asm.getContext();
1156 const MCSectionELF &Section =
1157 static_cast<const MCSectionELF &>(SD.getSection());
1159 const StringRef SectionName = Section.getSectionName();
1160 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1161 RelaSectionName += SectionName;
1164 if (hasRelocationAddend())
1165 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1167 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1170 if (Section.getFlags() & ELF::SHF_GROUP)
1171 Flags = ELF::SHF_GROUP;
1173 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1174 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1175 Flags, EntrySize, Section.getGroup());
1176 return &Asm.getOrCreateSectionData(*RelaSection);
1179 static SmallVector<char, 128>
1180 getUncompressedData(MCAsmLayout &Layout,
1181 MCSectionData::FragmentListType &Fragments) {
1182 SmallVector<char, 128> UncompressedData;
1183 for (const MCFragment &F : Fragments) {
1184 const SmallVectorImpl<char> *Contents;
1185 switch (F.getKind()) {
1186 case MCFragment::FT_Data:
1187 Contents = &cast<MCDataFragment>(F).getContents();
1189 case MCFragment::FT_Dwarf:
1190 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1192 case MCFragment::FT_DwarfFrame:
1193 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1197 "Not expecting any other fragment types in a debug_* section");
1199 UncompressedData.append(Contents->begin(), Contents->end());
1201 return UncompressedData;
1204 // Include the debug info compression header:
1205 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1206 // useful for consumers to preallocate a buffer to decompress into.
1208 prependCompressionHeader(uint64_t Size,
1209 SmallVectorImpl<char> &CompressedContents) {
1210 const StringRef Magic = "ZLIB";
1211 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1213 if (sys::IsLittleEndianHost)
1214 sys::swapByteOrder(Size);
1215 CompressedContents.insert(CompressedContents.begin(),
1216 Magic.size() + sizeof(Size), 0);
1217 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1218 std::copy(reinterpret_cast<char *>(&Size),
1219 reinterpret_cast<char *>(&Size + 1),
1220 CompressedContents.begin() + Magic.size());
1224 // Return a single fragment containing the compressed contents of the whole
1225 // section. Null if the section was not compressed for any reason.
1226 static std::unique_ptr<MCDataFragment>
1227 getCompressedFragment(MCAsmLayout &Layout,
1228 MCSectionData::FragmentListType &Fragments) {
1229 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1231 // Gather the uncompressed data from all the fragments, recording the
1232 // alignment fragment, if seen, and any fixups.
1233 SmallVector<char, 128> UncompressedData =
1234 getUncompressedData(Layout, Fragments);
1236 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1238 zlib::Status Success = zlib::compress(
1239 StringRef(UncompressedData.data(), UncompressedData.size()),
1240 CompressedContents);
1241 if (Success != zlib::StatusOK)
1244 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1247 return CompressedFragment;
1250 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1253 static void UpdateSymbols(const MCAsmLayout &Layout,
1254 const std::vector<MCSymbolData *> &Symbols,
1255 MCFragment &NewFragment) {
1256 for (MCSymbolData *Sym : Symbols) {
1257 Sym->setOffset(Sym->getOffset() +
1258 Layout.getFragmentOffset(Sym->getFragment()));
1259 Sym->setFragment(&NewFragment);
1263 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1264 const DefiningSymbolMap &DefiningSymbols,
1265 const MCSectionELF &Section,
1266 MCSectionData &SD) {
1267 StringRef SectionName = Section.getSectionName();
1268 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1270 std::unique_ptr<MCDataFragment> CompressedFragment =
1271 getCompressedFragment(Layout, Fragments);
1273 // Leave the section as-is if the fragments could not be compressed.
1274 if (!CompressedFragment)
1277 // Update the fragment+offsets of any symbols referring to fragments in this
1278 // section to refer to the new fragment.
1279 auto I = DefiningSymbols.find(&SD);
1280 if (I != DefiningSymbols.end())
1281 UpdateSymbols(Layout, I->second, *CompressedFragment);
1283 // Invalidate the layout for the whole section since it will have new and
1284 // different fragments now.
1285 Layout.invalidateFragmentsFrom(&Fragments.front());
1288 // Complete the initialization of the new fragment
1289 CompressedFragment->setParent(&SD);
1290 CompressedFragment->setLayoutOrder(0);
1291 Fragments.push_back(CompressedFragment.release());
1293 // Rename from .debug_* to .zdebug_*
1294 Asm.getContext().renameELFSection(&Section,
1295 (".z" + SectionName.drop_front(1)).str());
1298 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1299 MCAsmLayout &Layout) {
1300 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1303 DefiningSymbolMap DefiningSymbols;
1305 for (MCSymbolData &SD : Asm.symbols())
1306 if (MCFragment *F = SD.getFragment())
1307 DefiningSymbols[F->getParent()].push_back(&SD);
1309 for (MCSectionData &SD : Asm) {
1310 const MCSectionELF &Section =
1311 static_cast<const MCSectionELF &>(SD.getSection());
1312 StringRef SectionName = Section.getSectionName();
1314 // Compressing debug_frame requires handling alignment fragments which is
1315 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1316 // for writing to arbitrary buffers) for little benefit.
1317 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1320 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1324 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1325 const RelMapTy &RelMap) {
1326 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1327 MCSectionData &RelSD = *it;
1328 const MCSectionELF &RelSection =
1329 static_cast<const MCSectionELF &>(RelSD.getSection());
1331 unsigned Type = RelSection.getType();
1332 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1335 const MCSectionELF *Section = RelMap.lookup(&RelSection);
1336 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1337 RelSD.setAlignment(is64Bit() ? 8 : 4);
1339 MCDataFragment *F = new MCDataFragment(&RelSD);
1340 WriteRelocationsFragment(Asm, F, &SD);
1344 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1345 uint64_t Flags, uint64_t Address,
1346 uint64_t Offset, uint64_t Size,
1347 uint32_t Link, uint32_t Info,
1349 uint64_t EntrySize) {
1350 Write32(Name); // sh_name: index into string table
1351 Write32(Type); // sh_type
1352 WriteWord(Flags); // sh_flags
1353 WriteWord(Address); // sh_addr
1354 WriteWord(Offset); // sh_offset
1355 WriteWord(Size); // sh_size
1356 Write32(Link); // sh_link
1357 Write32(Info); // sh_info
1358 WriteWord(Alignment); // sh_addralign
1359 WriteWord(EntrySize); // sh_entsize
1362 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1363 // just to match gnu as for easier comparison. The use type is an arbitrary way
1364 // of making the sort deterministic.
1365 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1366 const ELFRelocationEntry &A = *AP;
1367 const ELFRelocationEntry &B = *BP;
1368 if (A.Offset != B.Offset)
1369 return B.Offset - A.Offset;
1370 if (B.Type != A.Type)
1371 return A.Type - B.Type;
1372 //llvm_unreachable("ELFRelocs might be unstable!");
1376 static void sortRelocs(const MCAssembler &Asm,
1377 std::vector<ELFRelocationEntry> &Relocs) {
1378 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1381 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1383 const MCSectionData *SD) {
1384 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1386 sortRelocs(Asm, Relocs);
1388 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1389 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1391 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1394 write(*F, Entry.Offset);
1395 if (TargetObjectWriter->isN64()) {
1396 write(*F, uint32_t(Index));
1398 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1399 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1400 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1401 write(*F, TargetObjectWriter->getRType(Entry.Type));
1403 struct ELF::Elf64_Rela ERE64;
1404 ERE64.setSymbolAndType(Index, Entry.Type);
1405 write(*F, ERE64.r_info);
1407 if (hasRelocationAddend())
1408 write(*F, Entry.Addend);
1410 write(*F, uint32_t(Entry.Offset));
1412 struct ELF::Elf32_Rela ERE32;
1413 ERE32.setSymbolAndType(Index, Entry.Type);
1414 write(*F, ERE32.r_info);
1416 if (hasRelocationAddend())
1417 write(*F, uint32_t(Entry.Addend));
1422 void ELFObjectWriter::CreateMetadataSections(
1423 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1424 MCContext &Ctx = Asm.getContext();
1427 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1429 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1430 const MCSectionELF *ShstrtabSection =
1431 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1432 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1433 ShstrtabSD.setAlignment(1);
1434 ShstrtabIndex = SectionIndexMap.size() + 1;
1435 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1437 const MCSectionELF *SymtabSection =
1438 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1440 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1441 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1442 SymbolTableIndex = SectionIndexMap.size() + 1;
1443 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1445 const MCSectionELF *StrtabSection;
1446 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1447 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1448 StrtabSD.setAlignment(1);
1449 StringTableIndex = SectionIndexMap.size() + 1;
1450 SectionIndexMap[StrtabSection] = StringTableIndex;
1453 F = new MCDataFragment(&SymtabSD);
1454 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1456 F = new MCDataFragment(&StrtabSD);
1457 F->getContents().append(StrTabBuilder.data().begin(),
1458 StrTabBuilder.data().end());
1460 F = new MCDataFragment(&ShstrtabSD);
1462 // Section header string table.
1463 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1464 const MCSectionELF &Section =
1465 static_cast<const MCSectionELF&>(it->getSection());
1466 ShStrTabBuilder.add(Section.getSectionName());
1468 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1469 F->getContents().append(ShStrTabBuilder.data().begin(),
1470 ShStrTabBuilder.data().end());
1473 void ELFObjectWriter::createIndexedSections(MCAssembler &Asm,
1474 MCAsmLayout &Layout,
1475 GroupMapTy &GroupMap,
1476 RevGroupMapTy &RevGroupMap,
1477 SectionIndexMapTy &SectionIndexMap,
1479 MCContext &Ctx = Asm.getContext();
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))
1489 const MCSymbol *SignatureSymbol = Section.getGroup();
1490 Asm.getOrCreateSymbolData(*SignatureSymbol);
1491 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1493 Group = Ctx.CreateELFGroupSection();
1494 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1495 Data.setAlignment(4);
1496 MCDataFragment *F = new MCDataFragment(&Data);
1497 write(*F, uint32_t(ELF::GRP_COMDAT));
1499 GroupMap[Group] = SignatureSymbol;
1502 computeIndexMap(Asm, SectionIndexMap, RelMap);
1504 // Add sections to the groups
1505 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1507 const MCSectionELF &Section =
1508 static_cast<const MCSectionELF&>(it->getSection());
1509 if (!(Section.getFlags() & ELF::SHF_GROUP))
1511 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1512 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1513 // FIXME: we could use the previous fragment
1514 MCDataFragment *F = new MCDataFragment(&Data);
1515 uint32_t Index = SectionIndexMap.lookup(&Section);
1520 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1521 const SectionIndexMapTy &SectionIndexMap,
1522 const RelMapTy &RelMap,
1523 uint32_t GroupSymbolIndex,
1524 uint64_t Offset, uint64_t Size,
1526 const MCSectionELF &Section) {
1527 uint64_t sh_link = 0;
1528 uint64_t sh_info = 0;
1530 switch(Section.getType()) {
1531 case ELF::SHT_DYNAMIC:
1532 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1537 case ELF::SHT_RELA: {
1538 sh_link = SymbolTableIndex;
1539 assert(sh_link && ".symtab not found");
1540 const MCSectionELF *InfoSection = RelMap.find(&Section)->second;
1541 sh_info = SectionIndexMap.lookup(InfoSection);
1545 case ELF::SHT_SYMTAB:
1546 case ELF::SHT_DYNSYM:
1547 sh_link = StringTableIndex;
1548 sh_info = LastLocalSymbolIndex;
1551 case ELF::SHT_SYMTAB_SHNDX:
1552 sh_link = SymbolTableIndex;
1555 case ELF::SHT_PROGBITS:
1556 case ELF::SHT_STRTAB:
1557 case ELF::SHT_NOBITS:
1560 case ELF::SHT_ARM_ATTRIBUTES:
1561 case ELF::SHT_INIT_ARRAY:
1562 case ELF::SHT_FINI_ARRAY:
1563 case ELF::SHT_PREINIT_ARRAY:
1564 case ELF::SHT_X86_64_UNWIND:
1565 case ELF::SHT_MIPS_REGINFO:
1566 case ELF::SHT_MIPS_OPTIONS:
1567 case ELF::SHT_MIPS_ABIFLAGS:
1571 case ELF::SHT_GROUP:
1572 sh_link = SymbolTableIndex;
1573 sh_info = GroupSymbolIndex;
1577 llvm_unreachable("FIXME: sh_type value not supported!");
1580 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1581 Section.getType() == ELF::SHT_ARM_EXIDX) {
1582 StringRef SecName(Section.getSectionName());
1583 if (SecName == ".ARM.exidx") {
1584 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1585 ".text", ELF::SHT_PROGBITS, ELF::SHF_EXECINSTR | ELF::SHF_ALLOC));
1586 } else if (SecName.startswith(".ARM.exidx")) {
1587 StringRef GroupName =
1588 Section.getGroup() ? Section.getGroup()->getName() : "";
1589 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1590 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1591 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, 0, GroupName));
1595 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1597 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1598 Alignment, Section.getEntrySize());
1601 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1602 return SD.getOrdinal() == ~UINT32_C(0) &&
1603 !SD.getSection().isVirtualSection();
1606 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1608 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1610 const MCFragment &F = *i;
1611 assert(F.getKind() == MCFragment::FT_Data);
1612 Ret += cast<MCDataFragment>(F).getContents().size();
1617 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1618 const MCSectionData &SD) {
1619 if (IsELFMetaDataSection(SD))
1620 return DataSectionSize(SD);
1621 return Layout.getSectionFileSize(&SD);
1624 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1625 const MCSectionData &SD) {
1626 if (IsELFMetaDataSection(SD))
1627 return DataSectionSize(SD);
1628 return Layout.getSectionAddressSize(&SD);
1631 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1632 const MCAsmLayout &Layout,
1633 const MCSectionELF &Section) {
1634 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1636 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1637 WriteZeros(Padding);
1639 if (IsELFMetaDataSection(SD)) {
1640 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1642 const MCFragment &F = *i;
1643 assert(F.getKind() == MCFragment::FT_Data);
1644 WriteBytes(cast<MCDataFragment>(F).getContents());
1647 Asm.writeSectionData(&SD, Layout);
1651 void ELFObjectWriter::writeSectionHeader(
1652 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1653 const SectionIndexMapTy &SectionIndexMap, const RelMapTy &RelMap,
1654 const SectionOffsetMapTy &SectionOffsetMap) {
1655 const unsigned NumSections = Asm.size() + 1;
1657 std::vector<const MCSectionELF*> Sections;
1658 Sections.resize(NumSections - 1);
1660 for (SectionIndexMapTy::const_iterator i=
1661 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1662 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1663 Sections[p.second - 1] = p.first;
1666 // Null section first.
1667 uint64_t FirstSectionSize =
1668 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1669 uint32_t FirstSectionLink =
1670 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1671 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1673 for (unsigned i = 0; i < NumSections - 1; ++i) {
1674 const MCSectionELF &Section = *Sections[i];
1675 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1676 uint32_t GroupSymbolIndex;
1677 if (Section.getType() != ELF::SHT_GROUP)
1678 GroupSymbolIndex = 0;
1680 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1681 GroupMap.lookup(&Section));
1683 uint64_t Size = GetSectionAddressSize(Layout, SD);
1685 writeSection(Asm, SectionIndexMap, RelMap, GroupSymbolIndex,
1686 SectionOffsetMap.lookup(&Section), Size,
1687 SD.getAlignment(), Section);
1691 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1692 std::vector<const MCSectionELF*> &Sections) {
1693 for (MCAssembler::iterator it = Asm.begin(),
1694 ie = Asm.end(); it != ie; ++it) {
1695 const MCSectionELF &Section =
1696 static_cast<const MCSectionELF &>(it->getSection());
1697 if (Section.getType() == ELF::SHT_GROUP)
1698 Sections.push_back(&Section);
1701 for (MCAssembler::iterator it = Asm.begin(),
1702 ie = Asm.end(); it != ie; ++it) {
1703 const MCSectionELF &Section =
1704 static_cast<const MCSectionELF &>(it->getSection());
1705 if (Section.getType() != ELF::SHT_GROUP &&
1706 Section.getType() != ELF::SHT_REL &&
1707 Section.getType() != ELF::SHT_RELA)
1708 Sections.push_back(&Section);
1711 for (MCAssembler::iterator it = Asm.begin(),
1712 ie = Asm.end(); it != ie; ++it) {
1713 const MCSectionELF &Section =
1714 static_cast<const MCSectionELF &>(it->getSection());
1715 if (Section.getType() == ELF::SHT_REL ||
1716 Section.getType() == ELF::SHT_RELA)
1717 Sections.push_back(&Section);
1721 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1722 const MCAsmLayout &Layout) {
1723 GroupMapTy GroupMap;
1724 RevGroupMapTy RevGroupMap;
1725 SectionIndexMapTy SectionIndexMap;
1727 unsigned NumUserSections = Asm.size();
1729 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1731 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1732 const unsigned NumUserAndRelocSections = Asm.size();
1733 createIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1734 RevGroupMap, SectionIndexMap, RelMap);
1735 const unsigned AllSections = Asm.size();
1736 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1738 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1740 // Compute symbol table information.
1741 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1742 NumRegularSections);
1744 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1746 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1747 const_cast<MCAsmLayout&>(Layout),
1750 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1751 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1752 sizeof(ELF::Elf32_Ehdr);
1753 uint64_t FileOff = HeaderSize;
1755 std::vector<const MCSectionELF*> Sections;
1756 ComputeSectionOrder(Asm, Sections);
1757 unsigned NumSections = Sections.size();
1758 SectionOffsetMapTy SectionOffsetMap;
1759 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1760 const MCSectionELF &Section = *Sections[i];
1761 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1763 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1765 // Remember the offset into the file for this section.
1766 SectionOffsetMap[&Section] = FileOff;
1768 // Get the size of the section in the output file (including padding).
1769 FileOff += GetSectionFileSize(Layout, SD);
1772 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1774 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1776 uint64_t SectionHeaderEntrySize = is64Bit() ?
1777 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1778 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1780 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1781 const MCSectionELF &Section = *Sections[i];
1782 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1784 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1786 // Remember the offset into the file for this section.
1787 SectionOffsetMap[&Section] = FileOff;
1789 // Get the size of the section in the output file (including padding).
1790 FileOff += GetSectionFileSize(Layout, SD);
1793 // Write out the ELF header ...
1794 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1796 // ... then the regular sections ...
1797 // + because of .shstrtab
1798 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1799 WriteDataSectionData(Asm, Layout, *Sections[i]);
1801 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1802 WriteZeros(Padding);
1804 // ... then the section header table ...
1805 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, RelMap,
1808 // ... and then the remaining sections ...
1809 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1810 WriteDataSectionData(Asm, Layout, *Sections[i]);
1814 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1815 const MCSymbolData &DataA,
1816 const MCFragment &FB,
1818 bool IsPCRel) const {
1819 if (::isWeak(DataA))
1821 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1822 Asm, DataA, FB,InSet, IsPCRel);
1825 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1826 return ::isWeak(SD);
1829 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1831 bool IsLittleEndian) {
1832 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);