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/Support/Compression.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
40 #define DEBUG_TYPE "reloc-info"
43 class FragmentWriter {
47 FragmentWriter(bool IsLittleEndian);
48 template <typename T> void write(MCDataFragment &F, T Val);
51 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
53 class SymbolTableWriter {
55 FragmentWriter &FWriter;
57 SectionIndexMapTy &SectionIndexMap;
59 // The symbol .symtab fragment we are writting to.
60 MCDataFragment *SymtabF;
62 // .symtab_shndx fragment we are writting to.
63 MCDataFragment *ShndxF;
65 // The numbel of symbols written so far.
68 void createSymtabShndx();
70 template <typename T> void write(MCDataFragment &F, T Value);
73 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
74 SectionIndexMapTy &SectionIndexMap,
75 MCDataFragment *SymtabF);
77 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
78 uint8_t other, uint32_t shndx, bool Reserved);
81 struct ELFRelocationEntry {
82 uint64_t Offset; // Where is the relocation.
83 bool UseSymbol; // Relocate with a symbol, not the section.
85 const MCSymbol *Symbol; // The symbol to relocate with.
86 const MCSectionData *Section; // The section to relocate with.
88 unsigned Type; // The type of the relocation.
89 uint64_t Addend; // The addend to use.
91 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
93 : Offset(Offset), UseSymbol(true), Symbol(Symbol), Type(Type),
96 ELFRelocationEntry(uint64_t Offset, const MCSectionData *Section,
97 unsigned Type, uint64_t Addend)
98 : Offset(Offset), UseSymbol(false), Section(Section), Type(Type),
102 class ELFObjectWriter : public MCObjectWriter {
103 FragmentWriter FWriter;
107 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
108 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
109 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
110 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
111 bool Used, bool Renamed);
112 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
113 static bool IsELFMetaDataSection(const MCSectionData &SD);
114 static uint64_t DataSectionSize(const MCSectionData &SD);
115 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
116 const MCSectionData &SD);
117 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
118 const MCSectionData &SD);
120 void WriteDataSectionData(MCAssembler &Asm,
121 const MCAsmLayout &Layout,
122 const MCSectionELF &Section);
124 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
125 return Kind == X86::reloc_riprel_4byte ||
126 Kind == X86::reloc_riprel_4byte_movq_load;
129 /// ELFSymbolData - Helper struct for containing some precomputed
130 /// information on symbols.
131 struct ELFSymbolData {
132 MCSymbolData *SymbolData;
133 uint64_t StringIndex;
134 uint32_t SectionIndex;
136 // Support lexicographic sorting.
137 bool operator<(const ELFSymbolData &RHS) const {
138 return SymbolData->getSymbol().getName() <
139 RHS.SymbolData->getSymbol().getName();
143 /// The target specific ELF writer instance.
144 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
146 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
147 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
148 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
150 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
152 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
155 /// @name Symbol Table Data
158 SmallString<256> StringTable;
159 std::vector<uint64_t> FileSymbolData;
160 std::vector<ELFSymbolData> LocalSymbolData;
161 std::vector<ELFSymbolData> ExternalSymbolData;
162 std::vector<ELFSymbolData> UndefinedSymbolData;
168 // This holds the symbol table index of the last local symbol.
169 unsigned LastLocalSymbolIndex;
170 // This holds the .strtab section index.
171 unsigned StringTableIndex;
172 // This holds the .symtab section index.
173 unsigned SymbolTableIndex;
175 unsigned ShstrtabIndex;
178 // TargetObjectWriter wrappers.
179 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
180 bool hasRelocationAddend() const {
181 return TargetObjectWriter->hasRelocationAddend();
183 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
184 bool IsPCRel) const {
185 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
189 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
191 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
192 TargetObjectWriter(MOTW), NeedsGOT(false) {}
194 virtual ~ELFObjectWriter();
196 void WriteWord(uint64_t W) {
203 template <typename T> void write(MCDataFragment &F, T Value) {
204 FWriter.write(F, Value);
207 void WriteHeader(const MCAssembler &Asm,
208 uint64_t SectionDataSize,
209 unsigned NumberOfSections);
211 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
212 const MCAsmLayout &Layout);
214 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
215 const MCAsmLayout &Layout,
216 SectionIndexMapTy &SectionIndexMap);
218 bool shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
219 const MCSymbolData *SD, uint64_t C,
220 unsigned Type) const;
222 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
223 const MCFragment *Fragment, const MCFixup &Fixup,
224 MCValue Target, bool &IsPCRel,
225 uint64_t &FixedValue) override;
227 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
230 // Map from a group section to the signature symbol
231 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
232 // Map from a signature symbol to the group section
233 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
234 // Map from a section to the section with the relocations
235 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
236 // Map from a section to its offset
237 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
239 /// Compute the symbol table data
241 /// \param Asm - The assembler.
242 /// \param SectionIndexMap - Maps a section to its index.
243 /// \param RevGroupMap - Maps a signature symbol to the group section.
244 /// \param NumRegularSections - Number of non-relocation sections.
245 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
246 const SectionIndexMapTy &SectionIndexMap,
247 RevGroupMapTy RevGroupMap,
248 unsigned NumRegularSections);
250 void ComputeIndexMap(MCAssembler &Asm,
251 SectionIndexMapTy &SectionIndexMap,
252 const RelMapTy &RelMap);
254 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
257 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
259 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
260 const RelMapTy &RelMap);
262 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
263 SectionIndexMapTy &SectionIndexMap,
264 const RelMapTy &RelMap);
266 // Create the sections that show up in the symbol table. Currently
267 // those are the .note.GNU-stack section and the group sections.
268 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
269 GroupMapTy &GroupMap,
270 RevGroupMapTy &RevGroupMap,
271 SectionIndexMapTy &SectionIndexMap,
272 const RelMapTy &RelMap);
274 void ExecutePostLayoutBinding(MCAssembler &Asm,
275 const MCAsmLayout &Layout) override;
277 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
278 const MCAsmLayout &Layout,
279 const SectionIndexMapTy &SectionIndexMap,
280 const SectionOffsetMapTy &SectionOffsetMap);
282 void ComputeSectionOrder(MCAssembler &Asm,
283 std::vector<const MCSectionELF*> &Sections);
285 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
286 uint64_t Address, uint64_t Offset,
287 uint64_t Size, uint32_t Link, uint32_t Info,
288 uint64_t Alignment, uint64_t EntrySize);
290 void WriteRelocationsFragment(const MCAssembler &Asm,
292 const MCSectionData *SD);
295 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
296 const MCSymbolData &DataA,
297 const MCFragment &FB,
299 bool IsPCRel) const override;
301 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
302 void WriteSection(MCAssembler &Asm,
303 const SectionIndexMapTy &SectionIndexMap,
304 uint32_t GroupSymbolIndex,
305 uint64_t Offset, uint64_t Size, uint64_t Alignment,
306 const MCSectionELF &Section);
310 FragmentWriter::FragmentWriter(bool IsLittleEndian)
311 : IsLittleEndian(IsLittleEndian) {}
313 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
315 Val = support::endian::byte_swap<T, support::little>(Val);
317 Val = support::endian::byte_swap<T, support::big>(Val);
318 const char *Start = (const char *)&Val;
319 F.getContents().append(Start, Start + sizeof(T));
322 void SymbolTableWriter::createSymtabShndx() {
326 MCContext &Ctx = Asm.getContext();
327 const MCSectionELF *SymtabShndxSection =
328 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
329 SectionKind::getReadOnly(), 4, "");
330 MCSectionData *SymtabShndxSD =
331 &Asm.getOrCreateSectionData(*SymtabShndxSection);
332 SymtabShndxSD->setAlignment(4);
333 ShndxF = new MCDataFragment(SymtabShndxSD);
334 unsigned Index = SectionIndexMap.size() + 1;
335 SectionIndexMap[SymtabShndxSection] = Index;
337 for (unsigned I = 0; I < NumWritten; ++I)
338 write(*ShndxF, uint32_t(0));
341 template <typename T>
342 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
343 FWriter.write(F, Value);
346 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
348 SectionIndexMapTy &SectionIndexMap,
349 MCDataFragment *SymtabF)
350 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
351 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
354 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
355 uint64_t size, uint8_t other,
356 uint32_t shndx, bool Reserved) {
357 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
364 write(*ShndxF, shndx);
366 write(*ShndxF, uint32_t(0));
369 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
371 raw_svector_ostream OS(SymtabF->getContents());
374 write(*SymtabF, name); // st_name
375 write(*SymtabF, info); // st_info
376 write(*SymtabF, other); // st_other
377 write(*SymtabF, Index); // st_shndx
378 write(*SymtabF, value); // st_value
379 write(*SymtabF, size); // st_size
381 write(*SymtabF, name); // st_name
382 write(*SymtabF, uint32_t(value)); // st_value
383 write(*SymtabF, uint32_t(size)); // st_size
384 write(*SymtabF, info); // st_info
385 write(*SymtabF, other); // st_other
386 write(*SymtabF, Index); // st_shndx
392 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
393 const MCFixupKindInfo &FKI =
394 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
396 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
399 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
403 case MCSymbolRefExpr::VK_GOT:
404 case MCSymbolRefExpr::VK_PLT:
405 case MCSymbolRefExpr::VK_GOTPCREL:
406 case MCSymbolRefExpr::VK_GOTOFF:
407 case MCSymbolRefExpr::VK_TPOFF:
408 case MCSymbolRefExpr::VK_TLSGD:
409 case MCSymbolRefExpr::VK_GOTTPOFF:
410 case MCSymbolRefExpr::VK_INDNTPOFF:
411 case MCSymbolRefExpr::VK_NTPOFF:
412 case MCSymbolRefExpr::VK_GOTNTPOFF:
413 case MCSymbolRefExpr::VK_TLSLDM:
414 case MCSymbolRefExpr::VK_DTPOFF:
415 case MCSymbolRefExpr::VK_TLSLD:
420 ELFObjectWriter::~ELFObjectWriter()
423 // Emit the ELF header.
424 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
425 uint64_t SectionDataSize,
426 unsigned NumberOfSections) {
432 // emitWord method behaves differently for ELF32 and ELF64, writing
433 // 4 bytes in the former and 8 in the latter.
435 Write8(0x7f); // e_ident[EI_MAG0]
436 Write8('E'); // e_ident[EI_MAG1]
437 Write8('L'); // e_ident[EI_MAG2]
438 Write8('F'); // e_ident[EI_MAG3]
440 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
443 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
445 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
447 Write8(TargetObjectWriter->getOSABI());
448 Write8(0); // e_ident[EI_ABIVERSION]
450 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
452 Write16(ELF::ET_REL); // e_type
454 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
456 Write32(ELF::EV_CURRENT); // e_version
457 WriteWord(0); // e_entry, no entry point in .o file
458 WriteWord(0); // e_phoff, no program header for .o
459 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
460 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
462 // e_flags = whatever the target wants
463 Write32(Asm.getELFHeaderEFlags());
465 // e_ehsize = ELF header size
466 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
468 Write16(0); // e_phentsize = prog header entry size
469 Write16(0); // e_phnum = # prog header entries = 0
471 // e_shentsize = Section header entry size
472 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
474 // e_shnum = # of section header ents
475 if (NumberOfSections >= ELF::SHN_LORESERVE)
476 Write16(ELF::SHN_UNDEF);
478 Write16(NumberOfSections);
480 // e_shstrndx = Section # of '.shstrtab'
481 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
482 Write16(ELF::SHN_XINDEX);
484 Write16(ShstrtabIndex);
487 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
488 const MCAsmLayout &Layout) {
489 MCSymbolData *Data = &OrigData;
490 if (Data->isCommon() && Data->isExternal())
491 return Data->getCommonAlignment();
493 const MCSymbol *Symbol = &Data->getSymbol();
496 if (Symbol->isVariable()) {
497 const MCExpr *Expr = Symbol->getVariableValue();
499 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
500 llvm_unreachable("Invalid expression");
502 assert(!Value.getSymB());
504 Res = Value.getConstant();
506 if (const MCSymbolRefExpr *A = Value.getSymA()) {
507 Symbol = &A->getSymbol();
508 Data = &Layout.getAssembler().getSymbolData(*Symbol);
515 if ((Data && Data->getFlags() & ELF_Other_ThumbFunc) ||
516 OrigData.getFlags() & ELF_Other_ThumbFunc)
519 if (!Symbol || !Symbol->isInSection())
522 Res += Layout.getSymbolOffset(Data);
527 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
528 const MCAsmLayout &Layout) {
529 // The presence of symbol versions causes undefined symbols and
530 // versions declared with @@@ to be renamed.
532 for (MCSymbolData &OriginalData : Asm.symbols()) {
533 const MCSymbol &Alias = OriginalData.getSymbol();
534 const MCSymbol &Symbol = Alias.AliasedSymbol();
535 MCSymbolData &SD = Asm.getSymbolData(Symbol);
538 if (&Symbol == &Alias)
541 StringRef AliasName = Alias.getName();
542 size_t Pos = AliasName.find('@');
543 if (Pos == StringRef::npos)
546 // Aliases defined with .symvar copy the binding from the symbol they alias.
547 // This is the first place we are able to copy this information.
548 OriginalData.setExternal(SD.isExternal());
549 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
551 StringRef Rest = AliasName.substr(Pos);
552 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
555 // FIXME: produce a better error message.
556 if (Symbol.isUndefined() && Rest.startswith("@@") &&
557 !Rest.startswith("@@@"))
558 report_fatal_error("A @@ version cannot be undefined");
560 Renames.insert(std::make_pair(&Symbol, &Alias));
564 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
565 uint8_t Type = newType;
567 // Propagation rules:
568 // IFUNC > FUNC > OBJECT > NOTYPE
569 // TLS_OBJECT > OBJECT > NOTYPE
571 // dont let the new type degrade the old type
575 case ELF::STT_GNU_IFUNC:
576 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
577 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
578 Type = ELF::STT_GNU_IFUNC;
581 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
582 Type == ELF::STT_TLS)
583 Type = ELF::STT_FUNC;
585 case ELF::STT_OBJECT:
586 if (Type == ELF::STT_NOTYPE)
587 Type = ELF::STT_OBJECT;
590 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
591 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
599 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
600 const MCSymbol &Symbol) {
601 if (!Symbol.isVariable())
604 const MCExpr *Expr = Symbol.getVariableValue();
606 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
607 llvm_unreachable("Invalid Expression");
608 const MCSymbolRefExpr *RefB = Value.getSymB();
610 Layout.getAssembler().getContext().FatalError(
611 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
612 "' could not be evaluated in a subtraction expression");
614 const MCSymbolRefExpr *A = Value.getSymA();
617 return getBaseSymbol(Layout, A->getSymbol());
620 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
621 const MCAsmLayout &Layout) {
622 MCSymbolData &OrigData = *MSD.SymbolData;
623 assert((!OrigData.getFragment() ||
624 (&OrigData.getFragment()->getParent()->getSection() ==
625 &OrigData.getSymbol().getSection())) &&
626 "The symbol's section doesn't match the fragment's symbol");
627 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
629 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
631 bool IsReserved = !Base || OrigData.isCommon();
633 // Binding and Type share the same byte as upper and lower nibbles
634 uint8_t Binding = MCELF::GetBinding(OrigData);
635 uint8_t Type = MCELF::GetType(OrigData);
636 MCSymbolData *BaseSD = nullptr;
638 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
639 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
641 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
642 Type = ELF::STT_FUNC;
643 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
645 // Other and Visibility share the same byte with Visibility using the lower
647 uint8_t Visibility = MCELF::GetVisibility(OrigData);
648 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
651 uint64_t Value = SymbolValue(OrigData, Layout);
654 const MCExpr *ESize = OrigData.getSize();
656 ESize = BaseSD->getSize();
660 if (!ESize->EvaluateAsAbsolute(Res, Layout))
661 report_fatal_error("Size expression must be absolute.");
665 // Write out the symbol table entry
666 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
667 MSD.SectionIndex, IsReserved);
670 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
672 const MCAsmLayout &Layout,
673 SectionIndexMapTy &SectionIndexMap) {
674 // The string table must be emitted first because we need the index
675 // into the string table for all the symbol names.
676 assert(StringTable.size() && "Missing string table");
678 // FIXME: Make sure the start of the symbol table is aligned.
680 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
682 // The first entry is the undefined symbol entry.
683 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
685 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
686 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
687 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
690 // Write the symbol table entries.
691 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
693 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
694 ELFSymbolData &MSD = LocalSymbolData[i];
695 WriteSymbol(Writer, MSD, Layout);
698 // Write out a symbol table entry for each regular section.
699 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
701 const MCSectionELF &Section =
702 static_cast<const MCSectionELF&>(i->getSection());
703 if (Section.getType() == ELF::SHT_RELA ||
704 Section.getType() == ELF::SHT_REL ||
705 Section.getType() == ELF::SHT_STRTAB ||
706 Section.getType() == ELF::SHT_SYMTAB ||
707 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
709 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
710 SectionIndexMap.lookup(&Section), false);
711 LastLocalSymbolIndex++;
714 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
715 ELFSymbolData &MSD = ExternalSymbolData[i];
716 MCSymbolData &Data = *MSD.SymbolData;
717 assert(((Data.getFlags() & ELF_STB_Global) ||
718 (Data.getFlags() & ELF_STB_Weak)) &&
719 "External symbol requires STB_GLOBAL or STB_WEAK flag");
720 WriteSymbol(Writer, MSD, Layout);
721 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
722 LastLocalSymbolIndex++;
725 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
726 ELFSymbolData &MSD = UndefinedSymbolData[i];
727 MCSymbolData &Data = *MSD.SymbolData;
728 WriteSymbol(Writer, MSD, Layout);
729 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
730 LastLocalSymbolIndex++;
734 // It is always valid to create a relocation with a symbol. It is preferable
735 // to use a relocation with a section if that is possible. Using the section
736 // allows us to omit some local symbols from the symbol table.
737 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
738 const MCSymbolData *SD,
740 unsigned Type) const {
741 // A PCRel relocation to an absolute value has no symbol (or section). We
742 // represent that with a relocation to a null section.
746 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
750 // The .odp creation emits a relocation against the symbol ".TOC." which
751 // create a R_PPC64_TOC relocation. However the relocation symbol name
752 // in final object creation should be NULL, since the symbol does not
753 // really exist, it is just the reference to TOC base for the current
754 // object file. Since the symbol is undefined, returning false results
755 // in a relocation with a null section which is the desired result.
756 case MCSymbolRefExpr::VK_PPC_TOCBASE:
759 // These VariantKind cause the relocation to refer to something other than
760 // the symbol itself, like a linker generated table. Since the address of
761 // symbol is not relevant, we cannot replace the symbol with the
762 // section and patch the difference in the addend.
763 case MCSymbolRefExpr::VK_GOT:
764 case MCSymbolRefExpr::VK_PLT:
765 case MCSymbolRefExpr::VK_GOTPCREL:
766 case MCSymbolRefExpr::VK_Mips_GOT:
767 case MCSymbolRefExpr::VK_PPC_GOT_LO:
768 case MCSymbolRefExpr::VK_PPC_GOT_HI:
769 case MCSymbolRefExpr::VK_PPC_GOT_HA:
773 // An undefined symbol is not in any section, so the relocation has to point
774 // to the symbol itself.
775 const MCSymbol &Sym = SD->getSymbol();
776 if (Sym.isUndefined())
779 unsigned Binding = MCELF::GetBinding(*SD);
782 llvm_unreachable("Invalid Binding");
786 // If the symbol is weak, it might be overridden by a symbol in another
787 // file. The relocation has to point to the symbol so that the linker
790 case ELF::STB_GLOBAL:
791 // Global ELF symbols can be preempted by the dynamic linker. The relocation
792 // has to point to the symbol for a reason analogous to the STB_WEAK case.
796 // If a relocation points to a mergeable section, we have to be careful.
797 // If the offset is zero, a relocation with the section will encode the
798 // same information. With a non-zero offset, the situation is different.
799 // For example, a relocation can point 42 bytes past the end of a string.
800 // If we change such a relocation to use the section, the linker would think
801 // that it pointed to another string and subtracting 42 at runtime will
802 // produce the wrong value.
803 auto &Sec = cast<MCSectionELF>(Sym.getSection());
804 unsigned Flags = Sec.getFlags();
805 if (Flags & ELF::SHF_MERGE) {
809 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
810 // only handle section relocations to mergeable sections if using RELA.
811 if (!hasRelocationAddend())
815 // Most TLS relocations use a got, so they need the symbol. Even those that
816 // are just an offset (@tpoff), require a symbol in some linkers (gold,
818 if (Flags & ELF::SHF_TLS)
821 // If the symbol is a thumb function the final relocation must set the lowest
822 // bit. With a symbol that is done by just having the symbol have that bit
823 // set, so we would lose the bit if we relocated with the section.
824 // FIXME: We could use the section but add the bit to the relocation value.
825 if (SD->getFlags() & ELF_Other_ThumbFunc)
828 if (TargetObjectWriter->needsRelocateWithSymbol(Type))
833 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
834 const MCAsmLayout &Layout,
835 const MCFragment *Fragment,
836 const MCFixup &Fixup,
839 uint64_t &FixedValue) {
840 const MCSectionData *FixupSection = Fragment->getParent();
841 uint64_t C = Target.getConstant();
842 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
844 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
845 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
846 "Should not have constructed this");
848 // Let A, B and C being the components of Target and R be the location of
849 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
850 // If it is pcrel, we want to compute (A - B + C - R).
852 // In general, ELF has no relocations for -B. It can only represent (A + C)
853 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
854 // replace B to implement it: (A - R - K + C)
856 Asm.getContext().FatalError(
858 "No relocation available to represent this relative expression");
860 const MCSymbol &SymB = RefB->getSymbol();
862 if (SymB.isUndefined())
863 Asm.getContext().FatalError(
865 Twine("symbol '") + SymB.getName() +
866 "' can not be undefined in a subtraction expression");
868 assert(!SymB.isAbsolute() && "Should have been folded");
869 const MCSection &SecB = SymB.getSection();
870 if (&SecB != &FixupSection->getSection())
871 Asm.getContext().FatalError(
872 Fixup.getLoc(), "Cannot represent a difference across sections");
874 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
875 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
876 uint64_t K = SymBOffset - FixupOffset;
881 // We either rejected the fixup or folded B into C at this point.
882 const MCSymbolRefExpr *RefA = Target.getSymA();
883 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
884 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
886 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
887 bool RelocateWithSymbol = shouldRelocateWithSymbol(RefA, SymAD, C, Type);
888 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
889 C += Layout.getSymbolOffset(SymAD);
892 if (hasRelocationAddend()) {
899 // FIXME: What is this!?!?
900 MCSymbolRefExpr::VariantKind Modifier =
901 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
902 if (RelocNeedsGOT(Modifier))
905 if (!RelocateWithSymbol) {
906 const MCSection *SecA =
907 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
908 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
909 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
910 Relocations[FixupSection].push_back(Rec);
915 if (const MCSymbol *R = Renames.lookup(SymA))
918 if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
919 WeakrefUsedInReloc.insert(SymA);
921 UsedInReloc.insert(SymA);
923 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
924 Relocations[FixupSection].push_back(Rec);
930 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
932 const MCSymbolData &SD = Asm.getSymbolData(*S);
933 return SD.getIndex();
936 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
937 const MCSymbolData &Data, bool Used,
939 const MCSymbol &Symbol = Data.getSymbol();
940 if (Symbol.isVariable()) {
941 const MCExpr *Expr = Symbol.getVariableValue();
942 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
943 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
954 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
957 if (Symbol.isVariable()) {
958 const MCSymbol *Base = getBaseSymbol(Layout, Symbol);
959 if (Base && Base->isUndefined())
963 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
964 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
967 if (Symbol.isTemporary())
973 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
974 if (Data.isExternal())
977 const MCSymbol &Symbol = Data.getSymbol();
978 if (Symbol.isDefined())
987 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
988 SectionIndexMapTy &SectionIndexMap,
989 const RelMapTy &RelMap) {
991 for (MCAssembler::iterator it = Asm.begin(),
992 ie = Asm.end(); it != ie; ++it) {
993 const MCSectionELF &Section =
994 static_cast<const MCSectionELF &>(it->getSection());
995 if (Section.getType() != ELF::SHT_GROUP)
997 SectionIndexMap[&Section] = Index++;
1000 for (MCAssembler::iterator it = Asm.begin(),
1001 ie = Asm.end(); it != ie; ++it) {
1002 const MCSectionELF &Section =
1003 static_cast<const MCSectionELF &>(it->getSection());
1004 if (Section.getType() == ELF::SHT_GROUP ||
1005 Section.getType() == ELF::SHT_REL ||
1006 Section.getType() == ELF::SHT_RELA)
1008 SectionIndexMap[&Section] = Index++;
1009 const MCSectionELF *RelSection = RelMap.lookup(&Section);
1011 SectionIndexMap[RelSection] = Index++;
1016 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1017 const SectionIndexMapTy &SectionIndexMap,
1018 RevGroupMapTy RevGroupMap,
1019 unsigned NumRegularSections) {
1020 // FIXME: Is this the correct place to do this?
1021 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1023 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1024 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1025 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1026 Data.setExternal(true);
1027 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1030 // Index 0 is always the empty string.
1031 StringMap<uint64_t> StringIndexMap;
1032 StringTable += '\x00';
1034 // FIXME: We could optimize suffixes in strtab in the same way we
1035 // optimize them in shstrtab.
1037 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
1038 ie = Asm.file_names_end();
1041 StringRef Name = *it;
1042 uint64_t &Entry = StringIndexMap[Name];
1044 Entry = StringTable.size();
1045 StringTable += Name;
1046 StringTable += '\x00';
1048 FileSymbolData.push_back(Entry);
1051 // Add the data for the symbols.
1052 for (MCSymbolData &SD : Asm.symbols()) {
1053 const MCSymbol &Symbol = SD.getSymbol();
1055 bool Used = UsedInReloc.count(&Symbol);
1056 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1057 bool isSignature = RevGroupMap.count(&Symbol);
1059 if (!isInSymtab(Layout, SD,
1060 Used || WeakrefUsed || isSignature,
1061 Renames.count(&Symbol)))
1065 MSD.SymbolData = &SD;
1066 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
1068 // Undefined symbols are global, but this is the first place we
1069 // are able to set it.
1070 bool Local = isLocal(SD, Used);
1071 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1073 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1074 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1075 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1079 MSD.SectionIndex = ELF::SHN_ABS;
1080 } else if (SD.isCommon()) {
1082 MSD.SectionIndex = ELF::SHN_COMMON;
1083 } else if (BaseSymbol->isUndefined()) {
1084 if (isSignature && !Used)
1085 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1087 MSD.SectionIndex = ELF::SHN_UNDEF;
1088 if (!Used && WeakrefUsed)
1089 MCELF::SetBinding(SD, ELF::STB_WEAK);
1091 const MCSectionELF &Section =
1092 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1093 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1094 assert(MSD.SectionIndex && "Invalid section index!");
1097 // The @@@ in symbol version is replaced with @ in undefined symbols and
1098 // @@ in defined ones.
1099 StringRef Name = Symbol.getName();
1100 SmallString<32> Buf;
1102 size_t Pos = Name.find("@@@");
1103 if (Pos != StringRef::npos) {
1104 Buf += Name.substr(0, Pos);
1105 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1106 Buf += Name.substr(Pos + Skip);
1110 uint64_t &Entry = StringIndexMap[Name];
1112 Entry = StringTable.size();
1113 StringTable += Name;
1114 StringTable += '\x00';
1116 MSD.StringIndex = Entry;
1117 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1118 UndefinedSymbolData.push_back(MSD);
1120 LocalSymbolData.push_back(MSD);
1122 ExternalSymbolData.push_back(MSD);
1125 // Symbols are required to be in lexicographic order.
1126 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1127 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1128 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1130 // Set the symbol indices. Local symbols must come before all other
1131 // symbols with non-local bindings.
1132 unsigned Index = FileSymbolData.size() + 1;
1133 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1134 LocalSymbolData[i].SymbolData->setIndex(Index++);
1136 Index += NumRegularSections;
1138 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1139 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1140 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1141 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1144 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1145 MCAsmLayout &Layout,
1147 for (MCAssembler::const_iterator it = Asm.begin(),
1148 ie = Asm.end(); it != ie; ++it) {
1149 const MCSectionData &SD = *it;
1150 if (Relocations[&SD].empty())
1153 MCContext &Ctx = Asm.getContext();
1154 const MCSectionELF &Section =
1155 static_cast<const MCSectionELF&>(SD.getSection());
1157 const StringRef SectionName = Section.getSectionName();
1158 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1159 RelaSectionName += SectionName;
1162 if (hasRelocationAddend())
1163 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1165 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1168 StringRef Group = "";
1169 if (Section.getFlags() & ELF::SHF_GROUP) {
1170 Flags = ELF::SHF_GROUP;
1171 Group = Section.getGroup()->getName();
1174 const MCSectionELF *RelaSection =
1175 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1176 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1177 SectionKind::getReadOnly(),
1179 RelMap[&Section] = RelaSection;
1180 Asm.getOrCreateSectionData(*RelaSection);
1184 static SmallVector<char, 128>
1185 getUncompressedData(MCAsmLayout &Layout,
1186 MCSectionData::FragmentListType &Fragments) {
1187 SmallVector<char, 128> UncompressedData;
1188 for (const MCFragment &F : Fragments) {
1189 const SmallVectorImpl<char> *Contents;
1190 switch (F.getKind()) {
1191 case MCFragment::FT_Data:
1192 Contents = &cast<MCDataFragment>(F).getContents();
1194 case MCFragment::FT_Dwarf:
1195 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1197 case MCFragment::FT_DwarfFrame:
1198 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1202 "Not expecting any other fragment types in a debug_* section");
1204 UncompressedData.append(Contents->begin(), Contents->end());
1206 return UncompressedData;
1209 // Include the debug info compression header:
1210 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1211 // useful for consumers to preallocate a buffer to decompress into.
1213 prependCompressionHeader(uint64_t Size,
1214 SmallVectorImpl<char> &CompressedContents) {
1215 static const StringRef Magic = "ZLIB";
1216 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1218 if (sys::IsLittleEndianHost)
1219 Size = sys::SwapByteOrder(Size);
1220 CompressedContents.insert(CompressedContents.begin(),
1221 Magic.size() + sizeof(Size), 0);
1222 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1223 std::copy(reinterpret_cast<char *>(&Size),
1224 reinterpret_cast<char *>(&Size + 1),
1225 CompressedContents.begin() + Magic.size());
1229 // Return a single fragment containing the compressed contents of the whole
1230 // section. Null if the section was not compressed for any reason.
1231 static std::unique_ptr<MCDataFragment>
1232 getCompressedFragment(MCAsmLayout &Layout,
1233 MCSectionData::FragmentListType &Fragments) {
1234 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1236 // Gather the uncompressed data from all the fragments, recording the
1237 // alignment fragment, if seen, and any fixups.
1238 SmallVector<char, 128> UncompressedData =
1239 getUncompressedData(Layout, Fragments);
1241 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1243 zlib::Status Success = zlib::compress(
1244 StringRef(UncompressedData.data(), UncompressedData.size()),
1245 CompressedContents);
1246 if (Success != zlib::StatusOK)
1249 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1252 return CompressedFragment;
1255 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1258 static void UpdateSymbols(const MCAsmLayout &Layout,
1259 const std::vector<MCSymbolData *> &Symbols,
1260 MCFragment &NewFragment) {
1261 for (MCSymbolData *Sym : Symbols) {
1262 Sym->setOffset(Sym->getOffset() +
1263 Layout.getFragmentOffset(Sym->getFragment()));
1264 Sym->setFragment(&NewFragment);
1268 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1269 const DefiningSymbolMap &DefiningSymbols,
1270 const MCSectionELF &Section,
1271 MCSectionData &SD) {
1272 StringRef SectionName = Section.getSectionName();
1273 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1275 std::unique_ptr<MCDataFragment> CompressedFragment =
1276 getCompressedFragment(Layout, Fragments);
1278 // Leave the section as-is if the fragments could not be compressed.
1279 if (!CompressedFragment)
1282 // Update the fragment+offsets of any symbols referring to fragments in this
1283 // section to refer to the new fragment.
1284 auto I = DefiningSymbols.find(&SD);
1285 if (I != DefiningSymbols.end())
1286 UpdateSymbols(Layout, I->second, *CompressedFragment);
1288 // Invalidate the layout for the whole section since it will have new and
1289 // different fragments now.
1290 Layout.invalidateFragmentsFrom(&Fragments.front());
1293 // Complete the initialization of the new fragment
1294 CompressedFragment->setParent(&SD);
1295 CompressedFragment->setLayoutOrder(0);
1296 Fragments.push_back(CompressedFragment.release());
1298 // Rename from .debug_* to .zdebug_*
1299 Asm.getContext().renameELFSection(&Section,
1300 (".z" + SectionName.drop_front(1)).str());
1303 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1304 MCAsmLayout &Layout) {
1305 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1308 DefiningSymbolMap DefiningSymbols;
1310 for (MCSymbolData &SD : Asm.symbols())
1311 if (MCFragment *F = SD.getFragment())
1312 DefiningSymbols[F->getParent()].push_back(&SD);
1314 for (MCSectionData &SD : Asm) {
1315 const MCSectionELF &Section =
1316 static_cast<const MCSectionELF &>(SD.getSection());
1317 StringRef SectionName = Section.getSectionName();
1319 // Compressing debug_frame requires handling alignment fragments which is
1320 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1321 // for writing to arbitrary buffers) for little benefit.
1322 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1325 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1329 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1330 const RelMapTy &RelMap) {
1331 for (MCAssembler::const_iterator it = Asm.begin(),
1332 ie = Asm.end(); it != ie; ++it) {
1333 const MCSectionData &SD = *it;
1334 const MCSectionELF &Section =
1335 static_cast<const MCSectionELF&>(SD.getSection());
1337 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1340 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1341 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1343 MCDataFragment *F = new MCDataFragment(&RelaSD);
1344 WriteRelocationsFragment(Asm, F, &*it);
1348 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1349 uint64_t Flags, uint64_t Address,
1350 uint64_t Offset, uint64_t Size,
1351 uint32_t Link, uint32_t Info,
1353 uint64_t EntrySize) {
1354 Write32(Name); // sh_name: index into string table
1355 Write32(Type); // sh_type
1356 WriteWord(Flags); // sh_flags
1357 WriteWord(Address); // sh_addr
1358 WriteWord(Offset); // sh_offset
1359 WriteWord(Size); // sh_size
1360 Write32(Link); // sh_link
1361 Write32(Info); // sh_info
1362 WriteWord(Alignment); // sh_addralign
1363 WriteWord(EntrySize); // sh_entsize
1366 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1367 // just to match gnu as for easier comparison. The use type is an arbitrary way
1368 // of making the sort deterministic.
1369 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1370 const ELFRelocationEntry &A = *AP;
1371 const ELFRelocationEntry &B = *BP;
1372 if (A.Offset != B.Offset)
1373 return B.Offset - A.Offset;
1374 if (B.Type != A.Type)
1375 return A.Type - B.Type;
1376 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];
1395 if (Entry.UseSymbol) {
1396 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1398 const MCSectionData *Sec = Entry.Section;
1400 Index = Sec->getOrdinal() + FileSymbolData.size() +
1401 LocalSymbolData.size() + 1;
1407 write(*F, Entry.Offset);
1408 if (TargetObjectWriter->isN64()) {
1409 write(*F, uint32_t(Index));
1411 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1412 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1413 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1414 write(*F, TargetObjectWriter->getRType(Entry.Type));
1416 struct ELF::Elf64_Rela ERE64;
1417 ERE64.setSymbolAndType(Index, Entry.Type);
1418 write(*F, ERE64.r_info);
1420 if (hasRelocationAddend())
1421 write(*F, Entry.Addend);
1423 write(*F, uint32_t(Entry.Offset));
1425 struct ELF::Elf32_Rela ERE32;
1426 ERE32.setSymbolAndType(Index, Entry.Type);
1427 write(*F, ERE32.r_info);
1429 if (hasRelocationAddend())
1430 write(*F, uint32_t(Entry.Addend));
1435 static int compareBySuffix(const MCSectionELF *const *a,
1436 const MCSectionELF *const *b) {
1437 const StringRef &NameA = (*a)->getSectionName();
1438 const StringRef &NameB = (*b)->getSectionName();
1439 const unsigned sizeA = NameA.size();
1440 const unsigned sizeB = NameB.size();
1441 const unsigned len = std::min(sizeA, sizeB);
1442 for (unsigned int i = 0; i < len; ++i) {
1443 char ca = NameA[sizeA - i - 1];
1444 char cb = NameB[sizeB - i - 1];
1449 return sizeB - sizeA;
1452 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1453 MCAsmLayout &Layout,
1454 SectionIndexMapTy &SectionIndexMap,
1455 const RelMapTy &RelMap) {
1456 MCContext &Ctx = Asm.getContext();
1459 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1461 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1462 const MCSectionELF *ShstrtabSection =
1463 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1464 SectionKind::getReadOnly());
1465 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1466 ShstrtabSD.setAlignment(1);
1468 const MCSectionELF *SymtabSection =
1469 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1470 SectionKind::getReadOnly(),
1472 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1473 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1475 const MCSectionELF *StrtabSection;
1476 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1477 SectionKind::getReadOnly());
1478 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1479 StrtabSD.setAlignment(1);
1481 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1483 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1484 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1485 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1488 F = new MCDataFragment(&SymtabSD);
1489 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1491 F = new MCDataFragment(&StrtabSD);
1492 F->getContents().append(StringTable.begin(), StringTable.end());
1494 F = new MCDataFragment(&ShstrtabSD);
1496 std::vector<const MCSectionELF*> Sections;
1497 for (MCAssembler::const_iterator it = Asm.begin(),
1498 ie = Asm.end(); it != ie; ++it) {
1499 const MCSectionELF &Section =
1500 static_cast<const MCSectionELF&>(it->getSection());
1501 Sections.push_back(&Section);
1503 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1505 // Section header string table.
1507 // The first entry of a string table holds a null character so skip
1510 F->getContents().push_back('\x00');
1512 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1513 const MCSectionELF &Section = *Sections[I];
1515 StringRef Name = Section.getSectionName();
1517 StringRef PreviousName = Sections[I - 1]->getSectionName();
1518 if (PreviousName.endswith(Name)) {
1519 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1523 // Remember the index into the string table so we can write it
1524 // into the sh_name field of the section header table.
1525 SectionStringTableIndex[&Section] = Index;
1527 Index += Name.size() + 1;
1528 F->getContents().append(Name.begin(), Name.end());
1529 F->getContents().push_back('\x00');
1533 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1534 MCAsmLayout &Layout,
1535 GroupMapTy &GroupMap,
1536 RevGroupMapTy &RevGroupMap,
1537 SectionIndexMapTy &SectionIndexMap,
1538 const RelMapTy &RelMap) {
1539 // Create the .note.GNU-stack section if needed.
1540 MCContext &Ctx = Asm.getContext();
1541 if (Asm.getNoExecStack()) {
1542 const MCSectionELF *GnuStackSection =
1543 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1544 SectionKind::getReadOnly());
1545 Asm.getOrCreateSectionData(*GnuStackSection);
1549 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1551 const MCSectionELF &Section =
1552 static_cast<const MCSectionELF&>(it->getSection());
1553 if (!(Section.getFlags() & ELF::SHF_GROUP))
1556 const MCSymbol *SignatureSymbol = Section.getGroup();
1557 Asm.getOrCreateSymbolData(*SignatureSymbol);
1558 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1560 Group = Ctx.CreateELFGroupSection();
1561 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1562 Data.setAlignment(4);
1563 MCDataFragment *F = new MCDataFragment(&Data);
1564 write(*F, uint32_t(ELF::GRP_COMDAT));
1566 GroupMap[Group] = SignatureSymbol;
1569 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1571 // Add sections to the groups
1572 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1574 const MCSectionELF &Section =
1575 static_cast<const MCSectionELF&>(it->getSection());
1576 if (!(Section.getFlags() & ELF::SHF_GROUP))
1578 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1579 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1580 // FIXME: we could use the previous fragment
1581 MCDataFragment *F = new MCDataFragment(&Data);
1582 uint32_t Index = SectionIndexMap.lookup(&Section);
1587 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1588 const SectionIndexMapTy &SectionIndexMap,
1589 uint32_t GroupSymbolIndex,
1590 uint64_t Offset, uint64_t Size,
1592 const MCSectionELF &Section) {
1593 uint64_t sh_link = 0;
1594 uint64_t sh_info = 0;
1596 switch(Section.getType()) {
1597 case ELF::SHT_DYNAMIC:
1598 sh_link = SectionStringTableIndex[&Section];
1603 case ELF::SHT_RELA: {
1604 const MCSectionELF *SymtabSection;
1605 const MCSectionELF *InfoSection;
1606 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1608 SectionKind::getReadOnly());
1609 sh_link = SectionIndexMap.lookup(SymtabSection);
1610 assert(sh_link && ".symtab not found");
1612 // Remove ".rel" and ".rela" prefixes.
1613 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1614 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1615 StringRef GroupName =
1616 Section.getGroup() ? Section.getGroup()->getName() : "";
1618 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1619 0, SectionKind::getReadOnly(),
1621 sh_info = SectionIndexMap.lookup(InfoSection);
1625 case ELF::SHT_SYMTAB:
1626 case ELF::SHT_DYNSYM:
1627 sh_link = StringTableIndex;
1628 sh_info = LastLocalSymbolIndex;
1631 case ELF::SHT_SYMTAB_SHNDX:
1632 sh_link = SymbolTableIndex;
1635 case ELF::SHT_PROGBITS:
1636 case ELF::SHT_STRTAB:
1637 case ELF::SHT_NOBITS:
1640 case ELF::SHT_ARM_ATTRIBUTES:
1641 case ELF::SHT_INIT_ARRAY:
1642 case ELF::SHT_FINI_ARRAY:
1643 case ELF::SHT_PREINIT_ARRAY:
1644 case ELF::SHT_X86_64_UNWIND:
1645 case ELF::SHT_MIPS_REGINFO:
1646 case ELF::SHT_MIPS_OPTIONS:
1650 case ELF::SHT_GROUP:
1651 sh_link = SymbolTableIndex;
1652 sh_info = GroupSymbolIndex;
1656 assert(0 && "FIXME: sh_type value not supported!");
1660 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1661 Section.getType() == ELF::SHT_ARM_EXIDX) {
1662 StringRef SecName(Section.getSectionName());
1663 if (SecName == ".ARM.exidx") {
1664 sh_link = SectionIndexMap.lookup(
1665 Asm.getContext().getELFSection(".text",
1667 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1668 SectionKind::getText()));
1669 } else if (SecName.startswith(".ARM.exidx")) {
1670 StringRef GroupName =
1671 Section.getGroup() ? Section.getGroup()->getName() : "";
1672 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1673 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1674 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1679 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1680 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1681 Alignment, Section.getEntrySize());
1684 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1685 return SD.getOrdinal() == ~UINT32_C(0) &&
1686 !SD.getSection().isVirtualSection();
1689 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1691 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1693 const MCFragment &F = *i;
1694 assert(F.getKind() == MCFragment::FT_Data);
1695 Ret += cast<MCDataFragment>(F).getContents().size();
1700 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1701 const MCSectionData &SD) {
1702 if (IsELFMetaDataSection(SD))
1703 return DataSectionSize(SD);
1704 return Layout.getSectionFileSize(&SD);
1707 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1708 const MCSectionData &SD) {
1709 if (IsELFMetaDataSection(SD))
1710 return DataSectionSize(SD);
1711 return Layout.getSectionAddressSize(&SD);
1714 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1715 const MCAsmLayout &Layout,
1716 const MCSectionELF &Section) {
1717 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1719 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1720 WriteZeros(Padding);
1722 if (IsELFMetaDataSection(SD)) {
1723 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1725 const MCFragment &F = *i;
1726 assert(F.getKind() == MCFragment::FT_Data);
1727 WriteBytes(cast<MCDataFragment>(F).getContents());
1730 Asm.writeSectionData(&SD, Layout);
1734 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1735 const GroupMapTy &GroupMap,
1736 const MCAsmLayout &Layout,
1737 const SectionIndexMapTy &SectionIndexMap,
1738 const SectionOffsetMapTy &SectionOffsetMap) {
1739 const unsigned NumSections = Asm.size() + 1;
1741 std::vector<const MCSectionELF*> Sections;
1742 Sections.resize(NumSections - 1);
1744 for (SectionIndexMapTy::const_iterator i=
1745 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1746 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1747 Sections[p.second - 1] = p.first;
1750 // Null section first.
1751 uint64_t FirstSectionSize =
1752 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1753 uint32_t FirstSectionLink =
1754 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1755 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1757 for (unsigned i = 0; i < NumSections - 1; ++i) {
1758 const MCSectionELF &Section = *Sections[i];
1759 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1760 uint32_t GroupSymbolIndex;
1761 if (Section.getType() != ELF::SHT_GROUP)
1762 GroupSymbolIndex = 0;
1764 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1765 GroupMap.lookup(&Section));
1767 uint64_t Size = GetSectionAddressSize(Layout, SD);
1769 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1770 SectionOffsetMap.lookup(&Section), Size,
1771 SD.getAlignment(), Section);
1775 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1776 std::vector<const MCSectionELF*> &Sections) {
1777 for (MCAssembler::iterator it = Asm.begin(),
1778 ie = Asm.end(); it != ie; ++it) {
1779 const MCSectionELF &Section =
1780 static_cast<const MCSectionELF &>(it->getSection());
1781 if (Section.getType() == ELF::SHT_GROUP)
1782 Sections.push_back(&Section);
1785 for (MCAssembler::iterator it = Asm.begin(),
1786 ie = Asm.end(); it != ie; ++it) {
1787 const MCSectionELF &Section =
1788 static_cast<const MCSectionELF &>(it->getSection());
1789 if (Section.getType() != ELF::SHT_GROUP &&
1790 Section.getType() != ELF::SHT_REL &&
1791 Section.getType() != ELF::SHT_RELA)
1792 Sections.push_back(&Section);
1795 for (MCAssembler::iterator it = Asm.begin(),
1796 ie = Asm.end(); it != ie; ++it) {
1797 const MCSectionELF &Section =
1798 static_cast<const MCSectionELF &>(it->getSection());
1799 if (Section.getType() == ELF::SHT_REL ||
1800 Section.getType() == ELF::SHT_RELA)
1801 Sections.push_back(&Section);
1805 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1806 const MCAsmLayout &Layout) {
1807 GroupMapTy GroupMap;
1808 RevGroupMapTy RevGroupMap;
1809 SectionIndexMapTy SectionIndexMap;
1811 unsigned NumUserSections = Asm.size();
1813 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1815 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1816 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1818 const unsigned NumUserAndRelocSections = Asm.size();
1819 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1820 RevGroupMap, SectionIndexMap, RelMap);
1821 const unsigned AllSections = Asm.size();
1822 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1824 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1826 // Compute symbol table information.
1827 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1828 NumRegularSections);
1830 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1832 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1833 const_cast<MCAsmLayout&>(Layout),
1837 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1838 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1839 sizeof(ELF::Elf32_Ehdr);
1840 uint64_t FileOff = HeaderSize;
1842 std::vector<const MCSectionELF*> Sections;
1843 ComputeSectionOrder(Asm, Sections);
1844 unsigned NumSections = Sections.size();
1845 SectionOffsetMapTy SectionOffsetMap;
1846 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1847 const MCSectionELF &Section = *Sections[i];
1848 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1850 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1852 // Remember the offset into the file for this section.
1853 SectionOffsetMap[&Section] = FileOff;
1855 // Get the size of the section in the output file (including padding).
1856 FileOff += GetSectionFileSize(Layout, SD);
1859 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1861 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1863 uint64_t SectionHeaderEntrySize = is64Bit() ?
1864 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1865 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1867 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1868 const MCSectionELF &Section = *Sections[i];
1869 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1871 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1873 // Remember the offset into the file for this section.
1874 SectionOffsetMap[&Section] = FileOff;
1876 // Get the size of the section in the output file (including padding).
1877 FileOff += GetSectionFileSize(Layout, SD);
1880 // Write out the ELF header ...
1881 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1883 // ... then the regular sections ...
1884 // + because of .shstrtab
1885 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1886 WriteDataSectionData(Asm, Layout, *Sections[i]);
1888 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1889 WriteZeros(Padding);
1891 // ... then the section header table ...
1892 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1895 // ... and then the remaining sections ...
1896 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1897 WriteDataSectionData(Asm, Layout, *Sections[i]);
1901 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1902 const MCSymbolData &DataA,
1903 const MCFragment &FB,
1905 bool IsPCRel) const {
1906 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1908 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1909 Asm, DataA, FB,InSet, IsPCRel);
1912 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1914 bool IsLittleEndian) {
1915 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);