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);
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 SectionIndexMapTy &SectionIndexMap);
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 group section to the signature symbol
221 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
222 // Map from a signature symbol to the group section
223 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
224 // Start and end offset of each section
225 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
227 /// Compute the symbol table data
229 /// \param Asm - The assembler.
230 /// \param SectionIndexMap - Maps a section to its index.
231 /// \param RevGroupMap - Maps a signature symbol to the group section.
232 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
233 const SectionIndexMapTy &SectionIndexMap,
234 const RevGroupMapTy &RevGroupMap);
236 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
238 MCSectionData *createRelocationSection(MCAssembler &Asm,
239 const MCSectionData &SD);
241 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
243 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
245 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
246 SectionIndexMapTy &SectionIndexMap);
248 // Create the sections that show up in the symbol table. Currently
249 // those are the .note.GNU-stack section and the group sections.
250 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
251 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
252 SectionIndexMapTy &SectionIndexMap);
254 void ExecutePostLayoutBinding(MCAssembler &Asm,
255 const MCAsmLayout &Layout) override;
257 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
258 MCAssembler &Asm, const GroupMapTy &GroupMap,
259 const MCAsmLayout &Layout,
260 const SectionIndexMapTy &SectionIndexMap,
261 const SectionOffsetsTy &SectionOffsets);
263 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
264 uint64_t Address, uint64_t Offset,
265 uint64_t Size, uint32_t Link, uint32_t Info,
266 uint64_t Alignment, uint64_t EntrySize);
268 void WriteRelocationsFragment(const MCAssembler &Asm,
270 const MCSectionData *SD);
273 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
274 const MCSymbolData &DataA,
275 const MCFragment &FB,
277 bool IsPCRel) const override;
279 bool isWeak(const MCSymbolData &SD) const override;
281 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
282 void writeSection(MCAssembler &Asm,
283 const SectionIndexMapTy &SectionIndexMap,
284 uint32_t GroupSymbolIndex,
285 uint64_t Offset, uint64_t Size, uint64_t Alignment,
286 const MCSectionELF &Section);
290 FragmentWriter::FragmentWriter(bool IsLittleEndian)
291 : IsLittleEndian(IsLittleEndian) {}
293 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
295 Val = support::endian::byte_swap<T, support::little>(Val);
297 Val = support::endian::byte_swap<T, support::big>(Val);
298 const char *Start = (const char *)&Val;
299 F.getContents().append(Start, Start + sizeof(T));
302 void SymbolTableWriter::createSymtabShndx() {
306 MCContext &Ctx = Asm.getContext();
307 const MCSectionELF *SymtabShndxSection =
308 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
309 MCSectionData *SymtabShndxSD =
310 &Asm.getOrCreateSectionData(*SymtabShndxSection);
311 SymtabShndxSD->setAlignment(4);
312 ShndxF = new MCDataFragment(SymtabShndxSD);
313 unsigned Index = SectionIndexMap.size() + 1;
314 SectionIndexMap[SymtabShndxSection] = Index;
316 for (unsigned I = 0; I < NumWritten; ++I)
317 write(*ShndxF, uint32_t(0));
320 template <typename T>
321 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
322 FWriter.write(F, Value);
325 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
327 SectionIndexMapTy &SectionIndexMap,
328 MCDataFragment *SymtabF)
329 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
330 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
333 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
334 uint64_t size, uint8_t other,
335 uint32_t shndx, bool Reserved) {
336 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
343 write(*ShndxF, shndx);
345 write(*ShndxF, uint32_t(0));
348 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
351 write(*SymtabF, name); // st_name
352 write(*SymtabF, info); // st_info
353 write(*SymtabF, other); // st_other
354 write(*SymtabF, Index); // st_shndx
355 write(*SymtabF, value); // st_value
356 write(*SymtabF, size); // st_size
358 write(*SymtabF, name); // st_name
359 write(*SymtabF, uint32_t(value)); // st_value
360 write(*SymtabF, uint32_t(size)); // st_size
361 write(*SymtabF, info); // st_info
362 write(*SymtabF, other); // st_other
363 write(*SymtabF, Index); // st_shndx
369 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
370 const MCFixupKindInfo &FKI =
371 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
373 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
376 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
380 case MCSymbolRefExpr::VK_GOT:
381 case MCSymbolRefExpr::VK_PLT:
382 case MCSymbolRefExpr::VK_GOTPCREL:
383 case MCSymbolRefExpr::VK_GOTOFF:
384 case MCSymbolRefExpr::VK_TPOFF:
385 case MCSymbolRefExpr::VK_TLSGD:
386 case MCSymbolRefExpr::VK_GOTTPOFF:
387 case MCSymbolRefExpr::VK_INDNTPOFF:
388 case MCSymbolRefExpr::VK_NTPOFF:
389 case MCSymbolRefExpr::VK_GOTNTPOFF:
390 case MCSymbolRefExpr::VK_TLSLDM:
391 case MCSymbolRefExpr::VK_DTPOFF:
392 case MCSymbolRefExpr::VK_TLSLD:
397 ELFObjectWriter::~ELFObjectWriter()
400 // Emit the ELF header.
401 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
402 unsigned NumberOfSections) {
408 // emitWord method behaves differently for ELF32 and ELF64, writing
409 // 4 bytes in the former and 8 in the latter.
411 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
413 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
416 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
418 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
420 Write8(TargetObjectWriter->getOSABI());
421 Write8(0); // e_ident[EI_ABIVERSION]
423 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
425 Write16(ELF::ET_REL); // e_type
427 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
429 Write32(ELF::EV_CURRENT); // e_version
430 WriteWord(0); // e_entry, no entry point in .o file
431 WriteWord(0); // e_phoff, no program header for .o
432 WriteWord(0); // e_shoff = sec hdr table off in bytes
434 // e_flags = whatever the target wants
435 Write32(Asm.getELFHeaderEFlags());
437 // e_ehsize = ELF header size
438 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
440 Write16(0); // e_phentsize = prog header entry size
441 Write16(0); // e_phnum = # prog header entries = 0
443 // e_shentsize = Section header entry size
444 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
446 // e_shnum = # of section header ents
447 if (NumberOfSections >= ELF::SHN_LORESERVE)
448 Write16(ELF::SHN_UNDEF);
450 Write16(NumberOfSections);
452 // e_shstrndx = Section # of '.shstrtab'
453 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
454 Write16(ELF::SHN_XINDEX);
456 Write16(ShstrtabIndex);
459 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
460 const MCAsmLayout &Layout) {
461 if (Data.isCommon() && Data.isExternal())
462 return Data.getCommonAlignment();
465 if (!Layout.getSymbolOffset(&Data, Res))
468 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
474 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
475 const MCAsmLayout &Layout) {
476 // The presence of symbol versions causes undefined symbols and
477 // versions declared with @@@ to be renamed.
479 for (MCSymbolData &OriginalData : Asm.symbols()) {
480 const MCSymbol &Alias = OriginalData.getSymbol();
483 if (!Alias.isVariable())
485 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
488 const MCSymbol &Symbol = Ref->getSymbol();
489 MCSymbolData &SD = Asm.getSymbolData(Symbol);
491 StringRef AliasName = Alias.getName();
492 size_t Pos = AliasName.find('@');
493 if (Pos == StringRef::npos)
496 // Aliases defined with .symvar copy the binding from the symbol they alias.
497 // This is the first place we are able to copy this information.
498 OriginalData.setExternal(SD.isExternal());
499 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
501 StringRef Rest = AliasName.substr(Pos);
502 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
505 // FIXME: produce a better error message.
506 if (Symbol.isUndefined() && Rest.startswith("@@") &&
507 !Rest.startswith("@@@"))
508 report_fatal_error("A @@ version cannot be undefined");
510 Renames.insert(std::make_pair(&Symbol, &Alias));
514 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
515 uint8_t Type = newType;
517 // Propagation rules:
518 // IFUNC > FUNC > OBJECT > NOTYPE
519 // TLS_OBJECT > OBJECT > NOTYPE
521 // dont let the new type degrade the old type
525 case ELF::STT_GNU_IFUNC:
526 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
527 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
528 Type = ELF::STT_GNU_IFUNC;
531 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
532 Type == ELF::STT_TLS)
533 Type = ELF::STT_FUNC;
535 case ELF::STT_OBJECT:
536 if (Type == ELF::STT_NOTYPE)
537 Type = ELF::STT_OBJECT;
540 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
541 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
549 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
550 const MCAsmLayout &Layout) {
551 MCSymbolData &OrigData = *MSD.SymbolData;
552 assert((!OrigData.getFragment() ||
553 (&OrigData.getFragment()->getParent()->getSection() ==
554 &OrigData.getSymbol().getSection())) &&
555 "The symbol's section doesn't match the fragment's symbol");
556 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
558 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
560 bool IsReserved = !Base || OrigData.isCommon();
562 // Binding and Type share the same byte as upper and lower nibbles
563 uint8_t Binding = MCELF::GetBinding(OrigData);
564 uint8_t Type = MCELF::GetType(OrigData);
565 MCSymbolData *BaseSD = nullptr;
567 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
568 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
570 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
572 // Other and Visibility share the same byte with Visibility using the lower
574 uint8_t Visibility = MCELF::GetVisibility(OrigData);
575 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
578 uint64_t Value = SymbolValue(OrigData, Layout);
581 const MCExpr *ESize = OrigData.getSize();
583 ESize = BaseSD->getSize();
587 if (!ESize->evaluateKnownAbsolute(Res, Layout))
588 report_fatal_error("Size expression must be absolute.");
592 // Write out the symbol table entry
593 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
594 MSD.SectionIndex, IsReserved);
597 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
599 const MCAsmLayout &Layout,
600 SectionIndexMapTy &SectionIndexMap) {
601 // The string table must be emitted first because we need the index
602 // into the string table for all the symbol names.
604 // FIXME: Make sure the start of the symbol table is aligned.
606 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
608 // The first entry is the undefined symbol entry.
609 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
611 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
612 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
613 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
616 // Write the symbol table entries.
617 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
619 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
620 ELFSymbolData &MSD = LocalSymbolData[i];
621 WriteSymbol(Writer, MSD, Layout);
624 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
625 ELFSymbolData &MSD = ExternalSymbolData[i];
626 MCSymbolData &Data = *MSD.SymbolData;
627 assert(((Data.getFlags() & ELF_STB_Global) ||
628 (Data.getFlags() & ELF_STB_Weak)) &&
629 "External symbol requires STB_GLOBAL or STB_WEAK flag");
630 WriteSymbol(Writer, MSD, Layout);
631 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
632 LastLocalSymbolIndex++;
635 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
636 ELFSymbolData &MSD = UndefinedSymbolData[i];
637 MCSymbolData &Data = *MSD.SymbolData;
638 WriteSymbol(Writer, MSD, Layout);
639 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
640 LastLocalSymbolIndex++;
644 // It is always valid to create a relocation with a symbol. It is preferable
645 // to use a relocation with a section if that is possible. Using the section
646 // allows us to omit some local symbols from the symbol table.
647 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
648 const MCSymbolRefExpr *RefA,
649 const MCSymbolData *SD,
651 unsigned Type) const {
652 // A PCRel relocation to an absolute value has no symbol (or section). We
653 // represent that with a relocation to a null section.
657 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
661 // The .odp creation emits a relocation against the symbol ".TOC." which
662 // create a R_PPC64_TOC relocation. However the relocation symbol name
663 // in final object creation should be NULL, since the symbol does not
664 // really exist, it is just the reference to TOC base for the current
665 // object file. Since the symbol is undefined, returning false results
666 // in a relocation with a null section which is the desired result.
667 case MCSymbolRefExpr::VK_PPC_TOCBASE:
670 // These VariantKind cause the relocation to refer to something other than
671 // the symbol itself, like a linker generated table. Since the address of
672 // symbol is not relevant, we cannot replace the symbol with the
673 // section and patch the difference in the addend.
674 case MCSymbolRefExpr::VK_GOT:
675 case MCSymbolRefExpr::VK_PLT:
676 case MCSymbolRefExpr::VK_GOTPCREL:
677 case MCSymbolRefExpr::VK_Mips_GOT:
678 case MCSymbolRefExpr::VK_PPC_GOT_LO:
679 case MCSymbolRefExpr::VK_PPC_GOT_HI:
680 case MCSymbolRefExpr::VK_PPC_GOT_HA:
684 // An undefined symbol is not in any section, so the relocation has to point
685 // to the symbol itself.
686 const MCSymbol &Sym = SD->getSymbol();
687 if (Sym.isUndefined())
690 unsigned Binding = MCELF::GetBinding(*SD);
693 llvm_unreachable("Invalid Binding");
697 // If the symbol is weak, it might be overridden by a symbol in another
698 // file. The relocation has to point to the symbol so that the linker
701 case ELF::STB_GLOBAL:
702 // Global ELF symbols can be preempted by the dynamic linker. The relocation
703 // has to point to the symbol for a reason analogous to the STB_WEAK case.
707 // If a relocation points to a mergeable section, we have to be careful.
708 // If the offset is zero, a relocation with the section will encode the
709 // same information. With a non-zero offset, the situation is different.
710 // For example, a relocation can point 42 bytes past the end of a string.
711 // If we change such a relocation to use the section, the linker would think
712 // that it pointed to another string and subtracting 42 at runtime will
713 // produce the wrong value.
714 auto &Sec = cast<MCSectionELF>(Sym.getSection());
715 unsigned Flags = Sec.getFlags();
716 if (Flags & ELF::SHF_MERGE) {
720 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
721 // only handle section relocations to mergeable sections if using RELA.
722 if (!hasRelocationAddend())
726 // Most TLS relocations use a got, so they need the symbol. Even those that
727 // are just an offset (@tpoff), require a symbol in gold versions before
728 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
729 // http://sourceware.org/PR16773.
730 if (Flags & ELF::SHF_TLS)
733 // If the symbol is a thumb function the final relocation must set the lowest
734 // bit. With a symbol that is done by just having the symbol have that bit
735 // set, so we would lose the bit if we relocated with the section.
736 // FIXME: We could use the section but add the bit to the relocation value.
737 if (Asm.isThumbFunc(&Sym))
740 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
745 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
746 const MCSymbol &Sym = Ref.getSymbol();
748 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
751 if (!Sym.isVariable())
754 const MCExpr *Expr = Sym.getVariableValue();
755 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
759 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
760 return &Inner->getSymbol();
764 // True if the assembler knows nothing about the final value of the symbol.
765 // This doesn't cover the comdat issues, since in those cases the assembler
766 // can at least know that all symbols in the section will move together.
767 static bool isWeak(const MCSymbolData &D) {
768 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
771 switch (MCELF::GetBinding(D)) {
773 llvm_unreachable("Unknown binding");
776 case ELF::STB_GLOBAL:
779 case ELF::STB_GNU_UNIQUE:
784 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
785 const MCAsmLayout &Layout,
786 const MCFragment *Fragment,
787 const MCFixup &Fixup, MCValue Target,
788 bool &IsPCRel, uint64_t &FixedValue) {
789 const MCSectionData *FixupSection = Fragment->getParent();
790 uint64_t C = Target.getConstant();
791 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
793 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
794 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
795 "Should not have constructed this");
797 // Let A, B and C being the components of Target and R be the location of
798 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
799 // If it is pcrel, we want to compute (A - B + C - R).
801 // In general, ELF has no relocations for -B. It can only represent (A + C)
802 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
803 // replace B to implement it: (A - R - K + C)
805 Asm.getContext().FatalError(
807 "No relocation available to represent this relative expression");
809 const MCSymbol &SymB = RefB->getSymbol();
811 if (SymB.isUndefined())
812 Asm.getContext().FatalError(
814 Twine("symbol '") + SymB.getName() +
815 "' can not be undefined in a subtraction expression");
817 assert(!SymB.isAbsolute() && "Should have been folded");
818 const MCSection &SecB = SymB.getSection();
819 if (&SecB != &FixupSection->getSection())
820 Asm.getContext().FatalError(
821 Fixup.getLoc(), "Cannot represent a difference across sections");
823 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
825 Asm.getContext().FatalError(
826 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
828 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
829 uint64_t K = SymBOffset - FixupOffset;
834 // We either rejected the fixup or folded B into C at this point.
835 const MCSymbolRefExpr *RefA = Target.getSymA();
836 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
837 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
839 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
840 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
841 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
842 C += Layout.getSymbolOffset(SymAD);
845 if (hasRelocationAddend()) {
852 // FIXME: What is this!?!?
853 MCSymbolRefExpr::VariantKind Modifier =
854 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
855 if (RelocNeedsGOT(Modifier))
858 if (!RelocateWithSymbol) {
859 const MCSection *SecA =
860 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
861 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
862 MCSymbol *SectionSymbol =
863 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
865 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
866 Relocations[FixupSection].push_back(Rec);
871 if (const MCSymbol *R = Renames.lookup(SymA))
874 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
875 WeakrefUsedInReloc.insert(WeakRef);
877 UsedInReloc.insert(SymA);
879 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
880 Relocations[FixupSection].push_back(Rec);
886 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
888 const MCSymbolData &SD = Asm.getSymbolData(*S);
889 return SD.getIndex();
892 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
893 const MCSymbolData &Data, bool Used,
895 const MCSymbol &Symbol = Data.getSymbol();
896 if (Symbol.isVariable()) {
897 const MCExpr *Expr = Symbol.getVariableValue();
898 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
899 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
910 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
913 if (Symbol.isVariable()) {
914 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
915 if (Base && Base->isUndefined())
919 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
920 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
923 if (Symbol.isTemporary())
929 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
930 if (Data.isExternal())
933 const MCSymbol &Symbol = Data.getSymbol();
934 if (Symbol.isDefined())
943 void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
944 SectionIndexMapTy &SectionIndexMap) {
946 for (MCAssembler::iterator it = Asm.begin(),
947 ie = Asm.end(); it != ie; ++it) {
948 const MCSectionELF &Section =
949 static_cast<const MCSectionELF &>(it->getSection());
950 if (Section.getType() != ELF::SHT_GROUP)
952 SectionIndexMap[&Section] = Index++;
955 std::vector<const MCSectionELF *> RelSections;
957 for (MCAssembler::iterator it = Asm.begin(),
958 ie = Asm.end(); it != ie; ++it) {
959 const MCSectionData &SD = *it;
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF &>(SD.getSection());
962 if (Section.getType() == ELF::SHT_GROUP ||
963 Section.getType() == ELF::SHT_REL ||
964 Section.getType() == ELF::SHT_RELA)
966 SectionIndexMap[&Section] = Index++;
967 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
968 const MCSectionELF *RelSection =
969 static_cast<const MCSectionELF *>(&RelSD->getSection());
970 RelSections.push_back(RelSection);
974 // Put relocation sections close together. The linker reads them
975 // first, so this improves cache locality.
976 for (const MCSectionELF * Sec: RelSections)
977 SectionIndexMap[Sec] = Index++;
980 void ELFObjectWriter::computeSymbolTable(
981 MCAssembler &Asm, const MCAsmLayout &Layout,
982 const SectionIndexMapTy &SectionIndexMap,
983 const RevGroupMapTy &RevGroupMap) {
984 // FIXME: Is this the correct place to do this?
985 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
987 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
988 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
989 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
990 Data.setExternal(true);
991 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
994 // Add the data for the symbols.
995 for (MCSymbolData &SD : Asm.symbols()) {
996 const MCSymbol &Symbol = SD.getSymbol();
998 bool Used = UsedInReloc.count(&Symbol);
999 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1000 bool isSignature = RevGroupMap.count(&Symbol);
1002 if (!isInSymtab(Layout, SD,
1003 Used || WeakrefUsed || isSignature,
1004 Renames.count(&Symbol)))
1008 MSD.SymbolData = &SD;
1009 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
1011 // Undefined symbols are global, but this is the first place we
1012 // are able to set it.
1013 bool Local = isLocal(SD, Used);
1014 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1016 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1017 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1018 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1022 MSD.SectionIndex = ELF::SHN_ABS;
1023 } else if (SD.isCommon()) {
1025 MSD.SectionIndex = ELF::SHN_COMMON;
1026 } else if (BaseSymbol->isUndefined()) {
1027 if (isSignature && !Used)
1028 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
1030 MSD.SectionIndex = ELF::SHN_UNDEF;
1031 if (!Used && WeakrefUsed)
1032 MCELF::SetBinding(SD, ELF::STB_WEAK);
1034 const MCSectionELF &Section =
1035 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1036 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1037 assert(MSD.SectionIndex && "Invalid section index!");
1040 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1043 // FIXME: All name handling should be done before we get to the writer,
1044 // including dealing with GNU-style version suffixes. Fixing this isn't
1047 // We thus have to be careful to not perform the symbol version replacement
1050 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1051 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1052 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1053 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1054 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1055 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1056 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1057 // "__imp_?" or "__imp_@?".
1059 // It would have been interesting to perform the MS mangling prefix check
1060 // only when the target triple is of the form *-pc-windows-elf. But, it
1061 // seems that this information is not easily accessible from the
1063 StringRef Name = Symbol.getName();
1064 if (!Name.startswith("?") && !Name.startswith("@?") &&
1065 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1066 // This symbol isn't following the MSVC C++ name mangling convention. We
1067 // can thus safely interpret the @@@ in symbol names as specifying symbol
1069 SmallString<32> Buf;
1070 size_t Pos = Name.find("@@@");
1071 if (Pos != StringRef::npos) {
1072 Buf += Name.substr(0, Pos);
1073 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1074 Buf += Name.substr(Pos + Skip);
1079 // Sections have their own string table
1080 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1081 MSD.Name = StrTabBuilder.add(Name);
1083 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1084 UndefinedSymbolData.push_back(MSD);
1086 LocalSymbolData.push_back(MSD);
1088 ExternalSymbolData.push_back(MSD);
1091 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1092 StrTabBuilder.add(*i);
1094 StrTabBuilder.finalize(StringTableBuilder::ELF);
1096 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1097 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1099 for (ELFSymbolData &MSD : LocalSymbolData)
1100 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1102 : StrTabBuilder.getOffset(MSD.Name);
1103 for (ELFSymbolData &MSD : ExternalSymbolData)
1104 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1105 for (ELFSymbolData& MSD : UndefinedSymbolData)
1106 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1108 // Symbols are required to be in lexicographic order.
1109 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1110 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1111 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1113 // Set the symbol indices. Local symbols must come before all other
1114 // symbols with non-local bindings.
1115 unsigned Index = FileSymbolData.size() + 1;
1116 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1117 LocalSymbolData[i].SymbolData->setIndex(Index++);
1119 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1120 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1121 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1122 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1126 ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1127 const MCSectionData &SD) {
1128 if (Relocations[&SD].empty())
1131 MCContext &Ctx = Asm.getContext();
1132 const MCSectionELF &Section =
1133 static_cast<const MCSectionELF &>(SD.getSection());
1135 const StringRef SectionName = Section.getSectionName();
1136 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1137 RelaSectionName += SectionName;
1140 if (hasRelocationAddend())
1141 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1143 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1146 if (Section.getFlags() & ELF::SHF_GROUP)
1147 Flags = ELF::SHF_GROUP;
1149 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
1150 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1151 Flags, EntrySize, Section.getGroup(), &Section);
1152 return &Asm.getOrCreateSectionData(*RelaSection);
1155 static SmallVector<char, 128>
1156 getUncompressedData(MCAsmLayout &Layout,
1157 MCSectionData::FragmentListType &Fragments) {
1158 SmallVector<char, 128> UncompressedData;
1159 for (const MCFragment &F : Fragments) {
1160 const SmallVectorImpl<char> *Contents;
1161 switch (F.getKind()) {
1162 case MCFragment::FT_Data:
1163 Contents = &cast<MCDataFragment>(F).getContents();
1165 case MCFragment::FT_Dwarf:
1166 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1168 case MCFragment::FT_DwarfFrame:
1169 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1173 "Not expecting any other fragment types in a debug_* section");
1175 UncompressedData.append(Contents->begin(), Contents->end());
1177 return UncompressedData;
1180 // Include the debug info compression header:
1181 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1182 // useful for consumers to preallocate a buffer to decompress into.
1184 prependCompressionHeader(uint64_t Size,
1185 SmallVectorImpl<char> &CompressedContents) {
1186 const StringRef Magic = "ZLIB";
1187 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1189 if (sys::IsLittleEndianHost)
1190 sys::swapByteOrder(Size);
1191 CompressedContents.insert(CompressedContents.begin(),
1192 Magic.size() + sizeof(Size), 0);
1193 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1194 std::copy(reinterpret_cast<char *>(&Size),
1195 reinterpret_cast<char *>(&Size + 1),
1196 CompressedContents.begin() + Magic.size());
1200 // Return a single fragment containing the compressed contents of the whole
1201 // section. Null if the section was not compressed for any reason.
1202 static std::unique_ptr<MCDataFragment>
1203 getCompressedFragment(MCAsmLayout &Layout,
1204 MCSectionData::FragmentListType &Fragments) {
1205 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1207 // Gather the uncompressed data from all the fragments, recording the
1208 // alignment fragment, if seen, and any fixups.
1209 SmallVector<char, 128> UncompressedData =
1210 getUncompressedData(Layout, Fragments);
1212 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1214 zlib::Status Success = zlib::compress(
1215 StringRef(UncompressedData.data(), UncompressedData.size()),
1216 CompressedContents);
1217 if (Success != zlib::StatusOK)
1220 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1223 return CompressedFragment;
1226 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1229 static void UpdateSymbols(const MCAsmLayout &Layout,
1230 const std::vector<MCSymbolData *> &Symbols,
1231 MCFragment &NewFragment) {
1232 for (MCSymbolData *Sym : Symbols) {
1233 Sym->setOffset(Sym->getOffset() +
1234 Layout.getFragmentOffset(Sym->getFragment()));
1235 Sym->setFragment(&NewFragment);
1239 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1240 const DefiningSymbolMap &DefiningSymbols,
1241 const MCSectionELF &Section,
1242 MCSectionData &SD) {
1243 StringRef SectionName = Section.getSectionName();
1244 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1246 std::unique_ptr<MCDataFragment> CompressedFragment =
1247 getCompressedFragment(Layout, Fragments);
1249 // Leave the section as-is if the fragments could not be compressed.
1250 if (!CompressedFragment)
1253 // Update the fragment+offsets of any symbols referring to fragments in this
1254 // section to refer to the new fragment.
1255 auto I = DefiningSymbols.find(&SD);
1256 if (I != DefiningSymbols.end())
1257 UpdateSymbols(Layout, I->second, *CompressedFragment);
1259 // Invalidate the layout for the whole section since it will have new and
1260 // different fragments now.
1261 Layout.invalidateFragmentsFrom(&Fragments.front());
1264 // Complete the initialization of the new fragment
1265 CompressedFragment->setParent(&SD);
1266 CompressedFragment->setLayoutOrder(0);
1267 Fragments.push_back(CompressedFragment.release());
1269 // Rename from .debug_* to .zdebug_*
1270 Asm.getContext().renameELFSection(&Section,
1271 (".z" + SectionName.drop_front(1)).str());
1274 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1275 MCAsmLayout &Layout) {
1276 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1279 DefiningSymbolMap DefiningSymbols;
1281 for (MCSymbolData &SD : Asm.symbols())
1282 if (MCFragment *F = SD.getFragment())
1283 DefiningSymbols[F->getParent()].push_back(&SD);
1285 for (MCSectionData &SD : Asm) {
1286 const MCSectionELF &Section =
1287 static_cast<const MCSectionELF &>(SD.getSection());
1288 StringRef SectionName = Section.getSectionName();
1290 // Compressing debug_frame requires handling alignment fragments which is
1291 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1292 // for writing to arbitrary buffers) for little benefit.
1293 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1296 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1300 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
1301 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1302 MCSectionData &RelSD = *it;
1303 const MCSectionELF &RelSection =
1304 static_cast<const MCSectionELF &>(RelSD.getSection());
1306 unsigned Type = RelSection.getType();
1307 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
1310 const MCSectionELF *Section = RelSection.getAssociatedSection();
1311 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1312 RelSD.setAlignment(is64Bit() ? 8 : 4);
1314 MCDataFragment *F = new MCDataFragment(&RelSD);
1315 WriteRelocationsFragment(Asm, F, &SD);
1319 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1320 uint64_t Flags, uint64_t Address,
1321 uint64_t Offset, uint64_t Size,
1322 uint32_t Link, uint32_t Info,
1324 uint64_t EntrySize) {
1325 Write32(Name); // sh_name: index into string table
1326 Write32(Type); // sh_type
1327 WriteWord(Flags); // sh_flags
1328 WriteWord(Address); // sh_addr
1329 WriteWord(Offset); // sh_offset
1330 WriteWord(Size); // sh_size
1331 Write32(Link); // sh_link
1332 Write32(Info); // sh_info
1333 WriteWord(Alignment); // sh_addralign
1334 WriteWord(EntrySize); // sh_entsize
1337 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1339 const MCSectionData *SD) {
1340 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1342 // Sort the relocation entries. Most targets just sort by Offset, but some
1343 // (e.g., MIPS) have additional constraints.
1344 TargetObjectWriter->sortRelocs(Asm, Relocs);
1346 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1347 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1349 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
1352 write(*F, Entry.Offset);
1353 if (TargetObjectWriter->isN64()) {
1354 write(*F, uint32_t(Index));
1356 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1357 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1358 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1359 write(*F, TargetObjectWriter->getRType(Entry.Type));
1361 struct ELF::Elf64_Rela ERE64;
1362 ERE64.setSymbolAndType(Index, Entry.Type);
1363 write(*F, ERE64.r_info);
1365 if (hasRelocationAddend())
1366 write(*F, Entry.Addend);
1368 write(*F, uint32_t(Entry.Offset));
1370 struct ELF::Elf32_Rela ERE32;
1371 ERE32.setSymbolAndType(Index, Entry.Type);
1372 write(*F, ERE32.r_info);
1374 if (hasRelocationAddend())
1375 write(*F, uint32_t(Entry.Addend));
1380 void ELFObjectWriter::CreateMetadataSections(
1381 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
1382 MCContext &Ctx = Asm.getContext();
1385 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1387 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1388 const MCSectionELF *ShstrtabSection =
1389 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1390 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1391 ShstrtabSD.setAlignment(1);
1392 ShstrtabIndex = SectionIndexMap.size() + 1;
1393 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
1395 const MCSectionELF *SymtabSection =
1396 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1398 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1399 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1400 SymbolTableIndex = SectionIndexMap.size() + 1;
1401 SectionIndexMap[SymtabSection] = SymbolTableIndex;
1403 const MCSectionELF *StrtabSection;
1404 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1405 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1406 StrtabSD.setAlignment(1);
1407 StringTableIndex = SectionIndexMap.size() + 1;
1408 SectionIndexMap[StrtabSection] = StringTableIndex;
1411 F = new MCDataFragment(&SymtabSD);
1412 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1414 F = new MCDataFragment(&StrtabSD);
1415 F->getContents().append(StrTabBuilder.data().begin(),
1416 StrTabBuilder.data().end());
1418 F = new MCDataFragment(&ShstrtabSD);
1420 // Section header string table.
1421 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1422 const MCSectionELF &Section =
1423 static_cast<const MCSectionELF&>(it->getSection());
1424 ShStrTabBuilder.add(Section.getSectionName());
1426 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1427 F->getContents().append(ShStrTabBuilder.data().begin(),
1428 ShStrTabBuilder.data().end());
1431 void ELFObjectWriter::createIndexedSections(
1432 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1433 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
1434 MCContext &Ctx = Asm.getContext();
1437 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1439 const MCSectionELF &Section =
1440 static_cast<const MCSectionELF&>(it->getSection());
1441 if (!(Section.getFlags() & ELF::SHF_GROUP))
1444 const MCSymbol *SignatureSymbol = Section.getGroup();
1445 Asm.getOrCreateSymbolData(*SignatureSymbol);
1446 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1448 Group = Ctx.CreateELFGroupSection();
1449 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1450 Data.setAlignment(4);
1451 MCDataFragment *F = new MCDataFragment(&Data);
1452 write(*F, uint32_t(ELF::GRP_COMDAT));
1454 GroupMap[Group] = SignatureSymbol;
1457 computeIndexMap(Asm, SectionIndexMap);
1459 // Add sections to the groups
1460 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1462 const MCSectionELF &Section =
1463 static_cast<const MCSectionELF&>(it->getSection());
1464 if (!(Section.getFlags() & ELF::SHF_GROUP))
1466 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1467 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1468 // FIXME: we could use the previous fragment
1469 MCDataFragment *F = new MCDataFragment(&Data);
1470 uint32_t Index = SectionIndexMap.lookup(&Section);
1475 void ELFObjectWriter::writeSection(MCAssembler &Asm,
1476 const SectionIndexMapTy &SectionIndexMap,
1477 uint32_t GroupSymbolIndex,
1478 uint64_t Offset, uint64_t Size,
1480 const MCSectionELF &Section) {
1481 uint64_t sh_link = 0;
1482 uint64_t sh_info = 0;
1484 switch(Section.getType()) {
1489 case ELF::SHT_DYNAMIC:
1490 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
1494 case ELF::SHT_RELA: {
1495 sh_link = SymbolTableIndex;
1496 assert(sh_link && ".symtab not found");
1497 const MCSectionELF *InfoSection = Section.getAssociatedSection();
1498 sh_info = SectionIndexMap.lookup(InfoSection);
1502 case ELF::SHT_SYMTAB:
1503 case ELF::SHT_DYNSYM:
1504 sh_link = StringTableIndex;
1505 sh_info = LastLocalSymbolIndex;
1508 case ELF::SHT_SYMTAB_SHNDX:
1509 sh_link = SymbolTableIndex;
1512 case ELF::SHT_GROUP:
1513 sh_link = SymbolTableIndex;
1514 sh_info = GroupSymbolIndex;
1518 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1519 Section.getType() == ELF::SHT_ARM_EXIDX)
1520 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1522 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1524 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1525 Alignment, Section.getEntrySize());
1528 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1529 return SD.getOrdinal() == ~UINT32_C(0) &&
1530 !SD.getSection().isVirtualSection();
1533 void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
1534 const MCAsmLayout &Layout,
1535 const MCSectionData &SD) {
1536 if (IsELFMetaDataSection(SD)) {
1537 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1539 const MCFragment &F = *i;
1540 assert(F.getKind() == MCFragment::FT_Data);
1541 WriteBytes(cast<MCDataFragment>(F).getContents());
1544 Asm.writeSectionData(&SD, Layout);
1548 void ELFObjectWriter::writeSectionHeader(
1549 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1550 const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
1551 const SectionIndexMapTy &SectionIndexMap,
1552 const SectionOffsetsTy &SectionOffsets) {
1553 const unsigned NumSections = Asm.size();
1555 // Null section first.
1556 uint64_t FirstSectionSize =
1557 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1558 uint32_t FirstSectionLink =
1559 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1560 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1562 for (unsigned i = 0; i < NumSections; ++i) {
1563 const MCSectionELF &Section = *Sections[i];
1564 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1565 uint32_t GroupSymbolIndex;
1566 if (Section.getType() != ELF::SHT_GROUP)
1567 GroupSymbolIndex = 0;
1569 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1570 GroupMap.lookup(&Section));
1572 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
1573 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1574 ? Layout.getSectionAddressSize(&SD)
1575 : Offsets.second - Offsets.first;
1577 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1578 SD.getAlignment(), Section);
1582 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1583 const MCAsmLayout &Layout) {
1584 GroupMapTy GroupMap;
1585 RevGroupMapTy RevGroupMap;
1586 SectionIndexMapTy SectionIndexMap;
1588 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1589 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1590 RevGroupMap, SectionIndexMap);
1592 // Compute symbol table information.
1593 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
1595 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
1597 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1598 const_cast<MCAsmLayout&>(Layout),
1601 unsigned NumSections = Asm.size();
1602 std::vector<const MCSectionELF*> Sections;
1603 Sections.resize(NumSections);
1605 for (auto &Pair : SectionIndexMap)
1606 Sections[Pair.second - 1] = Pair.first;
1608 SectionOffsetsTy SectionOffsets;
1610 // Write out the ELF header ...
1611 WriteHeader(Asm, NumSections + 1);
1613 // ... then the sections ...
1614 for (const MCSectionELF *Section : Sections) {
1615 const MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1616 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1617 WriteZeros(Padding);
1619 // Remember the offset into the file for this section.
1620 uint64_t SecStart = OS.tell();
1621 writeDataSectionData(Asm, Layout, SD);
1622 uint64_t SecEnd = OS.tell();
1623 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1626 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1627 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1628 WriteZeros(Padding);
1630 const unsigned SectionHeaderOffset = OS.tell();
1632 // ... then the section header table ...
1633 writeSectionHeader(Sections, Asm, GroupMap, Layout, SectionIndexMap,
1637 uint64_t Val = SectionHeaderOffset;
1638 if (sys::IsLittleEndianHost != IsLittleEndian)
1639 sys::swapByteOrder(Val);
1640 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1641 offsetof(ELF::Elf64_Ehdr, e_shoff));
1643 uint32_t Val = SectionHeaderOffset;
1644 if (sys::IsLittleEndianHost != IsLittleEndian)
1645 sys::swapByteOrder(Val);
1646 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1647 offsetof(ELF::Elf32_Ehdr, e_shoff));
1651 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1652 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1653 bool InSet, bool IsPCRel) const {
1656 if (::isWeak(DataA))
1659 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1663 bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1667 // It is invalid to replace a reference to a global in a comdat
1668 // with a reference to a local since out of comdat references
1669 // to a local are forbidden.
1670 // We could try to return false for more cases, like the reference
1671 // being in the same comdat or Sym being an alias to another global,
1672 // but it is not clear if it is worth the effort.
1673 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1676 const MCSymbol &Sym = SD.getSymbol();
1677 if (!Sym.isInSection())
1680 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1681 return Sec.getGroup();
1684 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1685 raw_pwrite_stream &OS,
1686 bool IsLittleEndian) {
1687 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);