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/MCAsmLayout.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELF.h"
24 #include "llvm/MC/MCELFSymbolFlags.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCFixupKindInfo.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
38 #define DEBUG_TYPE "reloc-info"
41 class FragmentWriter {
45 FragmentWriter(bool IsLittleEndian);
46 template <typename T> void write(MCDataFragment &F, T Val);
49 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
51 class SymbolTableWriter {
53 FragmentWriter &FWriter;
55 SectionIndexMapTy &SectionIndexMap;
57 // The symbol .symtab fragment we are writting to.
58 MCDataFragment *SymtabF;
60 // .symtab_shndx fragment we are writting to.
61 MCDataFragment *ShndxF;
63 // The numbel of symbols written so far.
66 void createSymtabShndx();
68 template <typename T> void write(MCDataFragment &F, T Value);
71 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
72 SectionIndexMapTy &SectionIndexMap,
73 MCDataFragment *SymtabF);
75 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
76 uint8_t other, uint32_t shndx, bool Reserved);
79 class ELFObjectWriter : public MCObjectWriter {
80 FragmentWriter FWriter;
84 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
85 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
86 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
87 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
88 bool Used, bool Renamed);
89 static bool isLocal(const MCSymbolData &Data, bool isSignature,
91 static bool IsELFMetaDataSection(const MCSectionData &SD);
92 static uint64_t DataSectionSize(const MCSectionData &SD);
93 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
94 const MCSectionData &SD);
95 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
98 void WriteDataSectionData(MCAssembler &Asm,
99 const MCAsmLayout &Layout,
100 const MCSectionELF &Section);
102 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
103 return Kind == X86::reloc_riprel_4byte ||
104 Kind == X86::reloc_riprel_4byte_movq_load;
107 /// ELFSymbolData - Helper struct for containing some precomputed
108 /// information on symbols.
109 struct ELFSymbolData {
110 MCSymbolData *SymbolData;
111 uint64_t StringIndex;
112 uint32_t SectionIndex;
114 // Support lexicographic sorting.
115 bool operator<(const ELFSymbolData &RHS) const {
116 return SymbolData->getSymbol().getName() <
117 RHS.SymbolData->getSymbol().getName();
121 /// The target specific ELF writer instance.
122 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
124 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
125 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
126 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
128 llvm::DenseMap<const MCSectionData*,
129 std::vector<ELFRelocationEntry> > Relocations;
130 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
133 /// @name Symbol Table Data
136 SmallString<256> StringTable;
137 std::vector<uint64_t> FileSymbolData;
138 std::vector<ELFSymbolData> LocalSymbolData;
139 std::vector<ELFSymbolData> ExternalSymbolData;
140 std::vector<ELFSymbolData> UndefinedSymbolData;
146 // This holds the symbol table index of the last local symbol.
147 unsigned LastLocalSymbolIndex;
148 // This holds the .strtab section index.
149 unsigned StringTableIndex;
150 // This holds the .symtab section index.
151 unsigned SymbolTableIndex;
153 unsigned ShstrtabIndex;
156 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
157 const MCValue &Target,
159 const MCFixup &Fixup,
162 // TargetObjectWriter wrappers.
163 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
164 const MCValue &Target,
166 const MCFixup &Fixup,
167 bool IsPCRel) const {
168 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
170 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
171 const MCFixup &Fixup,
172 bool IsPCRel) const {
173 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
177 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
178 bool hasRelocationAddend() const {
179 return TargetObjectWriter->hasRelocationAddend();
181 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
182 bool IsPCRel, bool IsRelocWithSymbol,
183 int64_t Addend) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
185 IsRelocWithSymbol, Addend);
189 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
191 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
192 TargetObjectWriter(MOTW), NeedsGOT(false) {}
194 virtual ~ELFObjectWriter();
196 void WriteWord(uint64_t W) {
203 template <typename T> void write(MCDataFragment &F, T Value) {
204 FWriter.write(F, Value);
207 void WriteHeader(const MCAssembler &Asm,
208 uint64_t SectionDataSize,
209 unsigned NumberOfSections);
211 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
212 const MCAsmLayout &Layout);
214 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
215 const MCAsmLayout &Layout,
216 SectionIndexMapTy &SectionIndexMap);
218 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
219 const MCFragment *Fragment, const MCFixup &Fixup,
220 MCValue Target, uint64_t &FixedValue) override;
222 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
225 // Map from a group section to the signature symbol
226 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
227 // Map from a signature symbol to the group section
228 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
229 // Map from a section to the section with the relocations
230 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
231 // Map from a section to its offset
232 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
234 /// Compute the symbol table data
236 /// \param Asm - The assembler.
237 /// \param SectionIndexMap - Maps a section to its index.
238 /// \param RevGroupMap - Maps a signature symbol to the group section.
239 /// \param NumRegularSections - Number of non-relocation sections.
240 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
241 const SectionIndexMapTy &SectionIndexMap,
242 RevGroupMapTy RevGroupMap,
243 unsigned NumRegularSections);
245 void ComputeIndexMap(MCAssembler &Asm,
246 SectionIndexMapTy &SectionIndexMap,
247 const RelMapTy &RelMap);
249 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
252 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
253 const RelMapTy &RelMap);
255 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
256 SectionIndexMapTy &SectionIndexMap,
257 const RelMapTy &RelMap);
259 // Create the sections that show up in the symbol table. Currently
260 // those are the .note.GNU-stack section and the group sections.
261 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
262 GroupMapTy &GroupMap,
263 RevGroupMapTy &RevGroupMap,
264 SectionIndexMapTy &SectionIndexMap,
265 const RelMapTy &RelMap);
267 void ExecutePostLayoutBinding(MCAssembler &Asm,
268 const MCAsmLayout &Layout) override;
270 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
271 const MCAsmLayout &Layout,
272 const SectionIndexMapTy &SectionIndexMap,
273 const SectionOffsetMapTy &SectionOffsetMap);
275 void ComputeSectionOrder(MCAssembler &Asm,
276 std::vector<const MCSectionELF*> &Sections);
278 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
279 uint64_t Address, uint64_t Offset,
280 uint64_t Size, uint32_t Link, uint32_t Info,
281 uint64_t Alignment, uint64_t EntrySize);
283 void WriteRelocationsFragment(const MCAssembler &Asm,
285 const MCSectionData *SD);
288 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
289 const MCSymbolData &DataA,
290 const MCFragment &FB,
292 bool IsPCRel) const override;
294 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
295 void WriteSection(MCAssembler &Asm,
296 const SectionIndexMapTy &SectionIndexMap,
297 uint32_t GroupSymbolIndex,
298 uint64_t Offset, uint64_t Size, uint64_t Alignment,
299 const MCSectionELF &Section);
303 FragmentWriter::FragmentWriter(bool IsLittleEndian)
304 : IsLittleEndian(IsLittleEndian) {}
306 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
308 Val = support::endian::byte_swap<T, support::little>(Val);
310 Val = support::endian::byte_swap<T, support::big>(Val);
311 const char *Start = (const char *)&Val;
312 F.getContents().append(Start, Start + sizeof(T));
315 void SymbolTableWriter::createSymtabShndx() {
319 MCContext &Ctx = Asm.getContext();
320 const MCSectionELF *SymtabShndxSection =
321 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
322 SectionKind::getReadOnly(), 4, "");
323 MCSectionData *SymtabShndxSD =
324 &Asm.getOrCreateSectionData(*SymtabShndxSection);
325 SymtabShndxSD->setAlignment(4);
326 ShndxF = new MCDataFragment(SymtabShndxSD);
327 unsigned Index = SectionIndexMap.size() + 1;
328 SectionIndexMap[SymtabShndxSection] = Index;
330 for (unsigned I = 0; I < NumWritten; ++I)
331 write(*ShndxF, uint32_t(0));
334 template <typename T>
335 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
336 FWriter.write(F, Value);
339 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
341 SectionIndexMapTy &SectionIndexMap,
342 MCDataFragment *SymtabF)
343 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
344 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
347 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
348 uint64_t size, uint8_t other,
349 uint32_t shndx, bool Reserved) {
350 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
357 write(*ShndxF, shndx);
359 write(*ShndxF, uint32_t(0));
362 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
364 raw_svector_ostream OS(SymtabF->getContents());
367 write(*SymtabF, name); // st_name
368 write(*SymtabF, info); // st_info
369 write(*SymtabF, other); // st_other
370 write(*SymtabF, Index); // st_shndx
371 write(*SymtabF, value); // st_value
372 write(*SymtabF, size); // st_size
374 write(*SymtabF, name); // st_name
375 write(*SymtabF, uint32_t(value)); // st_value
376 write(*SymtabF, uint32_t(size)); // st_size
377 write(*SymtabF, info); // st_info
378 write(*SymtabF, other); // st_other
379 write(*SymtabF, Index); // st_shndx
385 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
386 const MCFixupKindInfo &FKI =
387 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
389 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
392 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
396 case MCSymbolRefExpr::VK_GOT:
397 case MCSymbolRefExpr::VK_PLT:
398 case MCSymbolRefExpr::VK_GOTPCREL:
399 case MCSymbolRefExpr::VK_GOTOFF:
400 case MCSymbolRefExpr::VK_TPOFF:
401 case MCSymbolRefExpr::VK_TLSGD:
402 case MCSymbolRefExpr::VK_GOTTPOFF:
403 case MCSymbolRefExpr::VK_INDNTPOFF:
404 case MCSymbolRefExpr::VK_NTPOFF:
405 case MCSymbolRefExpr::VK_GOTNTPOFF:
406 case MCSymbolRefExpr::VK_TLSLDM:
407 case MCSymbolRefExpr::VK_DTPOFF:
408 case MCSymbolRefExpr::VK_TLSLD:
413 ELFObjectWriter::~ELFObjectWriter()
416 // Emit the ELF header.
417 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
418 uint64_t SectionDataSize,
419 unsigned NumberOfSections) {
425 // emitWord method behaves differently for ELF32 and ELF64, writing
426 // 4 bytes in the former and 8 in the latter.
428 Write8(0x7f); // e_ident[EI_MAG0]
429 Write8('E'); // e_ident[EI_MAG1]
430 Write8('L'); // e_ident[EI_MAG2]
431 Write8('F'); // e_ident[EI_MAG3]
433 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
436 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
438 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
440 Write8(TargetObjectWriter->getOSABI());
441 Write8(0); // e_ident[EI_ABIVERSION]
443 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
445 Write16(ELF::ET_REL); // e_type
447 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
449 Write32(ELF::EV_CURRENT); // e_version
450 WriteWord(0); // e_entry, no entry point in .o file
451 WriteWord(0); // e_phoff, no program header for .o
452 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
453 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
455 // e_flags = whatever the target wants
456 Write32(Asm.getELFHeaderEFlags());
458 // e_ehsize = ELF header size
459 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
461 Write16(0); // e_phentsize = prog header entry size
462 Write16(0); // e_phnum = # prog header entries = 0
464 // e_shentsize = Section header entry size
465 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
467 // e_shnum = # of section header ents
468 if (NumberOfSections >= ELF::SHN_LORESERVE)
469 Write16(ELF::SHN_UNDEF);
471 Write16(NumberOfSections);
473 // e_shstrndx = Section # of '.shstrtab'
474 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
475 Write16(ELF::SHN_XINDEX);
477 Write16(ShstrtabIndex);
480 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
481 const MCAsmLayout &Layout) {
482 MCSymbolData *Data = &OrigData;
483 if (Data->isCommon() && Data->isExternal())
484 return Data->getCommonAlignment();
486 const MCSymbol *Symbol = &Data->getSymbol();
487 bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
490 if (Symbol->isVariable()) {
491 const MCExpr *Expr = Symbol->getVariableValue();
493 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
494 llvm_unreachable("Invalid expression");
496 assert(!Value.getSymB());
498 Res = Value.getConstant();
500 if (const MCSymbolRefExpr *A = Value.getSymA()) {
501 Symbol = &A->getSymbol();
502 Data = &Layout.getAssembler().getSymbolData(*Symbol);
512 if (!Symbol || !Symbol->isInSection())
515 Res += Layout.getSymbolOffset(Data);
520 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
521 const MCAsmLayout &Layout) {
522 // The presence of symbol versions causes undefined symbols and
523 // versions declared with @@@ to be renamed.
525 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
526 ie = Asm.symbol_end(); it != ie; ++it) {
527 const MCSymbol &Alias = it->getSymbol();
528 const MCSymbol &Symbol = Alias.AliasedSymbol();
529 MCSymbolData &SD = Asm.getSymbolData(Symbol);
532 if (&Symbol == &Alias)
535 StringRef AliasName = Alias.getName();
536 size_t Pos = AliasName.find('@');
537 if (Pos == StringRef::npos)
540 // Aliases defined with .symvar copy the binding from the symbol they alias.
541 // This is the first place we are able to copy this information.
542 it->setExternal(SD.isExternal());
543 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
545 StringRef Rest = AliasName.substr(Pos);
546 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
549 // FIXME: produce a better error message.
550 if (Symbol.isUndefined() && Rest.startswith("@@") &&
551 !Rest.startswith("@@@"))
552 report_fatal_error("A @@ version cannot be undefined");
554 Renames.insert(std::make_pair(&Symbol, &Alias));
558 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
559 uint8_t Type = newType;
561 // Propagation rules:
562 // IFUNC > FUNC > OBJECT > NOTYPE
563 // TLS_OBJECT > OBJECT > NOTYPE
565 // dont let the new type degrade the old type
569 case ELF::STT_GNU_IFUNC:
570 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
571 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
572 Type = ELF::STT_GNU_IFUNC;
575 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
576 Type == ELF::STT_TLS)
577 Type = ELF::STT_FUNC;
579 case ELF::STT_OBJECT:
580 if (Type == ELF::STT_NOTYPE)
581 Type = ELF::STT_OBJECT;
584 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
585 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
593 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
594 const MCSymbol &Symbol) {
595 if (!Symbol.isVariable())
598 const MCExpr *Expr = Symbol.getVariableValue();
600 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
601 llvm_unreachable("Invalid Expression");
602 assert(!Value.getSymB());
603 const MCSymbolRefExpr *A = Value.getSymA();
606 return getBaseSymbol(Layout, A->getSymbol());
609 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
610 const MCAsmLayout &Layout) {
611 MCSymbolData &OrigData = *MSD.SymbolData;
613 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
615 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
616 Data.getSymbol().isVariable();
618 // Binding and Type share the same byte as upper and lower nibbles
619 uint8_t Binding = MCELF::GetBinding(OrigData);
620 uint8_t Type = MCELF::GetType(OrigData);
621 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
623 MCSymbolData BaseSD = Layout.getAssembler().getSymbolData(*Base);
624 Type = mergeTypeForSet(Type, MCELF::GetType(BaseSD));
626 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
627 Type = ELF::STT_FUNC;
628 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
630 // Other and Visibility share the same byte with Visibility using the lower
632 uint8_t Visibility = MCELF::GetVisibility(OrigData);
633 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
636 uint64_t Value = SymbolValue(OrigData, Layout);
637 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
641 assert(!(Data.isCommon() && !Data.isExternal()));
643 const MCExpr *ESize = Data.getSize();
646 if (!ESize->EvaluateAsAbsolute(Res, Layout))
647 report_fatal_error("Size expression must be absolute.");
651 // Write out the symbol table entry
652 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
653 MSD.SectionIndex, IsReserved);
656 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
658 const MCAsmLayout &Layout,
659 SectionIndexMapTy &SectionIndexMap) {
660 // The string table must be emitted first because we need the index
661 // into the string table for all the symbol names.
662 assert(StringTable.size() && "Missing string table");
664 // FIXME: Make sure the start of the symbol table is aligned.
666 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
668 // The first entry is the undefined symbol entry.
669 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
671 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
672 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
673 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
676 // Write the symbol table entries.
677 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
679 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
680 ELFSymbolData &MSD = LocalSymbolData[i];
681 WriteSymbol(Writer, MSD, Layout);
684 // Write out a symbol table entry for each regular section.
685 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
687 const MCSectionELF &Section =
688 static_cast<const MCSectionELF&>(i->getSection());
689 if (Section.getType() == ELF::SHT_RELA ||
690 Section.getType() == ELF::SHT_REL ||
691 Section.getType() == ELF::SHT_STRTAB ||
692 Section.getType() == ELF::SHT_SYMTAB ||
693 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
695 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
696 SectionIndexMap.lookup(&Section), false);
697 LastLocalSymbolIndex++;
700 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
701 ELFSymbolData &MSD = ExternalSymbolData[i];
702 MCSymbolData &Data = *MSD.SymbolData;
703 assert(((Data.getFlags() & ELF_STB_Global) ||
704 (Data.getFlags() & ELF_STB_Weak)) &&
705 "External symbol requires STB_GLOBAL or STB_WEAK flag");
706 WriteSymbol(Writer, MSD, Layout);
707 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
708 LastLocalSymbolIndex++;
711 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
712 ELFSymbolData &MSD = UndefinedSymbolData[i];
713 MCSymbolData &Data = *MSD.SymbolData;
714 WriteSymbol(Writer, MSD, Layout);
715 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
716 LastLocalSymbolIndex++;
720 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
721 const MCValue &Target,
723 const MCFixup &Fixup,
724 bool IsPCRel) const {
725 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
726 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
727 const MCSymbol *Renamed = Renames.lookup(&Symbol);
728 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
730 if (ASymbol.isUndefined()) {
733 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
736 if (SD.isExternal()) {
742 const MCSectionELF &Section =
743 static_cast<const MCSectionELF&>(ASymbol.getSection());
744 const SectionKind secKind = Section.getKind();
747 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
749 if (secKind.isThreadLocal()) {
755 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
756 const MCSectionELF &Sec2 =
757 static_cast<const MCSectionELF&>(F.getParent()->getSection());
759 if (&Sec2 != &Section &&
760 (Kind == MCSymbolRefExpr::VK_PLT ||
761 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
762 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
768 if (Section.getFlags() & ELF::SHF_MERGE) {
769 if (Target.getConstant() == 0)
770 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
776 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
781 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
782 const MCAsmLayout &Layout,
783 const MCFragment *Fragment,
784 const MCFixup &Fixup,
786 uint64_t &FixedValue) {
789 int64_t Value = Target.getConstant();
790 const MCSymbol *RelocSymbol = NULL;
792 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
793 if (!Target.isAbsolute()) {
794 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
795 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
796 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
798 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
799 const MCSymbol &SymbolB = RefB->getSymbol();
800 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
803 if (!SDB.getFragment())
804 Asm.getContext().FatalError(
806 Twine("symbol '") + SymbolB.getName() +
807 "' can not be undefined in a subtraction expression");
809 // Offset of the symbol in the section
810 int64_t a = Layout.getSymbolOffset(&SDB);
812 // Offset of the relocation in the section
813 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
818 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
819 MCFragment *F = SD.getFragment();
822 Index = F->getParent()->getOrdinal() + 1;
823 // Offset of the symbol in the section
824 Value += Layout.getSymbolOffset(&SD);
829 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
830 WeakrefUsedInReloc.insert(RelocSymbol);
832 UsedInReloc.insert(RelocSymbol);
836 if (hasRelocationAddend())
841 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
842 (RelocSymbol != 0), Addend);
843 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
844 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
845 if (RelocNeedsGOT(Modifier))
848 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
851 if (!hasRelocationAddend())
855 assert(isInt<64>(Addend));
857 assert(isInt<32>(Addend));
859 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
860 Relocations[Fragment->getParent()].push_back(ERE);
865 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
867 MCSymbolData &SD = Asm.getSymbolData(*S);
868 return SD.getIndex();
871 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
872 const MCSymbolData &Data,
873 bool Used, bool Renamed) {
874 const MCSymbol &Symbol = Data.getSymbol();
875 if (Symbol.isVariable()) {
876 const MCExpr *Expr = Symbol.getVariableValue();
877 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
878 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
889 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
892 const MCSymbol &A = Symbol.AliasedSymbol();
893 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
896 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
897 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
900 if (Symbol.isTemporary())
906 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
907 bool isUsedInReloc) {
908 if (Data.isExternal())
911 const MCSymbol &Symbol = Data.getSymbol();
912 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
914 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
915 if (isSignature && !isUsedInReloc)
924 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
925 SectionIndexMapTy &SectionIndexMap,
926 const RelMapTy &RelMap) {
928 for (MCAssembler::iterator it = Asm.begin(),
929 ie = Asm.end(); it != ie; ++it) {
930 const MCSectionELF &Section =
931 static_cast<const MCSectionELF &>(it->getSection());
932 if (Section.getType() != ELF::SHT_GROUP)
934 SectionIndexMap[&Section] = Index++;
937 for (MCAssembler::iterator it = Asm.begin(),
938 ie = Asm.end(); it != ie; ++it) {
939 const MCSectionELF &Section =
940 static_cast<const MCSectionELF &>(it->getSection());
941 if (Section.getType() == ELF::SHT_GROUP ||
942 Section.getType() == ELF::SHT_REL ||
943 Section.getType() == ELF::SHT_RELA)
945 SectionIndexMap[&Section] = Index++;
946 const MCSectionELF *RelSection = RelMap.lookup(&Section);
948 SectionIndexMap[RelSection] = Index++;
953 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
954 const SectionIndexMapTy &SectionIndexMap,
955 RevGroupMapTy RevGroupMap,
956 unsigned NumRegularSections) {
957 // FIXME: Is this the correct place to do this?
958 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
960 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
961 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
962 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
963 Data.setExternal(true);
964 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
967 // Index 0 is always the empty string.
968 StringMap<uint64_t> StringIndexMap;
969 StringTable += '\x00';
971 // FIXME: We could optimize suffixes in strtab in the same way we
972 // optimize them in shstrtab.
974 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
975 ie = Asm.file_names_end();
978 StringRef Name = *it;
979 uint64_t &Entry = StringIndexMap[Name];
981 Entry = StringTable.size();
983 StringTable += '\x00';
985 FileSymbolData.push_back(Entry);
988 // Add the data for the symbols.
989 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
990 ie = Asm.symbol_end(); it != ie; ++it) {
991 const MCSymbol &Symbol = it->getSymbol();
993 bool Used = UsedInReloc.count(&Symbol);
994 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
995 bool isSignature = RevGroupMap.count(&Symbol);
997 if (!isInSymtab(Asm, *it,
998 Used || WeakrefUsed || isSignature,
999 Renames.count(&Symbol)))
1003 MSD.SymbolData = it;
1004 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
1006 // Undefined symbols are global, but this is the first place we
1007 // are able to set it.
1008 bool Local = isLocal(*it, isSignature, Used);
1009 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
1011 MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
1012 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
1013 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1017 MSD.SectionIndex = ELF::SHN_ABS;
1018 } else if (it->isCommon()) {
1020 MSD.SectionIndex = ELF::SHN_COMMON;
1021 } else if (BaseSymbol->isUndefined()) {
1022 if (isSignature && !Used)
1023 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1025 MSD.SectionIndex = ELF::SHN_UNDEF;
1026 if (!Used && WeakrefUsed)
1027 MCELF::SetBinding(*it, ELF::STB_WEAK);
1029 const MCSectionELF &Section =
1030 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1031 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1032 assert(MSD.SectionIndex && "Invalid section index!");
1035 // The @@@ in symbol version is replaced with @ in undefined symbols and
1036 // @@ in defined ones.
1037 StringRef Name = Symbol.getName();
1038 SmallString<32> Buf;
1040 size_t Pos = Name.find("@@@");
1041 if (Pos != StringRef::npos) {
1042 Buf += Name.substr(0, Pos);
1043 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1044 Buf += Name.substr(Pos + Skip);
1048 uint64_t &Entry = StringIndexMap[Name];
1050 Entry = StringTable.size();
1051 StringTable += Name;
1052 StringTable += '\x00';
1054 MSD.StringIndex = Entry;
1055 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1056 UndefinedSymbolData.push_back(MSD);
1058 LocalSymbolData.push_back(MSD);
1060 ExternalSymbolData.push_back(MSD);
1063 // Symbols are required to be in lexicographic order.
1064 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1065 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1066 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1068 // Set the symbol indices. Local symbols must come before all other
1069 // symbols with non-local bindings.
1070 unsigned Index = FileSymbolData.size() + 1;
1071 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1072 LocalSymbolData[i].SymbolData->setIndex(Index++);
1074 Index += NumRegularSections;
1076 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1077 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1078 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1079 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1082 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1083 MCAsmLayout &Layout,
1085 for (MCAssembler::const_iterator it = Asm.begin(),
1086 ie = Asm.end(); it != ie; ++it) {
1087 const MCSectionData &SD = *it;
1088 if (Relocations[&SD].empty())
1091 MCContext &Ctx = Asm.getContext();
1092 const MCSectionELF &Section =
1093 static_cast<const MCSectionELF&>(SD.getSection());
1095 const StringRef SectionName = Section.getSectionName();
1096 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1097 RelaSectionName += SectionName;
1100 if (hasRelocationAddend())
1101 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1103 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1106 StringRef Group = "";
1107 if (Section.getFlags() & ELF::SHF_GROUP) {
1108 Flags = ELF::SHF_GROUP;
1109 Group = Section.getGroup()->getName();
1112 const MCSectionELF *RelaSection =
1113 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1114 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1115 SectionKind::getReadOnly(),
1117 RelMap[&Section] = RelaSection;
1118 Asm.getOrCreateSectionData(*RelaSection);
1122 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1123 const RelMapTy &RelMap) {
1124 for (MCAssembler::const_iterator it = Asm.begin(),
1125 ie = Asm.end(); it != ie; ++it) {
1126 const MCSectionData &SD = *it;
1127 const MCSectionELF &Section =
1128 static_cast<const MCSectionELF&>(SD.getSection());
1130 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1133 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1134 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1136 MCDataFragment *F = new MCDataFragment(&RelaSD);
1137 WriteRelocationsFragment(Asm, F, &*it);
1141 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1142 uint64_t Flags, uint64_t Address,
1143 uint64_t Offset, uint64_t Size,
1144 uint32_t Link, uint32_t Info,
1146 uint64_t EntrySize) {
1147 Write32(Name); // sh_name: index into string table
1148 Write32(Type); // sh_type
1149 WriteWord(Flags); // sh_flags
1150 WriteWord(Address); // sh_addr
1151 WriteWord(Offset); // sh_offset
1152 WriteWord(Size); // sh_size
1153 Write32(Link); // sh_link
1154 Write32(Info); // sh_info
1155 WriteWord(Alignment); // sh_addralign
1156 WriteWord(EntrySize); // sh_entsize
1159 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1161 const MCSectionData *SD) {
1162 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1164 // Sort the relocation entries. Most targets just sort by r_offset, but some
1165 // (e.g., MIPS) have additional constraints.
1166 TargetObjectWriter->sortRelocs(Asm, Relocs);
1168 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1169 ELFRelocationEntry entry = Relocs[e - i - 1];
1173 // FIXME: this is most likely a bug if index overflows.
1174 else if (entry.Index < 0)
1175 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1177 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1179 write(*F, entry.r_offset);
1180 if (TargetObjectWriter->isN64()) {
1181 write(*F, uint32_t(entry.Index));
1183 write(*F, TargetObjectWriter->getRSsym(entry.Type));
1184 write(*F, TargetObjectWriter->getRType3(entry.Type));
1185 write(*F, TargetObjectWriter->getRType2(entry.Type));
1186 write(*F, TargetObjectWriter->getRType(entry.Type));
1189 struct ELF::Elf64_Rela ERE64;
1190 ERE64.setSymbolAndType(entry.Index, entry.Type);
1191 write(*F, ERE64.r_info);
1193 if (hasRelocationAddend())
1194 write(*F, entry.r_addend);
1196 write(*F, uint32_t(entry.r_offset));
1198 struct ELF::Elf32_Rela ERE32;
1199 ERE32.setSymbolAndType(entry.Index, entry.Type);
1200 write(*F, ERE32.r_info);
1202 if (hasRelocationAddend())
1203 write(*F, uint32_t(entry.r_addend));
1208 static int compareBySuffix(const MCSectionELF *const *a,
1209 const MCSectionELF *const *b) {
1210 const StringRef &NameA = (*a)->getSectionName();
1211 const StringRef &NameB = (*b)->getSectionName();
1212 const unsigned sizeA = NameA.size();
1213 const unsigned sizeB = NameB.size();
1214 const unsigned len = std::min(sizeA, sizeB);
1215 for (unsigned int i = 0; i < len; ++i) {
1216 char ca = NameA[sizeA - i - 1];
1217 char cb = NameB[sizeB - i - 1];
1222 return sizeB - sizeA;
1225 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1226 MCAsmLayout &Layout,
1227 SectionIndexMapTy &SectionIndexMap,
1228 const RelMapTy &RelMap) {
1229 MCContext &Ctx = Asm.getContext();
1232 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1234 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1235 const MCSectionELF *ShstrtabSection =
1236 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1237 SectionKind::getReadOnly());
1238 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1239 ShstrtabSD.setAlignment(1);
1241 const MCSectionELF *SymtabSection =
1242 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1243 SectionKind::getReadOnly(),
1245 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1246 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1248 const MCSectionELF *StrtabSection;
1249 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1250 SectionKind::getReadOnly());
1251 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1252 StrtabSD.setAlignment(1);
1254 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1256 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1257 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1258 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1261 F = new MCDataFragment(&SymtabSD);
1262 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1264 F = new MCDataFragment(&StrtabSD);
1265 F->getContents().append(StringTable.begin(), StringTable.end());
1267 F = new MCDataFragment(&ShstrtabSD);
1269 std::vector<const MCSectionELF*> Sections;
1270 for (MCAssembler::const_iterator it = Asm.begin(),
1271 ie = Asm.end(); it != ie; ++it) {
1272 const MCSectionELF &Section =
1273 static_cast<const MCSectionELF&>(it->getSection());
1274 Sections.push_back(&Section);
1276 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1278 // Section header string table.
1280 // The first entry of a string table holds a null character so skip
1283 F->getContents().push_back('\x00');
1285 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1286 const MCSectionELF &Section = *Sections[I];
1288 StringRef Name = Section.getSectionName();
1290 StringRef PreviousName = Sections[I - 1]->getSectionName();
1291 if (PreviousName.endswith(Name)) {
1292 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1296 // Remember the index into the string table so we can write it
1297 // into the sh_name field of the section header table.
1298 SectionStringTableIndex[&Section] = Index;
1300 Index += Name.size() + 1;
1301 F->getContents().append(Name.begin(), Name.end());
1302 F->getContents().push_back('\x00');
1306 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1307 MCAsmLayout &Layout,
1308 GroupMapTy &GroupMap,
1309 RevGroupMapTy &RevGroupMap,
1310 SectionIndexMapTy &SectionIndexMap,
1311 const RelMapTy &RelMap) {
1312 // Create the .note.GNU-stack section if needed.
1313 MCContext &Ctx = Asm.getContext();
1314 if (Asm.getNoExecStack()) {
1315 const MCSectionELF *GnuStackSection =
1316 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1317 SectionKind::getReadOnly());
1318 Asm.getOrCreateSectionData(*GnuStackSection);
1322 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1324 const MCSectionELF &Section =
1325 static_cast<const MCSectionELF&>(it->getSection());
1326 if (!(Section.getFlags() & ELF::SHF_GROUP))
1329 const MCSymbol *SignatureSymbol = Section.getGroup();
1330 Asm.getOrCreateSymbolData(*SignatureSymbol);
1331 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1333 Group = Ctx.CreateELFGroupSection();
1334 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1335 Data.setAlignment(4);
1336 MCDataFragment *F = new MCDataFragment(&Data);
1337 write(*F, uint32_t(ELF::GRP_COMDAT));
1339 GroupMap[Group] = SignatureSymbol;
1342 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1344 // Add sections to the groups
1345 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1347 const MCSectionELF &Section =
1348 static_cast<const MCSectionELF&>(it->getSection());
1349 if (!(Section.getFlags() & ELF::SHF_GROUP))
1351 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1352 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1353 // FIXME: we could use the previous fragment
1354 MCDataFragment *F = new MCDataFragment(&Data);
1355 uint32_t Index = SectionIndexMap.lookup(&Section);
1360 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1361 const SectionIndexMapTy &SectionIndexMap,
1362 uint32_t GroupSymbolIndex,
1363 uint64_t Offset, uint64_t Size,
1365 const MCSectionELF &Section) {
1366 uint64_t sh_link = 0;
1367 uint64_t sh_info = 0;
1369 switch(Section.getType()) {
1370 case ELF::SHT_DYNAMIC:
1371 sh_link = SectionStringTableIndex[&Section];
1376 case ELF::SHT_RELA: {
1377 const MCSectionELF *SymtabSection;
1378 const MCSectionELF *InfoSection;
1379 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1381 SectionKind::getReadOnly());
1382 sh_link = SectionIndexMap.lookup(SymtabSection);
1383 assert(sh_link && ".symtab not found");
1385 // Remove ".rel" and ".rela" prefixes.
1386 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1387 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1388 StringRef GroupName =
1389 Section.getGroup() ? Section.getGroup()->getName() : "";
1391 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1392 0, SectionKind::getReadOnly(),
1394 sh_info = SectionIndexMap.lookup(InfoSection);
1398 case ELF::SHT_SYMTAB:
1399 case ELF::SHT_DYNSYM:
1400 sh_link = StringTableIndex;
1401 sh_info = LastLocalSymbolIndex;
1404 case ELF::SHT_SYMTAB_SHNDX:
1405 sh_link = SymbolTableIndex;
1408 case ELF::SHT_PROGBITS:
1409 case ELF::SHT_STRTAB:
1410 case ELF::SHT_NOBITS:
1413 case ELF::SHT_ARM_ATTRIBUTES:
1414 case ELF::SHT_INIT_ARRAY:
1415 case ELF::SHT_FINI_ARRAY:
1416 case ELF::SHT_PREINIT_ARRAY:
1417 case ELF::SHT_X86_64_UNWIND:
1418 case ELF::SHT_MIPS_REGINFO:
1419 case ELF::SHT_MIPS_OPTIONS:
1423 case ELF::SHT_GROUP:
1424 sh_link = SymbolTableIndex;
1425 sh_info = GroupSymbolIndex;
1429 assert(0 && "FIXME: sh_type value not supported!");
1433 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1434 Section.getType() == ELF::SHT_ARM_EXIDX) {
1435 StringRef SecName(Section.getSectionName());
1436 if (SecName == ".ARM.exidx") {
1437 sh_link = SectionIndexMap.lookup(
1438 Asm.getContext().getELFSection(".text",
1440 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1441 SectionKind::getText()));
1442 } else if (SecName.startswith(".ARM.exidx")) {
1443 StringRef GroupName =
1444 Section.getGroup() ? Section.getGroup()->getName() : "";
1445 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1446 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1447 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1452 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1453 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1454 Alignment, Section.getEntrySize());
1457 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1458 return SD.getOrdinal() == ~UINT32_C(0) &&
1459 !SD.getSection().isVirtualSection();
1462 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1464 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1466 const MCFragment &F = *i;
1467 assert(F.getKind() == MCFragment::FT_Data);
1468 Ret += cast<MCDataFragment>(F).getContents().size();
1473 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1474 const MCSectionData &SD) {
1475 if (IsELFMetaDataSection(SD))
1476 return DataSectionSize(SD);
1477 return Layout.getSectionFileSize(&SD);
1480 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1481 const MCSectionData &SD) {
1482 if (IsELFMetaDataSection(SD))
1483 return DataSectionSize(SD);
1484 return Layout.getSectionAddressSize(&SD);
1487 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1488 const MCAsmLayout &Layout,
1489 const MCSectionELF &Section) {
1490 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1492 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1493 WriteZeros(Padding);
1495 if (IsELFMetaDataSection(SD)) {
1496 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1498 const MCFragment &F = *i;
1499 assert(F.getKind() == MCFragment::FT_Data);
1500 WriteBytes(cast<MCDataFragment>(F).getContents());
1503 Asm.writeSectionData(&SD, Layout);
1507 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1508 const GroupMapTy &GroupMap,
1509 const MCAsmLayout &Layout,
1510 const SectionIndexMapTy &SectionIndexMap,
1511 const SectionOffsetMapTy &SectionOffsetMap) {
1512 const unsigned NumSections = Asm.size() + 1;
1514 std::vector<const MCSectionELF*> Sections;
1515 Sections.resize(NumSections - 1);
1517 for (SectionIndexMapTy::const_iterator i=
1518 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1519 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1520 Sections[p.second - 1] = p.first;
1523 // Null section first.
1524 uint64_t FirstSectionSize =
1525 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1526 uint32_t FirstSectionLink =
1527 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1528 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1530 for (unsigned i = 0; i < NumSections - 1; ++i) {
1531 const MCSectionELF &Section = *Sections[i];
1532 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1533 uint32_t GroupSymbolIndex;
1534 if (Section.getType() != ELF::SHT_GROUP)
1535 GroupSymbolIndex = 0;
1537 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1538 GroupMap.lookup(&Section));
1540 uint64_t Size = GetSectionAddressSize(Layout, SD);
1542 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1543 SectionOffsetMap.lookup(&Section), Size,
1544 SD.getAlignment(), Section);
1548 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1549 std::vector<const MCSectionELF*> &Sections) {
1550 for (MCAssembler::iterator it = Asm.begin(),
1551 ie = Asm.end(); it != ie; ++it) {
1552 const MCSectionELF &Section =
1553 static_cast<const MCSectionELF &>(it->getSection());
1554 if (Section.getType() == ELF::SHT_GROUP)
1555 Sections.push_back(&Section);
1558 for (MCAssembler::iterator it = Asm.begin(),
1559 ie = Asm.end(); it != ie; ++it) {
1560 const MCSectionELF &Section =
1561 static_cast<const MCSectionELF &>(it->getSection());
1562 if (Section.getType() != ELF::SHT_GROUP &&
1563 Section.getType() != ELF::SHT_REL &&
1564 Section.getType() != ELF::SHT_RELA)
1565 Sections.push_back(&Section);
1568 for (MCAssembler::iterator it = Asm.begin(),
1569 ie = Asm.end(); it != ie; ++it) {
1570 const MCSectionELF &Section =
1571 static_cast<const MCSectionELF &>(it->getSection());
1572 if (Section.getType() == ELF::SHT_REL ||
1573 Section.getType() == ELF::SHT_RELA)
1574 Sections.push_back(&Section);
1578 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1579 const MCAsmLayout &Layout) {
1580 GroupMapTy GroupMap;
1581 RevGroupMapTy RevGroupMap;
1582 SectionIndexMapTy SectionIndexMap;
1584 unsigned NumUserSections = Asm.size();
1586 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1587 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1589 const unsigned NumUserAndRelocSections = Asm.size();
1590 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1591 RevGroupMap, SectionIndexMap, RelMap);
1592 const unsigned AllSections = Asm.size();
1593 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1595 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1597 // Compute symbol table information.
1598 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1599 NumRegularSections);
1601 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1603 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1604 const_cast<MCAsmLayout&>(Layout),
1608 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1609 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1610 sizeof(ELF::Elf32_Ehdr);
1611 uint64_t FileOff = HeaderSize;
1613 std::vector<const MCSectionELF*> Sections;
1614 ComputeSectionOrder(Asm, Sections);
1615 unsigned NumSections = Sections.size();
1616 SectionOffsetMapTy SectionOffsetMap;
1617 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1618 const MCSectionELF &Section = *Sections[i];
1619 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1621 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1623 // Remember the offset into the file for this section.
1624 SectionOffsetMap[&Section] = FileOff;
1626 // Get the size of the section in the output file (including padding).
1627 FileOff += GetSectionFileSize(Layout, SD);
1630 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1632 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1634 uint64_t SectionHeaderEntrySize = is64Bit() ?
1635 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1636 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1638 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1639 const MCSectionELF &Section = *Sections[i];
1640 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1642 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1644 // Remember the offset into the file for this section.
1645 SectionOffsetMap[&Section] = FileOff;
1647 // Get the size of the section in the output file (including padding).
1648 FileOff += GetSectionFileSize(Layout, SD);
1651 // Write out the ELF header ...
1652 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1654 // ... then the regular sections ...
1655 // + because of .shstrtab
1656 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1657 WriteDataSectionData(Asm, Layout, *Sections[i]);
1659 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1660 WriteZeros(Padding);
1662 // ... then the section header table ...
1663 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1666 // ... and then the remaining sections ...
1667 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1668 WriteDataSectionData(Asm, Layout, *Sections[i]);
1672 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1673 const MCSymbolData &DataA,
1674 const MCFragment &FB,
1676 bool IsPCRel) const {
1677 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1679 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1680 Asm, DataA, FB,InSet, IsPCRel);
1683 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1685 bool IsLittleEndian) {
1686 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);