1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/Support/Compression.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
40 #define DEBUG_TYPE "reloc-info"
43 class FragmentWriter {
47 FragmentWriter(bool IsLittleEndian);
48 template <typename T> void write(MCDataFragment &F, T Val);
51 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
53 class SymbolTableWriter {
55 FragmentWriter &FWriter;
57 SectionIndexMapTy &SectionIndexMap;
59 // The symbol .symtab fragment we are writting to.
60 MCDataFragment *SymtabF;
62 // .symtab_shndx fragment we are writting to.
63 MCDataFragment *ShndxF;
65 // The numbel of symbols written so far.
68 void createSymtabShndx();
70 template <typename T> void write(MCDataFragment &F, T Value);
73 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
74 SectionIndexMapTy &SectionIndexMap,
75 MCDataFragment *SymtabF);
77 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
78 uint8_t other, uint32_t shndx, bool Reserved);
81 struct ELFRelocationEntry {
82 uint64_t Offset; // Where is the relocation.
83 bool UseSymbol; // Relocate with a symbol, not the section.
85 const MCSymbol *Symbol; // The symbol to relocate with.
86 const MCSectionData *Section; // The section to relocate with.
88 unsigned Type; // The type of the relocation.
89 uint64_t Addend; // The addend to use.
91 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
93 : Offset(Offset), UseSymbol(true), Symbol(Symbol), Type(Type),
96 ELFRelocationEntry(uint64_t Offset, const MCSectionData *Section,
97 unsigned Type, uint64_t Addend)
98 : Offset(Offset), UseSymbol(false), Section(Section), Type(Type),
102 class ELFObjectWriter : public MCObjectWriter {
103 FragmentWriter FWriter;
107 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
108 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
109 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
110 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
111 bool Used, bool Renamed);
112 static bool isLocal(const MCSymbolData &Data, bool isSignature,
114 static bool IsELFMetaDataSection(const MCSectionData &SD);
115 static uint64_t DataSectionSize(const MCSectionData &SD);
116 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
117 const MCSectionData &SD);
118 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
119 const MCSectionData &SD);
121 void WriteDataSectionData(MCAssembler &Asm,
122 const MCAsmLayout &Layout,
123 const MCSectionELF &Section);
125 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
126 return Kind == X86::reloc_riprel_4byte ||
127 Kind == X86::reloc_riprel_4byte_movq_load;
130 /// ELFSymbolData - Helper struct for containing some precomputed
131 /// information on symbols.
132 struct ELFSymbolData {
133 MCSymbolData *SymbolData;
134 uint64_t StringIndex;
135 uint32_t SectionIndex;
137 // Support lexicographic sorting.
138 bool operator<(const ELFSymbolData &RHS) const {
139 return SymbolData->getSymbol().getName() <
140 RHS.SymbolData->getSymbol().getName();
144 /// The target specific ELF writer instance.
145 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
147 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
148 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
149 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
151 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
153 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
156 /// @name Symbol Table Data
159 SmallString<256> StringTable;
160 std::vector<uint64_t> FileSymbolData;
161 std::vector<ELFSymbolData> LocalSymbolData;
162 std::vector<ELFSymbolData> ExternalSymbolData;
163 std::vector<ELFSymbolData> UndefinedSymbolData;
169 // This holds the symbol table index of the last local symbol.
170 unsigned LastLocalSymbolIndex;
171 // This holds the .strtab section index.
172 unsigned StringTableIndex;
173 // This holds the .symtab section index.
174 unsigned SymbolTableIndex;
176 unsigned ShstrtabIndex;
179 // TargetObjectWriter wrappers.
180 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
181 bool hasRelocationAddend() const {
182 return TargetObjectWriter->hasRelocationAddend();
184 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
185 bool IsPCRel) const {
186 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
190 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
192 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
193 TargetObjectWriter(MOTW), NeedsGOT(false) {}
195 virtual ~ELFObjectWriter();
197 void WriteWord(uint64_t W) {
204 template <typename T> void write(MCDataFragment &F, T Value) {
205 FWriter.write(F, Value);
208 void WriteHeader(const MCAssembler &Asm,
209 uint64_t SectionDataSize,
210 unsigned NumberOfSections);
212 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
213 const MCAsmLayout &Layout);
215 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
216 const MCAsmLayout &Layout,
217 SectionIndexMapTy &SectionIndexMap);
219 bool shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
220 const MCSymbolData *SD, uint64_t C,
221 unsigned Type) const;
223 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
224 const MCFragment *Fragment, const MCFixup &Fixup,
225 MCValue Target, bool &IsPCRel,
226 uint64_t &FixedValue) override;
228 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
231 // Map from a group section to the signature symbol
232 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
233 // Map from a signature symbol to the group section
234 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
235 // Map from a section to the section with the relocations
236 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
237 // Map from a section to its offset
238 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
240 /// Compute the symbol table data
242 /// \param Asm - The assembler.
243 /// \param SectionIndexMap - Maps a section to its index.
244 /// \param RevGroupMap - Maps a signature symbol to the group section.
245 /// \param NumRegularSections - Number of non-relocation sections.
246 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
247 const SectionIndexMapTy &SectionIndexMap,
248 RevGroupMapTy RevGroupMap,
249 unsigned NumRegularSections);
251 void ComputeIndexMap(MCAssembler &Asm,
252 SectionIndexMapTy &SectionIndexMap,
253 const RelMapTy &RelMap);
255 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
258 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
260 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
261 const RelMapTy &RelMap);
263 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
264 SectionIndexMapTy &SectionIndexMap,
265 const RelMapTy &RelMap);
267 // Create the sections that show up in the symbol table. Currently
268 // those are the .note.GNU-stack section and the group sections.
269 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
270 GroupMapTy &GroupMap,
271 RevGroupMapTy &RevGroupMap,
272 SectionIndexMapTy &SectionIndexMap,
273 const RelMapTy &RelMap);
275 void ExecutePostLayoutBinding(MCAssembler &Asm,
276 const MCAsmLayout &Layout) override;
278 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
279 const MCAsmLayout &Layout,
280 const SectionIndexMapTy &SectionIndexMap,
281 const SectionOffsetMapTy &SectionOffsetMap);
283 void ComputeSectionOrder(MCAssembler &Asm,
284 std::vector<const MCSectionELF*> &Sections);
286 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
287 uint64_t Address, uint64_t Offset,
288 uint64_t Size, uint32_t Link, uint32_t Info,
289 uint64_t Alignment, uint64_t EntrySize);
291 void WriteRelocationsFragment(const MCAssembler &Asm,
293 const MCSectionData *SD);
296 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
297 const MCSymbolData &DataA,
298 const MCFragment &FB,
300 bool IsPCRel) const override;
302 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
303 void WriteSection(MCAssembler &Asm,
304 const SectionIndexMapTy &SectionIndexMap,
305 uint32_t GroupSymbolIndex,
306 uint64_t Offset, uint64_t Size, uint64_t Alignment,
307 const MCSectionELF &Section);
311 FragmentWriter::FragmentWriter(bool IsLittleEndian)
312 : IsLittleEndian(IsLittleEndian) {}
314 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
316 Val = support::endian::byte_swap<T, support::little>(Val);
318 Val = support::endian::byte_swap<T, support::big>(Val);
319 const char *Start = (const char *)&Val;
320 F.getContents().append(Start, Start + sizeof(T));
323 void SymbolTableWriter::createSymtabShndx() {
327 MCContext &Ctx = Asm.getContext();
328 const MCSectionELF *SymtabShndxSection =
329 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
330 SectionKind::getReadOnly(), 4, "");
331 MCSectionData *SymtabShndxSD =
332 &Asm.getOrCreateSectionData(*SymtabShndxSection);
333 SymtabShndxSD->setAlignment(4);
334 ShndxF = new MCDataFragment(SymtabShndxSD);
335 unsigned Index = SectionIndexMap.size() + 1;
336 SectionIndexMap[SymtabShndxSection] = Index;
338 for (unsigned I = 0; I < NumWritten; ++I)
339 write(*ShndxF, uint32_t(0));
342 template <typename T>
343 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
344 FWriter.write(F, Value);
347 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
349 SectionIndexMapTy &SectionIndexMap,
350 MCDataFragment *SymtabF)
351 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
352 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
355 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
356 uint64_t size, uint8_t other,
357 uint32_t shndx, bool Reserved) {
358 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
365 write(*ShndxF, shndx);
367 write(*ShndxF, uint32_t(0));
370 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
372 raw_svector_ostream OS(SymtabF->getContents());
375 write(*SymtabF, name); // st_name
376 write(*SymtabF, info); // st_info
377 write(*SymtabF, other); // st_other
378 write(*SymtabF, Index); // st_shndx
379 write(*SymtabF, value); // st_value
380 write(*SymtabF, size); // st_size
382 write(*SymtabF, name); // st_name
383 write(*SymtabF, uint32_t(value)); // st_value
384 write(*SymtabF, uint32_t(size)); // st_size
385 write(*SymtabF, info); // st_info
386 write(*SymtabF, other); // st_other
387 write(*SymtabF, Index); // st_shndx
393 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
394 const MCFixupKindInfo &FKI =
395 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
397 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
400 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
404 case MCSymbolRefExpr::VK_GOT:
405 case MCSymbolRefExpr::VK_PLT:
406 case MCSymbolRefExpr::VK_GOTPCREL:
407 case MCSymbolRefExpr::VK_GOTOFF:
408 case MCSymbolRefExpr::VK_TPOFF:
409 case MCSymbolRefExpr::VK_TLSGD:
410 case MCSymbolRefExpr::VK_GOTTPOFF:
411 case MCSymbolRefExpr::VK_INDNTPOFF:
412 case MCSymbolRefExpr::VK_NTPOFF:
413 case MCSymbolRefExpr::VK_GOTNTPOFF:
414 case MCSymbolRefExpr::VK_TLSLDM:
415 case MCSymbolRefExpr::VK_DTPOFF:
416 case MCSymbolRefExpr::VK_TLSLD:
421 ELFObjectWriter::~ELFObjectWriter()
424 // Emit the ELF header.
425 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
426 uint64_t SectionDataSize,
427 unsigned NumberOfSections) {
433 // emitWord method behaves differently for ELF32 and ELF64, writing
434 // 4 bytes in the former and 8 in the latter.
436 Write8(0x7f); // e_ident[EI_MAG0]
437 Write8('E'); // e_ident[EI_MAG1]
438 Write8('L'); // e_ident[EI_MAG2]
439 Write8('F'); // e_ident[EI_MAG3]
441 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
444 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
446 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
448 Write8(TargetObjectWriter->getOSABI());
449 Write8(0); // e_ident[EI_ABIVERSION]
451 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
453 Write16(ELF::ET_REL); // e_type
455 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
457 Write32(ELF::EV_CURRENT); // e_version
458 WriteWord(0); // e_entry, no entry point in .o file
459 WriteWord(0); // e_phoff, no program header for .o
460 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
461 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
463 // e_flags = whatever the target wants
464 Write32(Asm.getELFHeaderEFlags());
466 // e_ehsize = ELF header size
467 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
469 Write16(0); // e_phentsize = prog header entry size
470 Write16(0); // e_phnum = # prog header entries = 0
472 // e_shentsize = Section header entry size
473 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
475 // e_shnum = # of section header ents
476 if (NumberOfSections >= ELF::SHN_LORESERVE)
477 Write16(ELF::SHN_UNDEF);
479 Write16(NumberOfSections);
481 // e_shstrndx = Section # of '.shstrtab'
482 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
483 Write16(ELF::SHN_XINDEX);
485 Write16(ShstrtabIndex);
488 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
489 const MCAsmLayout &Layout) {
490 MCSymbolData *Data = &OrigData;
491 if (Data->isCommon() && Data->isExternal())
492 return Data->getCommonAlignment();
494 const MCSymbol *Symbol = &Data->getSymbol();
497 if (Symbol->isVariable()) {
498 const MCExpr *Expr = Symbol->getVariableValue();
500 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
501 llvm_unreachable("Invalid expression");
503 assert(!Value.getSymB());
505 Res = Value.getConstant();
507 if (const MCSymbolRefExpr *A = Value.getSymA()) {
508 Symbol = &A->getSymbol();
509 Data = &Layout.getAssembler().getSymbolData(*Symbol);
516 if ((Data && Data->getFlags() & ELF_Other_ThumbFunc) ||
517 OrigData.getFlags() & ELF_Other_ThumbFunc)
520 if (!Symbol || !Symbol->isInSection())
523 Res += Layout.getSymbolOffset(Data);
528 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
529 const MCAsmLayout &Layout) {
530 // The presence of symbol versions causes undefined symbols and
531 // versions declared with @@@ to be renamed.
533 for (MCSymbolData &OriginalData : Asm.symbols()) {
534 const MCSymbol &Alias = OriginalData.getSymbol();
535 const MCSymbol &Symbol = Alias.AliasedSymbol();
536 MCSymbolData &SD = Asm.getSymbolData(Symbol);
539 if (&Symbol == &Alias)
542 StringRef AliasName = Alias.getName();
543 size_t Pos = AliasName.find('@');
544 if (Pos == StringRef::npos)
547 // Aliases defined with .symvar copy the binding from the symbol they alias.
548 // This is the first place we are able to copy this information.
549 OriginalData.setExternal(SD.isExternal());
550 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
552 StringRef Rest = AliasName.substr(Pos);
553 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
556 // FIXME: produce a better error message.
557 if (Symbol.isUndefined() && Rest.startswith("@@") &&
558 !Rest.startswith("@@@"))
559 report_fatal_error("A @@ version cannot be undefined");
561 Renames.insert(std::make_pair(&Symbol, &Alias));
565 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
566 uint8_t Type = newType;
568 // Propagation rules:
569 // IFUNC > FUNC > OBJECT > NOTYPE
570 // TLS_OBJECT > OBJECT > NOTYPE
572 // dont let the new type degrade the old type
576 case ELF::STT_GNU_IFUNC:
577 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
578 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
579 Type = ELF::STT_GNU_IFUNC;
582 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
583 Type == ELF::STT_TLS)
584 Type = ELF::STT_FUNC;
586 case ELF::STT_OBJECT:
587 if (Type == ELF::STT_NOTYPE)
588 Type = ELF::STT_OBJECT;
591 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
592 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
600 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
601 const MCSymbol &Symbol) {
602 if (!Symbol.isVariable())
605 const MCExpr *Expr = Symbol.getVariableValue();
607 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
608 llvm_unreachable("Invalid Expression");
609 assert(!Value.getSymB());
610 const MCSymbolRefExpr *A = Value.getSymA();
613 return getBaseSymbol(Layout, A->getSymbol());
616 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
617 const MCAsmLayout &Layout) {
618 MCSymbolData &OrigData = *MSD.SymbolData;
619 assert((!OrigData.getFragment() ||
620 (&OrigData.getFragment()->getParent()->getSection() ==
621 &OrigData.getSymbol().getSection())) &&
622 "The symbol's section doesn't match the fragment's symbol");
623 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
625 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
627 bool IsReserved = !Base || OrigData.isCommon();
629 // Binding and Type share the same byte as upper and lower nibbles
630 uint8_t Binding = MCELF::GetBinding(OrigData);
631 uint8_t Type = MCELF::GetType(OrigData);
632 MCSymbolData *BaseSD = nullptr;
634 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
635 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
637 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
638 Type = ELF::STT_FUNC;
639 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
641 // Other and Visibility share the same byte with Visibility using the lower
643 uint8_t Visibility = MCELF::GetVisibility(OrigData);
644 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
647 uint64_t Value = SymbolValue(OrigData, Layout);
650 const MCExpr *ESize = OrigData.getSize();
652 ESize = BaseSD->getSize();
656 if (!ESize->EvaluateAsAbsolute(Res, Layout))
657 report_fatal_error("Size expression must be absolute.");
661 // Write out the symbol table entry
662 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
663 MSD.SectionIndex, IsReserved);
666 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
668 const MCAsmLayout &Layout,
669 SectionIndexMapTy &SectionIndexMap) {
670 // The string table must be emitted first because we need the index
671 // into the string table for all the symbol names.
672 assert(StringTable.size() && "Missing string table");
674 // FIXME: Make sure the start of the symbol table is aligned.
676 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
678 // The first entry is the undefined symbol entry.
679 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
681 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
682 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
683 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
686 // Write the symbol table entries.
687 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
689 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
690 ELFSymbolData &MSD = LocalSymbolData[i];
691 WriteSymbol(Writer, MSD, Layout);
694 // Write out a symbol table entry for each regular section.
695 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
697 const MCSectionELF &Section =
698 static_cast<const MCSectionELF&>(i->getSection());
699 if (Section.getType() == ELF::SHT_RELA ||
700 Section.getType() == ELF::SHT_REL ||
701 Section.getType() == ELF::SHT_STRTAB ||
702 Section.getType() == ELF::SHT_SYMTAB ||
703 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
705 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
706 SectionIndexMap.lookup(&Section), false);
707 LastLocalSymbolIndex++;
710 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
711 ELFSymbolData &MSD = ExternalSymbolData[i];
712 MCSymbolData &Data = *MSD.SymbolData;
713 assert(((Data.getFlags() & ELF_STB_Global) ||
714 (Data.getFlags() & ELF_STB_Weak)) &&
715 "External symbol requires STB_GLOBAL or STB_WEAK flag");
716 WriteSymbol(Writer, MSD, Layout);
717 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
718 LastLocalSymbolIndex++;
721 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
722 ELFSymbolData &MSD = UndefinedSymbolData[i];
723 MCSymbolData &Data = *MSD.SymbolData;
724 WriteSymbol(Writer, MSD, Layout);
725 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
726 LastLocalSymbolIndex++;
730 // It is always valid to create a relocation with a symbol. It is preferable
731 // to use a relocation with a section if that is possible. Using the section
732 // allows us to omit some local symbols from the symbol table.
733 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
734 const MCSymbolData *SD,
736 unsigned Type) const {
737 // A PCRel relocation to an absolute value has no symbol (or section). We
738 // represent that with a relocation to a null section.
742 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
746 // The .odp creation emits a relocation against the symbol ".TOC." which
747 // create a R_PPC64_TOC relocation. However the relocation symbol name
748 // in final object creation should be NULL, since the symbol does not
749 // really exist, it is just the reference to TOC base for the current
750 // object file. Since the symbol is undefined, returning false results
751 // in a relocation with a null section which is the desired result.
752 case MCSymbolRefExpr::VK_PPC_TOCBASE:
755 // These VariantKind cause the relocation to refer to something other than
756 // the symbol itself, like a linker generated table. Since the address of
757 // symbol is not relevant, we cannot replace the symbol with the
758 // section and patch the difference in the addend.
759 case MCSymbolRefExpr::VK_GOT:
760 case MCSymbolRefExpr::VK_PLT:
761 case MCSymbolRefExpr::VK_GOTPCREL:
762 case MCSymbolRefExpr::VK_Mips_GOT:
763 case MCSymbolRefExpr::VK_PPC_GOT_LO:
764 case MCSymbolRefExpr::VK_PPC_GOT_HI:
765 case MCSymbolRefExpr::VK_PPC_GOT_HA:
769 // An undefined symbol is not in any section, so the relocation has to point
770 // to the symbol itself.
771 const MCSymbol &Sym = SD->getSymbol();
772 if (Sym.isUndefined())
775 unsigned Binding = MCELF::GetBinding(*SD);
778 llvm_unreachable("Invalid Binding");
782 // If the symbol is weak, it might be overridden by a symbol in another
783 // file. The relocation has to point to the symbol so that the linker
786 case ELF::STB_GLOBAL:
787 // Global ELF symbols can be preempted by the dynamic linker. The relocation
788 // has to point to the symbol for a reason analogous to the STB_WEAK case.
792 // If a relocation points to a mergeable section, we have to be careful.
793 // If the offset is zero, a relocation with the section will encode the
794 // same information. With a non-zero offset, the situation is different.
795 // For example, a relocation can point 42 bytes past the end of a string.
796 // If we change such a relocation to use the section, the linker would think
797 // that it pointed to another string and subtracting 42 at runtime will
798 // produce the wrong value.
799 auto &Sec = cast<MCSectionELF>(Sym.getSection());
800 unsigned Flags = Sec.getFlags();
801 if (Flags & ELF::SHF_MERGE) {
805 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
806 // only handle section relocations to mergeable sections if using RELA.
807 if (!hasRelocationAddend())
811 // Most TLS relocations use a got, so they need the symbol. Even those that
812 // are just an offset (@tpoff), require a symbol in some linkers (gold,
814 if (Flags & ELF::SHF_TLS)
817 // If the symbol is a thumb function the final relocation must set the lowest
818 // bit. With a symbol that is done by just having the symbol have that bit
819 // set, so we would lose the bit if we relocated with the section.
820 // FIXME: We could use the section but add the bit to the relocation value.
821 if (SD->getFlags() & ELF_Other_ThumbFunc)
824 if (TargetObjectWriter->needsRelocateWithSymbol(Type))
829 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
830 const MCAsmLayout &Layout,
831 const MCFragment *Fragment,
832 const MCFixup &Fixup,
835 uint64_t &FixedValue) {
836 const MCSectionData *FixupSection = Fragment->getParent();
837 uint64_t C = Target.getConstant();
838 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
840 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
841 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
842 "Should not have constructed this");
844 // Let A, B and C being the components of Target and R be the location of
845 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
846 // If it is pcrel, we want to compute (A - B + C - R).
848 // In general, ELF has no relocations for -B. It can only represent (A + C)
849 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
850 // replace B to implement it: (A - R - K + C)
852 Asm.getContext().FatalError(
854 "No relocation available to represent this relative expression");
856 const MCSymbol &SymB = RefB->getSymbol();
858 if (SymB.isUndefined())
859 Asm.getContext().FatalError(
861 Twine("symbol '") + SymB.getName() +
862 "' can not be undefined in a subtraction expression");
864 assert(!SymB.isAbsolute() && "Should have been folded");
865 const MCSection &SecB = SymB.getSection();
866 if (&SecB != &FixupSection->getSection())
867 Asm.getContext().FatalError(
868 Fixup.getLoc(), "Cannot represent a difference across sections");
870 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
871 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
872 uint64_t K = SymBOffset - FixupOffset;
877 // We either rejected the fixup or folded B into C at this point.
878 const MCSymbolRefExpr *RefA = Target.getSymA();
879 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
880 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
882 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
883 bool RelocateWithSymbol = shouldRelocateWithSymbol(RefA, SymAD, C, Type);
884 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
885 C += Layout.getSymbolOffset(SymAD);
888 if (hasRelocationAddend()) {
895 // FIXME: What is this!?!?
896 MCSymbolRefExpr::VariantKind Modifier =
897 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
898 if (RelocNeedsGOT(Modifier))
901 if (!RelocateWithSymbol) {
902 const MCSection *SecA =
903 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
904 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
905 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
906 Relocations[FixupSection].push_back(Rec);
911 if (const MCSymbol *R = Renames.lookup(SymA))
914 if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
915 WeakrefUsedInReloc.insert(SymA);
917 UsedInReloc.insert(SymA);
919 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
920 Relocations[FixupSection].push_back(Rec);
926 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
928 const MCSymbolData &SD = Asm.getSymbolData(*S);
929 return SD.getIndex();
932 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
933 const MCSymbolData &Data,
934 bool Used, bool Renamed) {
935 const MCSymbol &Symbol = Data.getSymbol();
936 if (Symbol.isVariable()) {
937 const MCExpr *Expr = Symbol.getVariableValue();
938 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
939 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
950 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
953 const MCSymbol &A = Symbol.AliasedSymbol();
954 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
957 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
958 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
961 if (Symbol.isTemporary())
967 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
968 bool isUsedInReloc) {
969 if (Data.isExternal())
972 const MCSymbol &Symbol = Data.getSymbol();
973 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
975 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
976 if (isSignature && !isUsedInReloc)
985 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
986 SectionIndexMapTy &SectionIndexMap,
987 const RelMapTy &RelMap) {
989 for (MCAssembler::iterator it = Asm.begin(),
990 ie = Asm.end(); it != ie; ++it) {
991 const MCSectionELF &Section =
992 static_cast<const MCSectionELF &>(it->getSection());
993 if (Section.getType() != ELF::SHT_GROUP)
995 SectionIndexMap[&Section] = Index++;
998 for (MCAssembler::iterator it = Asm.begin(),
999 ie = Asm.end(); it != ie; ++it) {
1000 const MCSectionELF &Section =
1001 static_cast<const MCSectionELF &>(it->getSection());
1002 if (Section.getType() == ELF::SHT_GROUP ||
1003 Section.getType() == ELF::SHT_REL ||
1004 Section.getType() == ELF::SHT_RELA)
1006 SectionIndexMap[&Section] = Index++;
1007 const MCSectionELF *RelSection = RelMap.lookup(&Section);
1009 SectionIndexMap[RelSection] = Index++;
1014 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1015 const SectionIndexMapTy &SectionIndexMap,
1016 RevGroupMapTy RevGroupMap,
1017 unsigned NumRegularSections) {
1018 // FIXME: Is this the correct place to do this?
1019 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
1021 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
1022 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1023 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1024 Data.setExternal(true);
1025 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
1028 // Index 0 is always the empty string.
1029 StringMap<uint64_t> StringIndexMap;
1030 StringTable += '\x00';
1032 // FIXME: We could optimize suffixes in strtab in the same way we
1033 // optimize them in shstrtab.
1035 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
1036 ie = Asm.file_names_end();
1039 StringRef Name = *it;
1040 uint64_t &Entry = StringIndexMap[Name];
1042 Entry = StringTable.size();
1043 StringTable += Name;
1044 StringTable += '\x00';
1046 FileSymbolData.push_back(Entry);
1049 // Add the data for the symbols.
1050 for (MCSymbolData &SD : Asm.symbols()) {
1051 const MCSymbol &Symbol = SD.getSymbol();
1053 bool Used = UsedInReloc.count(&Symbol);
1054 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
1055 bool isSignature = RevGroupMap.count(&Symbol);
1057 if (!isInSymtab(Asm, SD,
1058 Used || WeakrefUsed || isSignature,
1059 Renames.count(&Symbol)))
1063 MSD.SymbolData = &SD;
1064 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
1066 // Undefined symbols are global, but this is the first place we
1067 // are able to set it.
1068 bool Local = isLocal(SD, isSignature, Used);
1069 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
1071 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
1072 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1073 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
1077 MSD.SectionIndex = ELF::SHN_ABS;
1078 } else if (SD.isCommon()) {
1080 MSD.SectionIndex = ELF::SHN_COMMON;
1081 } else if (BaseSymbol->isUndefined()) {
1082 if (isSignature && !Used)
1083 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1085 MSD.SectionIndex = ELF::SHN_UNDEF;
1086 if (!Used && WeakrefUsed)
1087 MCELF::SetBinding(SD, ELF::STB_WEAK);
1089 const MCSectionELF &Section =
1090 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1091 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1092 assert(MSD.SectionIndex && "Invalid section index!");
1095 // The @@@ in symbol version is replaced with @ in undefined symbols and
1096 // @@ in defined ones.
1097 StringRef Name = Symbol.getName();
1098 SmallString<32> Buf;
1100 size_t Pos = Name.find("@@@");
1101 if (Pos != StringRef::npos) {
1102 Buf += Name.substr(0, Pos);
1103 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1104 Buf += Name.substr(Pos + Skip);
1108 uint64_t &Entry = StringIndexMap[Name];
1110 Entry = StringTable.size();
1111 StringTable += Name;
1112 StringTable += '\x00';
1114 MSD.StringIndex = Entry;
1115 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1116 UndefinedSymbolData.push_back(MSD);
1118 LocalSymbolData.push_back(MSD);
1120 ExternalSymbolData.push_back(MSD);
1123 // Symbols are required to be in lexicographic order.
1124 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1125 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1126 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1128 // Set the symbol indices. Local symbols must come before all other
1129 // symbols with non-local bindings.
1130 unsigned Index = FileSymbolData.size() + 1;
1131 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1132 LocalSymbolData[i].SymbolData->setIndex(Index++);
1134 Index += NumRegularSections;
1136 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1137 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1138 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1139 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1142 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1143 MCAsmLayout &Layout,
1145 for (MCAssembler::const_iterator it = Asm.begin(),
1146 ie = Asm.end(); it != ie; ++it) {
1147 const MCSectionData &SD = *it;
1148 if (Relocations[&SD].empty())
1151 MCContext &Ctx = Asm.getContext();
1152 const MCSectionELF &Section =
1153 static_cast<const MCSectionELF&>(SD.getSection());
1155 const StringRef SectionName = Section.getSectionName();
1156 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1157 RelaSectionName += SectionName;
1160 if (hasRelocationAddend())
1161 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1163 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1166 StringRef Group = "";
1167 if (Section.getFlags() & ELF::SHF_GROUP) {
1168 Flags = ELF::SHF_GROUP;
1169 Group = Section.getGroup()->getName();
1172 const MCSectionELF *RelaSection =
1173 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1174 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1175 SectionKind::getReadOnly(),
1177 RelMap[&Section] = RelaSection;
1178 Asm.getOrCreateSectionData(*RelaSection);
1182 static SmallVector<char, 128>
1183 getUncompressedData(MCAsmLayout &Layout,
1184 MCSectionData::FragmentListType &Fragments) {
1185 SmallVector<char, 128> UncompressedData;
1186 for (const MCFragment &F : Fragments) {
1187 const SmallVectorImpl<char> *Contents;
1188 switch (F.getKind()) {
1189 case MCFragment::FT_Data:
1190 Contents = &cast<MCDataFragment>(F).getContents();
1192 case MCFragment::FT_Dwarf:
1193 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1195 case MCFragment::FT_DwarfFrame:
1196 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1200 "Not expecting any other fragment types in a debug_* section");
1202 UncompressedData.append(Contents->begin(), Contents->end());
1204 return UncompressedData;
1207 // Include the debug info compression header:
1208 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1209 // useful for consumers to preallocate a buffer to decompress into.
1211 prependCompressionHeader(uint64_t Size,
1212 SmallVectorImpl<char> &CompressedContents) {
1213 static const StringRef Magic = "ZLIB";
1214 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1216 if (sys::IsLittleEndianHost)
1217 Size = sys::SwapByteOrder(Size);
1218 CompressedContents.insert(CompressedContents.begin(),
1219 Magic.size() + sizeof(Size), 0);
1220 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1221 std::copy(reinterpret_cast<char *>(&Size),
1222 reinterpret_cast<char *>(&Size + 1),
1223 CompressedContents.begin() + Magic.size());
1227 // Return a single fragment containing the compressed contents of the whole
1228 // section. Null if the section was not compressed for any reason.
1229 static std::unique_ptr<MCDataFragment>
1230 getCompressedFragment(MCAsmLayout &Layout,
1231 MCSectionData::FragmentListType &Fragments) {
1232 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1234 // Gather the uncompressed data from all the fragments, recording the
1235 // alignment fragment, if seen, and any fixups.
1236 SmallVector<char, 128> UncompressedData =
1237 getUncompressedData(Layout, Fragments);
1239 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1241 zlib::Status Success = zlib::compress(
1242 StringRef(UncompressedData.data(), UncompressedData.size()),
1243 CompressedContents);
1244 if (Success != zlib::StatusOK)
1247 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1250 return CompressedFragment;
1253 typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1256 static void UpdateSymbols(const MCAsmLayout &Layout,
1257 const std::vector<MCSymbolData *> &Symbols,
1258 MCFragment &NewFragment) {
1259 for (MCSymbolData *Sym : Symbols) {
1260 Sym->setOffset(Sym->getOffset() +
1261 Layout.getFragmentOffset(Sym->getFragment()));
1262 Sym->setFragment(&NewFragment);
1266 static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1267 const DefiningSymbolMap &DefiningSymbols,
1268 const MCSectionELF &Section,
1269 MCSectionData &SD) {
1270 StringRef SectionName = Section.getSectionName();
1271 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1273 std::unique_ptr<MCDataFragment> CompressedFragment =
1274 getCompressedFragment(Layout, Fragments);
1276 // Leave the section as-is if the fragments could not be compressed.
1277 if (!CompressedFragment)
1280 // Update the fragment+offsets of any symbols referring to fragments in this
1281 // section to refer to the new fragment.
1282 auto I = DefiningSymbols.find(&SD);
1283 if (I != DefiningSymbols.end())
1284 UpdateSymbols(Layout, I->second, *CompressedFragment);
1286 // Invalidate the layout for the whole section since it will have new and
1287 // different fragments now.
1288 Layout.invalidateFragmentsFrom(&Fragments.front());
1291 // Complete the initialization of the new fragment
1292 CompressedFragment->setParent(&SD);
1293 CompressedFragment->setLayoutOrder(0);
1294 Fragments.push_back(CompressedFragment.release());
1296 // Rename from .debug_* to .zdebug_*
1297 Asm.getContext().renameELFSection(&Section,
1298 (".z" + SectionName.drop_front(1)).str());
1301 void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1302 MCAsmLayout &Layout) {
1303 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1306 DefiningSymbolMap DefiningSymbols;
1308 for (MCSymbolData &SD : Asm.symbols())
1309 if (MCFragment *F = SD.getFragment())
1310 DefiningSymbols[F->getParent()].push_back(&SD);
1312 for (MCSectionData &SD : Asm) {
1313 const MCSectionELF &Section =
1314 static_cast<const MCSectionELF &>(SD.getSection());
1315 StringRef SectionName = Section.getSectionName();
1317 // Compressing debug_frame requires handling alignment fragments which is
1318 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1319 // for writing to arbitrary buffers) for little benefit.
1320 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1323 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
1327 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1328 const RelMapTy &RelMap) {
1329 for (MCAssembler::const_iterator it = Asm.begin(),
1330 ie = Asm.end(); it != ie; ++it) {
1331 const MCSectionData &SD = *it;
1332 const MCSectionELF &Section =
1333 static_cast<const MCSectionELF&>(SD.getSection());
1335 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1338 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1339 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1341 MCDataFragment *F = new MCDataFragment(&RelaSD);
1342 WriteRelocationsFragment(Asm, F, &*it);
1346 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1347 uint64_t Flags, uint64_t Address,
1348 uint64_t Offset, uint64_t Size,
1349 uint32_t Link, uint32_t Info,
1351 uint64_t EntrySize) {
1352 Write32(Name); // sh_name: index into string table
1353 Write32(Type); // sh_type
1354 WriteWord(Flags); // sh_flags
1355 WriteWord(Address); // sh_addr
1356 WriteWord(Offset); // sh_offset
1357 WriteWord(Size); // sh_size
1358 Write32(Link); // sh_link
1359 Write32(Info); // sh_info
1360 WriteWord(Alignment); // sh_addralign
1361 WriteWord(EntrySize); // sh_entsize
1364 // ELF doesn't require relocations to be in any order. We sort by the r_offset,
1365 // just to match gnu as for easier comparison. The use type is an arbitrary way
1366 // of making the sort deterministic.
1367 static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1368 const ELFRelocationEntry &A = *AP;
1369 const ELFRelocationEntry &B = *BP;
1370 if (A.Offset != B.Offset)
1371 return B.Offset - A.Offset;
1372 if (B.Type != A.Type)
1373 return A.Type - B.Type;
1374 llvm_unreachable("ELFRelocs might be unstable!");
1377 static void sortRelocs(const MCAssembler &Asm,
1378 std::vector<ELFRelocationEntry> &Relocs) {
1379 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1382 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1384 const MCSectionData *SD) {
1385 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1387 sortRelocs(Asm, Relocs);
1389 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1390 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1393 if (Entry.UseSymbol) {
1394 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1396 const MCSectionData *Sec = Entry.Section;
1398 Index = Sec->getOrdinal() + FileSymbolData.size() +
1399 LocalSymbolData.size() + 1;
1405 write(*F, Entry.Offset);
1406 if (TargetObjectWriter->isN64()) {
1407 write(*F, uint32_t(Index));
1409 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1410 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1411 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1412 write(*F, TargetObjectWriter->getRType(Entry.Type));
1414 struct ELF::Elf64_Rela ERE64;
1415 ERE64.setSymbolAndType(Index, Entry.Type);
1416 write(*F, ERE64.r_info);
1418 if (hasRelocationAddend())
1419 write(*F, Entry.Addend);
1421 write(*F, uint32_t(Entry.Offset));
1423 struct ELF::Elf32_Rela ERE32;
1424 ERE32.setSymbolAndType(Index, Entry.Type);
1425 write(*F, ERE32.r_info);
1427 if (hasRelocationAddend())
1428 write(*F, uint32_t(Entry.Addend));
1433 static int compareBySuffix(const MCSectionELF *const *a,
1434 const MCSectionELF *const *b) {
1435 const StringRef &NameA = (*a)->getSectionName();
1436 const StringRef &NameB = (*b)->getSectionName();
1437 const unsigned sizeA = NameA.size();
1438 const unsigned sizeB = NameB.size();
1439 const unsigned len = std::min(sizeA, sizeB);
1440 for (unsigned int i = 0; i < len; ++i) {
1441 char ca = NameA[sizeA - i - 1];
1442 char cb = NameB[sizeB - i - 1];
1447 return sizeB - sizeA;
1450 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1451 MCAsmLayout &Layout,
1452 SectionIndexMapTy &SectionIndexMap,
1453 const RelMapTy &RelMap) {
1454 MCContext &Ctx = Asm.getContext();
1457 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1459 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1460 const MCSectionELF *ShstrtabSection =
1461 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1462 SectionKind::getReadOnly());
1463 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1464 ShstrtabSD.setAlignment(1);
1466 const MCSectionELF *SymtabSection =
1467 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1468 SectionKind::getReadOnly(),
1470 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1471 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1473 const MCSectionELF *StrtabSection;
1474 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1475 SectionKind::getReadOnly());
1476 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1477 StrtabSD.setAlignment(1);
1479 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1481 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1482 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1483 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1486 F = new MCDataFragment(&SymtabSD);
1487 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1489 F = new MCDataFragment(&StrtabSD);
1490 F->getContents().append(StringTable.begin(), StringTable.end());
1492 F = new MCDataFragment(&ShstrtabSD);
1494 std::vector<const MCSectionELF*> Sections;
1495 for (MCAssembler::const_iterator it = Asm.begin(),
1496 ie = Asm.end(); it != ie; ++it) {
1497 const MCSectionELF &Section =
1498 static_cast<const MCSectionELF&>(it->getSection());
1499 Sections.push_back(&Section);
1501 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1503 // Section header string table.
1505 // The first entry of a string table holds a null character so skip
1508 F->getContents().push_back('\x00');
1510 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1511 const MCSectionELF &Section = *Sections[I];
1513 StringRef Name = Section.getSectionName();
1515 StringRef PreviousName = Sections[I - 1]->getSectionName();
1516 if (PreviousName.endswith(Name)) {
1517 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1521 // Remember the index into the string table so we can write it
1522 // into the sh_name field of the section header table.
1523 SectionStringTableIndex[&Section] = Index;
1525 Index += Name.size() + 1;
1526 F->getContents().append(Name.begin(), Name.end());
1527 F->getContents().push_back('\x00');
1531 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1532 MCAsmLayout &Layout,
1533 GroupMapTy &GroupMap,
1534 RevGroupMapTy &RevGroupMap,
1535 SectionIndexMapTy &SectionIndexMap,
1536 const RelMapTy &RelMap) {
1537 // Create the .note.GNU-stack section if needed.
1538 MCContext &Ctx = Asm.getContext();
1539 if (Asm.getNoExecStack()) {
1540 const MCSectionELF *GnuStackSection =
1541 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1542 SectionKind::getReadOnly());
1543 Asm.getOrCreateSectionData(*GnuStackSection);
1547 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1549 const MCSectionELF &Section =
1550 static_cast<const MCSectionELF&>(it->getSection());
1551 if (!(Section.getFlags() & ELF::SHF_GROUP))
1554 const MCSymbol *SignatureSymbol = Section.getGroup();
1555 Asm.getOrCreateSymbolData(*SignatureSymbol);
1556 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1558 Group = Ctx.CreateELFGroupSection();
1559 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1560 Data.setAlignment(4);
1561 MCDataFragment *F = new MCDataFragment(&Data);
1562 write(*F, uint32_t(ELF::GRP_COMDAT));
1564 GroupMap[Group] = SignatureSymbol;
1567 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1569 // Add sections to the groups
1570 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1572 const MCSectionELF &Section =
1573 static_cast<const MCSectionELF&>(it->getSection());
1574 if (!(Section.getFlags() & ELF::SHF_GROUP))
1576 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1577 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1578 // FIXME: we could use the previous fragment
1579 MCDataFragment *F = new MCDataFragment(&Data);
1580 uint32_t Index = SectionIndexMap.lookup(&Section);
1585 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1586 const SectionIndexMapTy &SectionIndexMap,
1587 uint32_t GroupSymbolIndex,
1588 uint64_t Offset, uint64_t Size,
1590 const MCSectionELF &Section) {
1591 uint64_t sh_link = 0;
1592 uint64_t sh_info = 0;
1594 switch(Section.getType()) {
1595 case ELF::SHT_DYNAMIC:
1596 sh_link = SectionStringTableIndex[&Section];
1601 case ELF::SHT_RELA: {
1602 const MCSectionELF *SymtabSection;
1603 const MCSectionELF *InfoSection;
1604 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1606 SectionKind::getReadOnly());
1607 sh_link = SectionIndexMap.lookup(SymtabSection);
1608 assert(sh_link && ".symtab not found");
1610 // Remove ".rel" and ".rela" prefixes.
1611 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1612 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1613 StringRef GroupName =
1614 Section.getGroup() ? Section.getGroup()->getName() : "";
1616 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1617 0, SectionKind::getReadOnly(),
1619 sh_info = SectionIndexMap.lookup(InfoSection);
1623 case ELF::SHT_SYMTAB:
1624 case ELF::SHT_DYNSYM:
1625 sh_link = StringTableIndex;
1626 sh_info = LastLocalSymbolIndex;
1629 case ELF::SHT_SYMTAB_SHNDX:
1630 sh_link = SymbolTableIndex;
1633 case ELF::SHT_PROGBITS:
1634 case ELF::SHT_STRTAB:
1635 case ELF::SHT_NOBITS:
1638 case ELF::SHT_ARM_ATTRIBUTES:
1639 case ELF::SHT_INIT_ARRAY:
1640 case ELF::SHT_FINI_ARRAY:
1641 case ELF::SHT_PREINIT_ARRAY:
1642 case ELF::SHT_X86_64_UNWIND:
1643 case ELF::SHT_MIPS_REGINFO:
1644 case ELF::SHT_MIPS_OPTIONS:
1648 case ELF::SHT_GROUP:
1649 sh_link = SymbolTableIndex;
1650 sh_info = GroupSymbolIndex;
1654 assert(0 && "FIXME: sh_type value not supported!");
1658 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1659 Section.getType() == ELF::SHT_ARM_EXIDX) {
1660 StringRef SecName(Section.getSectionName());
1661 if (SecName == ".ARM.exidx") {
1662 sh_link = SectionIndexMap.lookup(
1663 Asm.getContext().getELFSection(".text",
1665 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1666 SectionKind::getText()));
1667 } else if (SecName.startswith(".ARM.exidx")) {
1668 StringRef GroupName =
1669 Section.getGroup() ? Section.getGroup()->getName() : "";
1670 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1671 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1672 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1677 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1678 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1679 Alignment, Section.getEntrySize());
1682 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1683 return SD.getOrdinal() == ~UINT32_C(0) &&
1684 !SD.getSection().isVirtualSection();
1687 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1689 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1691 const MCFragment &F = *i;
1692 assert(F.getKind() == MCFragment::FT_Data);
1693 Ret += cast<MCDataFragment>(F).getContents().size();
1698 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1699 const MCSectionData &SD) {
1700 if (IsELFMetaDataSection(SD))
1701 return DataSectionSize(SD);
1702 return Layout.getSectionFileSize(&SD);
1705 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1706 const MCSectionData &SD) {
1707 if (IsELFMetaDataSection(SD))
1708 return DataSectionSize(SD);
1709 return Layout.getSectionAddressSize(&SD);
1712 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1713 const MCAsmLayout &Layout,
1714 const MCSectionELF &Section) {
1715 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1717 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1718 WriteZeros(Padding);
1720 if (IsELFMetaDataSection(SD)) {
1721 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1723 const MCFragment &F = *i;
1724 assert(F.getKind() == MCFragment::FT_Data);
1725 WriteBytes(cast<MCDataFragment>(F).getContents());
1728 Asm.writeSectionData(&SD, Layout);
1732 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1733 const GroupMapTy &GroupMap,
1734 const MCAsmLayout &Layout,
1735 const SectionIndexMapTy &SectionIndexMap,
1736 const SectionOffsetMapTy &SectionOffsetMap) {
1737 const unsigned NumSections = Asm.size() + 1;
1739 std::vector<const MCSectionELF*> Sections;
1740 Sections.resize(NumSections - 1);
1742 for (SectionIndexMapTy::const_iterator i=
1743 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1744 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1745 Sections[p.second - 1] = p.first;
1748 // Null section first.
1749 uint64_t FirstSectionSize =
1750 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1751 uint32_t FirstSectionLink =
1752 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1753 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1755 for (unsigned i = 0; i < NumSections - 1; ++i) {
1756 const MCSectionELF &Section = *Sections[i];
1757 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1758 uint32_t GroupSymbolIndex;
1759 if (Section.getType() != ELF::SHT_GROUP)
1760 GroupSymbolIndex = 0;
1762 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1763 GroupMap.lookup(&Section));
1765 uint64_t Size = GetSectionAddressSize(Layout, SD);
1767 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1768 SectionOffsetMap.lookup(&Section), Size,
1769 SD.getAlignment(), Section);
1773 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1774 std::vector<const MCSectionELF*> &Sections) {
1775 for (MCAssembler::iterator it = Asm.begin(),
1776 ie = Asm.end(); it != ie; ++it) {
1777 const MCSectionELF &Section =
1778 static_cast<const MCSectionELF &>(it->getSection());
1779 if (Section.getType() == ELF::SHT_GROUP)
1780 Sections.push_back(&Section);
1783 for (MCAssembler::iterator it = Asm.begin(),
1784 ie = Asm.end(); it != ie; ++it) {
1785 const MCSectionELF &Section =
1786 static_cast<const MCSectionELF &>(it->getSection());
1787 if (Section.getType() != ELF::SHT_GROUP &&
1788 Section.getType() != ELF::SHT_REL &&
1789 Section.getType() != ELF::SHT_RELA)
1790 Sections.push_back(&Section);
1793 for (MCAssembler::iterator it = Asm.begin(),
1794 ie = Asm.end(); it != ie; ++it) {
1795 const MCSectionELF &Section =
1796 static_cast<const MCSectionELF &>(it->getSection());
1797 if (Section.getType() == ELF::SHT_REL ||
1798 Section.getType() == ELF::SHT_RELA)
1799 Sections.push_back(&Section);
1803 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1804 const MCAsmLayout &Layout) {
1805 GroupMapTy GroupMap;
1806 RevGroupMapTy RevGroupMap;
1807 SectionIndexMapTy SectionIndexMap;
1809 unsigned NumUserSections = Asm.size();
1811 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
1813 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1814 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1816 const unsigned NumUserAndRelocSections = Asm.size();
1817 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1818 RevGroupMap, SectionIndexMap, RelMap);
1819 const unsigned AllSections = Asm.size();
1820 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1822 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1824 // Compute symbol table information.
1825 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1826 NumRegularSections);
1828 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1830 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1831 const_cast<MCAsmLayout&>(Layout),
1835 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1836 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1837 sizeof(ELF::Elf32_Ehdr);
1838 uint64_t FileOff = HeaderSize;
1840 std::vector<const MCSectionELF*> Sections;
1841 ComputeSectionOrder(Asm, Sections);
1842 unsigned NumSections = Sections.size();
1843 SectionOffsetMapTy SectionOffsetMap;
1844 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1845 const MCSectionELF &Section = *Sections[i];
1846 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1848 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1850 // Remember the offset into the file for this section.
1851 SectionOffsetMap[&Section] = FileOff;
1853 // Get the size of the section in the output file (including padding).
1854 FileOff += GetSectionFileSize(Layout, SD);
1857 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1859 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1861 uint64_t SectionHeaderEntrySize = is64Bit() ?
1862 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1863 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1865 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1866 const MCSectionELF &Section = *Sections[i];
1867 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1869 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1871 // Remember the offset into the file for this section.
1872 SectionOffsetMap[&Section] = FileOff;
1874 // Get the size of the section in the output file (including padding).
1875 FileOff += GetSectionFileSize(Layout, SD);
1878 // Write out the ELF header ...
1879 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1881 // ... then the regular sections ...
1882 // + because of .shstrtab
1883 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1884 WriteDataSectionData(Asm, Layout, *Sections[i]);
1886 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1887 WriteZeros(Padding);
1889 // ... then the section header table ...
1890 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1893 // ... and then the remaining sections ...
1894 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1895 WriteDataSectionData(Asm, Layout, *Sections[i]);
1899 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1900 const MCSymbolData &DataA,
1901 const MCFragment &FB,
1903 bool IsPCRel) const {
1904 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1906 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1907 Asm, DataA, FB,InSet, IsPCRel);
1910 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1912 bool IsLittleEndian) {
1913 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);