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 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
316 void writeSection(MCAssembler &Asm,
317 const SectionIndexMapTy &SectionIndexMap,
318 const RelMapTy &RelMap,
319 uint32_t GroupSymbolIndex,
320 uint64_t Offset, uint64_t Size, uint64_t Alignment,
321 const MCSectionELF &Section);
325 FragmentWriter::FragmentWriter(bool IsLittleEndian)
326 : IsLittleEndian(IsLittleEndian) {}
328 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
330 Val = support::endian::byte_swap<T, support::little>(Val);
332 Val = support::endian::byte_swap<T, support::big>(Val);
333 const char *Start = (const char *)&Val;
334 F.getContents().append(Start, Start + sizeof(T));
337 void SymbolTableWriter::createSymtabShndx() {
341 MCContext &Ctx = Asm.getContext();
342 const MCSectionELF *SymtabShndxSection =
343 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
344 MCSectionData *SymtabShndxSD =
345 &Asm.getOrCreateSectionData(*SymtabShndxSection);
346 SymtabShndxSD->setAlignment(4);
347 ShndxF = new MCDataFragment(SymtabShndxSD);
348 unsigned Index = SectionIndexMap.size() + 1;
349 SectionIndexMap[SymtabShndxSection] = Index;
351 for (unsigned I = 0; I < NumWritten; ++I)
352 write(*ShndxF, uint32_t(0));
355 template <typename T>
356 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
357 FWriter.write(F, Value);
360 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
362 SectionIndexMapTy &SectionIndexMap,
363 MCDataFragment *SymtabF)
364 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
365 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
368 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
369 uint64_t size, uint8_t other,
370 uint32_t shndx, bool Reserved) {
371 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
378 write(*ShndxF, shndx);
380 write(*ShndxF, uint32_t(0));
383 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
385 raw_svector_ostream OS(SymtabF->getContents());
388 write(*SymtabF, name); // st_name
389 write(*SymtabF, info); // st_info
390 write(*SymtabF, other); // st_other
391 write(*SymtabF, Index); // st_shndx
392 write(*SymtabF, value); // st_value
393 write(*SymtabF, size); // st_size
395 write(*SymtabF, name); // st_name
396 write(*SymtabF, uint32_t(value)); // st_value
397 write(*SymtabF, uint32_t(size)); // st_size
398 write(*SymtabF, info); // st_info
399 write(*SymtabF, other); // st_other
400 write(*SymtabF, Index); // st_shndx
406 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
407 const MCFixupKindInfo &FKI =
408 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
410 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
413 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
417 case MCSymbolRefExpr::VK_GOT:
418 case MCSymbolRefExpr::VK_PLT:
419 case MCSymbolRefExpr::VK_GOTPCREL:
420 case MCSymbolRefExpr::VK_GOTOFF:
421 case MCSymbolRefExpr::VK_TPOFF:
422 case MCSymbolRefExpr::VK_TLSGD:
423 case MCSymbolRefExpr::VK_GOTTPOFF:
424 case MCSymbolRefExpr::VK_INDNTPOFF:
425 case MCSymbolRefExpr::VK_NTPOFF:
426 case MCSymbolRefExpr::VK_GOTNTPOFF:
427 case MCSymbolRefExpr::VK_TLSLDM:
428 case MCSymbolRefExpr::VK_DTPOFF:
429 case MCSymbolRefExpr::VK_TLSLD:
434 ELFObjectWriter::~ELFObjectWriter()
437 // Emit the ELF header.
438 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
439 uint64_t SectionDataSize,
440 unsigned NumberOfSections) {
446 // emitWord method behaves differently for ELF32 and ELF64, writing
447 // 4 bytes in the former and 8 in the latter.
449 Write8(0x7f); // e_ident[EI_MAG0]
450 Write8('E'); // e_ident[EI_MAG1]
451 Write8('L'); // e_ident[EI_MAG2]
452 Write8('F'); // e_ident[EI_MAG3]
454 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
457 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
459 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
461 Write8(TargetObjectWriter->getOSABI());
462 Write8(0); // e_ident[EI_ABIVERSION]
464 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
466 Write16(ELF::ET_REL); // e_type
468 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
470 Write32(ELF::EV_CURRENT); // e_version
471 WriteWord(0); // e_entry, no entry point in .o file
472 WriteWord(0); // e_phoff, no program header for .o
473 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
474 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
476 // e_flags = whatever the target wants
477 Write32(Asm.getELFHeaderEFlags());
479 // e_ehsize = ELF header size
480 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
482 Write16(0); // e_phentsize = prog header entry size
483 Write16(0); // e_phnum = # prog header entries = 0
485 // e_shentsize = Section header entry size
486 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
488 // e_shnum = # of section header ents
489 if (NumberOfSections >= ELF::SHN_LORESERVE)
490 Write16(ELF::SHN_UNDEF);
492 Write16(NumberOfSections);
494 // e_shstrndx = Section # of '.shstrtab'
495 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
496 Write16(ELF::SHN_XINDEX);
498 Write16(ShstrtabIndex);
501 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
502 const MCAsmLayout &Layout) {
503 if (Data.isCommon() && Data.isExternal())
504 return Data.getCommonAlignment();
507 if (!Layout.getSymbolOffset(&Data, Res))
510 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
516 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
517 const MCAsmLayout &Layout) {
518 // The presence of symbol versions causes undefined symbols and
519 // versions declared with @@@ to be renamed.
521 for (MCSymbolData &OriginalData : Asm.symbols()) {
522 const MCSymbol &Alias = OriginalData.getSymbol();
525 if (!Alias.isVariable())
527 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
530 const MCSymbol &Symbol = Ref->getSymbol();
531 MCSymbolData &SD = Asm.getSymbolData(Symbol);
533 StringRef AliasName = Alias.getName();
534 size_t Pos = AliasName.find('@');
535 if (Pos == StringRef::npos)
538 // Aliases defined with .symvar copy the binding from the symbol they alias.
539 // This is the first place we are able to copy this information.
540 OriginalData.setExternal(SD.isExternal());
541 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
543 StringRef Rest = AliasName.substr(Pos);
544 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
547 // FIXME: produce a better error message.
548 if (Symbol.isUndefined() && Rest.startswith("@@") &&
549 !Rest.startswith("@@@"))
550 report_fatal_error("A @@ version cannot be undefined");
552 Renames.insert(std::make_pair(&Symbol, &Alias));
556 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
557 uint8_t Type = newType;
559 // Propagation rules:
560 // IFUNC > FUNC > OBJECT > NOTYPE
561 // TLS_OBJECT > OBJECT > NOTYPE
563 // dont let the new type degrade the old type
567 case ELF::STT_GNU_IFUNC:
568 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
569 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
570 Type = ELF::STT_GNU_IFUNC;
573 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
574 Type == ELF::STT_TLS)
575 Type = ELF::STT_FUNC;
577 case ELF::STT_OBJECT:
578 if (Type == ELF::STT_NOTYPE)
579 Type = ELF::STT_OBJECT;
582 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
583 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
591 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
592 const MCAsmLayout &Layout) {
593 MCSymbolData &OrigData = *MSD.SymbolData;
594 assert((!OrigData.getFragment() ||
595 (&OrigData.getFragment()->getParent()->getSection() ==
596 &OrigData.getSymbol().getSection())) &&
597 "The symbol's section doesn't match the fragment's symbol");
598 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
600 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
602 bool IsReserved = !Base || OrigData.isCommon();
604 // Binding and Type share the same byte as upper and lower nibbles
605 uint8_t Binding = MCELF::GetBinding(OrigData);
606 uint8_t Type = MCELF::GetType(OrigData);
607 MCSymbolData *BaseSD = nullptr;
609 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
610 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
612 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
614 // Other and Visibility share the same byte with Visibility using the lower
616 uint8_t Visibility = MCELF::GetVisibility(OrigData);
617 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
620 uint64_t Value = SymbolValue(OrigData, Layout);
623 const MCExpr *ESize = OrigData.getSize();
625 ESize = BaseSD->getSize();
629 if (!ESize->EvaluateAsAbsolute(Res, Layout))
630 report_fatal_error("Size expression must be absolute.");
634 // Write out the symbol table entry
635 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
636 MSD.SectionIndex, IsReserved);
639 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
641 const MCAsmLayout &Layout,
642 SectionIndexMapTy &SectionIndexMap) {
643 // The string table must be emitted first because we need the index
644 // into the string table for all the symbol names.
646 // FIXME: Make sure the start of the symbol table is aligned.
648 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
650 // The first entry is the undefined symbol entry.
651 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
653 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
654 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
655 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
658 // Write the symbol table entries.
659 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
661 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
662 ELFSymbolData &MSD = LocalSymbolData[i];
663 WriteSymbol(Writer, MSD, Layout);
666 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
667 ELFSymbolData &MSD = ExternalSymbolData[i];
668 MCSymbolData &Data = *MSD.SymbolData;
669 assert(((Data.getFlags() & ELF_STB_Global) ||
670 (Data.getFlags() & ELF_STB_Weak)) &&
671 "External symbol requires STB_GLOBAL or STB_WEAK flag");
672 WriteSymbol(Writer, MSD, Layout);
673 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
674 LastLocalSymbolIndex++;
677 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
678 ELFSymbolData &MSD = UndefinedSymbolData[i];
679 MCSymbolData &Data = *MSD.SymbolData;
680 WriteSymbol(Writer, MSD, Layout);
681 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
682 LastLocalSymbolIndex++;
686 // It is always valid to create a relocation with a symbol. It is preferable
687 // to use a relocation with a section if that is possible. Using the section
688 // allows us to omit some local symbols from the symbol table.
689 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
690 const MCSymbolRefExpr *RefA,
691 const MCSymbolData *SD,
693 unsigned Type) const {
694 // A PCRel relocation to an absolute value has no symbol (or section). We
695 // represent that with a relocation to a null section.
699 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
703 // The .odp creation emits a relocation against the symbol ".TOC." which
704 // create a R_PPC64_TOC relocation. However the relocation symbol name
705 // in final object creation should be NULL, since the symbol does not
706 // really exist, it is just the reference to TOC base for the current
707 // object file. Since the symbol is undefined, returning false results
708 // in a relocation with a null section which is the desired result.
709 case MCSymbolRefExpr::VK_PPC_TOCBASE:
712 // These VariantKind cause the relocation to refer to something other than
713 // the symbol itself, like a linker generated table. Since the address of
714 // symbol is not relevant, we cannot replace the symbol with the
715 // section and patch the difference in the addend.
716 case MCSymbolRefExpr::VK_GOT:
717 case MCSymbolRefExpr::VK_PLT:
718 case MCSymbolRefExpr::VK_GOTPCREL:
719 case MCSymbolRefExpr::VK_Mips_GOT:
720 case MCSymbolRefExpr::VK_PPC_GOT_LO:
721 case MCSymbolRefExpr::VK_PPC_GOT_HI:
722 case MCSymbolRefExpr::VK_PPC_GOT_HA:
726 // An undefined symbol is not in any section, so the relocation has to point
727 // to the symbol itself.
728 const MCSymbol &Sym = SD->getSymbol();
729 if (Sym.isUndefined())
732 unsigned Binding = MCELF::GetBinding(*SD);
735 llvm_unreachable("Invalid Binding");
739 // If the symbol is weak, it might be overridden by a symbol in another
740 // file. The relocation has to point to the symbol so that the linker
743 case ELF::STB_GLOBAL:
744 // Global ELF symbols can be preempted by the dynamic linker. The relocation
745 // has to point to the symbol for a reason analogous to the STB_WEAK case.
749 // If a relocation points to a mergeable section, we have to be careful.
750 // If the offset is zero, a relocation with the section will encode the
751 // same information. With a non-zero offset, the situation is different.
752 // For example, a relocation can point 42 bytes past the end of a string.
753 // If we change such a relocation to use the section, the linker would think
754 // that it pointed to another string and subtracting 42 at runtime will
755 // produce the wrong value.
756 auto &Sec = cast<MCSectionELF>(Sym.getSection());
757 unsigned Flags = Sec.getFlags();
758 if (Flags & ELF::SHF_MERGE) {
762 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
763 // only handle section relocations to mergeable sections if using RELA.
764 if (!hasRelocationAddend())
768 // Most TLS relocations use a got, so they need the symbol. Even those that
769 // are just an offset (@tpoff), require a symbol in gold versions before
770 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
771 // http://sourceware.org/PR16773.
772 if (Flags & ELF::SHF_TLS)
775 // If the symbol is a thumb function the final relocation must set the lowest
776 // bit. With a symbol that is done by just having the symbol have that bit
777 // set, so we would lose the bit if we relocated with the section.
778 // FIXME: We could use the section but add the bit to the relocation value.
779 if (Asm.isThumbFunc(&Sym))
782 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
787 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
788 const MCSymbol &Sym = Ref.getSymbol();
790 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
793 if (!Sym.isVariable())
796 const MCExpr *Expr = Sym.getVariableValue();
797 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
801 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
802 return &Inner->getSymbol();
806 static bool isWeak(const MCSymbolData &D) {
807 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
810 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
811 const MCAsmLayout &Layout,
812 const MCFragment *Fragment,
813 const MCFixup &Fixup, MCValue Target,
814 bool &IsPCRel, uint64_t &FixedValue) {
815 const MCSectionData *FixupSection = Fragment->getParent();
816 uint64_t C = Target.getConstant();
817 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
819 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
820 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
821 "Should not have constructed this");
823 // Let A, B and C being the components of Target and R be the location of
824 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
825 // If it is pcrel, we want to compute (A - B + C - R).
827 // In general, ELF has no relocations for -B. It can only represent (A + C)
828 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
829 // replace B to implement it: (A - R - K + C)
831 Asm.getContext().FatalError(
833 "No relocation available to represent this relative expression");
835 const MCSymbol &SymB = RefB->getSymbol();
837 if (SymB.isUndefined())
838 Asm.getContext().FatalError(
840 Twine("symbol '") + SymB.getName() +
841 "' can not be undefined in a subtraction expression");
843 assert(!SymB.isAbsolute() && "Should have been folded");
844 const MCSection &SecB = SymB.getSection();
845 if (&SecB != &FixupSection->getSection())
846 Asm.getContext().FatalError(
847 Fixup.getLoc(), "Cannot represent a difference across sections");
849 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
851 Asm.getContext().FatalError(
852 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
854 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
855 uint64_t K = SymBOffset - FixupOffset;
860 // We either rejected the fixup or folded B into C at this point.
861 const MCSymbolRefExpr *RefA = Target.getSymA();
862 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
863 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
865 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
866 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
867 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
868 C += Layout.getSymbolOffset(SymAD);
871 if (hasRelocationAddend()) {
878 // FIXME: What is this!?!?
879 MCSymbolRefExpr::VariantKind Modifier =
880 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
881 if (RelocNeedsGOT(Modifier))
884 if (!RelocateWithSymbol) {
885 const MCSection *SecA =
886 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
887 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
888 MCSymbol *SectionSymbol =
889 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
891 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
892 Relocations[FixupSection].push_back(Rec);
897 if (const MCSymbol *R = Renames.lookup(SymA))
900 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
901 WeakrefUsedInReloc.insert(WeakRef);
903 UsedInReloc.insert(SymA);
905 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
906 Relocations[FixupSection].push_back(Rec);
912 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
914 const MCSymbolData &SD = Asm.getSymbolData(*S);
915 return SD.getIndex();
918 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
919 const MCSymbolData &Data, bool Used,
921 const MCSymbol &Symbol = Data.getSymbol();
922 if (Symbol.isVariable()) {
923 const MCExpr *Expr = Symbol.getVariableValue();
924 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
925 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
936 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
939 if (Symbol.isVariable()) {
940 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
941 if (Base && Base->isUndefined())
945 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
946 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
949 if (Symbol.isTemporary())
955 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
956 if (Data.isExternal())
959 const MCSymbol &Symbol = Data.getSymbol();
960 if (Symbol.isDefined())
969 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
970 SectionIndexMapTy &SectionIndexMap,
973 for (MCAssembler::iterator it = Asm.begin(),
974 ie = Asm.end(); it != ie; ++it) {
975 const MCSectionELF &Section =
976 static_cast<const MCSectionELF &>(it->getSection());
977 if (Section.getType() != ELF::SHT_GROUP)
979 SectionIndexMap[&Section] = Index++;
982 for (MCAssembler::iterator it = Asm.begin(),
983 ie = Asm.end(); it != ie; ++it) {
984 const MCSectionData &SD = *it;
985 const MCSectionELF &Section =
986 static_cast<const MCSectionELF &>(SD.getSection());
987 if (Section.getType() == ELF::SHT_GROUP ||
988 Section.getType() == ELF::SHT_REL ||
989 Section.getType() == ELF::SHT_RELA)
991 SectionIndexMap[&Section] = Index++;
992 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
993 const MCSectionELF *RelSection =
994 static_cast<const MCSectionELF *>(&RelSD->getSection());
995 RelMap[RelSection] = &Section;
996 SectionIndexMap[RelSection] = Index++;
1002 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1003 const SectionIndexMapTy &SectionIndexMap,
1004 const RevGroupMapTy &RevGroupMap,
1005 unsigned NumRegularSections) {
1006 // FIXME: Is this the correct place to do this?
1007 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1009 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1010 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1011 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1012 Data.setExternal(true);
1013 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1016 // Add the data for the symbols.
1017 for (MCSymbolData &SD : Asm.symbols()) {
1018 const MCSymbol &Symbol = SD.getSymbol();
1020 bool Used = UsedInReloc.count(&Symbol);
1021 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1022 bool isSignature = RevGroupMap.count(&Symbol);
1024 if (!isInSymtab(Layout, SD,
1025 Used || WeakrefUsed || isSignature,
1026 Renames.count(&Symbol)))
1030 MSD.SymbolData = &SD;
1031 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1033 // Undefined symbols are global, but this is the first place we
1034 // are able to set it.
1035 bool Local = isLocal(SD, Used);
1036 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1038 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1039 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1040 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1044 MSD.SectionIndex = ELF::SHN_ABS;
1045 } else if (SD.isCommon()) {
1047 MSD.SectionIndex = ELF::SHN_COMMON;
1048 } else if (BaseSymbol->isUndefined()) {
1049 if (isSignature && !Used)
1050 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1052 MSD.SectionIndex = ELF::SHN_UNDEF;
1053 if (!Used && WeakrefUsed)
1054 MCELF::SetBinding(SD, ELF::STB_WEAK);
1056 const MCSectionELF &Section =
1057 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1058 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1059 assert(MSD.SectionIndex && "Invalid section index!");
1062 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1065 // FIXME: All name handling should be done before we get to the writer,
1066 // including dealing with GNU-style version suffixes. Fixing this isn't
1069 // We thus have to be careful to not perform the symbol version replacement
1072 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1073 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1074 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1075 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1076 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1077 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1078 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1079 // "__imp_?" or "__imp_@?".
1081 // It would have been interesting to perform the MS mangling prefix check
1082 // only when the target triple is of the form *-pc-windows-elf. But, it
1083 // seems that this information is not easily accessible from the
1085 StringRef Name = Symbol.getName();
1086 if (!Name.startswith("?") && !Name.startswith("@?") &&
1087 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1088 // This symbol isn't following the MSVC C++ name mangling convention. We
1089 // can thus safely interpret the @@@ in symbol names as specifying symbol
1091 SmallString<32> Buf;
1092 size_t Pos = Name.find("@@@");
1093 if (Pos != StringRef::npos) {
1094 Buf += Name.substr(0, Pos);
1095 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1096 Buf += Name.substr(Pos + Skip);
1101 // Sections have their own string table
1102 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1103 MSD.Name = StrTabBuilder.add(Name);
1105 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1106 UndefinedSymbolData.push_back(MSD);
1108 LocalSymbolData.push_back(MSD);
1110 ExternalSymbolData.push_back(MSD);
1113 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1114 StrTabBuilder.add(*i);
1116 StrTabBuilder.finalize(StringTableBuilder::ELF);
1118 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1119 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1121 for (ELFSymbolData &MSD : LocalSymbolData)
1122 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1124 : StrTabBuilder.getOffset(MSD.Name);
1125 for (ELFSymbolData &MSD : ExternalSymbolData)
1126 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1127 for (ELFSymbolData& MSD : UndefinedSymbolData)
1128 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1130 // Symbols are required to be in lexicographic order.
1131 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1132 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1133 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1135 // Set the symbol indices. Local symbols must come before all other
1136 // symbols with non-local bindings.
1137 unsigned Index = FileSymbolData.size() + 1;
1138 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1139 LocalSymbolData[i].SymbolData->setIndex(Index++);
1141 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1142 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1143 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1144 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1148 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1149 const MCSectionData &SD) {
1150 if (Relocations[&SD].empty())
1153 MCContext &Ctx = Asm.getContext();
1154 const MCSectionELF &Section =
1155 static_cast<const MCSectionELF &>(SD.getSection());
1157 const StringRef SectionName = Section.getSectionName();
1158 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1159 RelaSectionName += SectionName;
1162 if (hasRelocationAddend())
1163 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1165 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1168 StringRef Group = "";
1169 if (Section.getFlags() & ELF::SHF_GROUP) {
1170 Flags = ELF::SHF_GROUP;
1171 Group = Section.getGroup()->getName();
1174 const MCSectionELF *RelaSection = Ctx.getELFSection(
1175 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1176 Flags, EntrySize, Group, true);
1177 return &Asm.getOrCreateSectionData(*RelaSection);
1180 static SmallVector<char, 128>
1181 getUncompressedData(MCAsmLayout &Layout,
1182 MCSectionData::FragmentListType &Fragments) {
1183 SmallVector<char, 128> UncompressedData;
1184 for (const MCFragment &F : Fragments) {
1185 const SmallVectorImpl<char> *Contents;
1186 switch (F.getKind()) {
1187 case MCFragment::FT_Data:
1188 Contents = &cast<MCDataFragment>(F).getContents();
1190 case MCFragment::FT_Dwarf:
1191 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1193 case MCFragment::FT_DwarfFrame:
1194 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1198 "Not expecting any other fragment types in a debug_* section");
1200 UncompressedData.append(Contents->begin(), Contents->end());
1202 return UncompressedData;
1205 // Include the debug info compression header:
1206 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1207 // useful for consumers to preallocate a buffer to decompress into.
1209 prependCompressionHeader(uint64_t Size,
1210 SmallVectorImpl<char> &CompressedContents) {
1211 const StringRef Magic = "ZLIB";
1212 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1214 if (sys::IsLittleEndianHost)
1215 sys::swapByteOrder(Size);
1216 CompressedContents.insert(CompressedContents.begin(),
1217 Magic.size() + sizeof(Size), 0);
1218 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1219 std::copy(reinterpret_cast<char *>(&Size),
1220 reinterpret_cast<char *>(&Size + 1),
1221 CompressedContents.begin() + Magic.size());
1225 // Return a single fragment containing the compressed contents of the whole
1226 // section. Null if the section was not compressed for any reason.
1227 static std::unique_ptr<MCDataFragment>
1228 getCompressedFragment(MCAsmLayout &Layout,
1229 MCSectionData::FragmentListType &Fragments) {
1230 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1232 // Gather the uncompressed data from all the fragments, recording the
1233 // alignment fragment, if seen, and any fixups.
1234 SmallVector<char, 128> UncompressedData =
1235 getUncompressedData(Layout, Fragments);
1237 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1239 zlib::Status Success = zlib::compress(
1240 StringRef(UncompressedData.data(), UncompressedData.size()),
1241 CompressedContents);
1242 if (Success != zlib::StatusOK)
1245 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1248 return CompressedFragment;
1251 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1254 static void UpdateSymbols(const MCAsmLayout &Layout,
1255 const std::vector<MCSymbolData *> &Symbols,
1256 MCFragment &NewFragment) {
1257 for (MCSymbolData *Sym : Symbols) {
1258 Sym->setOffset(Sym->getOffset() +
1259 Layout.getFragmentOffset(Sym->getFragment()));
1260 Sym->setFragment(&NewFragment);
1264 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1265 const DefiningSymbolMap &DefiningSymbols,
1266 const MCSectionELF &Section,
1267 MCSectionData &SD) {
1268 StringRef SectionName = Section.getSectionName();
1269 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1271 std::unique_ptr<MCDataFragment> CompressedFragment =
1272 getCompressedFragment(Layout, Fragments);
1274 // Leave the section as-is if the fragments could not be compressed.
1275 if (!CompressedFragment)
1278 // Update the fragment+offsets of any symbols referring to fragments in this
1279 // section to refer to the new fragment.
1280 auto I = DefiningSymbols.find(&SD);
1281 if (I != DefiningSymbols.end())
1282 UpdateSymbols(Layout, I->second, *CompressedFragment);
1284 // Invalidate the layout for the whole section since it will have new and
1285 // different fragments now.
1286 Layout.invalidateFragmentsFrom(&Fragments.front());
1289 // Complete the initialization of the new fragment
1290 CompressedFragment->setParent(&SD);
1291 CompressedFragment->setLayoutOrder(0);
1292 Fragments.push_back(CompressedFragment.release());
1294 // Rename from .debug_* to .zdebug_*
1295 Asm.getContext().renameELFSection(&Section,
1296 (".z" + SectionName.drop_front(1)).str());
1299 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1300 MCAsmLayout &Layout) {
1301 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1304 DefiningSymbolMap DefiningSymbols;
1306 for (MCSymbolData &SD : Asm.symbols())
1307 if (MCFragment *F = SD.getFragment())
1308 DefiningSymbols[F->getParent()].push_back(&SD);
1310 for (MCSectionData &SD : Asm) {
1311 const MCSectionELF &Section =
1312 static_cast<const MCSectionELF &>(SD.getSection());
1313 StringRef SectionName = Section.getSectionName();
1315 // Compressing debug_frame requires handling alignment fragments which is
1316 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1317 // for writing to arbitrary buffers) for little benefit.
1318 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1321 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1325 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1326 const RelMapTy &RelMap) {
1327 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1328 MCSectionData &RelSD = *it;
1329 const MCSectionELF &RelSection =
1330 static_cast<const MCSectionELF &>(RelSD.getSection());
1332 unsigned Type = RelSection.getType();
1333 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1336 const MCSectionELF *Section = RelMap.lookup(&RelSection);
1337 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1338 RelSD.setAlignment(is64Bit() ? 8 : 4);
1340 MCDataFragment *F = new MCDataFragment(&RelSD);
1341 WriteRelocationsFragment(Asm, F, &SD);
1345 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1346 uint64_t Flags, uint64_t Address,
1347 uint64_t Offset, uint64_t Size,
1348 uint32_t Link, uint32_t Info,
1350 uint64_t EntrySize) {
1351 Write32(Name); // sh_name: index into string table
1352 Write32(Type); // sh_type
1353 WriteWord(Flags); // sh_flags
1354 WriteWord(Address); // sh_addr
1355 WriteWord(Offset); // sh_offset
1356 WriteWord(Size); // sh_size
1357 Write32(Link); // sh_link
1358 Write32(Info); // sh_info
1359 WriteWord(Alignment); // sh_addralign
1360 WriteWord(EntrySize); // sh_entsize
1363 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1364 // just to match gnu as for easier comparison. The use type is an arbitrary way
1365 // of making the sort deterministic.
1366 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1367 const ELFRelocationEntry &A = *AP;
1368 const ELFRelocationEntry &B = *BP;
1369 if (A.Offset != B.Offset)
1370 return B.Offset - A.Offset;
1371 if (B.Type != A.Type)
1372 return A.Type - B.Type;
1373 //llvm_unreachable("ELFRelocs might be unstable!");
1377 static void sortRelocs(const MCAssembler &Asm,
1378 std::vector<ELFRelocationEntry> &Relocs) {
1379 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1382 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1384 const MCSectionData *SD) {
1385 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1387 sortRelocs(Asm, Relocs);
1389 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1390 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1392 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1395 write(*F, Entry.Offset);
1396 if (TargetObjectWriter->isN64()) {
1397 write(*F, uint32_t(Index));
1399 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1400 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1401 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1402 write(*F, TargetObjectWriter->getRType(Entry.Type));
1404 struct ELF::Elf64_Rela ERE64;
1405 ERE64.setSymbolAndType(Index, Entry.Type);
1406 write(*F, ERE64.r_info);
1408 if (hasRelocationAddend())
1409 write(*F, Entry.Addend);
1411 write(*F, uint32_t(Entry.Offset));
1413 struct ELF::Elf32_Rela ERE32;
1414 ERE32.setSymbolAndType(Index, Entry.Type);
1415 write(*F, ERE32.r_info);
1417 if (hasRelocationAddend())
1418 write(*F, uint32_t(Entry.Addend));
1423 void ELFObjectWriter::CreateMetadataSections(
1424 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1425 MCContext &Ctx = Asm.getContext();
1428 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1430 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1431 const MCSectionELF *ShstrtabSection =
1432 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1433 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1434 ShstrtabSD.setAlignment(1);
1435 ShstrtabIndex = SectionIndexMap.size() + 1;
1436 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1438 const MCSectionELF *SymtabSection =
1439 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1441 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1442 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1443 SymbolTableIndex = SectionIndexMap.size() + 1;
1444 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1446 const MCSectionELF *StrtabSection;
1447 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1448 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1449 StrtabSD.setAlignment(1);
1450 StringTableIndex = SectionIndexMap.size() + 1;
1451 SectionIndexMap[StrtabSection] = StringTableIndex;
1454 F = new MCDataFragment(&SymtabSD);
1455 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1457 F = new MCDataFragment(&StrtabSD);
1458 F->getContents().append(StrTabBuilder.data().begin(),
1459 StrTabBuilder.data().end());
1461 F = new MCDataFragment(&ShstrtabSD);
1463 // Section header string table.
1464 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1465 const MCSectionELF &Section =
1466 static_cast<const MCSectionELF&>(it->getSection());
1467 ShStrTabBuilder.add(Section.getSectionName());
1469 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1470 F->getContents().append(ShStrTabBuilder.data().begin(),
1471 ShStrTabBuilder.data().end());
1474 void ELFObjectWriter::createIndexedSections(MCAssembler &Asm,
1475 MCAsmLayout &Layout,
1476 GroupMapTy &GroupMap,
1477 RevGroupMapTy &RevGroupMap,
1478 SectionIndexMapTy &SectionIndexMap,
1480 MCContext &Ctx = Asm.getContext();
1483 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1485 const MCSectionELF &Section =
1486 static_cast<const MCSectionELF&>(it->getSection());
1487 if (!(Section.getFlags() & ELF::SHF_GROUP))
1490 const MCSymbol *SignatureSymbol = Section.getGroup();
1491 Asm.getOrCreateSymbolData(*SignatureSymbol);
1492 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1494 Group = Ctx.CreateELFGroupSection();
1495 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1496 Data.setAlignment(4);
1497 MCDataFragment *F = new MCDataFragment(&Data);
1498 write(*F, uint32_t(ELF::GRP_COMDAT));
1500 GroupMap[Group] = SignatureSymbol;
1503 computeIndexMap(Asm, SectionIndexMap, RelMap);
1505 // Add sections to the groups
1506 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1508 const MCSectionELF &Section =
1509 static_cast<const MCSectionELF&>(it->getSection());
1510 if (!(Section.getFlags() & ELF::SHF_GROUP))
1512 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1513 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1514 // FIXME: we could use the previous fragment
1515 MCDataFragment *F = new MCDataFragment(&Data);
1516 uint32_t Index = SectionIndexMap.lookup(&Section);
1521 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1522 const SectionIndexMapTy &SectionIndexMap,
1523 const RelMapTy &RelMap,
1524 uint32_t GroupSymbolIndex,
1525 uint64_t Offset, uint64_t Size,
1527 const MCSectionELF &Section) {
1528 uint64_t sh_link = 0;
1529 uint64_t sh_info = 0;
1531 switch(Section.getType()) {
1532 case ELF::SHT_DYNAMIC:
1533 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1538 case ELF::SHT_RELA: {
1539 sh_link = SymbolTableIndex;
1540 assert(sh_link && ".symtab not found");
1541 const MCSectionELF *InfoSection = RelMap.find(&Section)->second;
1542 sh_info = SectionIndexMap.lookup(InfoSection);
1546 case ELF::SHT_SYMTAB:
1547 case ELF::SHT_DYNSYM:
1548 sh_link = StringTableIndex;
1549 sh_info = LastLocalSymbolIndex;
1552 case ELF::SHT_SYMTAB_SHNDX:
1553 sh_link = SymbolTableIndex;
1556 case ELF::SHT_PROGBITS:
1557 case ELF::SHT_STRTAB:
1558 case ELF::SHT_NOBITS:
1561 case ELF::SHT_ARM_ATTRIBUTES:
1562 case ELF::SHT_INIT_ARRAY:
1563 case ELF::SHT_FINI_ARRAY:
1564 case ELF::SHT_PREINIT_ARRAY:
1565 case ELF::SHT_X86_64_UNWIND:
1566 case ELF::SHT_MIPS_REGINFO:
1567 case ELF::SHT_MIPS_OPTIONS:
1568 case ELF::SHT_MIPS_ABIFLAGS:
1572 case ELF::SHT_GROUP:
1573 sh_link = SymbolTableIndex;
1574 sh_info = GroupSymbolIndex;
1578 llvm_unreachable("FIXME: sh_type value not supported!");
1581 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1582 Section.getType() == ELF::SHT_ARM_EXIDX) {
1583 StringRef SecName(Section.getSectionName());
1584 if (SecName == ".ARM.exidx") {
1585 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1586 ".text", ELF::SHT_PROGBITS, ELF::SHF_EXECINSTR | ELF::SHF_ALLOC));
1587 } else if (SecName.startswith(".ARM.exidx")) {
1588 StringRef GroupName =
1589 Section.getGroup() ? Section.getGroup()->getName() : "";
1590 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1591 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1592 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, 0, GroupName));
1596 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1598 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1599 Alignment, Section.getEntrySize());
1602 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1603 return SD.getOrdinal() == ~UINT32_C(0) &&
1604 !SD.getSection().isVirtualSection();
1607 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1609 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1611 const MCFragment &F = *i;
1612 assert(F.getKind() == MCFragment::FT_Data);
1613 Ret += cast<MCDataFragment>(F).getContents().size();
1618 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1619 const MCSectionData &SD) {
1620 if (IsELFMetaDataSection(SD))
1621 return DataSectionSize(SD);
1622 return Layout.getSectionFileSize(&SD);
1625 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1626 const MCSectionData &SD) {
1627 if (IsELFMetaDataSection(SD))
1628 return DataSectionSize(SD);
1629 return Layout.getSectionAddressSize(&SD);
1632 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1633 const MCAsmLayout &Layout,
1634 const MCSectionELF &Section) {
1635 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1637 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1638 WriteZeros(Padding);
1640 if (IsELFMetaDataSection(SD)) {
1641 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1643 const MCFragment &F = *i;
1644 assert(F.getKind() == MCFragment::FT_Data);
1645 WriteBytes(cast<MCDataFragment>(F).getContents());
1648 Asm.writeSectionData(&SD, Layout);
1652 void ELFObjectWriter::writeSectionHeader(
1653 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1654 const SectionIndexMapTy &SectionIndexMap, const RelMapTy &RelMap,
1655 const SectionOffsetMapTy &SectionOffsetMap) {
1656 const unsigned NumSections = Asm.size() + 1;
1658 std::vector<const MCSectionELF*> Sections;
1659 Sections.resize(NumSections - 1);
1661 for (SectionIndexMapTy::const_iterator i=
1662 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1663 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1664 Sections[p.second - 1] = p.first;
1667 // Null section first.
1668 uint64_t FirstSectionSize =
1669 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1670 uint32_t FirstSectionLink =
1671 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1672 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1674 for (unsigned i = 0; i < NumSections - 1; ++i) {
1675 const MCSectionELF &Section = *Sections[i];
1676 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1677 uint32_t GroupSymbolIndex;
1678 if (Section.getType() != ELF::SHT_GROUP)
1679 GroupSymbolIndex = 0;
1681 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1682 GroupMap.lookup(&Section));
1684 uint64_t Size = GetSectionAddressSize(Layout, SD);
1686 writeSection(Asm, SectionIndexMap, RelMap, GroupSymbolIndex,
1687 SectionOffsetMap.lookup(&Section), Size,
1688 SD.getAlignment(), Section);
1692 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1693 std::vector<const MCSectionELF*> &Sections) {
1694 for (MCAssembler::iterator it = Asm.begin(),
1695 ie = Asm.end(); it != ie; ++it) {
1696 const MCSectionELF &Section =
1697 static_cast<const MCSectionELF &>(it->getSection());
1698 if (Section.getType() == ELF::SHT_GROUP)
1699 Sections.push_back(&Section);
1702 for (MCAssembler::iterator it = Asm.begin(),
1703 ie = Asm.end(); it != ie; ++it) {
1704 const MCSectionELF &Section =
1705 static_cast<const MCSectionELF &>(it->getSection());
1706 if (Section.getType() != ELF::SHT_GROUP &&
1707 Section.getType() != ELF::SHT_REL &&
1708 Section.getType() != ELF::SHT_RELA)
1709 Sections.push_back(&Section);
1712 for (MCAssembler::iterator it = Asm.begin(),
1713 ie = Asm.end(); it != ie; ++it) {
1714 const MCSectionELF &Section =
1715 static_cast<const MCSectionELF &>(it->getSection());
1716 if (Section.getType() == ELF::SHT_REL ||
1717 Section.getType() == ELF::SHT_RELA)
1718 Sections.push_back(&Section);
1722 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1723 const MCAsmLayout &Layout) {
1724 GroupMapTy GroupMap;
1725 RevGroupMapTy RevGroupMap;
1726 SectionIndexMapTy SectionIndexMap;
1728 unsigned NumUserSections = Asm.size();
1730 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1732 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1733 const unsigned NumUserAndRelocSections = Asm.size();
1734 createIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1735 RevGroupMap, SectionIndexMap, RelMap);
1736 const unsigned AllSections = Asm.size();
1737 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1739 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1741 // Compute symbol table information.
1742 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1743 NumRegularSections);
1745 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1747 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1748 const_cast<MCAsmLayout&>(Layout),
1751 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1752 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1753 sizeof(ELF::Elf32_Ehdr);
1754 uint64_t FileOff = HeaderSize;
1756 std::vector<const MCSectionELF*> Sections;
1757 ComputeSectionOrder(Asm, Sections);
1758 unsigned NumSections = Sections.size();
1759 SectionOffsetMapTy SectionOffsetMap;
1760 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1761 const MCSectionELF &Section = *Sections[i];
1762 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1764 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1766 // Remember the offset into the file for this section.
1767 SectionOffsetMap[&Section] = FileOff;
1769 // Get the size of the section in the output file (including padding).
1770 FileOff += GetSectionFileSize(Layout, SD);
1773 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1775 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1777 uint64_t SectionHeaderEntrySize = is64Bit() ?
1778 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1779 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1781 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1782 const MCSectionELF &Section = *Sections[i];
1783 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1785 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1787 // Remember the offset into the file for this section.
1788 SectionOffsetMap[&Section] = FileOff;
1790 // Get the size of the section in the output file (including padding).
1791 FileOff += GetSectionFileSize(Layout, SD);
1794 // Write out the ELF header ...
1795 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1797 // ... then the regular sections ...
1798 // + because of .shstrtab
1799 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1800 WriteDataSectionData(Asm, Layout, *Sections[i]);
1802 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1803 WriteZeros(Padding);
1805 // ... then the section header table ...
1806 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, RelMap,
1809 // ... and then the remaining sections ...
1810 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1811 WriteDataSectionData(Asm, Layout, *Sections[i]);
1815 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1816 const MCSymbolData &DataA,
1817 const MCFragment &FB,
1819 bool IsPCRel) const {
1822 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1823 Asm, DataA, FB,InSet, IsPCRel);
1826 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1828 bool IsLittleEndian) {
1829 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);