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 std::vector<const MCSectionELF *> &Sections;
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 std::vector<const MCSectionELF *> &Sections,
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);
95 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
96 const MCSectionData &SD);
98 /// Helper struct for containing some precomputed information on symbols.
99 struct ELFSymbolData {
100 MCSymbolData *SymbolData;
101 uint64_t StringIndex;
102 uint32_t SectionIndex;
105 // Support lexicographic sorting.
106 bool operator<(const ELFSymbolData &RHS) const {
107 unsigned LHSType = MCELF::GetType(*SymbolData);
108 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
109 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
111 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
113 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
114 return SectionIndex < RHS.SectionIndex;
115 return Name < RHS.Name;
119 /// The target specific ELF writer instance.
120 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
122 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
123 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
124 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
126 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
128 StringTableBuilder ShStrTabBuilder;
131 /// @name Symbol Table Data
134 StringTableBuilder StrTabBuilder;
135 std::vector<uint64_t> FileSymbolData;
136 std::vector<ELFSymbolData> LocalSymbolData;
137 std::vector<ELFSymbolData> ExternalSymbolData;
138 std::vector<ELFSymbolData> UndefinedSymbolData;
144 // This holds the symbol table index of the last local symbol.
145 unsigned LastLocalSymbolIndex;
146 // This holds the .strtab section index.
147 unsigned StringTableIndex;
148 // This holds the .symtab section index.
149 unsigned SymbolTableIndex;
151 unsigned ShstrtabIndex;
154 // TargetObjectWriter wrappers.
155 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
156 bool hasRelocationAddend() const {
157 return TargetObjectWriter->hasRelocationAddend();
159 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
160 bool IsPCRel) const {
161 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
165 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
167 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
168 TargetObjectWriter(MOTW), NeedsGOT(false) {}
170 void reset() override {
172 WeakrefUsedInReloc.clear();
175 ShStrTabBuilder.clear();
176 StrTabBuilder.clear();
177 FileSymbolData.clear();
178 LocalSymbolData.clear();
179 ExternalSymbolData.clear();
180 UndefinedSymbolData.clear();
181 MCObjectWriter::reset();
184 ~ELFObjectWriter() override;
186 void WriteWord(uint64_t W) {
193 template <typename T> void write(MCDataFragment &F, T Value) {
194 FWriter.write(F, Value);
197 void WriteHeader(const MCAssembler &Asm,
198 unsigned NumberOfSections);
200 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
201 const MCAsmLayout &Layout);
203 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
204 const MCAsmLayout &Layout,
205 std::vector<const MCSectionELF *> &Sections);
207 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
208 const MCSymbolRefExpr *RefA,
209 const MCSymbolData *SD, uint64_t C,
210 unsigned Type) const;
212 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
213 const MCFragment *Fragment, const MCFixup &Fixup,
214 MCValue Target, bool &IsPCRel,
215 uint64_t &FixedValue) override;
217 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
220 // Map from a signature symbol to the group section index
221 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
222 // Start and end offset of each section
223 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
225 /// Compute the symbol table data
227 /// \param Asm - The assembler.
228 /// \param SectionIndexMap - Maps a section to its index.
229 /// \param RevGroupMap - Maps a signature symbol to the group section.
230 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
231 const SectionIndexMapTy &SectionIndexMap,
232 const RevGroupMapTy &RevGroupMap);
234 void maybeAddToGroup(MCAssembler &Asm,
235 ArrayRef<const MCSectionELF *> Sections,
236 const RevGroupMapTy &RevGroupMap,
237 const MCSectionELF &Section, unsigned Index);
239 void computeIndexMap(MCAssembler &Asm,
240 std::vector<const MCSectionELF *> &Sections,
241 SectionIndexMapTy &SectionIndexMap,
242 const RevGroupMapTy &RevGroupMap);
244 void createRelocationSection(MCAssembler &Asm, const MCSectionData &SD);
246 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
248 void WriteRelocations(MCAssembler &Asm, const MCAsmLayout &Layout);
251 createSectionHeaderStringTable(MCAssembler &Asm,
252 std::vector<const MCSectionELF *> &Sections);
253 void createStringTable(MCAssembler &Asm,
254 std::vector<const MCSectionELF *> &Sections);
255 void CreateMetadataSections(MCAssembler &Asm, const MCAsmLayout &Layout,
256 std::vector<const MCSectionELF *> &Sections);
258 // Create the sections that show up in the symbol table. Currently
259 // those are the .note.GNU-stack section and the group sections.
260 void createIndexedSections(MCAssembler &Asm, const MCAsmLayout &Layout,
261 RevGroupMapTy &RevGroupMap,
262 std::vector<const MCSectionELF *> &Sections,
263 SectionIndexMapTy &SectionIndexMap);
265 void ExecutePostLayoutBinding(MCAssembler &Asm,
266 const MCAsmLayout &Layout) override;
268 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
269 MCAssembler &Asm, const MCAsmLayout &Layout,
270 const SectionIndexMapTy &SectionIndexMap,
271 const SectionOffsetsTy &SectionOffsets);
273 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
274 uint64_t Address, uint64_t Offset,
275 uint64_t Size, uint32_t Link, uint32_t Info,
276 uint64_t Alignment, uint64_t EntrySize);
278 void WriteRelocationsFragment(const MCAssembler &Asm,
280 const MCSectionData *SD);
283 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
284 const MCSymbolData &DataA,
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 Sections.push_back(SymtabShndxSection);
325 for (unsigned I = 0; I < NumWritten; ++I)
326 write(*ShndxF, uint32_t(0));
329 template <typename T>
330 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
331 FWriter.write(F, Value);
334 SymbolTableWriter::SymbolTableWriter(
335 MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
336 std::vector<const MCSectionELF *> &Sections, MCDataFragment *SymtabF)
337 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit), Sections(Sections),
338 SymtabF(SymtabF), ShndxF(nullptr), NumWritten(0) {}
340 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
341 uint64_t size, uint8_t other,
342 uint32_t shndx, bool Reserved) {
343 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
350 write(*ShndxF, shndx);
352 write(*ShndxF, uint32_t(0));
355 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
358 write(*SymtabF, name); // st_name
359 write(*SymtabF, info); // st_info
360 write(*SymtabF, other); // st_other
361 write(*SymtabF, Index); // st_shndx
362 write(*SymtabF, value); // st_value
363 write(*SymtabF, size); // st_size
365 write(*SymtabF, name); // st_name
366 write(*SymtabF, uint32_t(value)); // st_value
367 write(*SymtabF, uint32_t(size)); // st_size
368 write(*SymtabF, info); // st_info
369 write(*SymtabF, other); // st_other
370 write(*SymtabF, Index); // st_shndx
376 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
377 const MCFixupKindInfo &FKI =
378 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
380 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
383 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
387 case MCSymbolRefExpr::VK_GOT:
388 case MCSymbolRefExpr::VK_PLT:
389 case MCSymbolRefExpr::VK_GOTPCREL:
390 case MCSymbolRefExpr::VK_GOTOFF:
391 case MCSymbolRefExpr::VK_TPOFF:
392 case MCSymbolRefExpr::VK_TLSGD:
393 case MCSymbolRefExpr::VK_GOTTPOFF:
394 case MCSymbolRefExpr::VK_INDNTPOFF:
395 case MCSymbolRefExpr::VK_NTPOFF:
396 case MCSymbolRefExpr::VK_GOTNTPOFF:
397 case MCSymbolRefExpr::VK_TLSLDM:
398 case MCSymbolRefExpr::VK_DTPOFF:
399 case MCSymbolRefExpr::VK_TLSLD:
404 ELFObjectWriter::~ELFObjectWriter()
407 // Emit the ELF header.
408 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
409 unsigned NumberOfSections) {
415 // emitWord method behaves differently for ELF32 and ELF64, writing
416 // 4 bytes in the former and 8 in the latter.
418 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
420 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
423 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
425 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
427 Write8(TargetObjectWriter->getOSABI());
428 Write8(0); // e_ident[EI_ABIVERSION]
430 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
432 Write16(ELF::ET_REL); // e_type
434 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
436 Write32(ELF::EV_CURRENT); // e_version
437 WriteWord(0); // e_entry, no entry point in .o file
438 WriteWord(0); // e_phoff, no program header for .o
439 WriteWord(0); // e_shoff = sec hdr table off in bytes
441 // e_flags = whatever the target wants
442 Write32(Asm.getELFHeaderEFlags());
444 // e_ehsize = ELF header size
445 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
447 Write16(0); // e_phentsize = prog header entry size
448 Write16(0); // e_phnum = # prog header entries = 0
450 // e_shentsize = Section header entry size
451 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
453 // e_shnum = # of section header ents
454 if (NumberOfSections >= ELF::SHN_LORESERVE)
455 Write16(ELF::SHN_UNDEF);
457 Write16(NumberOfSections);
459 // e_shstrndx = Section # of '.shstrtab'
460 assert(ShstrtabIndex < ELF::SHN_LORESERVE);
461 Write16(ShstrtabIndex);
464 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
465 const MCAsmLayout &Layout) {
466 if (Data.isCommon() && Data.isExternal())
467 return Data.getCommonAlignment();
470 if (!Layout.getSymbolOffset(&Data, Res))
473 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
479 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
480 const MCAsmLayout &Layout) {
481 // The presence of symbol versions causes undefined symbols and
482 // versions declared with @@@ to be renamed.
484 for (MCSymbolData &OriginalData : Asm.symbols()) {
485 const MCSymbol &Alias = OriginalData.getSymbol();
488 if (!Alias.isVariable())
490 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
493 const MCSymbol &Symbol = Ref->getSymbol();
494 MCSymbolData &SD = Asm.getSymbolData(Symbol);
496 StringRef AliasName = Alias.getName();
497 size_t Pos = AliasName.find('@');
498 if (Pos == StringRef::npos)
501 // Aliases defined with .symvar copy the binding from the symbol they alias.
502 // This is the first place we are able to copy this information.
503 OriginalData.setExternal(SD.isExternal());
504 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
506 StringRef Rest = AliasName.substr(Pos);
507 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
510 // FIXME: produce a better error message.
511 if (Symbol.isUndefined() && Rest.startswith("@@") &&
512 !Rest.startswith("@@@"))
513 report_fatal_error("A @@ version cannot be undefined");
515 Renames.insert(std::make_pair(&Symbol, &Alias));
519 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
520 uint8_t Type = newType;
522 // Propagation rules:
523 // IFUNC > FUNC > OBJECT > NOTYPE
524 // TLS_OBJECT > OBJECT > NOTYPE
526 // dont let the new type degrade the old type
530 case ELF::STT_GNU_IFUNC:
531 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
532 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
533 Type = ELF::STT_GNU_IFUNC;
536 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
537 Type == ELF::STT_TLS)
538 Type = ELF::STT_FUNC;
540 case ELF::STT_OBJECT:
541 if (Type == ELF::STT_NOTYPE)
542 Type = ELF::STT_OBJECT;
545 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
546 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
554 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
555 const MCAsmLayout &Layout) {
556 MCSymbolData &OrigData = *MSD.SymbolData;
557 assert((!OrigData.getFragment() ||
558 (&OrigData.getFragment()->getParent()->getSection() ==
559 &OrigData.getSymbol().getSection())) &&
560 "The symbol's section doesn't match the fragment's symbol");
561 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
563 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
565 bool IsReserved = !Base || OrigData.isCommon();
567 // Binding and Type share the same byte as upper and lower nibbles
568 uint8_t Binding = MCELF::GetBinding(OrigData);
569 uint8_t Type = MCELF::GetType(OrigData);
570 MCSymbolData *BaseSD = nullptr;
572 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
573 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
575 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
577 // Other and Visibility share the same byte with Visibility using the lower
579 uint8_t Visibility = MCELF::GetVisibility(OrigData);
580 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
583 uint64_t Value = SymbolValue(OrigData, Layout);
586 const MCExpr *ESize = OrigData.getSize();
588 ESize = BaseSD->getSize();
592 if (!ESize->evaluateKnownAbsolute(Res, Layout))
593 report_fatal_error("Size expression must be absolute.");
597 // Write out the symbol table entry
598 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
599 MSD.SectionIndex, IsReserved);
602 void ELFObjectWriter::WriteSymbolTable(
603 MCDataFragment *SymtabF, MCAssembler &Asm, const MCAsmLayout &Layout,
604 std::vector<const MCSectionELF *> &Sections) {
605 // The string table must be emitted first because we need the index
606 // into the string table for all the symbol names.
608 // FIXME: Make sure the start of the symbol table is aligned.
610 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), Sections, SymtabF);
612 // The first entry is the undefined symbol entry.
613 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
615 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
616 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
617 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
620 // Write the symbol table entries.
621 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
623 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
624 ELFSymbolData &MSD = LocalSymbolData[i];
625 WriteSymbol(Writer, MSD, Layout);
628 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
629 ELFSymbolData &MSD = ExternalSymbolData[i];
630 MCSymbolData &Data = *MSD.SymbolData;
631 assert(((Data.getFlags() & ELF_STB_Global) ||
632 (Data.getFlags() & ELF_STB_Weak)) &&
633 "External symbol requires STB_GLOBAL or STB_WEAK flag");
634 WriteSymbol(Writer, MSD, Layout);
635 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
636 LastLocalSymbolIndex++;
639 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
640 ELFSymbolData &MSD = UndefinedSymbolData[i];
641 MCSymbolData &Data = *MSD.SymbolData;
642 WriteSymbol(Writer, MSD, Layout);
643 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
644 LastLocalSymbolIndex++;
648 // It is always valid to create a relocation with a symbol. It is preferable
649 // to use a relocation with a section if that is possible. Using the section
650 // allows us to omit some local symbols from the symbol table.
651 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
652 const MCSymbolRefExpr *RefA,
653 const MCSymbolData *SD,
655 unsigned Type) const {
656 // A PCRel relocation to an absolute value has no symbol (or section). We
657 // represent that with a relocation to a null section.
661 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
665 // The .odp creation emits a relocation against the symbol ".TOC." which
666 // create a R_PPC64_TOC relocation. However the relocation symbol name
667 // in final object creation should be NULL, since the symbol does not
668 // really exist, it is just the reference to TOC base for the current
669 // object file. Since the symbol is undefined, returning false results
670 // in a relocation with a null section which is the desired result.
671 case MCSymbolRefExpr::VK_PPC_TOCBASE:
674 // These VariantKind cause the relocation to refer to something other than
675 // the symbol itself, like a linker generated table. Since the address of
676 // symbol is not relevant, we cannot replace the symbol with the
677 // section and patch the difference in the addend.
678 case MCSymbolRefExpr::VK_GOT:
679 case MCSymbolRefExpr::VK_PLT:
680 case MCSymbolRefExpr::VK_GOTPCREL:
681 case MCSymbolRefExpr::VK_Mips_GOT:
682 case MCSymbolRefExpr::VK_PPC_GOT_LO:
683 case MCSymbolRefExpr::VK_PPC_GOT_HI:
684 case MCSymbolRefExpr::VK_PPC_GOT_HA:
688 // An undefined symbol is not in any section, so the relocation has to point
689 // to the symbol itself.
690 const MCSymbol &Sym = SD->getSymbol();
691 if (Sym.isUndefined())
694 unsigned Binding = MCELF::GetBinding(*SD);
697 llvm_unreachable("Invalid Binding");
701 // If the symbol is weak, it might be overridden by a symbol in another
702 // file. The relocation has to point to the symbol so that the linker
705 case ELF::STB_GLOBAL:
706 // Global ELF symbols can be preempted by the dynamic linker. The relocation
707 // has to point to the symbol for a reason analogous to the STB_WEAK case.
711 // If a relocation points to a mergeable section, we have to be careful.
712 // If the offset is zero, a relocation with the section will encode the
713 // same information. With a non-zero offset, the situation is different.
714 // For example, a relocation can point 42 bytes past the end of a string.
715 // If we change such a relocation to use the section, the linker would think
716 // that it pointed to another string and subtracting 42 at runtime will
717 // produce the wrong value.
718 auto &Sec = cast<MCSectionELF>(Sym.getSection());
719 unsigned Flags = Sec.getFlags();
720 if (Flags & ELF::SHF_MERGE) {
724 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
725 // only handle section relocations to mergeable sections if using RELA.
726 if (!hasRelocationAddend())
730 // Most TLS relocations use a got, so they need the symbol. Even those that
731 // are just an offset (@tpoff), require a symbol in gold versions before
732 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
733 // http://sourceware.org/PR16773.
734 if (Flags & ELF::SHF_TLS)
737 // If the symbol is a thumb function the final relocation must set the lowest
738 // bit. With a symbol that is done by just having the symbol have that bit
739 // set, so we would lose the bit if we relocated with the section.
740 // FIXME: We could use the section but add the bit to the relocation value.
741 if (Asm.isThumbFunc(&Sym))
744 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
749 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
750 const MCSymbol &Sym = Ref.getSymbol();
752 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
755 if (!Sym.isVariable())
758 const MCExpr *Expr = Sym.getVariableValue();
759 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
763 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
764 return &Inner->getSymbol();
768 // True if the assembler knows nothing about the final value of the symbol.
769 // This doesn't cover the comdat issues, since in those cases the assembler
770 // can at least know that all symbols in the section will move together.
771 static bool isWeak(const MCSymbolData &D) {
772 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
775 switch (MCELF::GetBinding(D)) {
777 llvm_unreachable("Unknown binding");
780 case ELF::STB_GLOBAL:
783 case ELF::STB_GNU_UNIQUE:
788 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
789 const MCAsmLayout &Layout,
790 const MCFragment *Fragment,
791 const MCFixup &Fixup, MCValue Target,
792 bool &IsPCRel, uint64_t &FixedValue) {
793 const MCSectionData *FixupSection = Fragment->getParent();
794 uint64_t C = Target.getConstant();
795 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
797 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
798 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
799 "Should not have constructed this");
801 // Let A, B and C being the components of Target and R be the location of
802 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
803 // If it is pcrel, we want to compute (A - B + C - R).
805 // In general, ELF has no relocations for -B. It can only represent (A + C)
806 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
807 // replace B to implement it: (A - R - K + C)
809 Asm.getContext().FatalError(
811 "No relocation available to represent this relative expression");
813 const MCSymbol &SymB = RefB->getSymbol();
815 if (SymB.isUndefined())
816 Asm.getContext().FatalError(
818 Twine("symbol '") + SymB.getName() +
819 "' can not be undefined in a subtraction expression");
821 assert(!SymB.isAbsolute() && "Should have been folded");
822 const MCSection &SecB = SymB.getSection();
823 if (&SecB != &FixupSection->getSection())
824 Asm.getContext().FatalError(
825 Fixup.getLoc(), "Cannot represent a difference across sections");
827 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
829 Asm.getContext().FatalError(
830 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
832 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
833 uint64_t K = SymBOffset - FixupOffset;
838 // We either rejected the fixup or folded B into C at this point.
839 const MCSymbolRefExpr *RefA = Target.getSymA();
840 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
841 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
843 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
844 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
845 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
846 C += Layout.getSymbolOffset(SymAD);
849 if (hasRelocationAddend()) {
856 // FIXME: What is this!?!?
857 MCSymbolRefExpr::VariantKind Modifier =
858 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
859 if (RelocNeedsGOT(Modifier))
862 if (!RelocateWithSymbol) {
863 const MCSection *SecA =
864 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
865 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
866 MCSymbol *SectionSymbol =
867 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
869 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
870 Relocations[FixupSection].push_back(Rec);
875 if (const MCSymbol *R = Renames.lookup(SymA))
878 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
879 WeakrefUsedInReloc.insert(WeakRef);
881 UsedInReloc.insert(SymA);
883 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
884 Relocations[FixupSection].push_back(Rec);
890 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
892 const MCSymbolData &SD = Asm.getSymbolData(*S);
893 return SD.getIndex();
896 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
897 const MCSymbolData &Data, bool Used,
899 const MCSymbol &Symbol = Data.getSymbol();
900 if (Symbol.isVariable()) {
901 const MCExpr *Expr = Symbol.getVariableValue();
902 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
903 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
914 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
917 if (Symbol.isVariable()) {
918 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
919 if (Base && Base->isUndefined())
923 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
924 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
927 if (Symbol.isTemporary())
933 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
934 if (Data.isExternal())
937 const MCSymbol &Symbol = Data.getSymbol();
938 if (Symbol.isDefined())
947 void ELFObjectWriter::maybeAddToGroup(MCAssembler &Asm,
948 ArrayRef<const MCSectionELF *> Sections,
949 const RevGroupMapTy &RevGroupMap,
950 const MCSectionELF &Section,
952 const MCSymbol *Sym = Section.getGroup();
955 const MCSectionELF *Group = Sections[RevGroupMap.lookup(Sym) - 1];
956 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
957 // FIXME: we could use the previous fragment
958 MCDataFragment *F = new MCDataFragment(&Data);
962 void ELFObjectWriter::computeIndexMap(
963 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections,
964 SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap) {
965 for (const MCSectionData &SD : Asm) {
966 const MCSectionELF &Section =
967 static_cast<const MCSectionELF &>(SD.getSection());
968 if (Section.getType() == ELF::SHT_GROUP)
970 Sections.push_back(&Section);
971 unsigned Index = Sections.size();
972 SectionIndexMap[&Section] = Index;
973 maybeAddToGroup(Asm, Sections, RevGroupMap, Section, Index);
974 createRelocationSection(Asm, SD);
978 void ELFObjectWriter::computeSymbolTable(
979 MCAssembler &Asm, const MCAsmLayout &Layout,
980 const SectionIndexMapTy &SectionIndexMap,
981 const RevGroupMapTy &RevGroupMap) {
982 // FIXME: Is this the correct place to do this?
983 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
985 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
986 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
987 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
988 Data.setExternal(true);
989 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
992 // Add the data for the symbols.
993 for (MCSymbolData &SD : Asm.symbols()) {
994 const MCSymbol &Symbol = SD.getSymbol();
996 bool Used = UsedInReloc.count(&Symbol);
997 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
998 bool isSignature = RevGroupMap.count(&Symbol);
1000 if (!isInSymtab(Layout, SD,
1001 Used || WeakrefUsed || isSignature,
1002 Renames.count(&Symbol)))
1006 MSD.SymbolData = &SD;
1007 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1009 // Undefined symbols are global, but this is the first place we
1010 // are able to set it.
1011 bool Local = isLocal(SD, Used);
1012 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1014 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1015 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1016 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1020 MSD.SectionIndex = ELF::SHN_ABS;
1021 } else if (SD.isCommon()) {
1023 MSD.SectionIndex = ELF::SHN_COMMON;
1024 } else if (BaseSymbol->isUndefined()) {
1025 if (isSignature && !Used)
1026 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
1028 MSD.SectionIndex = ELF::SHN_UNDEF;
1029 if (!Used && WeakrefUsed)
1030 MCELF::SetBinding(SD, ELF::STB_WEAK);
1032 const MCSectionELF &Section =
1033 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1034 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1035 assert(MSD.SectionIndex && "Invalid section index!");
1038 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1041 // FIXME: All name handling should be done before we get to the writer,
1042 // including dealing with GNU-style version suffixes. Fixing this isn't
1045 // We thus have to be careful to not perform the symbol version replacement
1048 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1049 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1050 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1051 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1052 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1053 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1054 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1055 // "__imp_?" or "__imp_@?".
1057 // It would have been interesting to perform the MS mangling prefix check
1058 // only when the target triple is of the form *-pc-windows-elf. But, it
1059 // seems that this information is not easily accessible from the
1061 StringRef Name = Symbol.getName();
1062 if (!Name.startswith("?") && !Name.startswith("@?") &&
1063 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1064 // This symbol isn't following the MSVC C++ name mangling convention. We
1065 // can thus safely interpret the @@@ in symbol names as specifying symbol
1067 SmallString<32> Buf;
1068 size_t Pos = Name.find("@@@");
1069 if (Pos != StringRef::npos) {
1070 Buf += Name.substr(0, Pos);
1071 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1072 Buf += Name.substr(Pos + Skip);
1077 // Sections have their own string table
1078 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1079 MSD.Name = StrTabBuilder.add(Name);
1081 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1082 UndefinedSymbolData.push_back(MSD);
1084 LocalSymbolData.push_back(MSD);
1086 ExternalSymbolData.push_back(MSD);
1089 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1090 StrTabBuilder.add(*i);
1092 StrTabBuilder.finalize(StringTableBuilder::ELF);
1094 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1095 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1097 for (ELFSymbolData &MSD : LocalSymbolData)
1098 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1100 : StrTabBuilder.getOffset(MSD.Name);
1101 for (ELFSymbolData &MSD : ExternalSymbolData)
1102 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1103 for (ELFSymbolData& MSD : UndefinedSymbolData)
1104 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1106 // Symbols are required to be in lexicographic order.
1107 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1108 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1109 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1111 // Set the symbol indices. Local symbols must come before all other
1112 // symbols with non-local bindings.
1113 unsigned Index = FileSymbolData.size() + 1;
1114 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1115 LocalSymbolData[i].SymbolData->setIndex(Index++);
1117 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1118 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1119 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1120 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1123 void ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1124 const MCSectionData &SD) {
1125 if (Relocations[&SD].empty())
1128 MCContext &Ctx = Asm.getContext();
1129 const MCSectionELF &Section =
1130 static_cast<const MCSectionELF &>(SD.getSection());
1132 const StringRef SectionName = Section.getSectionName();
1133 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1134 RelaSectionName += SectionName;
1137 if (hasRelocationAddend())
1138 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1140 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1143 if (Section.getFlags() & ELF::SHF_GROUP)
1144 Flags = ELF::SHF_GROUP;
1146 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1147 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1148 Flags, EntrySize, Section.getGroup(), &Section);
1149 Asm.getOrCreateSectionData(*RelaSection);
1152 static SmallVector<char, 128>
1153 getUncompressedData(const MCAsmLayout &Layout,
1154 MCSectionData::FragmentListType &Fragments) {
1155 SmallVector<char, 128> UncompressedData;
1156 for (const MCFragment &F : Fragments) {
1157 const SmallVectorImpl<char> *Contents;
1158 switch (F.getKind()) {
1159 case MCFragment::FT_Data:
1160 Contents = &cast<MCDataFragment>(F).getContents();
1162 case MCFragment::FT_Dwarf:
1163 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1165 case MCFragment::FT_DwarfFrame:
1166 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1170 "Not expecting any other fragment types in a debug_* section");
1172 UncompressedData.append(Contents->begin(), Contents->end());
1174 return UncompressedData;
1177 // Include the debug info compression header:
1178 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1179 // useful for consumers to preallocate a buffer to decompress into.
1181 prependCompressionHeader(uint64_t Size,
1182 SmallVectorImpl<char> &CompressedContents) {
1183 const StringRef Magic = "ZLIB";
1184 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1186 if (sys::IsLittleEndianHost)
1187 sys::swapByteOrder(Size);
1188 CompressedContents.insert(CompressedContents.begin(),
1189 Magic.size() + sizeof(Size), 0);
1190 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1191 std::copy(reinterpret_cast<char *>(&Size),
1192 reinterpret_cast<char *>(&Size + 1),
1193 CompressedContents.begin() + Magic.size());
1197 // Return a single fragment containing the compressed contents of the whole
1198 // section. Null if the section was not compressed for any reason.
1199 static std::unique_ptr<MCDataFragment>
1200 getCompressedFragment(const MCAsmLayout &Layout,
1201 MCSectionData::FragmentListType &Fragments) {
1202 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1204 // Gather the uncompressed data from all the fragments, recording the
1205 // alignment fragment, if seen, and any fixups.
1206 SmallVector<char, 128> UncompressedData =
1207 getUncompressedData(Layout, Fragments);
1209 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1211 zlib::Status Success = zlib::compress(
1212 StringRef(UncompressedData.data(), UncompressedData.size()),
1213 CompressedContents);
1214 if (Success != zlib::StatusOK)
1217 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1220 return CompressedFragment;
1223 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1226 static void UpdateSymbols(const MCAsmLayout &Layout,
1227 const std::vector<MCSymbolData *> &Symbols,
1228 MCFragment &NewFragment) {
1229 for (MCSymbolData *Sym : Symbols) {
1230 Sym->setOffset(Sym->getOffset() +
1231 Layout.getFragmentOffset(Sym->getFragment()));
1232 Sym->setFragment(&NewFragment);
1236 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1237 const DefiningSymbolMap &DefiningSymbols,
1238 const MCSectionELF &Section,
1239 MCSectionData &SD) {
1240 StringRef SectionName = Section.getSectionName();
1241 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1243 std::unique_ptr<MCDataFragment> CompressedFragment =
1244 getCompressedFragment(Layout, Fragments);
1246 // Leave the section as-is if the fragments could not be compressed.
1247 if (!CompressedFragment)
1250 // Update the fragment+offsets of any symbols referring to fragments in this
1251 // section to refer to the new fragment.
1252 auto I = DefiningSymbols.find(&SD);
1253 if (I != DefiningSymbols.end())
1254 UpdateSymbols(Layout, I->second, *CompressedFragment);
1256 // Invalidate the layout for the whole section since it will have new and
1257 // different fragments now.
1258 Layout.invalidateFragmentsFrom(&Fragments.front());
1261 // Complete the initialization of the new fragment
1262 CompressedFragment->setParent(&SD);
1263 CompressedFragment->setLayoutOrder(0);
1264 Fragments.push_back(CompressedFragment.release());
1266 // Rename from .debug_* to .zdebug_*
1267 Asm.getContext().renameELFSection(&Section,
1268 (".z" + SectionName.drop_front(1)).str());
1271 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1272 MCAsmLayout &Layout) {
1273 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1276 DefiningSymbolMap DefiningSymbols;
1278 for (MCSymbolData &SD : Asm.symbols())
1279 if (MCFragment *F = SD.getFragment())
1280 DefiningSymbols[F->getParent()].push_back(&SD);
1282 for (MCSectionData &SD : Asm) {
1283 const MCSectionELF &Section =
1284 static_cast<const MCSectionELF &>(SD.getSection());
1285 StringRef SectionName = Section.getSectionName();
1287 // Compressing debug_frame requires handling alignment fragments which is
1288 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1289 // for writing to arbitrary buffers) for little benefit.
1290 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1293 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1297 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm,
1298 const MCAsmLayout &Layout) {
1299 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1300 MCSectionData &RelSD = *it;
1301 const MCSectionELF &RelSection =
1302 static_cast<const MCSectionELF &>(RelSD.getSection());
1304 unsigned Type = RelSection.getType();
1305 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1308 const MCSectionELF *Section = RelSection.getAssociatedSection();
1309 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1310 RelSD.setAlignment(is64Bit() ? 8 : 4);
1312 MCDataFragment *F = new MCDataFragment(&RelSD);
1313 WriteRelocationsFragment(Asm, F, &SD);
1317 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1318 uint64_t Flags, uint64_t Address,
1319 uint64_t Offset, uint64_t Size,
1320 uint32_t Link, uint32_t Info,
1322 uint64_t EntrySize) {
1323 Write32(Name); // sh_name: index into string table
1324 Write32(Type); // sh_type
1325 WriteWord(Flags); // sh_flags
1326 WriteWord(Address); // sh_addr
1327 WriteWord(Offset); // sh_offset
1328 WriteWord(Size); // sh_size
1329 Write32(Link); // sh_link
1330 Write32(Info); // sh_info
1331 WriteWord(Alignment); // sh_addralign
1332 WriteWord(EntrySize); // sh_entsize
1335 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1337 const MCSectionData *SD) {
1338 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1340 // Sort the relocation entries. Most targets just sort by Offset, but some
1341 // (e.g., MIPS) have additional constraints.
1342 TargetObjectWriter->sortRelocs(Asm, Relocs);
1344 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1345 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1347 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1350 write(*F, Entry.Offset);
1351 if (TargetObjectWriter->isN64()) {
1352 write(*F, uint32_t(Index));
1354 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1355 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1356 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1357 write(*F, TargetObjectWriter->getRType(Entry.Type));
1359 struct ELF::Elf64_Rela ERE64;
1360 ERE64.setSymbolAndType(Index, Entry.Type);
1361 write(*F, ERE64.r_info);
1363 if (hasRelocationAddend())
1364 write(*F, Entry.Addend);
1366 write(*F, uint32_t(Entry.Offset));
1368 struct ELF::Elf32_Rela ERE32;
1369 ERE32.setSymbolAndType(Index, Entry.Type);
1370 write(*F, ERE32.r_info);
1372 if (hasRelocationAddend())
1373 write(*F, uint32_t(Entry.Addend));
1378 void ELFObjectWriter::createSectionHeaderStringTable(
1379 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1380 const MCSectionELF *ShstrtabSection = Sections[ShstrtabIndex - 1];
1382 Asm.getOrCreateSectionData(*ShstrtabSection);
1384 for (MCSectionData &SD : Asm) {
1385 const MCSectionELF &Section =
1386 static_cast<const MCSectionELF &>(SD.getSection());
1387 ShStrTabBuilder.add(Section.getSectionName());
1389 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1390 OS << ShStrTabBuilder.data();
1393 void ELFObjectWriter::createStringTable(
1394 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1395 MCContext &Ctx = Asm.getContext();
1396 const MCSectionELF *StrtabSection =
1397 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1398 Asm.getOrCreateSectionData(*StrtabSection);
1399 Sections.push_back(StrtabSection);
1400 StringTableIndex = Sections.size();
1401 OS << StrTabBuilder.data();
1404 void ELFObjectWriter::CreateMetadataSections(
1405 MCAssembler &Asm, const MCAsmLayout &Layout,
1406 std::vector<const MCSectionELF *> &Sections) {
1407 MCContext &Ctx = Asm.getContext();
1410 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1413 const MCSectionELF *SymtabSection =
1414 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1416 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1417 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1418 SymbolTableIndex = Sections.size() + 1;
1419 Sections.push_back(SymtabSection);
1420 F = new MCDataFragment(&SymtabSD);
1421 WriteSymbolTable(F, Asm, Layout, Sections);
1424 void ELFObjectWriter::createIndexedSections(
1425 MCAssembler &Asm, const MCAsmLayout &Layout, RevGroupMapTy &RevGroupMap,
1426 std::vector<const MCSectionELF *> &Sections,
1427 SectionIndexMapTy &SectionIndexMap) {
1428 MCContext &Ctx = Asm.getContext();
1430 const MCSectionELF *ShstrtabSection =
1431 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1432 Sections.push_back(ShstrtabSection);
1433 ShstrtabIndex = Sections.size();
1434 assert(ShstrtabIndex == 1);
1437 for (const MCSectionData &SD : Asm) {
1438 const MCSectionELF &Section =
1439 static_cast<const MCSectionELF &>(SD.getSection());
1440 if (!(Section.getFlags() & ELF::SHF_GROUP))
1443 const MCSymbol *SignatureSymbol = Section.getGroup();
1444 Asm.getOrCreateSymbolData(*SignatureSymbol);
1445 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1447 const MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1448 Sections.push_back(Group);
1449 GroupIdx = Sections.size();
1451 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1452 Data.setAlignment(4);
1453 MCDataFragment *F = new MCDataFragment(&Data);
1454 write(*F, uint32_t(ELF::GRP_COMDAT));
1458 computeIndexMap(Asm, Sections, SectionIndexMap, RevGroupMap);
1461 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1462 const SectionIndexMapTy &SectionIndexMap,
1463 uint32_t GroupSymbolIndex,
1464 uint64_t Offset, uint64_t Size,
1466 const MCSectionELF &Section) {
1467 uint64_t sh_link = 0;
1468 uint64_t sh_info = 0;
1470 switch(Section.getType()) {
1475 case ELF::SHT_DYNAMIC:
1476 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1480 case ELF::SHT_RELA: {
1481 sh_link = SymbolTableIndex;
1482 assert(sh_link && ".symtab not found");
1483 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1484 sh_info = SectionIndexMap.lookup(InfoSection);
1488 case ELF::SHT_SYMTAB:
1489 case ELF::SHT_DYNSYM:
1490 sh_link = StringTableIndex;
1491 sh_info = LastLocalSymbolIndex;
1494 case ELF::SHT_SYMTAB_SHNDX:
1495 sh_link = SymbolTableIndex;
1498 case ELF::SHT_GROUP:
1499 sh_link = SymbolTableIndex;
1500 sh_info = GroupSymbolIndex;
1504 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1505 Section.getType() == ELF::SHT_ARM_EXIDX)
1506 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1508 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1510 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1511 Alignment, Section.getEntrySize());
1514 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1515 return SD.getOrdinal() == ~UINT32_C(0) &&
1516 !SD.getSection().isVirtualSection();
1519 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1520 const MCAsmLayout &Layout,
1521 const MCSectionData &SD) {
1522 if (IsELFMetaDataSection(SD)) {
1523 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1525 const MCFragment &F = *i;
1526 assert(F.getKind() == MCFragment::FT_Data);
1527 WriteBytes(cast<MCDataFragment>(F).getContents());
1530 Asm.writeSectionData(&SD, Layout);
1534 void ELFObjectWriter::writeSectionHeader(
1535 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1536 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1537 const SectionOffsetsTy &SectionOffsets) {
1538 const unsigned NumSections = Asm.size();
1540 // Null section first.
1541 uint64_t FirstSectionSize =
1542 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1543 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1545 for (unsigned i = 0; i < NumSections; ++i) {
1546 const MCSectionELF &Section = *Sections[i];
1547 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1548 uint32_t GroupSymbolIndex;
1549 if (Section.getType() != ELF::SHT_GROUP)
1550 GroupSymbolIndex = 0;
1552 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section.getGroup());
1554 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
1555 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1556 ? Layout.getSectionAddressSize(&SD)
1557 : Offsets.second - Offsets.first;
1559 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1560 SD.getAlignment(), Section);
1564 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1565 const MCAsmLayout &Layout) {
1566 RevGroupMapTy RevGroupMap;
1567 SectionIndexMapTy SectionIndexMap;
1569 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1570 std::vector<const MCSectionELF *> Sections;
1571 createIndexedSections(Asm, Layout, RevGroupMap, Sections, SectionIndexMap);
1573 // Compute symbol table information.
1574 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1576 WriteRelocations(Asm, Layout);
1578 CreateMetadataSections(Asm, Layout, Sections);
1580 unsigned NumSections = Asm.size() + 2;
1581 SectionOffsetsTy SectionOffsets;
1583 // Write out the ELF header ...
1584 WriteHeader(Asm, NumSections + 1);
1586 // ... then the sections ...
1587 SectionOffsets.push_back(std::make_pair(0, 0));
1588 for (auto I = ++Sections.begin(), E = Sections.end(); I != E; ++I) {
1589 const MCSectionData &SD = Asm.getOrCreateSectionData(**I);
1590 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1591 WriteZeros(Padding);
1593 // Remember the offset into the file for this section.
1594 uint64_t SecStart = OS.tell();
1595 writeDataSectionData(Asm, Layout, SD);
1596 uint64_t SecEnd = OS.tell();
1597 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1601 uint64_t SecStart = OS.tell();
1602 createStringTable(Asm, Sections);
1603 uint64_t SecEnd = OS.tell();
1604 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1608 uint64_t SecStart = OS.tell();
1609 createSectionHeaderStringTable(Asm, Sections);
1610 uint64_t SecEnd = OS.tell();
1611 SectionOffsets[0] = std::make_pair(SecStart, SecEnd);
1614 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1615 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1616 WriteZeros(Padding);
1618 const unsigned SectionHeaderOffset = OS.tell();
1620 // ... then the section header table ...
1621 writeSectionHeader(Sections, Asm, Layout, SectionIndexMap, SectionOffsets);
1624 uint64_t Val = SectionHeaderOffset;
1625 if (sys::IsLittleEndianHost != IsLittleEndian)
1626 sys::swapByteOrder(Val);
1627 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1628 offsetof(ELF::Elf64_Ehdr, e_shoff));
1630 uint32_t Val = SectionHeaderOffset;
1631 if (sys::IsLittleEndianHost != IsLittleEndian)
1632 sys::swapByteOrder(Val);
1633 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1634 offsetof(ELF::Elf32_Ehdr, e_shoff));
1638 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1639 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1640 bool InSet, bool IsPCRel) const {
1643 if (::isWeak(DataA))
1646 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1650 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1654 // It is invalid to replace a reference to a global in a comdat
1655 // with a reference to a local since out of comdat references
1656 // to a local are forbidden.
1657 // We could try to return false for more cases, like the reference
1658 // being in the same comdat or Sym being an alias to another global,
1659 // but it is not clear if it is worth the effort.
1660 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1663 const MCSymbol &Sym = SD.getSymbol();
1664 if (!Sym.isInSection())
1667 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1668 return Sec.getGroup();
1671 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1672 raw_pwrite_stream &OS,
1673 bool IsLittleEndian) {
1674 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);