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 StringRef Group = "";
1171 if (Section.getFlags() & ELF::SHF_GROUP) {
1172 Flags = ELF::SHF_GROUP;
1173 Group = Section.getGroup()->getName();
1176 const MCSectionELF *RelaSection = Ctx.getELFSection(
1177 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1178 Flags, EntrySize, Group, true);
1179 return &Asm.getOrCreateSectionData(*RelaSection);
1182 static SmallVector<char, 128>
1183 getUncompressedData(MCAsmLayout &Layout,
1184 MCSectionData::FragmentListType &Fragments) {
1185 SmallVector<char, 128> UncompressedData;
1186 for (const MCFragment &F : Fragments) {
1187 const SmallVectorImpl<char> *Contents;
1188 switch (F.getKind()) {
1189 case MCFragment::FT_Data:
1190 Contents = &cast<MCDataFragment>(F).getContents();
1192 case MCFragment::FT_Dwarf:
1193 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1195 case MCFragment::FT_DwarfFrame:
1196 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1200 "Not expecting any other fragment types in a debug_* section");
1202 UncompressedData.append(Contents->begin(), Contents->end());
1204 return UncompressedData;
1207 // Include the debug info compression header:
1208 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1209 // useful for consumers to preallocate a buffer to decompress into.
1211 prependCompressionHeader(uint64_t Size,
1212 SmallVectorImpl<char> &CompressedContents) {
1213 const StringRef Magic = "ZLIB";
1214 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1216 if (sys::IsLittleEndianHost)
1217 sys::swapByteOrder(Size);
1218 CompressedContents.insert(CompressedContents.begin(),
1219 Magic.size() + sizeof(Size), 0);
1220 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1221 std::copy(reinterpret_cast<char *>(&Size),
1222 reinterpret_cast<char *>(&Size + 1),
1223 CompressedContents.begin() + Magic.size());
1227 // Return a single fragment containing the compressed contents of the whole
1228 // section. Null if the section was not compressed for any reason.
1229 static std::unique_ptr<MCDataFragment>
1230 getCompressedFragment(MCAsmLayout &Layout,
1231 MCSectionData::FragmentListType &Fragments) {
1232 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1234 // Gather the uncompressed data from all the fragments, recording the
1235 // alignment fragment, if seen, and any fixups.
1236 SmallVector<char, 128> UncompressedData =
1237 getUncompressedData(Layout, Fragments);
1239 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1241 zlib::Status Success = zlib::compress(
1242 StringRef(UncompressedData.data(), UncompressedData.size()),
1243 CompressedContents);
1244 if (Success != zlib::StatusOK)
1247 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1250 return CompressedFragment;
1253 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1256 static void UpdateSymbols(const MCAsmLayout &Layout,
1257 const std::vector<MCSymbolData *> &Symbols,
1258 MCFragment &NewFragment) {
1259 for (MCSymbolData *Sym : Symbols) {
1260 Sym->setOffset(Sym->getOffset() +
1261 Layout.getFragmentOffset(Sym->getFragment()));
1262 Sym->setFragment(&NewFragment);
1266 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1267 const DefiningSymbolMap &DefiningSymbols,
1268 const MCSectionELF &Section,
1269 MCSectionData &SD) {
1270 StringRef SectionName = Section.getSectionName();
1271 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1273 std::unique_ptr<MCDataFragment> CompressedFragment =
1274 getCompressedFragment(Layout, Fragments);
1276 // Leave the section as-is if the fragments could not be compressed.
1277 if (!CompressedFragment)
1280 // Update the fragment+offsets of any symbols referring to fragments in this
1281 // section to refer to the new fragment.
1282 auto I = DefiningSymbols.find(&SD);
1283 if (I != DefiningSymbols.end())
1284 UpdateSymbols(Layout, I->second, *CompressedFragment);
1286 // Invalidate the layout for the whole section since it will have new and
1287 // different fragments now.
1288 Layout.invalidateFragmentsFrom(&Fragments.front());
1291 // Complete the initialization of the new fragment
1292 CompressedFragment->setParent(&SD);
1293 CompressedFragment->setLayoutOrder(0);
1294 Fragments.push_back(CompressedFragment.release());
1296 // Rename from .debug_* to .zdebug_*
1297 Asm.getContext().renameELFSection(&Section,
1298 (".z" + SectionName.drop_front(1)).str());
1301 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1302 MCAsmLayout &Layout) {
1303 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1306 DefiningSymbolMap DefiningSymbols;
1308 for (MCSymbolData &SD : Asm.symbols())
1309 if (MCFragment *F = SD.getFragment())
1310 DefiningSymbols[F->getParent()].push_back(&SD);
1312 for (MCSectionData &SD : Asm) {
1313 const MCSectionELF &Section =
1314 static_cast<const MCSectionELF &>(SD.getSection());
1315 StringRef SectionName = Section.getSectionName();
1317 // Compressing debug_frame requires handling alignment fragments which is
1318 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1319 // for writing to arbitrary buffers) for little benefit.
1320 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1323 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1327 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1328 const RelMapTy &RelMap) {
1329 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1330 MCSectionData &RelSD = *it;
1331 const MCSectionELF &RelSection =
1332 static_cast<const MCSectionELF &>(RelSD.getSection());
1334 unsigned Type = RelSection.getType();
1335 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1338 const MCSectionELF *Section = RelMap.lookup(&RelSection);
1339 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1340 RelSD.setAlignment(is64Bit() ? 8 : 4);
1342 MCDataFragment *F = new MCDataFragment(&RelSD);
1343 WriteRelocationsFragment(Asm, F, &SD);
1347 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1348 uint64_t Flags, uint64_t Address,
1349 uint64_t Offset, uint64_t Size,
1350 uint32_t Link, uint32_t Info,
1352 uint64_t EntrySize) {
1353 Write32(Name); // sh_name: index into string table
1354 Write32(Type); // sh_type
1355 WriteWord(Flags); // sh_flags
1356 WriteWord(Address); // sh_addr
1357 WriteWord(Offset); // sh_offset
1358 WriteWord(Size); // sh_size
1359 Write32(Link); // sh_link
1360 Write32(Info); // sh_info
1361 WriteWord(Alignment); // sh_addralign
1362 WriteWord(EntrySize); // sh_entsize
1365 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1366 // just to match gnu as for easier comparison. The use type is an arbitrary way
1367 // of making the sort deterministic.
1368 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1369 const ELFRelocationEntry &A = *AP;
1370 const ELFRelocationEntry &B = *BP;
1371 if (A.Offset != B.Offset)
1372 return B.Offset - A.Offset;
1373 if (B.Type != A.Type)
1374 return A.Type - B.Type;
1375 //llvm_unreachable("ELFRelocs might be unstable!");
1379 static void sortRelocs(const MCAssembler &Asm,
1380 std::vector<ELFRelocationEntry> &Relocs) {
1381 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1384 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1386 const MCSectionData *SD) {
1387 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1389 sortRelocs(Asm, Relocs);
1391 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1392 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1394 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1397 write(*F, Entry.Offset);
1398 if (TargetObjectWriter->isN64()) {
1399 write(*F, uint32_t(Index));
1401 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1402 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1403 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1404 write(*F, TargetObjectWriter->getRType(Entry.Type));
1406 struct ELF::Elf64_Rela ERE64;
1407 ERE64.setSymbolAndType(Index, Entry.Type);
1408 write(*F, ERE64.r_info);
1410 if (hasRelocationAddend())
1411 write(*F, Entry.Addend);
1413 write(*F, uint32_t(Entry.Offset));
1415 struct ELF::Elf32_Rela ERE32;
1416 ERE32.setSymbolAndType(Index, Entry.Type);
1417 write(*F, ERE32.r_info);
1419 if (hasRelocationAddend())
1420 write(*F, uint32_t(Entry.Addend));
1425 void ELFObjectWriter::CreateMetadataSections(
1426 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1427 MCContext &Ctx = Asm.getContext();
1430 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1432 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1433 const MCSectionELF *ShstrtabSection =
1434 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1435 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1436 ShstrtabSD.setAlignment(1);
1437 ShstrtabIndex = SectionIndexMap.size() + 1;
1438 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1440 const MCSectionELF *SymtabSection =
1441 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1443 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1444 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1445 SymbolTableIndex = SectionIndexMap.size() + 1;
1446 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1448 const MCSectionELF *StrtabSection;
1449 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1450 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1451 StrtabSD.setAlignment(1);
1452 StringTableIndex = SectionIndexMap.size() + 1;
1453 SectionIndexMap[StrtabSection] = StringTableIndex;
1456 F = new MCDataFragment(&SymtabSD);
1457 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1459 F = new MCDataFragment(&StrtabSD);
1460 F->getContents().append(StrTabBuilder.data().begin(),
1461 StrTabBuilder.data().end());
1463 F = new MCDataFragment(&ShstrtabSD);
1465 // Section header string table.
1466 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1467 const MCSectionELF &Section =
1468 static_cast<const MCSectionELF&>(it->getSection());
1469 ShStrTabBuilder.add(Section.getSectionName());
1471 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1472 F->getContents().append(ShStrTabBuilder.data().begin(),
1473 ShStrTabBuilder.data().end());
1476 void ELFObjectWriter::createIndexedSections(MCAssembler &Asm,
1477 MCAsmLayout &Layout,
1478 GroupMapTy &GroupMap,
1479 RevGroupMapTy &RevGroupMap,
1480 SectionIndexMapTy &SectionIndexMap,
1482 MCContext &Ctx = Asm.getContext();
1485 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1487 const MCSectionELF &Section =
1488 static_cast<const MCSectionELF&>(it->getSection());
1489 if (!(Section.getFlags() & ELF::SHF_GROUP))
1492 const MCSymbol *SignatureSymbol = Section.getGroup();
1493 Asm.getOrCreateSymbolData(*SignatureSymbol);
1494 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1496 Group = Ctx.CreateELFGroupSection();
1497 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1498 Data.setAlignment(4);
1499 MCDataFragment *F = new MCDataFragment(&Data);
1500 write(*F, uint32_t(ELF::GRP_COMDAT));
1502 GroupMap[Group] = SignatureSymbol;
1505 computeIndexMap(Asm, SectionIndexMap, RelMap);
1507 // Add sections to the groups
1508 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1510 const MCSectionELF &Section =
1511 static_cast<const MCSectionELF&>(it->getSection());
1512 if (!(Section.getFlags() & ELF::SHF_GROUP))
1514 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1515 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1516 // FIXME: we could use the previous fragment
1517 MCDataFragment *F = new MCDataFragment(&Data);
1518 uint32_t Index = SectionIndexMap.lookup(&Section);
1523 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1524 const SectionIndexMapTy &SectionIndexMap,
1525 const RelMapTy &RelMap,
1526 uint32_t GroupSymbolIndex,
1527 uint64_t Offset, uint64_t Size,
1529 const MCSectionELF &Section) {
1530 uint64_t sh_link = 0;
1531 uint64_t sh_info = 0;
1533 switch(Section.getType()) {
1534 case ELF::SHT_DYNAMIC:
1535 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1540 case ELF::SHT_RELA: {
1541 sh_link = SymbolTableIndex;
1542 assert(sh_link && ".symtab not found");
1543 const MCSectionELF *InfoSection = RelMap.find(&Section)->second;
1544 sh_info = SectionIndexMap.lookup(InfoSection);
1548 case ELF::SHT_SYMTAB:
1549 case ELF::SHT_DYNSYM:
1550 sh_link = StringTableIndex;
1551 sh_info = LastLocalSymbolIndex;
1554 case ELF::SHT_SYMTAB_SHNDX:
1555 sh_link = SymbolTableIndex;
1558 case ELF::SHT_PROGBITS:
1559 case ELF::SHT_STRTAB:
1560 case ELF::SHT_NOBITS:
1563 case ELF::SHT_ARM_ATTRIBUTES:
1564 case ELF::SHT_INIT_ARRAY:
1565 case ELF::SHT_FINI_ARRAY:
1566 case ELF::SHT_PREINIT_ARRAY:
1567 case ELF::SHT_X86_64_UNWIND:
1568 case ELF::SHT_MIPS_REGINFO:
1569 case ELF::SHT_MIPS_OPTIONS:
1570 case ELF::SHT_MIPS_ABIFLAGS:
1574 case ELF::SHT_GROUP:
1575 sh_link = SymbolTableIndex;
1576 sh_info = GroupSymbolIndex;
1580 llvm_unreachable("FIXME: sh_type value not supported!");
1583 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1584 Section.getType() == ELF::SHT_ARM_EXIDX) {
1585 StringRef SecName(Section.getSectionName());
1586 if (SecName == ".ARM.exidx") {
1587 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1588 ".text", ELF::SHT_PROGBITS, ELF::SHF_EXECINSTR | ELF::SHF_ALLOC));
1589 } else if (SecName.startswith(".ARM.exidx")) {
1590 StringRef GroupName =
1591 Section.getGroup() ? Section.getGroup()->getName() : "";
1592 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1593 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1594 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, 0, GroupName));
1598 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1600 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1601 Alignment, Section.getEntrySize());
1604 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1605 return SD.getOrdinal() == ~UINT32_C(0) &&
1606 !SD.getSection().isVirtualSection();
1609 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1611 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1613 const MCFragment &F = *i;
1614 assert(F.getKind() == MCFragment::FT_Data);
1615 Ret += cast<MCDataFragment>(F).getContents().size();
1620 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1621 const MCSectionData &SD) {
1622 if (IsELFMetaDataSection(SD))
1623 return DataSectionSize(SD);
1624 return Layout.getSectionFileSize(&SD);
1627 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1628 const MCSectionData &SD) {
1629 if (IsELFMetaDataSection(SD))
1630 return DataSectionSize(SD);
1631 return Layout.getSectionAddressSize(&SD);
1634 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1635 const MCAsmLayout &Layout,
1636 const MCSectionELF &Section) {
1637 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1639 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1640 WriteZeros(Padding);
1642 if (IsELFMetaDataSection(SD)) {
1643 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1645 const MCFragment &F = *i;
1646 assert(F.getKind() == MCFragment::FT_Data);
1647 WriteBytes(cast<MCDataFragment>(F).getContents());
1650 Asm.writeSectionData(&SD, Layout);
1654 void ELFObjectWriter::writeSectionHeader(
1655 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1656 const SectionIndexMapTy &SectionIndexMap, const RelMapTy &RelMap,
1657 const SectionOffsetMapTy &SectionOffsetMap) {
1658 const unsigned NumSections = Asm.size() + 1;
1660 std::vector<const MCSectionELF*> Sections;
1661 Sections.resize(NumSections - 1);
1663 for (SectionIndexMapTy::const_iterator i=
1664 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1665 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1666 Sections[p.second - 1] = p.first;
1669 // Null section first.
1670 uint64_t FirstSectionSize =
1671 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1672 uint32_t FirstSectionLink =
1673 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1674 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1676 for (unsigned i = 0; i < NumSections - 1; ++i) {
1677 const MCSectionELF &Section = *Sections[i];
1678 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1679 uint32_t GroupSymbolIndex;
1680 if (Section.getType() != ELF::SHT_GROUP)
1681 GroupSymbolIndex = 0;
1683 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1684 GroupMap.lookup(&Section));
1686 uint64_t Size = GetSectionAddressSize(Layout, SD);
1688 writeSection(Asm, SectionIndexMap, RelMap, GroupSymbolIndex,
1689 SectionOffsetMap.lookup(&Section), Size,
1690 SD.getAlignment(), Section);
1694 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1695 std::vector<const MCSectionELF*> &Sections) {
1696 for (MCAssembler::iterator it = Asm.begin(),
1697 ie = Asm.end(); it != ie; ++it) {
1698 const MCSectionELF &Section =
1699 static_cast<const MCSectionELF &>(it->getSection());
1700 if (Section.getType() == ELF::SHT_GROUP)
1701 Sections.push_back(&Section);
1704 for (MCAssembler::iterator it = Asm.begin(),
1705 ie = Asm.end(); it != ie; ++it) {
1706 const MCSectionELF &Section =
1707 static_cast<const MCSectionELF &>(it->getSection());
1708 if (Section.getType() != ELF::SHT_GROUP &&
1709 Section.getType() != ELF::SHT_REL &&
1710 Section.getType() != ELF::SHT_RELA)
1711 Sections.push_back(&Section);
1714 for (MCAssembler::iterator it = Asm.begin(),
1715 ie = Asm.end(); it != ie; ++it) {
1716 const MCSectionELF &Section =
1717 static_cast<const MCSectionELF &>(it->getSection());
1718 if (Section.getType() == ELF::SHT_REL ||
1719 Section.getType() == ELF::SHT_RELA)
1720 Sections.push_back(&Section);
1724 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1725 const MCAsmLayout &Layout) {
1726 GroupMapTy GroupMap;
1727 RevGroupMapTy RevGroupMap;
1728 SectionIndexMapTy SectionIndexMap;
1730 unsigned NumUserSections = Asm.size();
1732 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1734 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1735 const unsigned NumUserAndRelocSections = Asm.size();
1736 createIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1737 RevGroupMap, SectionIndexMap, RelMap);
1738 const unsigned AllSections = Asm.size();
1739 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1741 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1743 // Compute symbol table information.
1744 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1745 NumRegularSections);
1747 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1749 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1750 const_cast<MCAsmLayout&>(Layout),
1753 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1754 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1755 sizeof(ELF::Elf32_Ehdr);
1756 uint64_t FileOff = HeaderSize;
1758 std::vector<const MCSectionELF*> Sections;
1759 ComputeSectionOrder(Asm, Sections);
1760 unsigned NumSections = Sections.size();
1761 SectionOffsetMapTy SectionOffsetMap;
1762 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1763 const MCSectionELF &Section = *Sections[i];
1764 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1766 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1768 // Remember the offset into the file for this section.
1769 SectionOffsetMap[&Section] = FileOff;
1771 // Get the size of the section in the output file (including padding).
1772 FileOff += GetSectionFileSize(Layout, SD);
1775 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1777 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1779 uint64_t SectionHeaderEntrySize = is64Bit() ?
1780 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1781 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1783 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1784 const MCSectionELF &Section = *Sections[i];
1785 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1787 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1789 // Remember the offset into the file for this section.
1790 SectionOffsetMap[&Section] = FileOff;
1792 // Get the size of the section in the output file (including padding).
1793 FileOff += GetSectionFileSize(Layout, SD);
1796 // Write out the ELF header ...
1797 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1799 // ... then the regular sections ...
1800 // + because of .shstrtab
1801 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1802 WriteDataSectionData(Asm, Layout, *Sections[i]);
1804 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1805 WriteZeros(Padding);
1807 // ... then the section header table ...
1808 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, RelMap,
1811 // ... and then the remaining sections ...
1812 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1813 WriteDataSectionData(Asm, Layout, *Sections[i]);
1817 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1818 const MCSymbolData &DataA,
1819 const MCFragment &FB,
1821 bool IsPCRel) const {
1822 if (::isWeak(DataA))
1824 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1825 Asm, DataA, FB,InSet, IsPCRel);
1828 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1829 return ::isWeak(SD);
1832 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1834 bool IsLittleEndian) {
1835 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);