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/ADT/OwningPtr.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCELFObjectWriter.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Target/TargetAsmBackend.h"
33 #include "llvm/ADT/StringSwitch.h"
35 #include "../Target/X86/X86FixupKinds.h"
36 #include "../Target/ARM/ARMFixupKinds.h"
41 static unsigned GetType(const MCSymbolData &SD) {
42 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
43 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
44 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
45 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
46 Type == ELF::STT_TLS);
50 static unsigned GetBinding(const MCSymbolData &SD) {
51 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
52 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
53 Binding == ELF::STB_WEAK);
57 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
58 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
59 Binding == ELF::STB_WEAK);
60 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
61 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
64 static unsigned GetVisibility(MCSymbolData &SD) {
66 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
67 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
68 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
73 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
77 case MCSymbolRefExpr::VK_GOT:
78 case MCSymbolRefExpr::VK_PLT:
79 case MCSymbolRefExpr::VK_GOTPCREL:
80 case MCSymbolRefExpr::VK_TPOFF:
81 case MCSymbolRefExpr::VK_TLSGD:
82 case MCSymbolRefExpr::VK_GOTTPOFF:
83 case MCSymbolRefExpr::VK_INDNTPOFF:
84 case MCSymbolRefExpr::VK_NTPOFF:
85 case MCSymbolRefExpr::VK_GOTNTPOFF:
86 case MCSymbolRefExpr::VK_TLSLDM:
87 case MCSymbolRefExpr::VK_DTPOFF:
88 case MCSymbolRefExpr::VK_TLSLD:
93 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
94 const MCFixupKindInfo &FKI =
95 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
97 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
101 class ELFObjectWriter : public MCObjectWriter {
103 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
104 return Kind == X86::reloc_riprel_4byte ||
105 Kind == X86::reloc_riprel_4byte_movq_load;
109 /// ELFSymbolData - Helper struct for containing some precomputed information
111 struct ELFSymbolData {
112 MCSymbolData *SymbolData;
113 uint64_t StringIndex;
114 uint32_t SectionIndex;
116 // Support lexicographic sorting.
117 bool operator<(const ELFSymbolData &RHS) const {
118 if (GetType(*SymbolData) == ELF::STT_FILE)
120 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
122 return SymbolData->getSymbol().getName() <
123 RHS.SymbolData->getSymbol().getName();
127 /// @name Relocation Data
130 struct ELFRelocationEntry {
131 // Make these big enough for both 32-bit and 64-bit
135 const MCSymbol *Symbol;
139 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
141 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
142 unsigned RelType, const MCSymbol *Sym,
144 : r_offset(RelocOffset), Index(Idx), Type(RelType),
145 Symbol(Sym), r_addend(Addend) {}
147 // Support lexicographic sorting.
148 bool operator<(const ELFRelocationEntry &RE) const {
149 return RE.r_offset < r_offset;
153 /// The target specific ELF writer instance.
154 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
156 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
157 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
158 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
160 llvm::DenseMap<const MCSectionData*,
161 std::vector<ELFRelocationEntry> > Relocations;
162 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
165 /// @name Symbol Table Data
168 SmallString<256> StringTable;
169 std::vector<ELFSymbolData> LocalSymbolData;
170 std::vector<ELFSymbolData> ExternalSymbolData;
171 std::vector<ELFSymbolData> UndefinedSymbolData;
177 bool NeedsSymtabShndx;
179 // This holds the symbol table index of the last local symbol.
180 unsigned LastLocalSymbolIndex;
181 // This holds the .strtab section index.
182 unsigned StringTableIndex;
183 // This holds the .symtab section index.
184 unsigned SymbolTableIndex;
186 unsigned ShstrtabIndex;
189 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
190 const MCValue &Target,
191 const MCFragment &F) const;
193 // For arch-specific emission of explicit reloc symbol
194 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
195 const MCValue &Target,
201 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
202 bool hasRelocationAddend() const {
203 return TargetObjectWriter->hasRelocationAddend();
207 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
208 raw_ostream &_OS, bool IsLittleEndian)
209 : MCObjectWriter(_OS, IsLittleEndian),
210 TargetObjectWriter(MOTW),
211 NeedsGOT(false), NeedsSymtabShndx(false){
214 virtual ~ELFObjectWriter();
216 void WriteWord(uint64_t W) {
223 void StringLE16(char *buf, uint16_t Value) {
224 buf[0] = char(Value >> 0);
225 buf[1] = char(Value >> 8);
228 void StringLE32(char *buf, uint32_t Value) {
229 StringLE16(buf, uint16_t(Value >> 0));
230 StringLE16(buf + 2, uint16_t(Value >> 16));
233 void StringLE64(char *buf, uint64_t Value) {
234 StringLE32(buf, uint32_t(Value >> 0));
235 StringLE32(buf + 4, uint32_t(Value >> 32));
238 void StringBE16(char *buf ,uint16_t Value) {
239 buf[0] = char(Value >> 8);
240 buf[1] = char(Value >> 0);
243 void StringBE32(char *buf, uint32_t Value) {
244 StringBE16(buf, uint16_t(Value >> 16));
245 StringBE16(buf + 2, uint16_t(Value >> 0));
248 void StringBE64(char *buf, uint64_t Value) {
249 StringBE32(buf, uint32_t(Value >> 32));
250 StringBE32(buf + 4, uint32_t(Value >> 0));
253 void String8(MCDataFragment &F, uint8_t Value) {
256 F.getContents() += StringRef(buf, 1);
259 void String16(MCDataFragment &F, uint16_t Value) {
261 if (isLittleEndian())
262 StringLE16(buf, Value);
264 StringBE16(buf, Value);
265 F.getContents() += StringRef(buf, 2);
268 void String32(MCDataFragment &F, uint32_t Value) {
270 if (isLittleEndian())
271 StringLE32(buf, Value);
273 StringBE32(buf, Value);
274 F.getContents() += StringRef(buf, 4);
277 void String64(MCDataFragment &F, uint64_t Value) {
279 if (isLittleEndian())
280 StringLE64(buf, Value);
282 StringBE64(buf, Value);
283 F.getContents() += StringRef(buf, 8);
286 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
288 /// Default e_flags = 0
289 virtual void WriteEFlags() { Write32(0); }
291 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
292 uint64_t name, uint8_t info,
293 uint64_t value, uint64_t size,
294 uint8_t other, uint32_t shndx,
297 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
299 const MCAsmLayout &Layout);
301 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
302 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
303 const MCAssembler &Asm,
304 const MCAsmLayout &Layout,
305 const SectionIndexMapTy &SectionIndexMap);
307 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
308 const MCFragment *Fragment, const MCFixup &Fixup,
309 MCValue Target, uint64_t &FixedValue);
311 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
314 // Map from a group section to the signature symbol
315 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
316 // Map from a signature symbol to the group section
317 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
319 /// ComputeSymbolTable - Compute the symbol table data
321 /// \param StringTable [out] - The string table data.
322 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
324 virtual void ComputeSymbolTable(MCAssembler &Asm,
325 const SectionIndexMapTy &SectionIndexMap,
326 RevGroupMapTy RevGroupMap);
328 virtual void ComputeIndexMap(MCAssembler &Asm,
329 SectionIndexMapTy &SectionIndexMap);
331 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
332 const MCSectionData &SD);
334 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
335 for (MCAssembler::const_iterator it = Asm.begin(),
336 ie = Asm.end(); it != ie; ++it) {
337 WriteRelocation(Asm, Layout, *it);
341 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
342 const SectionIndexMapTy &SectionIndexMap);
344 // Create the sections that show up in the symbol table. Currently
345 // those are the .note.GNU-stack section and the group sections.
346 virtual void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
347 GroupMapTy &GroupMap,
348 RevGroupMapTy &RevGroupMap);
350 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
351 const MCAsmLayout &Layout);
353 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
354 uint64_t Address, uint64_t Offset,
355 uint64_t Size, uint32_t Link, uint32_t Info,
356 uint64_t Alignment, uint64_t EntrySize);
358 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
360 const MCSectionData *SD);
362 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
363 virtual void WriteSection(MCAssembler &Asm,
364 const SectionIndexMapTy &SectionIndexMap,
365 uint32_t GroupSymbolIndex,
366 uint64_t Offset, uint64_t Size, uint64_t Alignment,
367 const MCSectionELF &Section);
370 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
371 bool IsPCRel, bool IsRelocWithSymbol,
375 //===- X86ELFObjectWriter -------------------------------------------===//
377 class X86ELFObjectWriter : public ELFObjectWriter {
379 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
381 bool IsLittleEndian);
383 virtual ~X86ELFObjectWriter();
385 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
386 bool IsPCRel, bool IsRelocWithSymbol,
391 //===- ARMELFObjectWriter -------------------------------------------===//
393 class ARMELFObjectWriter : public ELFObjectWriter {
395 // FIXME: MCAssembler can't yet return the Subtarget,
396 enum { DefaultEABIVersion = 0x05000000U };
398 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
400 bool IsLittleEndian);
402 virtual ~ARMELFObjectWriter();
404 virtual void WriteEFlags();
406 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
407 const MCValue &Target,
411 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
412 bool IsPCRel, bool IsRelocWithSymbol,
416 //===- MBlazeELFObjectWriter -------------------------------------------===//
418 class MBlazeELFObjectWriter : public ELFObjectWriter {
420 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
422 bool IsLittleEndian);
424 virtual ~MBlazeELFObjectWriter();
426 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
427 bool IsPCRel, bool IsRelocWithSymbol,
432 ELFObjectWriter::~ELFObjectWriter()
435 // Emit the ELF header.
436 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
437 unsigned NumberOfSections) {
443 // emitWord method behaves differently for ELF32 and ELF64, writing
444 // 4 bytes in the former and 8 in the latter.
446 Write8(0x7f); // e_ident[EI_MAG0]
447 Write8('E'); // e_ident[EI_MAG1]
448 Write8('L'); // e_ident[EI_MAG2]
449 Write8('F'); // e_ident[EI_MAG3]
451 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
454 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
456 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
458 switch (TargetObjectWriter->getOSType()) {
459 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
460 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
461 default: Write8(ELF::ELFOSABI_NONE); break;
463 Write8(0); // e_ident[EI_ABIVERSION]
465 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
467 Write16(ELF::ET_REL); // e_type
469 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
471 Write32(ELF::EV_CURRENT); // e_version
472 WriteWord(0); // e_entry, no entry point in .o file
473 WriteWord(0); // e_phoff, no program header for .o
474 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
475 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
477 // e_flags = whatever the target wants
480 // e_ehsize = ELF header size
481 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
483 Write16(0); // e_phentsize = prog header entry size
484 Write16(0); // e_phnum = # prog header entries = 0
486 // e_shentsize = Section header entry size
487 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
489 // e_shnum = # of section header ents
490 if (NumberOfSections >= ELF::SHN_LORESERVE)
493 Write16(NumberOfSections);
495 // e_shstrndx = Section # of '.shstrtab'
496 if (NumberOfSections >= ELF::SHN_LORESERVE)
497 Write16(ELF::SHN_XINDEX);
499 Write16(ShstrtabIndex);
502 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
503 MCDataFragment *ShndxF,
505 uint8_t info, uint64_t value,
506 uint64_t size, uint8_t other,
510 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
511 String32(*ShndxF, shndx);
513 String32(*ShndxF, 0);
516 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
517 uint16_t(ELF::SHN_XINDEX) : shndx;
520 String32(*SymtabF, name); // st_name
521 String8(*SymtabF, info); // st_info
522 String8(*SymtabF, other); // st_other
523 String16(*SymtabF, Index); // st_shndx
524 String64(*SymtabF, value); // st_value
525 String64(*SymtabF, size); // st_size
527 String32(*SymtabF, name); // st_name
528 String32(*SymtabF, value); // st_value
529 String32(*SymtabF, size); // st_size
530 String8(*SymtabF, info); // st_info
531 String8(*SymtabF, other); // st_other
532 String16(*SymtabF, Index); // st_shndx
536 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
537 if (Data.isCommon() && Data.isExternal())
538 return Data.getCommonAlignment();
540 const MCSymbol &Symbol = Data.getSymbol();
542 if (Symbol.isAbsolute() && Symbol.isVariable()) {
543 if (const MCExpr *Value = Symbol.getVariableValue()) {
545 if (Value->EvaluateAsAbsolute(IntValue, Layout))
546 return (uint64_t)IntValue;
550 if (!Symbol.isInSection())
553 if (Data.getFragment())
554 return Layout.getSymbolOffset(&Data);
559 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
560 const MCAsmLayout &Layout) {
561 // The presence of symbol versions causes undefined symbols and
562 // versions declared with @@@ to be renamed.
564 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
565 ie = Asm.symbol_end(); it != ie; ++it) {
566 const MCSymbol &Alias = it->getSymbol();
567 const MCSymbol &Symbol = Alias.AliasedSymbol();
568 MCSymbolData &SD = Asm.getSymbolData(Symbol);
571 if (&Symbol == &Alias)
574 StringRef AliasName = Alias.getName();
575 size_t Pos = AliasName.find('@');
576 if (Pos == StringRef::npos)
579 // Aliases defined with .symvar copy the binding from the symbol they alias.
580 // This is the first place we are able to copy this information.
581 it->setExternal(SD.isExternal());
582 SetBinding(*it, GetBinding(SD));
584 StringRef Rest = AliasName.substr(Pos);
585 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
588 // FIXME: produce a better error message.
589 if (Symbol.isUndefined() && Rest.startswith("@@") &&
590 !Rest.startswith("@@@"))
591 report_fatal_error("A @@ version cannot be undefined");
593 Renames.insert(std::make_pair(&Symbol, &Alias));
597 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
598 MCDataFragment *ShndxF,
600 const MCAsmLayout &Layout) {
601 MCSymbolData &OrigData = *MSD.SymbolData;
603 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
605 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
606 Data.getSymbol().isVariable();
608 uint8_t Binding = GetBinding(OrigData);
609 uint8_t Visibility = GetVisibility(OrigData);
610 uint8_t Type = GetType(Data);
612 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
613 uint8_t Other = Visibility;
615 uint64_t Value = SymbolValue(Data, Layout);
618 assert(!(Data.isCommon() && !Data.isExternal()));
620 const MCExpr *ESize = Data.getSize();
623 if (!ESize->EvaluateAsAbsolute(Res, Layout))
624 report_fatal_error("Size expression must be absolute.");
628 // Write out the symbol table entry
629 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
630 Size, Other, MSD.SectionIndex, IsReserved);
633 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
634 MCDataFragment *ShndxF,
635 const MCAssembler &Asm,
636 const MCAsmLayout &Layout,
637 const SectionIndexMapTy &SectionIndexMap) {
638 // The string table must be emitted first because we need the index
639 // into the string table for all the symbol names.
640 assert(StringTable.size() && "Missing string table");
642 // FIXME: Make sure the start of the symbol table is aligned.
644 // The first entry is the undefined symbol entry.
645 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
647 // Write the symbol table entries.
648 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
649 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
650 ELFSymbolData &MSD = LocalSymbolData[i];
651 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
654 // Write out a symbol table entry for each regular section.
655 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
657 const MCSectionELF &Section =
658 static_cast<const MCSectionELF&>(i->getSection());
659 if (Section.getType() == ELF::SHT_RELA ||
660 Section.getType() == ELF::SHT_REL ||
661 Section.getType() == ELF::SHT_STRTAB ||
662 Section.getType() == ELF::SHT_SYMTAB)
664 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
665 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
666 LastLocalSymbolIndex++;
669 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
670 ELFSymbolData &MSD = ExternalSymbolData[i];
671 MCSymbolData &Data = *MSD.SymbolData;
672 assert(((Data.getFlags() & ELF_STB_Global) ||
673 (Data.getFlags() & ELF_STB_Weak)) &&
674 "External symbol requires STB_GLOBAL or STB_WEAK flag");
675 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
676 if (GetBinding(Data) == ELF::STB_LOCAL)
677 LastLocalSymbolIndex++;
680 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
681 ELFSymbolData &MSD = UndefinedSymbolData[i];
682 MCSymbolData &Data = *MSD.SymbolData;
683 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
684 if (GetBinding(Data) == ELF::STB_LOCAL)
685 LastLocalSymbolIndex++;
689 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
690 const MCValue &Target,
691 const MCFragment &F) const {
692 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
693 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
694 const MCSymbol *Renamed = Renames.lookup(&Symbol);
695 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
697 if (ASymbol.isUndefined()) {
703 if (SD.isExternal()) {
709 const MCSectionELF &Section =
710 static_cast<const MCSectionELF&>(ASymbol.getSection());
711 const SectionKind secKind = Section.getKind();
714 return ExplicitRelSym(Asm, Target, F, true);
716 if (secKind.isThreadLocal()) {
722 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
723 const MCSectionELF &Sec2 =
724 static_cast<const MCSectionELF&>(F.getParent()->getSection());
726 if (&Sec2 != &Section &&
727 (Kind == MCSymbolRefExpr::VK_PLT ||
728 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
729 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
735 if (Section.getFlags() & ELF::SHF_MERGE) {
736 if (Target.getConstant() == 0)
743 return ExplicitRelSym(Asm, Target, F, false);
747 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
748 const MCAsmLayout &Layout,
749 const MCFragment *Fragment,
750 const MCFixup &Fixup,
752 uint64_t &FixedValue) {
755 int64_t Value = Target.getConstant();
756 const MCSymbol *RelocSymbol = NULL;
758 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
759 if (!Target.isAbsolute()) {
760 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
761 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
762 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
764 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
765 const MCSymbol &SymbolB = RefB->getSymbol();
766 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
769 // Offset of the symbol in the section
770 int64_t a = Layout.getSymbolOffset(&SDB);
772 // Ofeset of the relocation in the section
773 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
778 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
779 MCFragment *F = SD.getFragment();
781 Index = F->getParent()->getOrdinal() + 1;
783 // Offset of the symbol in the section
784 Value += Layout.getSymbolOffset(&SD);
786 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
787 WeakrefUsedInReloc.insert(RelocSymbol);
789 UsedInReloc.insert(RelocSymbol);
793 // Compensate for the addend on i386.
799 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
800 (RelocSymbol != 0), Addend);
802 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
805 if (!hasRelocationAddend())
807 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
808 Relocations[Fragment->getParent()].push_back(ERE);
813 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
815 MCSymbolData &SD = Asm.getSymbolData(*S);
816 return SD.getIndex();
819 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
820 bool Used, bool Renamed) {
821 if (Data.getFlags() & ELF_Other_Weakref)
830 const MCSymbol &Symbol = Data.getSymbol();
832 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
835 const MCSymbol &A = Symbol.AliasedSymbol();
836 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
839 bool IsGlobal = GetBinding(Data) == ELF::STB_GLOBAL;
840 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
843 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
846 if (Symbol.isTemporary())
852 static bool isLocal(const MCSymbolData &Data, bool isSignature,
853 bool isUsedInReloc) {
854 if (Data.isExternal())
857 const MCSymbol &Symbol = Data.getSymbol();
858 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
860 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
861 if (isSignature && !isUsedInReloc)
870 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
871 SectionIndexMapTy &SectionIndexMap) {
873 for (MCAssembler::iterator it = Asm.begin(),
874 ie = Asm.end(); it != ie; ++it) {
875 const MCSectionELF &Section =
876 static_cast<const MCSectionELF &>(it->getSection());
877 if (Section.getType() != ELF::SHT_GROUP)
879 SectionIndexMap[&Section] = Index++;
882 for (MCAssembler::iterator it = Asm.begin(),
883 ie = Asm.end(); it != ie; ++it) {
884 const MCSectionELF &Section =
885 static_cast<const MCSectionELF &>(it->getSection());
886 if (Section.getType() == ELF::SHT_GROUP)
888 SectionIndexMap[&Section] = Index++;
892 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
893 const SectionIndexMapTy &SectionIndexMap,
894 RevGroupMapTy RevGroupMap) {
895 // FIXME: Is this the correct place to do this?
897 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
898 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
899 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
900 Data.setExternal(true);
901 SetBinding(Data, ELF::STB_GLOBAL);
904 // Build section lookup table.
905 int NumRegularSections = Asm.size();
907 // Index 0 is always the empty string.
908 StringMap<uint64_t> StringIndexMap;
909 StringTable += '\x00';
911 // Add the data for the symbols.
912 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
913 ie = Asm.symbol_end(); it != ie; ++it) {
914 const MCSymbol &Symbol = it->getSymbol();
916 bool Used = UsedInReloc.count(&Symbol);
917 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
918 bool isSignature = RevGroupMap.count(&Symbol);
920 if (!isInSymtab(Asm, *it,
921 Used || WeakrefUsed || isSignature,
922 Renames.count(&Symbol)))
927 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
929 // Undefined symbols are global, but this is the first place we
930 // are able to set it.
931 bool Local = isLocal(*it, isSignature, Used);
932 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
933 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
934 SetBinding(*it, ELF::STB_GLOBAL);
935 SetBinding(SD, ELF::STB_GLOBAL);
938 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
939 SetBinding(*it, ELF::STB_WEAK);
941 if (it->isCommon()) {
943 MSD.SectionIndex = ELF::SHN_COMMON;
944 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
945 MSD.SectionIndex = ELF::SHN_ABS;
946 } else if (RefSymbol.isUndefined()) {
947 if (isSignature && !Used)
948 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
950 MSD.SectionIndex = ELF::SHN_UNDEF;
952 const MCSectionELF &Section =
953 static_cast<const MCSectionELF&>(RefSymbol.getSection());
954 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
955 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
956 NeedsSymtabShndx = true;
957 assert(MSD.SectionIndex && "Invalid section index!");
960 // The @@@ in symbol version is replaced with @ in undefined symbols and
961 // @@ in defined ones.
962 StringRef Name = Symbol.getName();
965 size_t Pos = Name.find("@@@");
966 if (Pos != StringRef::npos) {
967 Buf += Name.substr(0, Pos);
968 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
969 Buf += Name.substr(Pos + Skip);
973 uint64_t &Entry = StringIndexMap[Name];
975 Entry = StringTable.size();
977 StringTable += '\x00';
979 MSD.StringIndex = Entry;
980 if (MSD.SectionIndex == ELF::SHN_UNDEF)
981 UndefinedSymbolData.push_back(MSD);
983 LocalSymbolData.push_back(MSD);
985 ExternalSymbolData.push_back(MSD);
988 // Symbols are required to be in lexicographic order.
989 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
990 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
991 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
993 // Set the symbol indices. Local symbols must come before all other
994 // symbols with non-local bindings.
996 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
997 LocalSymbolData[i].SymbolData->setIndex(Index++);
999 Index += NumRegularSections;
1001 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1002 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1003 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1004 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1007 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1008 const MCSectionData &SD) {
1009 if (!Relocations[&SD].empty()) {
1010 MCContext &Ctx = Asm.getContext();
1011 const MCSectionELF *RelaSection;
1012 const MCSectionELF &Section =
1013 static_cast<const MCSectionELF&>(SD.getSection());
1015 const StringRef SectionName = Section.getSectionName();
1016 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1017 RelaSectionName += SectionName;
1020 if (hasRelocationAddend())
1021 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1023 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1025 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1026 ELF::SHT_RELA : ELF::SHT_REL, 0,
1027 SectionKind::getReadOnly(),
1030 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1031 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1033 MCDataFragment *F = new MCDataFragment(&RelaSD);
1035 WriteRelocationsFragment(Asm, F, &SD);
1039 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1040 uint64_t Flags, uint64_t Address,
1041 uint64_t Offset, uint64_t Size,
1042 uint32_t Link, uint32_t Info,
1044 uint64_t EntrySize) {
1045 Write32(Name); // sh_name: index into string table
1046 Write32(Type); // sh_type
1047 WriteWord(Flags); // sh_flags
1048 WriteWord(Address); // sh_addr
1049 WriteWord(Offset); // sh_offset
1050 WriteWord(Size); // sh_size
1051 Write32(Link); // sh_link
1052 Write32(Info); // sh_info
1053 WriteWord(Alignment); // sh_addralign
1054 WriteWord(EntrySize); // sh_entsize
1057 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1059 const MCSectionData *SD) {
1060 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1061 // sort by the r_offset just like gnu as does
1062 array_pod_sort(Relocs.begin(), Relocs.end());
1064 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1065 ELFRelocationEntry entry = Relocs[e - i - 1];
1069 else if (entry.Index < 0)
1070 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1072 entry.Index += LocalSymbolData.size();
1074 String64(*F, entry.r_offset);
1076 struct ELF::Elf64_Rela ERE64;
1077 ERE64.setSymbolAndType(entry.Index, entry.Type);
1078 String64(*F, ERE64.r_info);
1080 if (hasRelocationAddend())
1081 String64(*F, entry.r_addend);
1083 String32(*F, entry.r_offset);
1085 struct ELF::Elf32_Rela ERE32;
1086 ERE32.setSymbolAndType(entry.Index, entry.Type);
1087 String32(*F, ERE32.r_info);
1089 if (hasRelocationAddend())
1090 String32(*F, entry.r_addend);
1095 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1096 MCAsmLayout &Layout,
1097 const SectionIndexMapTy &SectionIndexMap) {
1098 MCContext &Ctx = Asm.getContext();
1101 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1103 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1104 const MCSectionELF *ShstrtabSection =
1105 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1106 SectionKind::getReadOnly());
1107 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1108 ShstrtabSD.setAlignment(1);
1109 ShstrtabIndex = Asm.size();
1111 const MCSectionELF *SymtabSection =
1112 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1113 SectionKind::getReadOnly(),
1115 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1116 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1117 SymbolTableIndex = Asm.size();
1119 MCSectionData *SymtabShndxSD = NULL;
1121 if (NeedsSymtabShndx) {
1122 const MCSectionELF *SymtabShndxSection =
1123 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1124 SectionKind::getReadOnly(), 4, "");
1125 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1126 SymtabShndxSD->setAlignment(4);
1129 const MCSection *StrtabSection;
1130 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1131 SectionKind::getReadOnly());
1132 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1133 StrtabSD.setAlignment(1);
1134 StringTableIndex = Asm.size();
1136 WriteRelocations(Asm, Layout);
1139 F = new MCDataFragment(&SymtabSD);
1140 MCDataFragment *ShndxF = NULL;
1141 if (NeedsSymtabShndx) {
1142 ShndxF = new MCDataFragment(SymtabShndxSD);
1144 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1146 F = new MCDataFragment(&StrtabSD);
1147 F->getContents().append(StringTable.begin(), StringTable.end());
1149 F = new MCDataFragment(&ShstrtabSD);
1151 // Section header string table.
1153 // The first entry of a string table holds a null character so skip
1156 F->getContents() += '\x00';
1158 StringMap<uint64_t> SecStringMap;
1159 for (MCAssembler::const_iterator it = Asm.begin(),
1160 ie = Asm.end(); it != ie; ++it) {
1161 const MCSectionELF &Section =
1162 static_cast<const MCSectionELF&>(it->getSection());
1163 // FIXME: We could merge suffixes like in .text and .rela.text.
1165 StringRef Name = Section.getSectionName();
1166 if (SecStringMap.count(Name)) {
1167 SectionStringTableIndex[&Section] = SecStringMap[Name];
1170 // Remember the index into the string table so we can write it
1171 // into the sh_name field of the section header table.
1172 SectionStringTableIndex[&Section] = Index;
1173 SecStringMap[Name] = Index;
1175 Index += Name.size() + 1;
1176 F->getContents() += Name;
1177 F->getContents() += '\x00';
1181 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1182 MCAsmLayout &Layout,
1183 GroupMapTy &GroupMap,
1184 RevGroupMapTy &RevGroupMap) {
1185 // Create the .note.GNU-stack section if needed.
1186 MCContext &Ctx = Asm.getContext();
1187 if (Asm.getNoExecStack()) {
1188 const MCSectionELF *GnuStackSection =
1189 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1190 SectionKind::getReadOnly());
1191 Asm.getOrCreateSectionData(*GnuStackSection);
1195 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1197 const MCSectionELF &Section =
1198 static_cast<const MCSectionELF&>(it->getSection());
1199 if (!(Section.getFlags() & ELF::SHF_GROUP))
1202 const MCSymbol *SignatureSymbol = Section.getGroup();
1203 Asm.getOrCreateSymbolData(*SignatureSymbol);
1204 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1206 Group = Ctx.CreateELFGroupSection();
1207 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1208 Data.setAlignment(4);
1209 MCDataFragment *F = new MCDataFragment(&Data);
1210 String32(*F, ELF::GRP_COMDAT);
1212 GroupMap[Group] = SignatureSymbol;
1215 // Add sections to the groups
1217 unsigned NumGroups = RevGroupMap.size();
1218 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1219 it != ie; ++it, ++Index) {
1220 const MCSectionELF &Section =
1221 static_cast<const MCSectionELF&>(it->getSection());
1222 if (!(Section.getFlags() & ELF::SHF_GROUP))
1224 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1225 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1226 // FIXME: we could use the previous fragment
1227 MCDataFragment *F = new MCDataFragment(&Data);
1228 String32(*F, NumGroups + Index);
1232 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1233 const SectionIndexMapTy &SectionIndexMap,
1234 uint32_t GroupSymbolIndex,
1235 uint64_t Offset, uint64_t Size,
1237 const MCSectionELF &Section) {
1238 uint64_t sh_link = 0;
1239 uint64_t sh_info = 0;
1241 switch(Section.getType()) {
1242 case ELF::SHT_DYNAMIC:
1243 sh_link = SectionStringTableIndex[&Section];
1248 case ELF::SHT_RELA: {
1249 const MCSectionELF *SymtabSection;
1250 const MCSectionELF *InfoSection;
1251 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1253 SectionKind::getReadOnly());
1254 sh_link = SectionIndexMap.lookup(SymtabSection);
1255 assert(sh_link && ".symtab not found");
1257 // Remove ".rel" and ".rela" prefixes.
1258 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1259 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1261 InfoSection = Asm.getContext().getELFSection(SectionName,
1262 ELF::SHT_PROGBITS, 0,
1263 SectionKind::getReadOnly());
1264 sh_info = SectionIndexMap.lookup(InfoSection);
1268 case ELF::SHT_SYMTAB:
1269 case ELF::SHT_DYNSYM:
1270 sh_link = StringTableIndex;
1271 sh_info = LastLocalSymbolIndex;
1274 case ELF::SHT_SYMTAB_SHNDX:
1275 sh_link = SymbolTableIndex;
1278 case ELF::SHT_PROGBITS:
1279 case ELF::SHT_STRTAB:
1280 case ELF::SHT_NOBITS:
1283 case ELF::SHT_ARM_ATTRIBUTES:
1284 case ELF::SHT_INIT_ARRAY:
1285 case ELF::SHT_FINI_ARRAY:
1286 case ELF::SHT_PREINIT_ARRAY:
1287 case ELF::SHT_X86_64_UNWIND:
1291 case ELF::SHT_GROUP: {
1292 sh_link = SymbolTableIndex;
1293 sh_info = GroupSymbolIndex;
1298 assert(0 && "FIXME: sh_type value not supported!");
1302 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1303 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1304 Alignment, Section.getEntrySize());
1307 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1308 return SD.getOrdinal() == ~UINT32_C(0) &&
1309 !SD.getSection().isVirtualSection();
1312 static uint64_t DataSectionSize(const MCSectionData &SD) {
1314 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1316 const MCFragment &F = *i;
1317 assert(F.getKind() == MCFragment::FT_Data);
1318 Ret += cast<MCDataFragment>(F).getContents().size();
1323 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1324 const MCSectionData &SD) {
1325 if (IsELFMetaDataSection(SD))
1326 return DataSectionSize(SD);
1327 return Layout.getSectionFileSize(&SD);
1330 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1331 const MCSectionData &SD) {
1332 if (IsELFMetaDataSection(SD))
1333 return DataSectionSize(SD);
1334 return Layout.getSectionAddressSize(&SD);
1337 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1338 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1340 const MCFragment &F = *i;
1341 assert(F.getKind() == MCFragment::FT_Data);
1342 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1346 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1347 const MCAsmLayout &Layout) {
1348 GroupMapTy GroupMap;
1349 RevGroupMapTy RevGroupMap;
1350 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1353 SectionIndexMapTy SectionIndexMap;
1355 ComputeIndexMap(Asm, SectionIndexMap);
1357 // Compute symbol table information.
1358 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1360 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1361 const_cast<MCAsmLayout&>(Layout),
1364 // Update to include the metadata sections.
1365 ComputeIndexMap(Asm, SectionIndexMap);
1367 // Add 1 for the null section.
1368 unsigned NumSections = Asm.size() + 1;
1369 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1370 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1371 sizeof(ELF::Elf32_Ehdr);
1372 uint64_t FileOff = HeaderSize;
1374 std::vector<const MCSectionELF*> Sections;
1375 Sections.resize(NumSections);
1377 for (SectionIndexMapTy::const_iterator i=
1378 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1379 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1380 Sections[p.second] = p.first;
1383 for (unsigned i = 1; i < NumSections; ++i) {
1384 const MCSectionELF &Section = *Sections[i];
1385 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1387 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1389 // Get the size of the section in the output file (including padding).
1390 FileOff += GetSectionFileSize(Layout, SD);
1393 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1395 // Write out the ELF header ...
1396 WriteHeader(FileOff - HeaderSize, NumSections);
1398 FileOff = HeaderSize;
1400 // ... then all of the sections ...
1401 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1403 for (unsigned i = 1; i < NumSections; ++i) {
1404 const MCSectionELF &Section = *Sections[i];
1405 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1407 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1408 WriteZeros(Padding);
1411 // Remember the offset into the file for this section.
1412 SectionOffsetMap[&Section] = FileOff;
1414 FileOff += GetSectionFileSize(Layout, SD);
1416 if (IsELFMetaDataSection(SD))
1417 WriteDataSectionData(this, SD);
1419 Asm.WriteSectionData(&SD, Layout);
1422 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1423 WriteZeros(Padding);
1426 // ... and then the section header table.
1427 // Should we align the section header table?
1429 // Null section first.
1430 uint64_t FirstSectionSize =
1431 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1432 uint32_t FirstSectionLink =
1433 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1434 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1436 for (unsigned i = 1; i < NumSections; ++i) {
1437 const MCSectionELF &Section = *Sections[i];
1438 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1439 uint32_t GroupSymbolIndex;
1440 if (Section.getType() != ELF::SHT_GROUP)
1441 GroupSymbolIndex = 0;
1443 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1445 uint64_t Size = GetSectionAddressSize(Layout, SD);
1447 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1448 SectionOffsetMap[&Section], Size,
1449 SD.getAlignment(), Section);
1453 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1455 bool IsLittleEndian) {
1456 switch (MOTW->getEMachine()) {
1458 case ELF::EM_X86_64:
1459 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1461 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1462 case ELF::EM_MBLAZE:
1463 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1464 default: llvm_unreachable("Unsupported architecture"); break;
1469 /// START OF SUBCLASSES for ELFObjectWriter
1470 //===- ARMELFObjectWriter -------------------------------------------===//
1472 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1474 bool IsLittleEndian)
1475 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1478 ARMELFObjectWriter::~ARMELFObjectWriter()
1481 // FIXME: get the real EABI Version from the Triple.
1482 void ARMELFObjectWriter::WriteEFlags() {
1483 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1486 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1487 // I.e. not as an offset to a section symbol.
1488 // This code is a first-cut approximation of what ARM/gcc does.
1490 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1491 const MCValue &Target,
1492 const MCFragment &F,
1494 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1495 bool EmitThisSym = false;
1498 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1499 .Case("_MergedGlobals", true)
1502 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1503 .Case("_MergedGlobals", true)
1504 .StartsWith(".L.str", true)
1509 if (! Symbol.isTemporary())
1514 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1515 const MCFixup &Fixup,
1517 bool IsRelocWithSymbol,
1519 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1520 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1524 switch ((unsigned)Fixup.getKind()) {
1525 default: assert(0 && "Unimplemented");
1528 default: llvm_unreachable("Unsupported Modifier");
1529 case MCSymbolRefExpr::VK_None:
1530 Type = ELF::R_ARM_BASE_PREL;
1532 case MCSymbolRefExpr::VK_ARM_TLSGD:
1533 assert(0 && "unimplemented");
1535 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1536 Type = ELF::R_ARM_TLS_IE32;
1540 case ARM::fixup_arm_uncondbranch:
1542 case MCSymbolRefExpr::VK_ARM_PLT:
1543 Type = ELF::R_ARM_PLT32;
1546 Type = ELF::R_ARM_CALL;
1550 case ARM::fixup_arm_condbranch:
1551 Type = ELF::R_ARM_JUMP24;
1553 case ARM::fixup_arm_movt_hi16:
1554 case ARM::fixup_arm_movt_hi16_pcrel:
1555 Type = ELF::R_ARM_MOVT_PREL;
1557 case ARM::fixup_arm_movw_lo16:
1558 case ARM::fixup_arm_movw_lo16_pcrel:
1559 Type = ELF::R_ARM_MOVW_PREL_NC;
1561 case ARM::fixup_t2_movt_hi16:
1562 case ARM::fixup_t2_movt_hi16_pcrel:
1563 Type = ELF::R_ARM_THM_MOVT_PREL;
1565 case ARM::fixup_t2_movw_lo16:
1566 case ARM::fixup_t2_movw_lo16_pcrel:
1567 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1571 switch ((unsigned)Fixup.getKind()) {
1572 default: llvm_unreachable("invalid fixup kind!");
1575 default: llvm_unreachable("Unsupported Modifier"); break;
1576 case MCSymbolRefExpr::VK_ARM_GOT:
1577 Type = ELF::R_ARM_GOT_BREL;
1579 case MCSymbolRefExpr::VK_ARM_TLSGD:
1580 Type = ELF::R_ARM_TLS_GD32;
1582 case MCSymbolRefExpr::VK_ARM_TPOFF:
1583 Type = ELF::R_ARM_TLS_LE32;
1585 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1586 Type = ELF::R_ARM_TLS_IE32;
1588 case MCSymbolRefExpr::VK_None:
1589 Type = ELF::R_ARM_ABS32;
1591 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1592 Type = ELF::R_ARM_GOTOFF32;
1596 case ARM::fixup_arm_ldst_pcrel_12:
1597 case ARM::fixup_arm_pcrel_10:
1598 case ARM::fixup_arm_adr_pcrel_12:
1599 case ARM::fixup_arm_thumb_bl:
1600 case ARM::fixup_arm_thumb_cb:
1601 case ARM::fixup_arm_thumb_cp:
1602 case ARM::fixup_arm_thumb_br:
1603 assert(0 && "Unimplemented");
1605 case ARM::fixup_arm_uncondbranch:
1606 Type = ELF::R_ARM_CALL;
1608 case ARM::fixup_arm_condbranch:
1609 Type = ELF::R_ARM_JUMP24;
1611 case ARM::fixup_arm_movt_hi16:
1612 Type = ELF::R_ARM_MOVT_ABS;
1614 case ARM::fixup_arm_movw_lo16:
1615 Type = ELF::R_ARM_MOVW_ABS_NC;
1617 case ARM::fixup_t2_movt_hi16:
1618 Type = ELF::R_ARM_THM_MOVT_ABS;
1620 case ARM::fixup_t2_movw_lo16:
1621 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1626 if (RelocNeedsGOT(Modifier))
1632 //===- MBlazeELFObjectWriter -------------------------------------------===//
1634 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1636 bool IsLittleEndian)
1637 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1640 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1643 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1644 const MCFixup &Fixup,
1646 bool IsRelocWithSymbol,
1648 // determine the type of the relocation
1651 switch ((unsigned)Fixup.getKind()) {
1653 llvm_unreachable("Unimplemented");
1655 Type = ELF::R_MICROBLAZE_64_PCREL;
1658 Type = ELF::R_MICROBLAZE_32_PCREL;
1662 switch ((unsigned)Fixup.getKind()) {
1663 default: llvm_unreachable("invalid fixup kind!");
1665 Type = ((IsRelocWithSymbol || Addend !=0)
1666 ? ELF::R_MICROBLAZE_32
1667 : ELF::R_MICROBLAZE_64);
1670 Type = ELF::R_MICROBLAZE_32;
1677 //===- X86ELFObjectWriter -------------------------------------------===//
1680 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1682 bool IsLittleEndian)
1683 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1686 X86ELFObjectWriter::~X86ELFObjectWriter()
1689 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1690 const MCFixup &Fixup,
1692 bool IsRelocWithSymbol,
1694 // determine the type of the relocation
1696 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1697 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1701 switch ((unsigned)Fixup.getKind()) {
1702 default: llvm_unreachable("invalid fixup kind!");
1704 assert(Modifier == MCSymbolRefExpr::VK_None);
1705 Type = ELF::R_X86_64_PC64;
1707 case X86::reloc_signed_4byte:
1708 case X86::reloc_riprel_4byte_movq_load:
1709 case FK_Data_4: // FIXME?
1710 case X86::reloc_riprel_4byte:
1714 llvm_unreachable("Unimplemented");
1715 case MCSymbolRefExpr::VK_None:
1716 Type = ELF::R_X86_64_PC32;
1718 case MCSymbolRefExpr::VK_PLT:
1719 Type = ELF::R_X86_64_PLT32;
1721 case MCSymbolRefExpr::VK_GOTPCREL:
1722 Type = ELF::R_X86_64_GOTPCREL;
1724 case MCSymbolRefExpr::VK_GOTTPOFF:
1725 Type = ELF::R_X86_64_GOTTPOFF;
1727 case MCSymbolRefExpr::VK_TLSGD:
1728 Type = ELF::R_X86_64_TLSGD;
1730 case MCSymbolRefExpr::VK_TLSLD:
1731 Type = ELF::R_X86_64_TLSLD;
1736 assert(Modifier == MCSymbolRefExpr::VK_None);
1737 Type = ELF::R_X86_64_PC16;
1740 assert(Modifier == MCSymbolRefExpr::VK_None);
1741 Type = ELF::R_X86_64_PC8;
1745 switch ((unsigned)Fixup.getKind()) {
1746 default: llvm_unreachable("invalid fixup kind!");
1747 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1748 case X86::reloc_signed_4byte:
1749 assert(isInt<32>(Target.getConstant()));
1752 llvm_unreachable("Unimplemented");
1753 case MCSymbolRefExpr::VK_None:
1754 Type = ELF::R_X86_64_32S;
1756 case MCSymbolRefExpr::VK_GOT:
1757 Type = ELF::R_X86_64_GOT32;
1759 case MCSymbolRefExpr::VK_GOTPCREL:
1760 Type = ELF::R_X86_64_GOTPCREL;
1762 case MCSymbolRefExpr::VK_TPOFF:
1763 Type = ELF::R_X86_64_TPOFF32;
1765 case MCSymbolRefExpr::VK_DTPOFF:
1766 Type = ELF::R_X86_64_DTPOFF32;
1771 Type = ELF::R_X86_64_32;
1773 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1775 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1782 llvm_unreachable("Unimplemented");
1783 case MCSymbolRefExpr::VK_None:
1784 Type = ELF::R_386_PC32;
1786 case MCSymbolRefExpr::VK_PLT:
1787 Type = ELF::R_386_PLT32;
1791 switch ((unsigned)Fixup.getKind()) {
1792 default: llvm_unreachable("invalid fixup kind!");
1794 case X86::reloc_global_offset_table:
1795 Type = ELF::R_386_GOTPC;
1798 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1800 case X86::reloc_signed_4byte:
1805 llvm_unreachable("Unimplemented");
1806 case MCSymbolRefExpr::VK_None:
1807 Type = ELF::R_386_32;
1809 case MCSymbolRefExpr::VK_GOT:
1810 Type = ELF::R_386_GOT32;
1812 case MCSymbolRefExpr::VK_GOTOFF:
1813 Type = ELF::R_386_GOTOFF;
1815 case MCSymbolRefExpr::VK_TLSGD:
1816 Type = ELF::R_386_TLS_GD;
1818 case MCSymbolRefExpr::VK_TPOFF:
1819 Type = ELF::R_386_TLS_LE_32;
1821 case MCSymbolRefExpr::VK_INDNTPOFF:
1822 Type = ELF::R_386_TLS_IE;
1824 case MCSymbolRefExpr::VK_NTPOFF:
1825 Type = ELF::R_386_TLS_LE;
1827 case MCSymbolRefExpr::VK_GOTNTPOFF:
1828 Type = ELF::R_386_TLS_GOTIE;
1830 case MCSymbolRefExpr::VK_TLSLDM:
1831 Type = ELF::R_386_TLS_LDM;
1833 case MCSymbolRefExpr::VK_DTPOFF:
1834 Type = ELF::R_386_TLS_LDO_32;
1838 case FK_Data_2: Type = ELF::R_386_16; break;
1840 case FK_Data_1: Type = ELF::R_386_8; break;
1845 if (RelocNeedsGOT(Modifier))