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/Endian.h"
35 #include "llvm/Support/ELF.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 bool UseSymbol; // Relocate with a symbol, not the section.
86 const MCSymbol *Symbol; // The symbol to relocate with.
87 const MCSectionData *Section; // The section to relocate with.
89 unsigned Type; // The type of the relocation.
90 uint64_t Addend; // The addend to use.
92 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
94 : Offset(Offset), UseSymbol(true), Symbol(Symbol), Type(Type),
97 ELFRelocationEntry(uint64_t Offset, const MCSectionData *Section,
98 unsigned Type, uint64_t Addend)
99 : Offset(Offset), UseSymbol(false), Section(Section), Type(Type),
103 class ELFObjectWriter : public MCObjectWriter {
104 FragmentWriter FWriter;
108 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
109 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
110 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
111 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
112 bool Used, bool Renamed);
113 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
114 static bool IsELFMetaDataSection(const MCSectionData &SD);
115 static uint64_t DataSectionSize(const MCSectionData &SD);
116 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
117 const MCSectionData &SD);
118 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
119 const MCSectionData &SD);
121 void WriteDataSectionData(MCAssembler &Asm,
122 const MCAsmLayout &Layout,
123 const MCSectionELF &Section);
125 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
126 return Kind == X86::reloc_riprel_4byte ||
127 Kind == X86::reloc_riprel_4byte_movq_load;
130 /// ELFSymbolData - Helper struct for containing some precomputed
131 /// information on symbols.
132 struct ELFSymbolData {
133 MCSymbolData *SymbolData;
134 uint64_t StringIndex;
135 uint32_t SectionIndex;
138 // Support lexicographic sorting.
139 bool operator<(const ELFSymbolData &RHS) const {
140 return Name < RHS.Name;
144 /// The target specific ELF writer instance.
145 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
147 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
148 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
149 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
151 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
153 StringTableBuilder ShStrTabBuilder;
156 /// @name Symbol Table Data
159 StringTableBuilder StrTabBuilder;
160 std::vector<uint64_t> FileSymbolData;
161 std::vector<ELFSymbolData> LocalSymbolData;
162 std::vector<ELFSymbolData> ExternalSymbolData;
163 std::vector<ELFSymbolData> UndefinedSymbolData;
169 // This holds the symbol table index of the last local symbol.
170 unsigned LastLocalSymbolIndex;
171 // This holds the .strtab section index.
172 unsigned StringTableIndex;
173 // This holds the .symtab section index.
174 unsigned SymbolTableIndex;
176 unsigned ShstrtabIndex;
179 // TargetObjectWriter wrappers.
180 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
181 bool hasRelocationAddend() const {
182 return TargetObjectWriter->hasRelocationAddend();
184 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
185 bool IsPCRel) const {
186 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
190 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
192 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
193 TargetObjectWriter(MOTW), NeedsGOT(false) {}
195 virtual ~ELFObjectWriter();
197 void WriteWord(uint64_t W) {
204 template <typename T> void write(MCDataFragment &F, T Value) {
205 FWriter.write(F, Value);
208 void WriteHeader(const MCAssembler &Asm,
209 uint64_t SectionDataSize,
210 unsigned NumberOfSections);
212 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
213 const MCAsmLayout &Layout);
215 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
216 const MCAsmLayout &Layout,
217 SectionIndexMapTy &SectionIndexMap);
219 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
220 const MCSymbolRefExpr *RefA,
221 const MCSymbolData *SD, uint64_t C,
222 unsigned Type) const;
224 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
225 const MCFragment *Fragment, const MCFixup &Fixup,
226 MCValue Target, bool &IsPCRel,
227 uint64_t &FixedValue) override;
229 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
232 // Map from a group section to the signature symbol
233 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
234 // Map from a signature symbol to the group section
235 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
236 // Map from a section to the section with the relocations
237 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
238 // Map from a section to its offset
239 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
241 /// Compute the symbol table data
243 /// \param Asm - The assembler.
244 /// \param SectionIndexMap - Maps a section to its index.
245 /// \param RevGroupMap - Maps a signature symbol to the group section.
246 /// \param NumRegularSections - Number of non-relocation sections.
247 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
248 const SectionIndexMapTy &SectionIndexMap,
249 RevGroupMapTy RevGroupMap,
250 unsigned NumRegularSections);
252 void ComputeIndexMap(MCAssembler &Asm,
253 SectionIndexMapTy &SectionIndexMap,
254 const RelMapTy &RelMap);
256 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
259 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
261 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
262 const RelMapTy &RelMap);
264 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
265 SectionIndexMapTy &SectionIndexMap,
266 const RelMapTy &RelMap);
268 // Create the sections that show up in the symbol table. Currently
269 // those are the .note.GNU-stack section and the group sections.
270 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
271 GroupMapTy &GroupMap,
272 RevGroupMapTy &RevGroupMap,
273 SectionIndexMapTy &SectionIndexMap,
274 const RelMapTy &RelMap);
276 void ExecutePostLayoutBinding(MCAssembler &Asm,
277 const MCAsmLayout &Layout) override;
279 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
280 const MCAsmLayout &Layout,
281 const SectionIndexMapTy &SectionIndexMap,
282 const SectionOffsetMapTy &SectionOffsetMap);
284 void ComputeSectionOrder(MCAssembler &Asm,
285 std::vector<const MCSectionELF*> &Sections);
287 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
288 uint64_t Address, uint64_t Offset,
289 uint64_t Size, uint32_t Link, uint32_t Info,
290 uint64_t Alignment, uint64_t EntrySize);
292 void WriteRelocationsFragment(const MCAssembler &Asm,
294 const MCSectionData *SD);
297 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
298 const MCSymbolData &DataA,
299 const MCFragment &FB,
301 bool IsPCRel) const override;
303 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
304 void WriteSection(MCAssembler &Asm,
305 const SectionIndexMapTy &SectionIndexMap,
306 uint32_t GroupSymbolIndex,
307 uint64_t Offset, uint64_t Size, uint64_t Alignment,
308 const MCSectionELF &Section);
312 FragmentWriter::FragmentWriter(bool IsLittleEndian)
313 : IsLittleEndian(IsLittleEndian) {}
315 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
317 Val = support::endian::byte_swap<T, support::little>(Val);
319 Val = support::endian::byte_swap<T, support::big>(Val);
320 const char *Start = (const char *)&Val;
321 F.getContents().append(Start, Start + sizeof(T));
324 void SymbolTableWriter::createSymtabShndx() {
328 MCContext &Ctx = Asm.getContext();
329 const MCSectionELF *SymtabShndxSection =
330 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
331 SectionKind::getReadOnly(), 4, "");
332 MCSectionData *SymtabShndxSD =
333 &Asm.getOrCreateSectionData(*SymtabShndxSection);
334 SymtabShndxSD->setAlignment(4);
335 ShndxF = new MCDataFragment(SymtabShndxSD);
336 unsigned Index = SectionIndexMap.size() + 1;
337 SectionIndexMap[SymtabShndxSection] = Index;
339 for (unsigned I = 0; I < NumWritten; ++I)
340 write(*ShndxF, uint32_t(0));
343 template <typename T>
344 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
345 FWriter.write(F, Value);
348 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
350 SectionIndexMapTy &SectionIndexMap,
351 MCDataFragment *SymtabF)
352 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
353 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
356 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
357 uint64_t size, uint8_t other,
358 uint32_t shndx, bool Reserved) {
359 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
366 write(*ShndxF, shndx);
368 write(*ShndxF, uint32_t(0));
371 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
373 raw_svector_ostream OS(SymtabF->getContents());
376 write(*SymtabF, name); // st_name
377 write(*SymtabF, info); // st_info
378 write(*SymtabF, other); // st_other
379 write(*SymtabF, Index); // st_shndx
380 write(*SymtabF, value); // st_value
381 write(*SymtabF, size); // st_size
383 write(*SymtabF, name); // st_name
384 write(*SymtabF, uint32_t(value)); // st_value
385 write(*SymtabF, uint32_t(size)); // st_size
386 write(*SymtabF, info); // st_info
387 write(*SymtabF, other); // st_other
388 write(*SymtabF, Index); // st_shndx
394 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
395 const MCFixupKindInfo &FKI =
396 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
398 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
401 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
405 case MCSymbolRefExpr::VK_GOT:
406 case MCSymbolRefExpr::VK_PLT:
407 case MCSymbolRefExpr::VK_GOTPCREL:
408 case MCSymbolRefExpr::VK_GOTOFF:
409 case MCSymbolRefExpr::VK_TPOFF:
410 case MCSymbolRefExpr::VK_TLSGD:
411 case MCSymbolRefExpr::VK_GOTTPOFF:
412 case MCSymbolRefExpr::VK_INDNTPOFF:
413 case MCSymbolRefExpr::VK_NTPOFF:
414 case MCSymbolRefExpr::VK_GOTNTPOFF:
415 case MCSymbolRefExpr::VK_TLSLDM:
416 case MCSymbolRefExpr::VK_DTPOFF:
417 case MCSymbolRefExpr::VK_TLSLD:
422 ELFObjectWriter::~ELFObjectWriter()
425 // Emit the ELF header.
426 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
427 uint64_t SectionDataSize,
428 unsigned NumberOfSections) {
434 // emitWord method behaves differently for ELF32 and ELF64, writing
435 // 4 bytes in the former and 8 in the latter.
437 Write8(0x7f); // e_ident[EI_MAG0]
438 Write8('E'); // e_ident[EI_MAG1]
439 Write8('L'); // e_ident[EI_MAG2]
440 Write8('F'); // e_ident[EI_MAG3]
442 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
445 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
447 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
449 Write8(TargetObjectWriter->getOSABI());
450 Write8(0); // e_ident[EI_ABIVERSION]
452 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
454 Write16(ELF::ET_REL); // e_type
456 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
458 Write32(ELF::EV_CURRENT); // e_version
459 WriteWord(0); // e_entry, no entry point in .o file
460 WriteWord(0); // e_phoff, no program header for .o
461 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
462 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
464 // e_flags = whatever the target wants
465 Write32(Asm.getELFHeaderEFlags());
467 // e_ehsize = ELF header size
468 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
470 Write16(0); // e_phentsize = prog header entry size
471 Write16(0); // e_phnum = # prog header entries = 0
473 // e_shentsize = Section header entry size
474 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
476 // e_shnum = # of section header ents
477 if (NumberOfSections >= ELF::SHN_LORESERVE)
478 Write16(ELF::SHN_UNDEF);
480 Write16(NumberOfSections);
482 // e_shstrndx = Section # of '.shstrtab'
483 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
484 Write16(ELF::SHN_XINDEX);
486 Write16(ShstrtabIndex);
489 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
490 const MCAsmLayout &Layout) {
491 if (Data.isCommon() && Data.isExternal())
492 return Data.getCommonAlignment();
495 if (!Layout.getSymbolOffset(&Data, Res))
498 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
504 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
505 const MCAsmLayout &Layout) {
506 // The presence of symbol versions causes undefined symbols and
507 // versions declared with @@@ to be renamed.
509 for (MCSymbolData &OriginalData : Asm.symbols()) {
510 const MCSymbol &Alias = OriginalData.getSymbol();
513 if (!Alias.isVariable())
515 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
518 const MCSymbol &Symbol = Ref->getSymbol();
519 MCSymbolData &SD = Asm.getSymbolData(Symbol);
521 StringRef AliasName = Alias.getName();
522 size_t Pos = AliasName.find('@');
523 if (Pos == StringRef::npos)
526 // Aliases defined with .symvar copy the binding from the symbol they alias.
527 // This is the first place we are able to copy this information.
528 OriginalData.setExternal(SD.isExternal());
529 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
531 StringRef Rest = AliasName.substr(Pos);
532 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
535 // FIXME: produce a better error message.
536 if (Symbol.isUndefined() && Rest.startswith("@@") &&
537 !Rest.startswith("@@@"))
538 report_fatal_error("A @@ version cannot be undefined");
540 Renames.insert(std::make_pair(&Symbol, &Alias));
544 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
545 uint8_t Type = newType;
547 // Propagation rules:
548 // IFUNC > FUNC > OBJECT > NOTYPE
549 // TLS_OBJECT > OBJECT > NOTYPE
551 // dont let the new type degrade the old type
555 case ELF::STT_GNU_IFUNC:
556 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
557 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
558 Type = ELF::STT_GNU_IFUNC;
561 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
562 Type == ELF::STT_TLS)
563 Type = ELF::STT_FUNC;
565 case ELF::STT_OBJECT:
566 if (Type == ELF::STT_NOTYPE)
567 Type = ELF::STT_OBJECT;
570 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
571 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
579 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
580 const MCAsmLayout &Layout) {
581 MCSymbolData &OrigData = *MSD.SymbolData;
582 assert((!OrigData.getFragment() ||
583 (&OrigData.getFragment()->getParent()->getSection() ==
584 &OrigData.getSymbol().getSection())) &&
585 "The symbol's section doesn't match the fragment's symbol");
586 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
588 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
590 bool IsReserved = !Base || OrigData.isCommon();
592 // Binding and Type share the same byte as upper and lower nibbles
593 uint8_t Binding = MCELF::GetBinding(OrigData);
594 uint8_t Type = MCELF::GetType(OrigData);
595 MCSymbolData *BaseSD = nullptr;
597 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
598 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
600 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
602 // Other and Visibility share the same byte with Visibility using the lower
604 uint8_t Visibility = MCELF::GetVisibility(OrigData);
605 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
608 uint64_t Value = SymbolValue(OrigData, Layout);
611 const MCExpr *ESize = OrigData.getSize();
613 ESize = BaseSD->getSize();
617 if (!ESize->EvaluateAsAbsolute(Res, Layout))
618 report_fatal_error("Size expression must be absolute.");
622 // Write out the symbol table entry
623 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
624 MSD.SectionIndex, IsReserved);
627 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
629 const MCAsmLayout &Layout,
630 SectionIndexMapTy &SectionIndexMap) {
631 // The string table must be emitted first because we need the index
632 // into the string table for all the symbol names.
634 // FIXME: Make sure the start of the symbol table is aligned.
636 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
638 // The first entry is the undefined symbol entry.
639 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
641 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
642 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
643 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
646 // Write the symbol table entries.
647 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
649 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
650 ELFSymbolData &MSD = LocalSymbolData[i];
651 WriteSymbol(Writer, MSD, Layout);
654 // Write out a symbol table entry for each regular section.
655 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
657 const MCSectionELF &Section =
658 static_cast<const MCSectionELF&>(i->getSection());
659 if (Section.getType() == ELF::SHT_RELA ||
660 Section.getType() == ELF::SHT_REL ||
661 Section.getType() == ELF::SHT_STRTAB ||
662 Section.getType() == ELF::SHT_SYMTAB ||
663 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
665 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
666 SectionIndexMap.lookup(&Section), false);
667 LastLocalSymbolIndex++;
670 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
671 ELFSymbolData &MSD = ExternalSymbolData[i];
672 MCSymbolData &Data = *MSD.SymbolData;
673 assert(((Data.getFlags() & ELF_STB_Global) ||
674 (Data.getFlags() & ELF_STB_Weak)) &&
675 "External symbol requires STB_GLOBAL or STB_WEAK flag");
676 WriteSymbol(Writer, MSD, Layout);
677 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
678 LastLocalSymbolIndex++;
681 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
682 ELFSymbolData &MSD = UndefinedSymbolData[i];
683 MCSymbolData &Data = *MSD.SymbolData;
684 WriteSymbol(Writer, MSD, Layout);
685 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
686 LastLocalSymbolIndex++;
690 // It is always valid to create a relocation with a symbol. It is preferable
691 // to use a relocation with a section if that is possible. Using the section
692 // allows us to omit some local symbols from the symbol table.
693 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
694 const MCSymbolRefExpr *RefA,
695 const MCSymbolData *SD,
697 unsigned Type) const {
698 // A PCRel relocation to an absolute value has no symbol (or section). We
699 // represent that with a relocation to a null section.
703 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
707 // The .odp creation emits a relocation against the symbol ".TOC." which
708 // create a R_PPC64_TOC relocation. However the relocation symbol name
709 // in final object creation should be NULL, since the symbol does not
710 // really exist, it is just the reference to TOC base for the current
711 // object file. Since the symbol is undefined, returning false results
712 // in a relocation with a null section which is the desired result.
713 case MCSymbolRefExpr::VK_PPC_TOCBASE:
716 // These VariantKind cause the relocation to refer to something other than
717 // the symbol itself, like a linker generated table. Since the address of
718 // symbol is not relevant, we cannot replace the symbol with the
719 // section and patch the difference in the addend.
720 case MCSymbolRefExpr::VK_GOT:
721 case MCSymbolRefExpr::VK_PLT:
722 case MCSymbolRefExpr::VK_GOTPCREL:
723 case MCSymbolRefExpr::VK_Mips_GOT:
724 case MCSymbolRefExpr::VK_PPC_GOT_LO:
725 case MCSymbolRefExpr::VK_PPC_GOT_HI:
726 case MCSymbolRefExpr::VK_PPC_GOT_HA:
730 // An undefined symbol is not in any section, so the relocation has to point
731 // to the symbol itself.
732 const MCSymbol &Sym = SD->getSymbol();
733 if (Sym.isUndefined())
736 unsigned Binding = MCELF::GetBinding(*SD);
739 llvm_unreachable("Invalid Binding");
743 // If the symbol is weak, it might be overridden by a symbol in another
744 // file. The relocation has to point to the symbol so that the linker
747 case ELF::STB_GLOBAL:
748 // Global ELF symbols can be preempted by the dynamic linker. The relocation
749 // has to point to the symbol for a reason analogous to the STB_WEAK case.
753 // If a relocation points to a mergeable section, we have to be careful.
754 // If the offset is zero, a relocation with the section will encode the
755 // same information. With a non-zero offset, the situation is different.
756 // For example, a relocation can point 42 bytes past the end of a string.
757 // If we change such a relocation to use the section, the linker would think
758 // that it pointed to another string and subtracting 42 at runtime will
759 // produce the wrong value.
760 auto &Sec = cast<MCSectionELF>(Sym.getSection());
761 unsigned Flags = Sec.getFlags();
762 if (Flags & ELF::SHF_MERGE) {
766 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
767 // only handle section relocations to mergeable sections if using RELA.
768 if (!hasRelocationAddend())
772 // Most TLS relocations use a got, so they need the symbol. Even those that
773 // are just an offset (@tpoff), require a symbol in some linkers (gold,
775 if (Flags & ELF::SHF_TLS)
778 // If the symbol is a thumb function the final relocation must set the lowest
779 // bit. With a symbol that is done by just having the symbol have that bit
780 // set, so we would lose the bit if we relocated with the section.
781 // FIXME: We could use the section but add the bit to the relocation value.
782 if (Asm.isThumbFunc(&Sym))
785 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
790 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
791 const MCSymbol &Sym = Ref.getSymbol();
793 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
796 if (!Sym.isVariable())
799 const MCExpr *Expr = Sym.getVariableValue();
800 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
804 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
805 return &Inner->getSymbol();
809 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
810 const MCAsmLayout &Layout,
811 const MCFragment *Fragment,
812 const MCFixup &Fixup,
815 uint64_t &FixedValue) {
816 const MCSectionData *FixupSection = Fragment->getParent();
817 uint64_t C = Target.getConstant();
818 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
820 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
821 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
822 "Should not have constructed this");
824 // Let A, B and C being the components of Target and R be the location of
825 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
826 // If it is pcrel, we want to compute (A - B + C - R).
828 // In general, ELF has no relocations for -B. It can only represent (A + C)
829 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
830 // replace B to implement it: (A - R - K + C)
832 Asm.getContext().FatalError(
834 "No relocation available to represent this relative expression");
836 const MCSymbol &SymB = RefB->getSymbol();
838 if (SymB.isUndefined())
839 Asm.getContext().FatalError(
841 Twine("symbol '") + SymB.getName() +
842 "' can not be undefined in a subtraction expression");
844 assert(!SymB.isAbsolute() && "Should have been folded");
845 const MCSection &SecB = SymB.getSection();
846 if (&SecB != &FixupSection->getSection())
847 Asm.getContext().FatalError(
848 Fixup.getLoc(), "Cannot represent a difference across sections");
850 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
851 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
852 uint64_t K = SymBOffset - FixupOffset;
857 // We either rejected the fixup or folded B into C at this point.
858 const MCSymbolRefExpr *RefA = Target.getSymA();
859 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
860 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
862 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
863 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
864 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
865 C += Layout.getSymbolOffset(SymAD);
868 if (hasRelocationAddend()) {
875 // FIXME: What is this!?!?
876 MCSymbolRefExpr::VariantKind Modifier =
877 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
878 if (RelocNeedsGOT(Modifier))
881 if (!RelocateWithSymbol) {
882 const MCSection *SecA =
883 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
884 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
885 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
886 Relocations[FixupSection].push_back(Rec);
891 if (const MCSymbol *R = Renames.lookup(SymA))
894 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
895 WeakrefUsedInReloc.insert(WeakRef);
897 UsedInReloc.insert(SymA);
899 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
900 Relocations[FixupSection].push_back(Rec);
906 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
908 const MCSymbolData &SD = Asm.getSymbolData(*S);
909 return SD.getIndex();
912 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
913 const MCSymbolData &Data, bool Used,
915 const MCSymbol &Symbol = Data.getSymbol();
916 if (Symbol.isVariable()) {
917 const MCExpr *Expr = Symbol.getVariableValue();
918 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
919 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
930 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
933 if (Symbol.isVariable()) {
934 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
935 if (Base && Base->isUndefined())
939 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
940 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
943 if (Symbol.isTemporary())
949 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
950 if (Data.isExternal())
953 const MCSymbol &Symbol = Data.getSymbol();
954 if (Symbol.isDefined())
963 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
964 SectionIndexMapTy &SectionIndexMap,
965 const RelMapTy &RelMap) {
967 for (MCAssembler::iterator it = Asm.begin(),
968 ie = Asm.end(); it != ie; ++it) {
969 const MCSectionELF &Section =
970 static_cast<const MCSectionELF &>(it->getSection());
971 if (Section.getType() != ELF::SHT_GROUP)
973 SectionIndexMap[&Section] = Index++;
976 for (MCAssembler::iterator it = Asm.begin(),
977 ie = Asm.end(); it != ie; ++it) {
978 const MCSectionELF &Section =
979 static_cast<const MCSectionELF &>(it->getSection());
980 if (Section.getType() == ELF::SHT_GROUP ||
981 Section.getType() == ELF::SHT_REL ||
982 Section.getType() == ELF::SHT_RELA)
984 SectionIndexMap[&Section] = Index++;
985 const MCSectionELF *RelSection = RelMap.lookup(&Section);
987 SectionIndexMap[RelSection] = Index++;
992 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
993 const SectionIndexMapTy &SectionIndexMap,
994 RevGroupMapTy RevGroupMap,
995 unsigned NumRegularSections) {
996 // FIXME: Is this the correct place to do this?
997 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
999 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1000 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1001 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1002 Data.setExternal(true);
1003 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1006 // Add the data for the symbols.
1007 for (MCSymbolData &SD : Asm.symbols()) {
1008 const MCSymbol &Symbol = SD.getSymbol();
1010 bool Used = UsedInReloc.count(&Symbol);
1011 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1012 bool isSignature = RevGroupMap.count(&Symbol);
1014 if (!isInSymtab(Layout, SD,
1015 Used || WeakrefUsed || isSignature,
1016 Renames.count(&Symbol)))
1020 MSD.SymbolData = &SD;
1021 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1023 // Undefined symbols are global, but this is the first place we
1024 // are able to set it.
1025 bool Local = isLocal(SD, Used);
1026 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1028 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1029 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1030 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1034 MSD.SectionIndex = ELF::SHN_ABS;
1035 } else if (SD.isCommon()) {
1037 MSD.SectionIndex = ELF::SHN_COMMON;
1038 } else if (BaseSymbol->isUndefined()) {
1039 if (isSignature && !Used)
1040 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1042 MSD.SectionIndex = ELF::SHN_UNDEF;
1043 if (!Used && WeakrefUsed)
1044 MCELF::SetBinding(SD, ELF::STB_WEAK);
1046 const MCSectionELF &Section =
1047 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1048 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1049 assert(MSD.SectionIndex && "Invalid section index!");
1052 // The @@@ in symbol version is replaced with @ in undefined symbols and
1053 // @@ in defined ones.
1054 StringRef Name = Symbol.getName();
1055 SmallString<32> Buf;
1056 size_t Pos = Name.find("@@@");
1057 if (Pos != StringRef::npos) {
1058 Buf += Name.substr(0, Pos);
1059 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1060 Buf += Name.substr(Pos + Skip);
1063 MSD.Name = StrTabBuilder.add(Name);
1065 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1066 UndefinedSymbolData.push_back(MSD);
1068 LocalSymbolData.push_back(MSD);
1070 ExternalSymbolData.push_back(MSD);
1073 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1074 StrTabBuilder.add(*i);
1076 StrTabBuilder.finalize();
1078 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1079 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1081 for (ELFSymbolData& MSD : LocalSymbolData)
1082 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1083 for (ELFSymbolData& MSD : ExternalSymbolData)
1084 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1085 for (ELFSymbolData& MSD : UndefinedSymbolData)
1086 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1088 // Symbols are required to be in lexicographic order.
1089 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1090 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1091 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1093 // Set the symbol indices. Local symbols must come before all other
1094 // symbols with non-local bindings.
1095 unsigned Index = FileSymbolData.size() + 1;
1096 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1097 LocalSymbolData[i].SymbolData->setIndex(Index++);
1099 Index += NumRegularSections;
1101 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1102 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1103 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1104 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1107 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1108 MCAsmLayout &Layout,
1110 for (MCAssembler::const_iterator it = Asm.begin(),
1111 ie = Asm.end(); it != ie; ++it) {
1112 const MCSectionData &SD = *it;
1113 if (Relocations[&SD].empty())
1116 MCContext &Ctx = Asm.getContext();
1117 const MCSectionELF &Section =
1118 static_cast<const MCSectionELF&>(SD.getSection());
1120 const StringRef SectionName = Section.getSectionName();
1121 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1122 RelaSectionName += SectionName;
1125 if (hasRelocationAddend())
1126 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1128 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1131 StringRef Group = "";
1132 if (Section.getFlags() & ELF::SHF_GROUP) {
1133 Flags = ELF::SHF_GROUP;
1134 Group = Section.getGroup()->getName();
1137 const MCSectionELF *RelaSection =
1138 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1139 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1140 SectionKind::getReadOnly(),
1142 RelMap[&Section] = RelaSection;
1143 Asm.getOrCreateSectionData(*RelaSection);
1147 static SmallVector<char, 128>
1148 getUncompressedData(MCAsmLayout &Layout,
1149 MCSectionData::FragmentListType &Fragments) {
1150 SmallVector<char, 128> UncompressedData;
1151 for (const MCFragment &F : Fragments) {
1152 const SmallVectorImpl<char> *Contents;
1153 switch (F.getKind()) {
1154 case MCFragment::FT_Data:
1155 Contents = &cast<MCDataFragment>(F).getContents();
1157 case MCFragment::FT_Dwarf:
1158 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1160 case MCFragment::FT_DwarfFrame:
1161 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1165 "Not expecting any other fragment types in a debug_* section");
1167 UncompressedData.append(Contents->begin(), Contents->end());
1169 return UncompressedData;
1172 // Include the debug info compression header:
1173 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1174 // useful for consumers to preallocate a buffer to decompress into.
1176 prependCompressionHeader(uint64_t Size,
1177 SmallVectorImpl<char> &CompressedContents) {
1178 static const StringRef Magic = "ZLIB";
1179 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1181 if (sys::IsLittleEndianHost)
1182 sys::swapByteOrder(Size);
1183 CompressedContents.insert(CompressedContents.begin(),
1184 Magic.size() + sizeof(Size), 0);
1185 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1186 std::copy(reinterpret_cast<char *>(&Size),
1187 reinterpret_cast<char *>(&Size + 1),
1188 CompressedContents.begin() + Magic.size());
1192 // Return a single fragment containing the compressed contents of the whole
1193 // section. Null if the section was not compressed for any reason.
1194 static std::unique_ptr<MCDataFragment>
1195 getCompressedFragment(MCAsmLayout &Layout,
1196 MCSectionData::FragmentListType &Fragments) {
1197 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1199 // Gather the uncompressed data from all the fragments, recording the
1200 // alignment fragment, if seen, and any fixups.
1201 SmallVector<char, 128> UncompressedData =
1202 getUncompressedData(Layout, Fragments);
1204 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1206 zlib::Status Success = zlib::compress(
1207 StringRef(UncompressedData.data(), UncompressedData.size()),
1208 CompressedContents);
1209 if (Success != zlib::StatusOK)
1212 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1215 return CompressedFragment;
1218 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1221 static void UpdateSymbols(const MCAsmLayout &Layout,
1222 const std::vector<MCSymbolData *> &Symbols,
1223 MCFragment &NewFragment) {
1224 for (MCSymbolData *Sym : Symbols) {
1225 Sym->setOffset(Sym->getOffset() +
1226 Layout.getFragmentOffset(Sym->getFragment()));
1227 Sym->setFragment(&NewFragment);
1231 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1232 const DefiningSymbolMap &DefiningSymbols,
1233 const MCSectionELF &Section,
1234 MCSectionData &SD) {
1235 StringRef SectionName = Section.getSectionName();
1236 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1238 std::unique_ptr<MCDataFragment> CompressedFragment =
1239 getCompressedFragment(Layout, Fragments);
1241 // Leave the section as-is if the fragments could not be compressed.
1242 if (!CompressedFragment)
1245 // Update the fragment+offsets of any symbols referring to fragments in this
1246 // section to refer to the new fragment.
1247 auto I = DefiningSymbols.find(&SD);
1248 if (I != DefiningSymbols.end())
1249 UpdateSymbols(Layout, I->second, *CompressedFragment);
1251 // Invalidate the layout for the whole section since it will have new and
1252 // different fragments now.
1253 Layout.invalidateFragmentsFrom(&Fragments.front());
1256 // Complete the initialization of the new fragment
1257 CompressedFragment->setParent(&SD);
1258 CompressedFragment->setLayoutOrder(0);
1259 Fragments.push_back(CompressedFragment.release());
1261 // Rename from .debug_* to .zdebug_*
1262 Asm.getContext().renameELFSection(&Section,
1263 (".z" + SectionName.drop_front(1)).str());
1266 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1267 MCAsmLayout &Layout) {
1268 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1271 DefiningSymbolMap DefiningSymbols;
1273 for (MCSymbolData &SD : Asm.symbols())
1274 if (MCFragment *F = SD.getFragment())
1275 DefiningSymbols[F->getParent()].push_back(&SD);
1277 for (MCSectionData &SD : Asm) {
1278 const MCSectionELF &Section =
1279 static_cast<const MCSectionELF &>(SD.getSection());
1280 StringRef SectionName = Section.getSectionName();
1282 // Compressing debug_frame requires handling alignment fragments which is
1283 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1284 // for writing to arbitrary buffers) for little benefit.
1285 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1288 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1292 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1293 const RelMapTy &RelMap) {
1294 for (MCAssembler::const_iterator it = Asm.begin(),
1295 ie = Asm.end(); it != ie; ++it) {
1296 const MCSectionData &SD = *it;
1297 const MCSectionELF &Section =
1298 static_cast<const MCSectionELF&>(SD.getSection());
1300 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1303 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1304 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1306 MCDataFragment *F = new MCDataFragment(&RelaSD);
1307 WriteRelocationsFragment(Asm, F, &*it);
1311 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1312 uint64_t Flags, uint64_t Address,
1313 uint64_t Offset, uint64_t Size,
1314 uint32_t Link, uint32_t Info,
1316 uint64_t EntrySize) {
1317 Write32(Name); // sh_name: index into string table
1318 Write32(Type); // sh_type
1319 WriteWord(Flags); // sh_flags
1320 WriteWord(Address); // sh_addr
1321 WriteWord(Offset); // sh_offset
1322 WriteWord(Size); // sh_size
1323 Write32(Link); // sh_link
1324 Write32(Info); // sh_info
1325 WriteWord(Alignment); // sh_addralign
1326 WriteWord(EntrySize); // sh_entsize
1329 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1330 // just to match gnu as for easier comparison. The use type is an arbitrary way
1331 // of making the sort deterministic.
1332 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1333 const ELFRelocationEntry &A = *AP;
1334 const ELFRelocationEntry &B = *BP;
1335 if (A.Offset != B.Offset)
1336 return B.Offset - A.Offset;
1337 if (B.Type != A.Type)
1338 return A.Type - B.Type;
1339 llvm_unreachable("ELFRelocs might be unstable!");
1342 static void sortRelocs(const MCAssembler &Asm,
1343 std::vector<ELFRelocationEntry> &Relocs) {
1344 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1347 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1349 const MCSectionData *SD) {
1350 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1352 sortRelocs(Asm, Relocs);
1354 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1355 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1358 if (Entry.UseSymbol) {
1359 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1361 const MCSectionData *Sec = Entry.Section;
1363 Index = Sec->getOrdinal() + FileSymbolData.size() +
1364 LocalSymbolData.size() + 1;
1370 write(*F, Entry.Offset);
1371 if (TargetObjectWriter->isN64()) {
1372 write(*F, uint32_t(Index));
1374 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1375 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1376 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1377 write(*F, TargetObjectWriter->getRType(Entry.Type));
1379 struct ELF::Elf64_Rela ERE64;
1380 ERE64.setSymbolAndType(Index, Entry.Type);
1381 write(*F, ERE64.r_info);
1383 if (hasRelocationAddend())
1384 write(*F, Entry.Addend);
1386 write(*F, uint32_t(Entry.Offset));
1388 struct ELF::Elf32_Rela ERE32;
1389 ERE32.setSymbolAndType(Index, Entry.Type);
1390 write(*F, ERE32.r_info);
1392 if (hasRelocationAddend())
1393 write(*F, uint32_t(Entry.Addend));
1398 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1399 MCAsmLayout &Layout,
1400 SectionIndexMapTy &SectionIndexMap,
1401 const RelMapTy &RelMap) {
1402 MCContext &Ctx = Asm.getContext();
1405 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1407 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1408 const MCSectionELF *ShstrtabSection =
1409 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1410 SectionKind::getReadOnly());
1411 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1412 ShstrtabSD.setAlignment(1);
1414 const MCSectionELF *SymtabSection =
1415 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1416 SectionKind::getReadOnly(),
1418 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1419 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1421 const MCSectionELF *StrtabSection;
1422 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1423 SectionKind::getReadOnly());
1424 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1425 StrtabSD.setAlignment(1);
1427 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1429 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1430 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1431 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1434 F = new MCDataFragment(&SymtabSD);
1435 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1437 F = new MCDataFragment(&StrtabSD);
1438 F->getContents().append(StrTabBuilder.data().begin(),
1439 StrTabBuilder.data().end());
1441 F = new MCDataFragment(&ShstrtabSD);
1443 // Section header string table.
1444 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1445 const MCSectionELF &Section =
1446 static_cast<const MCSectionELF&>(it->getSection());
1447 ShStrTabBuilder.add(Section.getSectionName());
1449 ShStrTabBuilder.finalize();
1450 F->getContents().append(ShStrTabBuilder.data().begin(),
1451 ShStrTabBuilder.data().end());
1454 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1455 MCAsmLayout &Layout,
1456 GroupMapTy &GroupMap,
1457 RevGroupMapTy &RevGroupMap,
1458 SectionIndexMapTy &SectionIndexMap,
1459 const RelMapTy &RelMap) {
1460 // Create the .note.GNU-stack section if needed.
1461 MCContext &Ctx = Asm.getContext();
1462 if (Asm.getNoExecStack()) {
1463 const MCSectionELF *GnuStackSection =
1464 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1465 SectionKind::getReadOnly());
1466 Asm.getOrCreateSectionData(*GnuStackSection);
1470 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1472 const MCSectionELF &Section =
1473 static_cast<const MCSectionELF&>(it->getSection());
1474 if (!(Section.getFlags() & ELF::SHF_GROUP))
1477 const MCSymbol *SignatureSymbol = Section.getGroup();
1478 Asm.getOrCreateSymbolData(*SignatureSymbol);
1479 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1481 Group = Ctx.CreateELFGroupSection();
1482 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1483 Data.setAlignment(4);
1484 MCDataFragment *F = new MCDataFragment(&Data);
1485 write(*F, uint32_t(ELF::GRP_COMDAT));
1487 GroupMap[Group] = SignatureSymbol;
1490 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1492 // Add sections to the groups
1493 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1495 const MCSectionELF &Section =
1496 static_cast<const MCSectionELF&>(it->getSection());
1497 if (!(Section.getFlags() & ELF::SHF_GROUP))
1499 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1500 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1501 // FIXME: we could use the previous fragment
1502 MCDataFragment *F = new MCDataFragment(&Data);
1503 uint32_t Index = SectionIndexMap.lookup(&Section);
1508 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1509 const SectionIndexMapTy &SectionIndexMap,
1510 uint32_t GroupSymbolIndex,
1511 uint64_t Offset, uint64_t Size,
1513 const MCSectionELF &Section) {
1514 uint64_t sh_link = 0;
1515 uint64_t sh_info = 0;
1517 switch(Section.getType()) {
1518 case ELF::SHT_DYNAMIC:
1519 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1524 case ELF::SHT_RELA: {
1525 const MCSectionELF *SymtabSection;
1526 const MCSectionELF *InfoSection;
1527 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1529 SectionKind::getReadOnly());
1530 sh_link = SectionIndexMap.lookup(SymtabSection);
1531 assert(sh_link && ".symtab not found");
1533 // Remove ".rel" and ".rela" prefixes.
1534 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1535 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1536 StringRef GroupName =
1537 Section.getGroup() ? Section.getGroup()->getName() : "";
1539 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1540 0, SectionKind::getReadOnly(),
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(
1586 Asm.getContext().getELFSection(".text",
1588 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1589 SectionKind::getText()));
1590 } else if (SecName.startswith(".ARM.exidx")) {
1591 StringRef GroupName =
1592 Section.getGroup() ? Section.getGroup()->getName() : "";
1593 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1594 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1595 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1600 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1602 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1603 Alignment, Section.getEntrySize());
1606 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1607 return SD.getOrdinal() == ~UINT32_C(0) &&
1608 !SD.getSection().isVirtualSection();
1611 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1613 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1615 const MCFragment &F = *i;
1616 assert(F.getKind() == MCFragment::FT_Data);
1617 Ret += cast<MCDataFragment>(F).getContents().size();
1622 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1623 const MCSectionData &SD) {
1624 if (IsELFMetaDataSection(SD))
1625 return DataSectionSize(SD);
1626 return Layout.getSectionFileSize(&SD);
1629 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1630 const MCSectionData &SD) {
1631 if (IsELFMetaDataSection(SD))
1632 return DataSectionSize(SD);
1633 return Layout.getSectionAddressSize(&SD);
1636 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1637 const MCAsmLayout &Layout,
1638 const MCSectionELF &Section) {
1639 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1641 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1642 WriteZeros(Padding);
1644 if (IsELFMetaDataSection(SD)) {
1645 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1647 const MCFragment &F = *i;
1648 assert(F.getKind() == MCFragment::FT_Data);
1649 WriteBytes(cast<MCDataFragment>(F).getContents());
1652 Asm.writeSectionData(&SD, Layout);
1656 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1657 const GroupMapTy &GroupMap,
1658 const MCAsmLayout &Layout,
1659 const SectionIndexMapTy &SectionIndexMap,
1660 const SectionOffsetMapTy &SectionOffsetMap) {
1661 const unsigned NumSections = Asm.size() + 1;
1663 std::vector<const MCSectionELF*> Sections;
1664 Sections.resize(NumSections - 1);
1666 for (SectionIndexMapTy::const_iterator i=
1667 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1668 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1669 Sections[p.second - 1] = p.first;
1672 // Null section first.
1673 uint64_t FirstSectionSize =
1674 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1675 uint32_t FirstSectionLink =
1676 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1677 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1679 for (unsigned i = 0; i < NumSections - 1; ++i) {
1680 const MCSectionELF &Section = *Sections[i];
1681 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1682 uint32_t GroupSymbolIndex;
1683 if (Section.getType() != ELF::SHT_GROUP)
1684 GroupSymbolIndex = 0;
1686 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1687 GroupMap.lookup(&Section));
1689 uint64_t Size = GetSectionAddressSize(Layout, SD);
1691 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1692 SectionOffsetMap.lookup(&Section), Size,
1693 SD.getAlignment(), Section);
1697 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1698 std::vector<const MCSectionELF*> &Sections) {
1699 for (MCAssembler::iterator it = Asm.begin(),
1700 ie = Asm.end(); it != ie; ++it) {
1701 const MCSectionELF &Section =
1702 static_cast<const MCSectionELF &>(it->getSection());
1703 if (Section.getType() == ELF::SHT_GROUP)
1704 Sections.push_back(&Section);
1707 for (MCAssembler::iterator it = Asm.begin(),
1708 ie = Asm.end(); it != ie; ++it) {
1709 const MCSectionELF &Section =
1710 static_cast<const MCSectionELF &>(it->getSection());
1711 if (Section.getType() != ELF::SHT_GROUP &&
1712 Section.getType() != ELF::SHT_REL &&
1713 Section.getType() != ELF::SHT_RELA)
1714 Sections.push_back(&Section);
1717 for (MCAssembler::iterator it = Asm.begin(),
1718 ie = Asm.end(); it != ie; ++it) {
1719 const MCSectionELF &Section =
1720 static_cast<const MCSectionELF &>(it->getSection());
1721 if (Section.getType() == ELF::SHT_REL ||
1722 Section.getType() == ELF::SHT_RELA)
1723 Sections.push_back(&Section);
1727 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1728 const MCAsmLayout &Layout) {
1729 GroupMapTy GroupMap;
1730 RevGroupMapTy RevGroupMap;
1731 SectionIndexMapTy SectionIndexMap;
1733 unsigned NumUserSections = Asm.size();
1735 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1737 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1738 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1740 const unsigned NumUserAndRelocSections = Asm.size();
1741 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1742 RevGroupMap, SectionIndexMap, RelMap);
1743 const unsigned AllSections = Asm.size();
1744 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1746 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1748 // Compute symbol table information.
1749 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1750 NumRegularSections);
1752 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1754 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1755 const_cast<MCAsmLayout&>(Layout),
1759 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1760 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1761 sizeof(ELF::Elf32_Ehdr);
1762 uint64_t FileOff = HeaderSize;
1764 std::vector<const MCSectionELF*> Sections;
1765 ComputeSectionOrder(Asm, Sections);
1766 unsigned NumSections = Sections.size();
1767 SectionOffsetMapTy SectionOffsetMap;
1768 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1769 const MCSectionELF &Section = *Sections[i];
1770 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1772 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1774 // Remember the offset into the file for this section.
1775 SectionOffsetMap[&Section] = FileOff;
1777 // Get the size of the section in the output file (including padding).
1778 FileOff += GetSectionFileSize(Layout, SD);
1781 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1783 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1785 uint64_t SectionHeaderEntrySize = is64Bit() ?
1786 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1787 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1789 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1790 const MCSectionELF &Section = *Sections[i];
1791 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1793 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1795 // Remember the offset into the file for this section.
1796 SectionOffsetMap[&Section] = FileOff;
1798 // Get the size of the section in the output file (including padding).
1799 FileOff += GetSectionFileSize(Layout, SD);
1802 // Write out the ELF header ...
1803 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1805 // ... then the regular sections ...
1806 // + because of .shstrtab
1807 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1808 WriteDataSectionData(Asm, Layout, *Sections[i]);
1810 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1811 WriteZeros(Padding);
1813 // ... then the section header table ...
1814 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1817 // ... and then the remaining sections ...
1818 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1819 WriteDataSectionData(Asm, Layout, *Sections[i]);
1823 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1824 const MCSymbolData &DataA,
1825 const MCFragment &FB,
1827 bool IsPCRel) const {
1828 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1830 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1831 Asm, DataA, FB,InSet, IsPCRel);
1834 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1836 bool IsLittleEndian) {
1837 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);