1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
41 #define DEBUG_TYPE "reloc-info"
44 class FragmentWriter {
48 FragmentWriter(bool IsLittleEndian);
49 template <typename T> void write(MCDataFragment &F, T Val);
52 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
54 class SymbolTableWriter {
56 FragmentWriter &FWriter;
58 SectionIndexMapTy &SectionIndexMap;
60 // The symbol .symtab fragment we are writting to.
61 MCDataFragment *SymtabF;
63 // .symtab_shndx fragment we are writting to.
64 MCDataFragment *ShndxF;
66 // The numbel of symbols written so far.
69 void createSymtabShndx();
71 template <typename T> void write(MCDataFragment &F, T Value);
74 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75 SectionIndexMapTy &SectionIndexMap,
76 MCDataFragment *SymtabF);
78 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79 uint8_t other, uint32_t shndx, bool Reserved);
82 class ELFObjectWriter : public MCObjectWriter {
83 FragmentWriter FWriter;
87 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
88 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
89 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
90 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
91 bool Used, bool Renamed);
92 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
93 static bool IsELFMetaDataSection(const MCSectionData &SD);
94 static uint64_t DataSectionSize(const MCSectionData &SD);
95 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
97 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
98 const MCSectionData &SD);
100 void WriteDataSectionData(MCAssembler &Asm,
101 const MCAsmLayout &Layout,
102 const MCSectionELF &Section);
104 /// Helper struct for containing some precomputed information on symbols.
105 struct ELFSymbolData {
106 MCSymbolData *SymbolData;
107 uint64_t StringIndex;
108 uint32_t SectionIndex;
111 // Support lexicographic sorting.
112 bool operator<(const ELFSymbolData &RHS) const {
113 unsigned LHSType = MCELF::GetType(*SymbolData);
114 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
115 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
117 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
119 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
120 return SectionIndex < RHS.SectionIndex;
121 return Name < RHS.Name;
125 /// The target specific ELF writer instance.
126 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
128 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
129 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
130 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
132 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
134 StringTableBuilder ShStrTabBuilder;
137 /// @name Symbol Table Data
140 StringTableBuilder StrTabBuilder;
141 std::vector<uint64_t> FileSymbolData;
142 std::vector<ELFSymbolData> LocalSymbolData;
143 std::vector<ELFSymbolData> ExternalSymbolData;
144 std::vector<ELFSymbolData> UndefinedSymbolData;
150 // This holds the symbol table index of the last local symbol.
151 unsigned LastLocalSymbolIndex;
152 // This holds the .strtab section index.
153 unsigned StringTableIndex;
154 // This holds the .symtab section index.
155 unsigned SymbolTableIndex;
157 unsigned ShstrtabIndex;
160 // TargetObjectWriter wrappers.
161 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
162 bool hasRelocationAddend() const {
163 return TargetObjectWriter->hasRelocationAddend();
165 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
166 bool IsPCRel) const {
167 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
171 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
173 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
174 TargetObjectWriter(MOTW), NeedsGOT(false) {}
176 void reset() override {
178 WeakrefUsedInReloc.clear();
181 ShStrTabBuilder.clear();
182 StrTabBuilder.clear();
183 FileSymbolData.clear();
184 LocalSymbolData.clear();
185 ExternalSymbolData.clear();
186 UndefinedSymbolData.clear();
187 MCObjectWriter::reset();
190 ~ELFObjectWriter() override;
192 void WriteWord(uint64_t W) {
199 template <typename T> void write(MCDataFragment &F, T Value) {
200 FWriter.write(F, Value);
203 void WriteHeader(const MCAssembler &Asm,
204 uint64_t SectionHeaderOffset,
205 unsigned NumberOfSections);
207 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
208 const MCAsmLayout &Layout);
210 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
211 const MCAsmLayout &Layout,
212 SectionIndexMapTy &SectionIndexMap);
214 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
215 const MCSymbolRefExpr *RefA,
216 const MCSymbolData *SD, uint64_t C,
217 unsigned Type) const;
219 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
220 const MCFragment *Fragment, const MCFixup &Fixup,
221 MCValue Target, bool &IsPCRel,
222 uint64_t &FixedValue) override;
224 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
227 // Map from a group section to the signature symbol
228 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
229 // Map from a signature symbol to the group section
230 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
231 // Map from a section to its offset
232 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
234 /// Compute the symbol table data
236 /// \param Asm - The assembler.
237 /// \param SectionIndexMap - Maps a section to its index.
238 /// \param RevGroupMap - Maps a signature symbol to the group section.
239 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
240 const SectionIndexMapTy &SectionIndexMap,
241 const RevGroupMapTy &RevGroupMap);
243 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
245 MCSectionData *createRelocationSection(MCAssembler &Asm,
246 const MCSectionData &SD);
248 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
250 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
252 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
253 SectionIndexMapTy &SectionIndexMap);
255 // Create the sections that show up in the symbol table. Currently
256 // those are the .note.GNU-stack section and the group sections.
257 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
258 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
259 SectionIndexMapTy &SectionIndexMap);
261 void ExecutePostLayoutBinding(MCAssembler &Asm,
262 const MCAsmLayout &Layout) override;
264 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
265 const MCAsmLayout &Layout,
266 const SectionIndexMapTy &SectionIndexMap,
267 const SectionOffsetMapTy &SectionOffsetMap);
269 void ComputeSectionOrder(MCAssembler &Asm,
270 std::vector<const MCSectionELF*> &Sections);
272 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
273 uint64_t Address, uint64_t Offset,
274 uint64_t Size, uint32_t Link, uint32_t Info,
275 uint64_t Alignment, uint64_t EntrySize);
277 void WriteRelocationsFragment(const MCAssembler &Asm,
279 const MCSectionData *SD);
282 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
283 const MCSymbolData &DataA,
284 const MCSymbolData *DataB,
285 const MCFragment &FB,
287 bool IsPCRel) const override;
289 bool isWeak(const MCSymbolData &SD) const override;
291 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
292 void writeSection(MCAssembler &Asm,
293 const SectionIndexMapTy &SectionIndexMap,
294 uint32_t GroupSymbolIndex,
295 uint64_t Offset, uint64_t Size, uint64_t Alignment,
296 const MCSectionELF &Section);
300 FragmentWriter::FragmentWriter(bool IsLittleEndian)
301 : IsLittleEndian(IsLittleEndian) {}
303 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
305 Val = support::endian::byte_swap<T, support::little>(Val);
307 Val = support::endian::byte_swap<T, support::big>(Val);
308 const char *Start = (const char *)&Val;
309 F.getContents().append(Start, Start + sizeof(T));
312 void SymbolTableWriter::createSymtabShndx() {
316 MCContext &Ctx = Asm.getContext();
317 const MCSectionELF *SymtabShndxSection =
318 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
319 MCSectionData *SymtabShndxSD =
320 &Asm.getOrCreateSectionData(*SymtabShndxSection);
321 SymtabShndxSD->setAlignment(4);
322 ShndxF = new MCDataFragment(SymtabShndxSD);
323 unsigned Index = SectionIndexMap.size() + 1;
324 SectionIndexMap[SymtabShndxSection] = Index;
326 for (unsigned I = 0; I < NumWritten; ++I)
327 write(*ShndxF, uint32_t(0));
330 template <typename T>
331 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
332 FWriter.write(F, Value);
335 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
337 SectionIndexMapTy &SectionIndexMap,
338 MCDataFragment *SymtabF)
339 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
340 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
343 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
344 uint64_t size, uint8_t other,
345 uint32_t shndx, bool Reserved) {
346 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
353 write(*ShndxF, shndx);
355 write(*ShndxF, uint32_t(0));
358 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
361 write(*SymtabF, name); // st_name
362 write(*SymtabF, info); // st_info
363 write(*SymtabF, other); // st_other
364 write(*SymtabF, Index); // st_shndx
365 write(*SymtabF, value); // st_value
366 write(*SymtabF, size); // st_size
368 write(*SymtabF, name); // st_name
369 write(*SymtabF, uint32_t(value)); // st_value
370 write(*SymtabF, uint32_t(size)); // st_size
371 write(*SymtabF, info); // st_info
372 write(*SymtabF, other); // st_other
373 write(*SymtabF, Index); // st_shndx
379 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
380 const MCFixupKindInfo &FKI =
381 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
383 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
386 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
390 case MCSymbolRefExpr::VK_GOT:
391 case MCSymbolRefExpr::VK_PLT:
392 case MCSymbolRefExpr::VK_GOTPCREL:
393 case MCSymbolRefExpr::VK_GOTOFF:
394 case MCSymbolRefExpr::VK_TPOFF:
395 case MCSymbolRefExpr::VK_TLSGD:
396 case MCSymbolRefExpr::VK_GOTTPOFF:
397 case MCSymbolRefExpr::VK_INDNTPOFF:
398 case MCSymbolRefExpr::VK_NTPOFF:
399 case MCSymbolRefExpr::VK_GOTNTPOFF:
400 case MCSymbolRefExpr::VK_TLSLDM:
401 case MCSymbolRefExpr::VK_DTPOFF:
402 case MCSymbolRefExpr::VK_TLSLD:
407 ELFObjectWriter::~ELFObjectWriter()
410 // Emit the ELF header.
411 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
412 uint64_t SectionHeaderOffset,
413 unsigned NumberOfSections) {
419 // emitWord method behaves differently for ELF32 and ELF64, writing
420 // 4 bytes in the former and 8 in the latter.
422 Write8(0x7f); // e_ident[EI_MAG0]
423 Write8('E'); // e_ident[EI_MAG1]
424 Write8('L'); // e_ident[EI_MAG2]
425 Write8('F'); // e_ident[EI_MAG3]
427 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
430 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
432 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
434 Write8(TargetObjectWriter->getOSABI());
435 Write8(0); // e_ident[EI_ABIVERSION]
437 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
439 Write16(ELF::ET_REL); // e_type
441 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
443 Write32(ELF::EV_CURRENT); // e_version
444 WriteWord(0); // e_entry, no entry point in .o file
445 WriteWord(0); // e_phoff, no program header for .o
446 WriteWord(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
448 // e_flags = whatever the target wants
449 Write32(Asm.getELFHeaderEFlags());
451 // e_ehsize = ELF header size
452 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
454 Write16(0); // e_phentsize = prog header entry size
455 Write16(0); // e_phnum = # prog header entries = 0
457 // e_shentsize = Section header entry size
458 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
460 // e_shnum = # of section header ents
461 if (NumberOfSections >= ELF::SHN_LORESERVE)
462 Write16(ELF::SHN_UNDEF);
464 Write16(NumberOfSections);
466 // e_shstrndx = Section # of '.shstrtab'
467 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
468 Write16(ELF::SHN_XINDEX);
470 Write16(ShstrtabIndex);
473 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
474 const MCAsmLayout &Layout) {
475 if (Data.isCommon() && Data.isExternal())
476 return Data.getCommonAlignment();
479 if (!Layout.getSymbolOffset(&Data, Res))
482 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
488 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
489 const MCAsmLayout &Layout) {
490 // The presence of symbol versions causes undefined symbols and
491 // versions declared with @@@ to be renamed.
493 for (MCSymbolData &OriginalData : Asm.symbols()) {
494 const MCSymbol &Alias = OriginalData.getSymbol();
497 if (!Alias.isVariable())
499 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
502 const MCSymbol &Symbol = Ref->getSymbol();
503 MCSymbolData &SD = Asm.getSymbolData(Symbol);
505 StringRef AliasName = Alias.getName();
506 size_t Pos = AliasName.find('@');
507 if (Pos == StringRef::npos)
510 // Aliases defined with .symvar copy the binding from the symbol they alias.
511 // This is the first place we are able to copy this information.
512 OriginalData.setExternal(SD.isExternal());
513 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
515 StringRef Rest = AliasName.substr(Pos);
516 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
519 // FIXME: produce a better error message.
520 if (Symbol.isUndefined() && Rest.startswith("@@") &&
521 !Rest.startswith("@@@"))
522 report_fatal_error("A @@ version cannot be undefined");
524 Renames.insert(std::make_pair(&Symbol, &Alias));
528 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
529 uint8_t Type = newType;
531 // Propagation rules:
532 // IFUNC > FUNC > OBJECT > NOTYPE
533 // TLS_OBJECT > OBJECT > NOTYPE
535 // dont let the new type degrade the old type
539 case ELF::STT_GNU_IFUNC:
540 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
541 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
542 Type = ELF::STT_GNU_IFUNC;
545 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
546 Type == ELF::STT_TLS)
547 Type = ELF::STT_FUNC;
549 case ELF::STT_OBJECT:
550 if (Type == ELF::STT_NOTYPE)
551 Type = ELF::STT_OBJECT;
554 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
555 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
563 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
564 const MCAsmLayout &Layout) {
565 MCSymbolData &OrigData = *MSD.SymbolData;
566 assert((!OrigData.getFragment() ||
567 (&OrigData.getFragment()->getParent()->getSection() ==
568 &OrigData.getSymbol().getSection())) &&
569 "The symbol's section doesn't match the fragment's symbol");
570 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
572 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
574 bool IsReserved = !Base || OrigData.isCommon();
576 // Binding and Type share the same byte as upper and lower nibbles
577 uint8_t Binding = MCELF::GetBinding(OrigData);
578 uint8_t Type = MCELF::GetType(OrigData);
579 MCSymbolData *BaseSD = nullptr;
581 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
582 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
584 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
586 // Other and Visibility share the same byte with Visibility using the lower
588 uint8_t Visibility = MCELF::GetVisibility(OrigData);
589 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
592 uint64_t Value = SymbolValue(OrigData, Layout);
595 const MCExpr *ESize = OrigData.getSize();
597 ESize = BaseSD->getSize();
601 if (!ESize->evaluateKnownAbsolute(Res, Layout))
602 report_fatal_error("Size expression must be absolute.");
606 // Write out the symbol table entry
607 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
608 MSD.SectionIndex, IsReserved);
611 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
613 const MCAsmLayout &Layout,
614 SectionIndexMapTy &SectionIndexMap) {
615 // The string table must be emitted first because we need the index
616 // into the string table for all the symbol names.
618 // FIXME: Make sure the start of the symbol table is aligned.
620 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
622 // The first entry is the undefined symbol entry.
623 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
625 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
626 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
627 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
630 // Write the symbol table entries.
631 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
633 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
634 ELFSymbolData &MSD = LocalSymbolData[i];
635 WriteSymbol(Writer, MSD, Layout);
638 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
639 ELFSymbolData &MSD = ExternalSymbolData[i];
640 MCSymbolData &Data = *MSD.SymbolData;
641 assert(((Data.getFlags() & ELF_STB_Global) ||
642 (Data.getFlags() & ELF_STB_Weak)) &&
643 "External symbol requires STB_GLOBAL or STB_WEAK flag");
644 WriteSymbol(Writer, MSD, Layout);
645 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
646 LastLocalSymbolIndex++;
649 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
650 ELFSymbolData &MSD = UndefinedSymbolData[i];
651 MCSymbolData &Data = *MSD.SymbolData;
652 WriteSymbol(Writer, MSD, Layout);
653 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
654 LastLocalSymbolIndex++;
658 // It is always valid to create a relocation with a symbol. It is preferable
659 // to use a relocation with a section if that is possible. Using the section
660 // allows us to omit some local symbols from the symbol table.
661 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
662 const MCSymbolRefExpr *RefA,
663 const MCSymbolData *SD,
665 unsigned Type) const {
666 // A PCRel relocation to an absolute value has no symbol (or section). We
667 // represent that with a relocation to a null section.
671 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
675 // The .odp creation emits a relocation against the symbol ".TOC." which
676 // create a R_PPC64_TOC relocation. However the relocation symbol name
677 // in final object creation should be NULL, since the symbol does not
678 // really exist, it is just the reference to TOC base for the current
679 // object file. Since the symbol is undefined, returning false results
680 // in a relocation with a null section which is the desired result.
681 case MCSymbolRefExpr::VK_PPC_TOCBASE:
684 // These VariantKind cause the relocation to refer to something other than
685 // the symbol itself, like a linker generated table. Since the address of
686 // symbol is not relevant, we cannot replace the symbol with the
687 // section and patch the difference in the addend.
688 case MCSymbolRefExpr::VK_GOT:
689 case MCSymbolRefExpr::VK_PLT:
690 case MCSymbolRefExpr::VK_GOTPCREL:
691 case MCSymbolRefExpr::VK_Mips_GOT:
692 case MCSymbolRefExpr::VK_PPC_GOT_LO:
693 case MCSymbolRefExpr::VK_PPC_GOT_HI:
694 case MCSymbolRefExpr::VK_PPC_GOT_HA:
698 // An undefined symbol is not in any section, so the relocation has to point
699 // to the symbol itself.
700 const MCSymbol &Sym = SD->getSymbol();
701 if (Sym.isUndefined())
704 unsigned Binding = MCELF::GetBinding(*SD);
707 llvm_unreachable("Invalid Binding");
711 // If the symbol is weak, it might be overridden by a symbol in another
712 // file. The relocation has to point to the symbol so that the linker
715 case ELF::STB_GLOBAL:
716 // Global ELF symbols can be preempted by the dynamic linker. The relocation
717 // has to point to the symbol for a reason analogous to the STB_WEAK case.
721 // If a relocation points to a mergeable section, we have to be careful.
722 // If the offset is zero, a relocation with the section will encode the
723 // same information. With a non-zero offset, the situation is different.
724 // For example, a relocation can point 42 bytes past the end of a string.
725 // If we change such a relocation to use the section, the linker would think
726 // that it pointed to another string and subtracting 42 at runtime will
727 // produce the wrong value.
728 auto &Sec = cast<MCSectionELF>(Sym.getSection());
729 unsigned Flags = Sec.getFlags();
730 if (Flags & ELF::SHF_MERGE) {
734 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
735 // only handle section relocations to mergeable sections if using RELA.
736 if (!hasRelocationAddend())
740 // Most TLS relocations use a got, so they need the symbol. Even those that
741 // are just an offset (@tpoff), require a symbol in gold versions before
742 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
743 // http://sourceware.org/PR16773.
744 if (Flags & ELF::SHF_TLS)
747 // If the symbol is a thumb function the final relocation must set the lowest
748 // bit. With a symbol that is done by just having the symbol have that bit
749 // set, so we would lose the bit if we relocated with the section.
750 // FIXME: We could use the section but add the bit to the relocation value.
751 if (Asm.isThumbFunc(&Sym))
754 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
759 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
760 const MCSymbol &Sym = Ref.getSymbol();
762 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
765 if (!Sym.isVariable())
768 const MCExpr *Expr = Sym.getVariableValue();
769 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
773 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
774 return &Inner->getSymbol();
778 static bool isWeak(const MCSymbolData &D) {
779 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
782 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
783 const MCAsmLayout &Layout,
784 const MCFragment *Fragment,
785 const MCFixup &Fixup, MCValue Target,
786 bool &IsPCRel, uint64_t &FixedValue) {
787 const MCSectionData *FixupSection = Fragment->getParent();
788 uint64_t C = Target.getConstant();
789 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
791 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
792 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
793 "Should not have constructed this");
795 // Let A, B and C being the components of Target and R be the location of
796 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
797 // If it is pcrel, we want to compute (A - B + C - R).
799 // In general, ELF has no relocations for -B. It can only represent (A + C)
800 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
801 // replace B to implement it: (A - R - K + C)
803 Asm.getContext().FatalError(
805 "No relocation available to represent this relative expression");
807 const MCSymbol &SymB = RefB->getSymbol();
809 if (SymB.isUndefined())
810 Asm.getContext().FatalError(
812 Twine("symbol '") + SymB.getName() +
813 "' can not be undefined in a subtraction expression");
815 assert(!SymB.isAbsolute() && "Should have been folded");
816 const MCSection &SecB = SymB.getSection();
817 if (&SecB != &FixupSection->getSection())
818 Asm.getContext().FatalError(
819 Fixup.getLoc(), "Cannot represent a difference across sections");
821 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
823 Asm.getContext().FatalError(
824 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
826 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
827 uint64_t K = SymBOffset - FixupOffset;
832 // We either rejected the fixup or folded B into C at this point.
833 const MCSymbolRefExpr *RefA = Target.getSymA();
834 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
835 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
837 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
838 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
839 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
840 C += Layout.getSymbolOffset(SymAD);
843 if (hasRelocationAddend()) {
850 // FIXME: What is this!?!?
851 MCSymbolRefExpr::VariantKind Modifier =
852 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
853 if (RelocNeedsGOT(Modifier))
856 if (!RelocateWithSymbol) {
857 const MCSection *SecA =
858 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
859 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
860 MCSymbol *SectionSymbol =
861 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
863 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
864 Relocations[FixupSection].push_back(Rec);
869 if (const MCSymbol *R = Renames.lookup(SymA))
872 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
873 WeakrefUsedInReloc.insert(WeakRef);
875 UsedInReloc.insert(SymA);
877 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
878 Relocations[FixupSection].push_back(Rec);
884 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
886 const MCSymbolData &SD = Asm.getSymbolData(*S);
887 return SD.getIndex();
890 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
891 const MCSymbolData &Data, bool Used,
893 const MCSymbol &Symbol = Data.getSymbol();
894 if (Symbol.isVariable()) {
895 const MCExpr *Expr = Symbol.getVariableValue();
896 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
897 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
908 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
911 if (Symbol.isVariable()) {
912 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
913 if (Base && Base->isUndefined())
917 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
918 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
921 if (Symbol.isTemporary())
927 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
928 if (Data.isExternal())
931 const MCSymbol &Symbol = Data.getSymbol();
932 if (Symbol.isDefined())
941 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
942 SectionIndexMapTy &SectionIndexMap) {
944 for (MCAssembler::iterator it = Asm.begin(),
945 ie = Asm.end(); it != ie; ++it) {
946 const MCSectionELF &Section =
947 static_cast<const MCSectionELF &>(it->getSection());
948 if (Section.getType() != ELF::SHT_GROUP)
950 SectionIndexMap[&Section] = Index++;
953 for (MCAssembler::iterator it = Asm.begin(),
954 ie = Asm.end(); it != ie; ++it) {
955 const MCSectionData &SD = *it;
956 const MCSectionELF &Section =
957 static_cast<const MCSectionELF &>(SD.getSection());
958 if (Section.getType() == ELF::SHT_GROUP ||
959 Section.getType() == ELF::SHT_REL ||
960 Section.getType() == ELF::SHT_RELA)
962 SectionIndexMap[&Section] = Index++;
963 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
964 const MCSectionELF *RelSection =
965 static_cast<const MCSectionELF *>(&RelSD->getSection());
966 SectionIndexMap[RelSection] = Index++;
971 void ELFObjectWriter::computeSymbolTable(
972 MCAssembler &Asm, const MCAsmLayout &Layout,
973 const SectionIndexMapTy &SectionIndexMap,
974 const RevGroupMapTy &RevGroupMap) {
975 // FIXME: Is this the correct place to do this?
976 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
978 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
979 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
980 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
981 Data.setExternal(true);
982 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
985 // Add the data for the symbols.
986 for (MCSymbolData &SD : Asm.symbols()) {
987 const MCSymbol &Symbol = SD.getSymbol();
989 bool Used = UsedInReloc.count(&Symbol);
990 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
991 bool isSignature = RevGroupMap.count(&Symbol);
993 if (!isInSymtab(Layout, SD,
994 Used || WeakrefUsed || isSignature,
995 Renames.count(&Symbol)))
999 MSD.SymbolData = &SD;
1000 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1002 // Undefined symbols are global, but this is the first place we
1003 // are able to set it.
1004 bool Local = isLocal(SD, Used);
1005 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1007 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1008 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1009 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1013 MSD.SectionIndex = ELF::SHN_ABS;
1014 } else if (SD.isCommon()) {
1016 MSD.SectionIndex = ELF::SHN_COMMON;
1017 } else if (BaseSymbol->isUndefined()) {
1018 if (isSignature && !Used)
1019 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1021 MSD.SectionIndex = ELF::SHN_UNDEF;
1022 if (!Used && WeakrefUsed)
1023 MCELF::SetBinding(SD, ELF::STB_WEAK);
1025 const MCSectionELF &Section =
1026 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1027 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1028 assert(MSD.SectionIndex && "Invalid section index!");
1031 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1034 // FIXME: All name handling should be done before we get to the writer,
1035 // including dealing with GNU-style version suffixes. Fixing this isn't
1038 // We thus have to be careful to not perform the symbol version replacement
1041 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1042 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1043 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1044 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1045 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1046 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1047 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1048 // "__imp_?" or "__imp_@?".
1050 // It would have been interesting to perform the MS mangling prefix check
1051 // only when the target triple is of the form *-pc-windows-elf. But, it
1052 // seems that this information is not easily accessible from the
1054 StringRef Name = Symbol.getName();
1055 if (!Name.startswith("?") && !Name.startswith("@?") &&
1056 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1057 // This symbol isn't following the MSVC C++ name mangling convention. We
1058 // can thus safely interpret the @@@ in symbol names as specifying symbol
1060 SmallString<32> Buf;
1061 size_t Pos = Name.find("@@@");
1062 if (Pos != StringRef::npos) {
1063 Buf += Name.substr(0, Pos);
1064 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1065 Buf += Name.substr(Pos + Skip);
1070 // Sections have their own string table
1071 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1072 MSD.Name = StrTabBuilder.add(Name);
1074 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1075 UndefinedSymbolData.push_back(MSD);
1077 LocalSymbolData.push_back(MSD);
1079 ExternalSymbolData.push_back(MSD);
1082 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1083 StrTabBuilder.add(*i);
1085 StrTabBuilder.finalize(StringTableBuilder::ELF);
1087 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1088 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1090 for (ELFSymbolData &MSD : LocalSymbolData)
1091 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1093 : StrTabBuilder.getOffset(MSD.Name);
1094 for (ELFSymbolData &MSD : ExternalSymbolData)
1095 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1096 for (ELFSymbolData& MSD : UndefinedSymbolData)
1097 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1099 // Symbols are required to be in lexicographic order.
1100 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1101 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1102 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1104 // Set the symbol indices. Local symbols must come before all other
1105 // symbols with non-local bindings.
1106 unsigned Index = FileSymbolData.size() + 1;
1107 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1108 LocalSymbolData[i].SymbolData->setIndex(Index++);
1110 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1111 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1112 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1113 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1117 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1118 const MCSectionData &SD) {
1119 if (Relocations[&SD].empty())
1122 MCContext &Ctx = Asm.getContext();
1123 const MCSectionELF &Section =
1124 static_cast<const MCSectionELF &>(SD.getSection());
1126 const StringRef SectionName = Section.getSectionName();
1127 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1128 RelaSectionName += SectionName;
1131 if (hasRelocationAddend())
1132 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1134 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1137 if (Section.getFlags() & ELF::SHF_GROUP)
1138 Flags = ELF::SHF_GROUP;
1140 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1141 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1142 Flags, EntrySize, Section.getGroup(), &Section);
1143 return &Asm.getOrCreateSectionData(*RelaSection);
1146 static SmallVector<char, 128>
1147 getUncompressedData(MCAsmLayout &Layout,
1148 MCSectionData::FragmentListType &Fragments) {
1149 SmallVector<char, 128> UncompressedData;
1150 for (const MCFragment &F : Fragments) {
1151 const SmallVectorImpl<char> *Contents;
1152 switch (F.getKind()) {
1153 case MCFragment::FT_Data:
1154 Contents = &cast<MCDataFragment>(F).getContents();
1156 case MCFragment::FT_Dwarf:
1157 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1159 case MCFragment::FT_DwarfFrame:
1160 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1164 "Not expecting any other fragment types in a debug_* section");
1166 UncompressedData.append(Contents->begin(), Contents->end());
1168 return UncompressedData;
1171 // Include the debug info compression header:
1172 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1173 // useful for consumers to preallocate a buffer to decompress into.
1175 prependCompressionHeader(uint64_t Size,
1176 SmallVectorImpl<char> &CompressedContents) {
1177 const StringRef Magic = "ZLIB";
1178 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1180 if (sys::IsLittleEndianHost)
1181 sys::swapByteOrder(Size);
1182 CompressedContents.insert(CompressedContents.begin(),
1183 Magic.size() + sizeof(Size), 0);
1184 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1185 std::copy(reinterpret_cast<char *>(&Size),
1186 reinterpret_cast<char *>(&Size + 1),
1187 CompressedContents.begin() + Magic.size());
1191 // Return a single fragment containing the compressed contents of the whole
1192 // section. Null if the section was not compressed for any reason.
1193 static std::unique_ptr<MCDataFragment>
1194 getCompressedFragment(MCAsmLayout &Layout,
1195 MCSectionData::FragmentListType &Fragments) {
1196 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1198 // Gather the uncompressed data from all the fragments, recording the
1199 // alignment fragment, if seen, and any fixups.
1200 SmallVector<char, 128> UncompressedData =
1201 getUncompressedData(Layout, Fragments);
1203 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1205 zlib::Status Success = zlib::compress(
1206 StringRef(UncompressedData.data(), UncompressedData.size()),
1207 CompressedContents);
1208 if (Success != zlib::StatusOK)
1211 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1214 return CompressedFragment;
1217 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1220 static void UpdateSymbols(const MCAsmLayout &Layout,
1221 const std::vector<MCSymbolData *> &Symbols,
1222 MCFragment &NewFragment) {
1223 for (MCSymbolData *Sym : Symbols) {
1224 Sym->setOffset(Sym->getOffset() +
1225 Layout.getFragmentOffset(Sym->getFragment()));
1226 Sym->setFragment(&NewFragment);
1230 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1231 const DefiningSymbolMap &DefiningSymbols,
1232 const MCSectionELF &Section,
1233 MCSectionData &SD) {
1234 StringRef SectionName = Section.getSectionName();
1235 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1237 std::unique_ptr<MCDataFragment> CompressedFragment =
1238 getCompressedFragment(Layout, Fragments);
1240 // Leave the section as-is if the fragments could not be compressed.
1241 if (!CompressedFragment)
1244 // Update the fragment+offsets of any symbols referring to fragments in this
1245 // section to refer to the new fragment.
1246 auto I = DefiningSymbols.find(&SD);
1247 if (I != DefiningSymbols.end())
1248 UpdateSymbols(Layout, I->second, *CompressedFragment);
1250 // Invalidate the layout for the whole section since it will have new and
1251 // different fragments now.
1252 Layout.invalidateFragmentsFrom(&Fragments.front());
1255 // Complete the initialization of the new fragment
1256 CompressedFragment->setParent(&SD);
1257 CompressedFragment->setLayoutOrder(0);
1258 Fragments.push_back(CompressedFragment.release());
1260 // Rename from .debug_* to .zdebug_*
1261 Asm.getContext().renameELFSection(&Section,
1262 (".z" + SectionName.drop_front(1)).str());
1265 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1266 MCAsmLayout &Layout) {
1267 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1270 DefiningSymbolMap DefiningSymbols;
1272 for (MCSymbolData &SD : Asm.symbols())
1273 if (MCFragment *F = SD.getFragment())
1274 DefiningSymbols[F->getParent()].push_back(&SD);
1276 for (MCSectionData &SD : Asm) {
1277 const MCSectionELF &Section =
1278 static_cast<const MCSectionELF &>(SD.getSection());
1279 StringRef SectionName = Section.getSectionName();
1281 // Compressing debug_frame requires handling alignment fragments which is
1282 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1283 // for writing to arbitrary buffers) for little benefit.
1284 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1287 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1291 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1292 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1293 MCSectionData &RelSD = *it;
1294 const MCSectionELF &RelSection =
1295 static_cast<const MCSectionELF &>(RelSD.getSection());
1297 unsigned Type = RelSection.getType();
1298 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1301 const MCSectionELF *Section = RelSection.getAssociatedSection();
1302 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1303 RelSD.setAlignment(is64Bit() ? 8 : 4);
1305 MCDataFragment *F = new MCDataFragment(&RelSD);
1306 WriteRelocationsFragment(Asm, F, &SD);
1310 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1311 uint64_t Flags, uint64_t Address,
1312 uint64_t Offset, uint64_t Size,
1313 uint32_t Link, uint32_t Info,
1315 uint64_t EntrySize) {
1316 Write32(Name); // sh_name: index into string table
1317 Write32(Type); // sh_type
1318 WriteWord(Flags); // sh_flags
1319 WriteWord(Address); // sh_addr
1320 WriteWord(Offset); // sh_offset
1321 WriteWord(Size); // sh_size
1322 Write32(Link); // sh_link
1323 Write32(Info); // sh_info
1324 WriteWord(Alignment); // sh_addralign
1325 WriteWord(EntrySize); // sh_entsize
1328 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1330 const MCSectionData *SD) {
1331 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1333 // Sort the relocation entries. Most targets just sort by Offset, but some
1334 // (e.g., MIPS) have additional constraints.
1335 TargetObjectWriter->sortRelocs(Asm, Relocs);
1337 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1338 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1340 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1343 write(*F, Entry.Offset);
1344 if (TargetObjectWriter->isN64()) {
1345 write(*F, uint32_t(Index));
1347 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1348 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1349 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1350 write(*F, TargetObjectWriter->getRType(Entry.Type));
1352 struct ELF::Elf64_Rela ERE64;
1353 ERE64.setSymbolAndType(Index, Entry.Type);
1354 write(*F, ERE64.r_info);
1356 if (hasRelocationAddend())
1357 write(*F, Entry.Addend);
1359 write(*F, uint32_t(Entry.Offset));
1361 struct ELF::Elf32_Rela ERE32;
1362 ERE32.setSymbolAndType(Index, Entry.Type);
1363 write(*F, ERE32.r_info);
1365 if (hasRelocationAddend())
1366 write(*F, uint32_t(Entry.Addend));
1371 void ELFObjectWriter::CreateMetadataSections(
1372 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1373 MCContext &Ctx = Asm.getContext();
1376 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1378 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1379 const MCSectionELF *ShstrtabSection =
1380 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1381 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1382 ShstrtabSD.setAlignment(1);
1383 ShstrtabIndex = SectionIndexMap.size() + 1;
1384 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1386 const MCSectionELF *SymtabSection =
1387 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1389 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1390 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1391 SymbolTableIndex = SectionIndexMap.size() + 1;
1392 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1394 const MCSectionELF *StrtabSection;
1395 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1396 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1397 StrtabSD.setAlignment(1);
1398 StringTableIndex = SectionIndexMap.size() + 1;
1399 SectionIndexMap[StrtabSection] = StringTableIndex;
1402 F = new MCDataFragment(&SymtabSD);
1403 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1405 F = new MCDataFragment(&StrtabSD);
1406 F->getContents().append(StrTabBuilder.data().begin(),
1407 StrTabBuilder.data().end());
1409 F = new MCDataFragment(&ShstrtabSD);
1411 // Section header string table.
1412 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1413 const MCSectionELF &Section =
1414 static_cast<const MCSectionELF&>(it->getSection());
1415 ShStrTabBuilder.add(Section.getSectionName());
1417 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1418 F->getContents().append(ShStrTabBuilder.data().begin(),
1419 ShStrTabBuilder.data().end());
1422 void ELFObjectWriter::createIndexedSections(
1423 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1424 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1425 MCContext &Ctx = Asm.getContext();
1428 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1430 const MCSectionELF &Section =
1431 static_cast<const MCSectionELF&>(it->getSection());
1432 if (!(Section.getFlags() & ELF::SHF_GROUP))
1435 const MCSymbol *SignatureSymbol = Section.getGroup();
1436 Asm.getOrCreateSymbolData(*SignatureSymbol);
1437 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1439 Group = Ctx.CreateELFGroupSection();
1440 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1441 Data.setAlignment(4);
1442 MCDataFragment *F = new MCDataFragment(&Data);
1443 write(*F, uint32_t(ELF::GRP_COMDAT));
1445 GroupMap[Group] = SignatureSymbol;
1448 computeIndexMap(Asm, SectionIndexMap);
1450 // Add sections to the groups
1451 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF&>(it->getSection());
1455 if (!(Section.getFlags() & ELF::SHF_GROUP))
1457 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1458 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1459 // FIXME: we could use the previous fragment
1460 MCDataFragment *F = new MCDataFragment(&Data);
1461 uint32_t Index = SectionIndexMap.lookup(&Section);
1466 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1467 const SectionIndexMapTy &SectionIndexMap,
1468 uint32_t GroupSymbolIndex,
1469 uint64_t Offset, uint64_t Size,
1471 const MCSectionELF &Section) {
1472 uint64_t sh_link = 0;
1473 uint64_t sh_info = 0;
1475 switch(Section.getType()) {
1480 case ELF::SHT_DYNAMIC:
1481 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1485 case ELF::SHT_RELA: {
1486 sh_link = SymbolTableIndex;
1487 assert(sh_link && ".symtab not found");
1488 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1489 sh_info = SectionIndexMap.lookup(InfoSection);
1493 case ELF::SHT_SYMTAB:
1494 case ELF::SHT_DYNSYM:
1495 sh_link = StringTableIndex;
1496 sh_info = LastLocalSymbolIndex;
1499 case ELF::SHT_SYMTAB_SHNDX:
1500 sh_link = SymbolTableIndex;
1503 case ELF::SHT_GROUP:
1504 sh_link = SymbolTableIndex;
1505 sh_info = GroupSymbolIndex;
1509 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1510 Section.getType() == ELF::SHT_ARM_EXIDX)
1511 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1513 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1515 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1516 Alignment, Section.getEntrySize());
1519 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1520 return SD.getOrdinal() == ~UINT32_C(0) &&
1521 !SD.getSection().isVirtualSection();
1524 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1526 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1528 const MCFragment &F = *i;
1529 assert(F.getKind() == MCFragment::FT_Data);
1530 Ret += cast<MCDataFragment>(F).getContents().size();
1535 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1536 const MCSectionData &SD) {
1537 if (IsELFMetaDataSection(SD))
1538 return DataSectionSize(SD);
1539 return Layout.getSectionFileSize(&SD);
1542 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1543 const MCSectionData &SD) {
1544 if (IsELFMetaDataSection(SD))
1545 return DataSectionSize(SD);
1546 return Layout.getSectionAddressSize(&SD);
1549 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1550 const MCAsmLayout &Layout,
1551 const MCSectionELF &Section) {
1552 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1554 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1555 WriteZeros(Padding);
1557 if (IsELFMetaDataSection(SD)) {
1558 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1560 const MCFragment &F = *i;
1561 assert(F.getKind() == MCFragment::FT_Data);
1562 WriteBytes(cast<MCDataFragment>(F).getContents());
1565 Asm.writeSectionData(&SD, Layout);
1569 void ELFObjectWriter::writeSectionHeader(
1570 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1571 const SectionIndexMapTy &SectionIndexMap,
1572 const SectionOffsetMapTy &SectionOffsetMap) {
1573 const unsigned NumSections = Asm.size() + 1;
1575 std::vector<const MCSectionELF*> Sections;
1576 Sections.resize(NumSections - 1);
1578 for (SectionIndexMapTy::const_iterator i=
1579 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1580 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1581 Sections[p.second - 1] = p.first;
1584 // Null section first.
1585 uint64_t FirstSectionSize =
1586 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1587 uint32_t FirstSectionLink =
1588 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1589 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1591 for (unsigned i = 0; i < NumSections - 1; ++i) {
1592 const MCSectionELF &Section = *Sections[i];
1593 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1594 uint32_t GroupSymbolIndex;
1595 if (Section.getType() != ELF::SHT_GROUP)
1596 GroupSymbolIndex = 0;
1598 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1599 GroupMap.lookup(&Section));
1601 uint64_t Size = GetSectionAddressSize(Layout, SD);
1603 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1604 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1609 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1610 std::vector<const MCSectionELF*> &Sections) {
1611 for (MCAssembler::iterator it = Asm.begin(),
1612 ie = Asm.end(); it != ie; ++it) {
1613 const MCSectionELF &Section =
1614 static_cast<const MCSectionELF &>(it->getSection());
1615 if (Section.getType() == ELF::SHT_GROUP)
1616 Sections.push_back(&Section);
1619 for (MCAssembler::iterator it = Asm.begin(),
1620 ie = Asm.end(); it != ie; ++it) {
1621 const MCSectionELF &Section =
1622 static_cast<const MCSectionELF &>(it->getSection());
1623 if (Section.getType() != ELF::SHT_GROUP &&
1624 Section.getType() != ELF::SHT_REL &&
1625 Section.getType() != ELF::SHT_RELA)
1626 Sections.push_back(&Section);
1629 for (MCAssembler::iterator it = Asm.begin(),
1630 ie = Asm.end(); it != ie; ++it) {
1631 const MCSectionELF &Section =
1632 static_cast<const MCSectionELF &>(it->getSection());
1633 if (Section.getType() == ELF::SHT_REL ||
1634 Section.getType() == ELF::SHT_RELA)
1635 Sections.push_back(&Section);
1639 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1640 const MCAsmLayout &Layout) {
1641 GroupMapTy GroupMap;
1642 RevGroupMapTy RevGroupMap;
1643 SectionIndexMapTy SectionIndexMap;
1645 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1646 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1647 RevGroupMap, SectionIndexMap);
1649 // Compute symbol table information.
1650 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1652 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1654 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1655 const_cast<MCAsmLayout&>(Layout),
1658 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1659 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1660 sizeof(ELF::Elf32_Ehdr);
1661 uint64_t FileOff = HeaderSize;
1663 std::vector<const MCSectionELF*> Sections;
1664 ComputeSectionOrder(Asm, Sections);
1665 unsigned NumSections = Sections.size();
1666 SectionOffsetMapTy SectionOffsetMap;
1667 for (unsigned i = 0; i < NumSections; ++i) {
1669 const MCSectionELF &Section = *Sections[i];
1670 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1672 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1674 // Remember the offset into the file for this section.
1675 SectionOffsetMap[&Section] = FileOff;
1677 // Get the size of the section in the output file (including padding).
1678 FileOff += GetSectionFileSize(Layout, SD);
1681 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1683 const unsigned SectionHeaderOffset = FileOff;
1685 // Write out the ELF header ...
1686 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1688 // ... then the sections ...
1689 for (unsigned i = 0; i < NumSections; ++i)
1690 WriteDataSectionData(Asm, Layout, *Sections[i]);
1692 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1693 WriteZeros(Padding);
1695 // ... then the section header table ...
1696 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
1699 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1700 const MCAssembler &Asm, const MCSymbolData &DataA,
1701 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1702 bool IsPCRel) const {
1703 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
1705 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1706 Asm, DataA, DataB, FB, InSet, IsPCRel);
1709 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1710 return ::isWeak(SD);
1713 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1715 bool IsLittleEndian) {
1716 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);