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/SmallPtrSet.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Target/TargetAsmBackend.h"
32 #include "../Target/X86/X86FixupKinds.h"
33 #include "../Target/ARM/ARMFixupKinds.h"
34 #include "../Target/MBlaze/MBlazeFixupKinds.h"
39 static unsigned GetType(const MCSymbolData &SD) {
40 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
41 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
42 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
43 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
44 Type == ELF::STT_TLS);
48 static unsigned GetBinding(const MCSymbolData &SD) {
49 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
50 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
51 Binding == ELF::STB_WEAK);
55 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
56 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
57 Binding == ELF::STB_WEAK);
58 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
59 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
62 static unsigned GetVisibility(MCSymbolData &SD) {
64 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
65 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
66 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
71 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
75 case MCSymbolRefExpr::VK_GOT:
76 case MCSymbolRefExpr::VK_PLT:
77 case MCSymbolRefExpr::VK_GOTPCREL:
78 case MCSymbolRefExpr::VK_TPOFF:
79 case MCSymbolRefExpr::VK_TLSGD:
80 case MCSymbolRefExpr::VK_GOTTPOFF:
81 case MCSymbolRefExpr::VK_INDNTPOFF:
82 case MCSymbolRefExpr::VK_NTPOFF:
83 case MCSymbolRefExpr::VK_GOTNTPOFF:
84 case MCSymbolRefExpr::VK_TLSLDM:
85 case MCSymbolRefExpr::VK_DTPOFF:
86 case MCSymbolRefExpr::VK_TLSLD:
92 class ELFObjectWriter : public MCObjectWriter {
94 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
95 return Kind == X86::reloc_riprel_4byte ||
96 Kind == X86::reloc_riprel_4byte_movq_load;
100 /// ELFSymbolData - Helper struct for containing some precomputed information
102 struct ELFSymbolData {
103 MCSymbolData *SymbolData;
104 uint64_t StringIndex;
105 uint32_t SectionIndex;
107 // Support lexicographic sorting.
108 bool operator<(const ELFSymbolData &RHS) const {
109 if (GetType(*SymbolData) == ELF::STT_FILE)
111 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
113 return SymbolData->getSymbol().getName() <
114 RHS.SymbolData->getSymbol().getName();
118 /// @name Relocation Data
121 struct ELFRelocationEntry {
122 // Make these big enough for both 32-bit and 64-bit
126 const MCSymbol *Symbol;
130 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
132 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
133 unsigned RelType, const MCSymbol *Sym,
135 : r_offset(RelocOffset), Index(Idx), Type(RelType),
136 Symbol(Sym), r_addend(Addend) {}
138 // Support lexicographic sorting.
139 bool operator<(const ELFRelocationEntry &RE) const {
140 return RE.r_offset < r_offset;
144 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
145 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
146 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
148 llvm::DenseMap<const MCSectionData*,
149 std::vector<ELFRelocationEntry> > Relocations;
150 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
153 /// @name Symbol Table Data
156 SmallString<256> StringTable;
157 std::vector<ELFSymbolData> LocalSymbolData;
158 std::vector<ELFSymbolData> ExternalSymbolData;
159 std::vector<ELFSymbolData> UndefinedSymbolData;
165 bool NeedsSymtabShndx;
167 unsigned Is64Bit : 1;
169 bool HasRelocationAddend;
171 Triple::OSType OSType;
175 // This holds the symbol table index of the last local symbol.
176 unsigned LastLocalSymbolIndex;
177 // This holds the .strtab section index.
178 unsigned StringTableIndex;
179 // This holds the .symtab section index.
180 unsigned SymbolTableIndex;
182 unsigned ShstrtabIndex;
185 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
186 const MCValue &Target,
187 const MCFragment &F) const;
190 ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
191 uint16_t _EMachine, bool _HasRelAddend,
192 Triple::OSType _OSType)
193 : MCObjectWriter(_OS, IsLittleEndian),
194 NeedsGOT(false), NeedsSymtabShndx(false),
195 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
196 OSType(_OSType), EMachine(_EMachine) {
199 virtual ~ELFObjectWriter();
201 void WriteWord(uint64_t W) {
208 void StringLE16(char *buf, uint16_t Value) {
209 buf[0] = char(Value >> 0);
210 buf[1] = char(Value >> 8);
213 void StringLE32(char *buf, uint32_t Value) {
214 StringLE16(buf, uint16_t(Value >> 0));
215 StringLE16(buf + 2, uint16_t(Value >> 16));
218 void StringLE64(char *buf, uint64_t Value) {
219 StringLE32(buf, uint32_t(Value >> 0));
220 StringLE32(buf + 4, uint32_t(Value >> 32));
223 void StringBE16(char *buf ,uint16_t Value) {
224 buf[0] = char(Value >> 8);
225 buf[1] = char(Value >> 0);
228 void StringBE32(char *buf, uint32_t Value) {
229 StringBE16(buf, uint16_t(Value >> 16));
230 StringBE16(buf + 2, uint16_t(Value >> 0));
233 void StringBE64(char *buf, uint64_t Value) {
234 StringBE32(buf, uint32_t(Value >> 32));
235 StringBE32(buf + 4, uint32_t(Value >> 0));
238 void String8(MCDataFragment &F, uint8_t Value) {
241 F.getContents() += StringRef(buf, 1);
244 void String16(MCDataFragment &F, uint16_t Value) {
246 if (isLittleEndian())
247 StringLE16(buf, Value);
249 StringBE16(buf, Value);
250 F.getContents() += StringRef(buf, 2);
253 void String32(MCDataFragment &F, uint32_t Value) {
255 if (isLittleEndian())
256 StringLE32(buf, Value);
258 StringBE32(buf, Value);
259 F.getContents() += StringRef(buf, 4);
262 void String64(MCDataFragment &F, uint64_t Value) {
264 if (isLittleEndian())
265 StringLE64(buf, Value);
267 StringBE64(buf, Value);
268 F.getContents() += StringRef(buf, 8);
271 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
273 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
274 uint64_t name, uint8_t info,
275 uint64_t value, uint64_t size,
276 uint8_t other, uint32_t shndx,
279 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
281 const MCAsmLayout &Layout);
283 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
284 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
285 const MCAssembler &Asm,
286 const MCAsmLayout &Layout,
287 const SectionIndexMapTy &SectionIndexMap);
289 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
290 const MCFragment *Fragment, const MCFixup &Fixup,
291 MCValue Target, uint64_t &FixedValue) {
292 assert(0 && "RecordRelocation is not specific enough");
295 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
298 // Map from a group section to the signature symbol
299 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
300 // Map from a signature symbol to the group section
301 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
303 /// ComputeSymbolTable - Compute the symbol table data
305 /// \param StringTable [out] - The string table data.
306 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
308 virtual void ComputeSymbolTable(MCAssembler &Asm,
309 const SectionIndexMapTy &SectionIndexMap,
310 RevGroupMapTy RevGroupMap);
312 virtual void ComputeIndexMap(MCAssembler &Asm,
313 SectionIndexMapTy &SectionIndexMap);
315 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
316 const MCSectionData &SD);
318 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
319 for (MCAssembler::const_iterator it = Asm.begin(),
320 ie = Asm.end(); it != ie; ++it) {
321 WriteRelocation(Asm, Layout, *it);
325 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
326 const SectionIndexMapTy &SectionIndexMap);
328 virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
329 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
331 virtual void ExecutePostLayoutBinding(MCAssembler &Asm);
333 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
334 uint64_t Address, uint64_t Offset,
335 uint64_t Size, uint32_t Link, uint32_t Info,
336 uint64_t Alignment, uint64_t EntrySize);
338 virtual void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
339 const MCSectionData *SD);
341 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
342 const MCValue Target,
344 const MCFragment *DF) const;
346 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
347 virtual void WriteSection(MCAssembler &Asm,
348 const SectionIndexMapTy &SectionIndexMap,
349 uint32_t GroupSymbolIndex,
350 uint64_t Offset, uint64_t Size, uint64_t Alignment,
351 const MCSectionELF &Section);
354 //===- X86ELFObjectWriter -------------------------------------------===//
356 class X86ELFObjectWriter : public ELFObjectWriter {
358 X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
359 uint16_t _EMachine, bool _HasRelAddend,
360 Triple::OSType _OSType);
362 virtual ~X86ELFObjectWriter();
363 virtual void RecordRelocation(const MCAssembler &Asm,
364 const MCAsmLayout &Layout,
365 const MCFragment *Fragment,
366 const MCFixup &Fixup, MCValue Target,
367 uint64_t &FixedValue);
370 static bool isFixupKindPCRel(unsigned Kind) {
374 case X86::reloc_pcrel_1byte:
375 case X86::reloc_pcrel_4byte:
376 case X86::reloc_riprel_4byte:
377 case X86::reloc_riprel_4byte_movq_load:
384 //===- ARMELFObjectWriter -------------------------------------------===//
386 class ARMELFObjectWriter : public ELFObjectWriter {
388 ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
389 uint16_t _EMachine, bool _HasRelAddend,
390 Triple::OSType _OSType);
392 virtual ~ARMELFObjectWriter();
393 virtual void RecordRelocation(const MCAssembler &Asm,
394 const MCAsmLayout &Layout,
395 const MCFragment *Fragment,
396 const MCFixup &Fixup, MCValue Target,
397 uint64_t &FixedValue);
400 static bool isFixupKindPCRel(unsigned Kind) {
404 case ARM::fixup_arm_pcrel_12:
405 case ARM::fixup_arm_vfp_pcrel_12:
406 case ARM::fixup_arm_branch:
412 //===- MBlazeELFObjectWriter -------------------------------------------===//
414 class MBlazeELFObjectWriter : public ELFObjectWriter {
416 MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
417 uint16_t _EMachine, bool _HasRelAddend,
418 Triple::OSType _OSType);
420 virtual ~MBlazeELFObjectWriter();
421 virtual void RecordRelocation(const MCAssembler &Asm,
422 const MCAsmLayout &Layout,
423 const MCFragment *Fragment,
424 const MCFixup &Fixup, MCValue Target,
425 uint64_t &FixedValue);
428 static bool isFixupKindPCRel(unsigned Kind) {
432 case MBlaze::reloc_pcrel_2byte:
433 case MBlaze::reloc_pcrel_4byte:
440 ELFObjectWriter::~ELFObjectWriter()
443 // Emit the ELF header.
444 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
445 unsigned NumberOfSections) {
451 // emitWord method behaves differently for ELF32 and ELF64, writing
452 // 4 bytes in the former and 8 in the latter.
454 Write8(0x7f); // e_ident[EI_MAG0]
455 Write8('E'); // e_ident[EI_MAG1]
456 Write8('L'); // e_ident[EI_MAG2]
457 Write8('F'); // e_ident[EI_MAG3]
459 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
462 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
464 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
467 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
468 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
469 default: Write8(ELF::ELFOSABI_NONE); break;
471 Write8(0); // e_ident[EI_ABIVERSION]
473 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
475 Write16(ELF::ET_REL); // e_type
477 Write16(EMachine); // e_machine = target
479 Write32(ELF::EV_CURRENT); // e_version
480 WriteWord(0); // e_entry, no entry point in .o file
481 WriteWord(0); // e_phoff, no program header for .o
482 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
483 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
485 // FIXME: Make this configurable.
486 Write32(0); // e_flags = whatever the target wants
488 // e_ehsize = ELF header size
489 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
491 Write16(0); // e_phentsize = prog header entry size
492 Write16(0); // e_phnum = # prog header entries = 0
494 // e_shentsize = Section header entry size
495 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
497 // e_shnum = # of section header ents
498 if (NumberOfSections >= ELF::SHN_LORESERVE)
501 Write16(NumberOfSections);
503 // e_shstrndx = Section # of '.shstrtab'
504 if (NumberOfSections >= ELF::SHN_LORESERVE)
505 Write16(ELF::SHN_XINDEX);
507 Write16(ShstrtabIndex);
510 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
511 MCDataFragment *ShndxF,
513 uint8_t info, uint64_t value,
514 uint64_t size, uint8_t other,
518 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
519 String32(*ShndxF, shndx);
521 String32(*ShndxF, 0);
524 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
525 uint16_t(ELF::SHN_XINDEX) : shndx;
528 String32(*SymtabF, name); // st_name
529 String8(*SymtabF, info); // st_info
530 String8(*SymtabF, other); // st_other
531 String16(*SymtabF, Index); // st_shndx
532 String64(*SymtabF, value); // st_value
533 String64(*SymtabF, size); // st_size
535 String32(*SymtabF, name); // st_name
536 String32(*SymtabF, value); // st_value
537 String32(*SymtabF, size); // st_size
538 String8(*SymtabF, info); // st_info
539 String8(*SymtabF, other); // st_other
540 String16(*SymtabF, Index); // st_shndx
544 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
545 if (Data.isCommon() && Data.isExternal())
546 return Data.getCommonAlignment();
548 const MCSymbol &Symbol = Data.getSymbol();
549 if (!Symbol.isInSection())
552 if (MCFragment *FF = Data.getFragment())
553 return Layout.getSymbolAddress(&Data) -
554 Layout.getSectionAddress(FF->getParent());
559 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
560 // The presence of symbol versions causes undefined symbols and
561 // versions declared with @@@ to be renamed.
563 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
564 ie = Asm.symbol_end(); it != ie; ++it) {
565 const MCSymbol &Alias = it->getSymbol();
566 const MCSymbol &Symbol = Alias.AliasedSymbol();
567 MCSymbolData &SD = Asm.getSymbolData(Symbol);
570 if (&Symbol == &Alias)
573 StringRef AliasName = Alias.getName();
574 size_t Pos = AliasName.find('@');
575 if (Pos == StringRef::npos)
578 // Aliases defined with .symvar copy the binding from the symbol they alias.
579 // This is the first place we are able to copy this information.
580 it->setExternal(SD.isExternal());
581 SetBinding(*it, GetBinding(SD));
583 StringRef Rest = AliasName.substr(Pos);
584 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
587 // FIXME: produce a better error message.
588 if (Symbol.isUndefined() && Rest.startswith("@@") &&
589 !Rest.startswith("@@@"))
590 report_fatal_error("A @@ version cannot be undefined");
592 Renames.insert(std::make_pair(&Symbol, &Alias));
596 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
597 MCDataFragment *ShndxF,
599 const MCAsmLayout &Layout) {
600 MCSymbolData &OrigData = *MSD.SymbolData;
602 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
604 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
605 Data.getSymbol().isVariable();
607 uint8_t Binding = GetBinding(OrigData);
608 uint8_t Visibility = GetVisibility(OrigData);
609 uint8_t Type = GetType(Data);
611 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
612 uint8_t Other = Visibility;
614 uint64_t Value = SymbolValue(Data, Layout);
618 assert(!(Data.isCommon() && !Data.isExternal()));
620 ESize = Data.getSize();
621 if (Data.getSize()) {
623 if (ESize->getKind() == MCExpr::Binary) {
624 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
626 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
627 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
628 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
629 Size = Res.getConstant();
631 } else if (ESize->getKind() == MCExpr::Constant) {
632 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
634 assert(0 && "Unsupported size expression");
638 // Write out the symbol table entry
639 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
640 Size, Other, MSD.SectionIndex, IsReserved);
643 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
644 MCDataFragment *ShndxF,
645 const MCAssembler &Asm,
646 const MCAsmLayout &Layout,
647 const SectionIndexMapTy &SectionIndexMap) {
648 // The string table must be emitted first because we need the index
649 // into the string table for all the symbol names.
650 assert(StringTable.size() && "Missing string table");
652 // FIXME: Make sure the start of the symbol table is aligned.
654 // The first entry is the undefined symbol entry.
655 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
657 // Write the symbol table entries.
658 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
659 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
660 ELFSymbolData &MSD = LocalSymbolData[i];
661 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
664 // Write out a symbol table entry for each regular section.
665 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
667 const MCSectionELF &Section =
668 static_cast<const MCSectionELF&>(i->getSection());
669 if (Section.getType() == ELF::SHT_RELA ||
670 Section.getType() == ELF::SHT_REL ||
671 Section.getType() == ELF::SHT_STRTAB ||
672 Section.getType() == ELF::SHT_SYMTAB)
674 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
675 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
676 LastLocalSymbolIndex++;
679 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
680 ELFSymbolData &MSD = ExternalSymbolData[i];
681 MCSymbolData &Data = *MSD.SymbolData;
682 assert(((Data.getFlags() & ELF_STB_Global) ||
683 (Data.getFlags() & ELF_STB_Weak)) &&
684 "External symbol requires STB_GLOBAL or STB_WEAK flag");
685 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
686 if (GetBinding(Data) == ELF::STB_LOCAL)
687 LastLocalSymbolIndex++;
690 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
691 ELFSymbolData &MSD = UndefinedSymbolData[i];
692 MCSymbolData &Data = *MSD.SymbolData;
693 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
694 if (GetBinding(Data) == ELF::STB_LOCAL)
695 LastLocalSymbolIndex++;
699 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
700 const MCValue &Target,
701 const MCFragment &F) const {
702 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
703 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
704 const MCSymbol *Renamed = Renames.lookup(&Symbol);
705 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
707 if (ASymbol.isUndefined()) {
713 if (SD.isExternal()) {
719 const MCSectionELF &Section =
720 static_cast<const MCSectionELF&>(ASymbol.getSection());
722 if (Section.getKind().isBSS())
725 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
726 const MCSectionELF &Sec2 =
727 static_cast<const MCSectionELF&>(F.getParent()->getSection());
729 if (&Sec2 != &Section &&
730 (Kind == MCSymbolRefExpr::VK_PLT ||
731 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
732 Kind == MCSymbolRefExpr::VK_GOTOFF ||
733 Kind == MCSymbolRefExpr::VK_NTPOFF)) {
739 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
740 if (Target.getConstant() == 0)
752 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
754 MCSymbolData &SD = Asm.getSymbolData(*S);
755 return SD.getIndex();
758 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
759 bool Used, bool Renamed) {
760 if (Data.getFlags() & ELF_Other_Weakref)
769 const MCSymbol &Symbol = Data.getSymbol();
771 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
774 const MCSymbol &A = Symbol.AliasedSymbol();
775 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
778 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
781 if (Symbol.isTemporary())
787 static bool isLocal(const MCSymbolData &Data, bool isSignature,
788 bool isUsedInReloc) {
789 if (Data.isExternal())
792 const MCSymbol &Symbol = Data.getSymbol();
793 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
795 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
796 if (isSignature && !isUsedInReloc)
805 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
806 SectionIndexMapTy &SectionIndexMap) {
808 for (MCAssembler::iterator it = Asm.begin(),
809 ie = Asm.end(); it != ie; ++it) {
810 const MCSectionELF &Section =
811 static_cast<const MCSectionELF &>(it->getSection());
812 if (Section.getType() != ELF::SHT_GROUP)
814 SectionIndexMap[&Section] = Index++;
817 for (MCAssembler::iterator it = Asm.begin(),
818 ie = Asm.end(); it != ie; ++it) {
819 const MCSectionELF &Section =
820 static_cast<const MCSectionELF &>(it->getSection());
821 if (Section.getType() == ELF::SHT_GROUP)
823 SectionIndexMap[&Section] = Index++;
827 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
828 const SectionIndexMapTy &SectionIndexMap,
829 RevGroupMapTy RevGroupMap) {
830 // FIXME: Is this the correct place to do this?
832 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
833 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
834 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
835 Data.setExternal(true);
836 SetBinding(Data, ELF::STB_GLOBAL);
839 // Build section lookup table.
840 int NumRegularSections = Asm.size();
842 // Index 0 is always the empty string.
843 StringMap<uint64_t> StringIndexMap;
844 StringTable += '\x00';
846 // Add the data for the symbols.
847 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
848 ie = Asm.symbol_end(); it != ie; ++it) {
849 const MCSymbol &Symbol = it->getSymbol();
851 bool Used = UsedInReloc.count(&Symbol);
852 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
853 bool isSignature = RevGroupMap.count(&Symbol);
855 if (!isInSymtab(Asm, *it,
856 Used || WeakrefUsed || isSignature,
857 Renames.count(&Symbol)))
862 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
864 // Undefined symbols are global, but this is the first place we
865 // are able to set it.
866 bool Local = isLocal(*it, isSignature, Used);
867 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
868 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
869 SetBinding(*it, ELF::STB_GLOBAL);
870 SetBinding(SD, ELF::STB_GLOBAL);
873 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
874 SetBinding(*it, ELF::STB_WEAK);
876 if (it->isCommon()) {
878 MSD.SectionIndex = ELF::SHN_COMMON;
879 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
880 MSD.SectionIndex = ELF::SHN_ABS;
881 } else if (RefSymbol.isUndefined()) {
882 if (isSignature && !Used)
883 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
885 MSD.SectionIndex = ELF::SHN_UNDEF;
887 const MCSectionELF &Section =
888 static_cast<const MCSectionELF&>(RefSymbol.getSection());
889 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
890 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
891 NeedsSymtabShndx = true;
892 assert(MSD.SectionIndex && "Invalid section index!");
895 // The @@@ in symbol version is replaced with @ in undefined symbols and
896 // @@ in defined ones.
897 StringRef Name = Symbol.getName();
900 size_t Pos = Name.find("@@@");
901 if (Pos != StringRef::npos) {
902 Buf += Name.substr(0, Pos);
903 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
904 Buf += Name.substr(Pos + Skip);
908 uint64_t &Entry = StringIndexMap[Name];
910 Entry = StringTable.size();
912 StringTable += '\x00';
914 MSD.StringIndex = Entry;
915 if (MSD.SectionIndex == ELF::SHN_UNDEF)
916 UndefinedSymbolData.push_back(MSD);
918 LocalSymbolData.push_back(MSD);
920 ExternalSymbolData.push_back(MSD);
923 // Symbols are required to be in lexicographic order.
924 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
925 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
926 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
928 // Set the symbol indices. Local symbols must come before all other
929 // symbols with non-local bindings.
931 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
932 LocalSymbolData[i].SymbolData->setIndex(Index++);
934 Index += NumRegularSections;
936 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
937 ExternalSymbolData[i].SymbolData->setIndex(Index++);
938 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
939 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
942 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
943 const MCSectionData &SD) {
944 if (!Relocations[&SD].empty()) {
945 MCContext &Ctx = Asm.getContext();
946 const MCSectionELF *RelaSection;
947 const MCSectionELF &Section =
948 static_cast<const MCSectionELF&>(SD.getSection());
950 const StringRef SectionName = Section.getSectionName();
951 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
952 RelaSectionName += SectionName;
955 if (HasRelocationAddend)
956 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
958 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
960 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
961 ELF::SHT_RELA : ELF::SHT_REL, 0,
962 SectionKind::getReadOnly(),
965 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
966 RelaSD.setAlignment(Is64Bit ? 8 : 4);
968 MCDataFragment *F = new MCDataFragment(&RelaSD);
970 WriteRelocationsFragment(Asm, F, &SD);
972 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
976 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
977 uint64_t Flags, uint64_t Address,
978 uint64_t Offset, uint64_t Size,
979 uint32_t Link, uint32_t Info,
981 uint64_t EntrySize) {
982 Write32(Name); // sh_name: index into string table
983 Write32(Type); // sh_type
984 WriteWord(Flags); // sh_flags
985 WriteWord(Address); // sh_addr
986 WriteWord(Offset); // sh_offset
987 WriteWord(Size); // sh_size
988 Write32(Link); // sh_link
989 Write32(Info); // sh_info
990 WriteWord(Alignment); // sh_addralign
991 WriteWord(EntrySize); // sh_entsize
994 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
996 const MCSectionData *SD) {
997 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
998 // sort by the r_offset just like gnu as does
999 array_pod_sort(Relocs.begin(), Relocs.end());
1001 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1002 ELFRelocationEntry entry = Relocs[e - i - 1];
1006 else if (entry.Index < 0)
1007 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1009 entry.Index += LocalSymbolData.size();
1011 String64(*F, entry.r_offset);
1013 struct ELF::Elf64_Rela ERE64;
1014 ERE64.setSymbolAndType(entry.Index, entry.Type);
1015 String64(*F, ERE64.r_info);
1017 if (HasRelocationAddend)
1018 String64(*F, entry.r_addend);
1020 String32(*F, entry.r_offset);
1022 struct ELF::Elf32_Rela ERE32;
1023 ERE32.setSymbolAndType(entry.Index, entry.Type);
1024 String32(*F, ERE32.r_info);
1026 if (HasRelocationAddend)
1027 String32(*F, entry.r_addend);
1032 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1033 MCAsmLayout &Layout,
1034 const SectionIndexMapTy &SectionIndexMap) {
1035 MCContext &Ctx = Asm.getContext();
1038 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1040 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1041 const MCSectionELF *ShstrtabSection =
1042 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1043 SectionKind::getReadOnly());
1044 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1045 ShstrtabSD.setAlignment(1);
1046 ShstrtabIndex = Asm.size();
1048 const MCSectionELF *SymtabSection =
1049 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1050 SectionKind::getReadOnly(),
1052 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1053 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1054 SymbolTableIndex = Asm.size();
1056 MCSectionData *SymtabShndxSD = NULL;
1058 if (NeedsSymtabShndx) {
1059 const MCSectionELF *SymtabShndxSection =
1060 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1061 SectionKind::getReadOnly(), 4, "");
1062 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1063 SymtabShndxSD->setAlignment(4);
1066 const MCSection *StrtabSection;
1067 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1068 SectionKind::getReadOnly());
1069 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1070 StrtabSD.setAlignment(1);
1071 StringTableIndex = Asm.size();
1073 WriteRelocations(Asm, Layout);
1076 F = new MCDataFragment(&SymtabSD);
1077 MCDataFragment *ShndxF = NULL;
1078 if (NeedsSymtabShndx) {
1079 ShndxF = new MCDataFragment(SymtabShndxSD);
1080 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1082 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1083 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1085 F = new MCDataFragment(&StrtabSD);
1086 F->getContents().append(StringTable.begin(), StringTable.end());
1087 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1089 F = new MCDataFragment(&ShstrtabSD);
1091 // Section header string table.
1093 // The first entry of a string table holds a null character so skip
1096 F->getContents() += '\x00';
1098 StringMap<uint64_t> SecStringMap;
1099 for (MCAssembler::const_iterator it = Asm.begin(),
1100 ie = Asm.end(); it != ie; ++it) {
1101 const MCSectionELF &Section =
1102 static_cast<const MCSectionELF&>(it->getSection());
1103 // FIXME: We could merge suffixes like in .text and .rela.text.
1105 StringRef Name = Section.getSectionName();
1106 if (SecStringMap.count(Name)) {
1107 SectionStringTableIndex[&Section] = SecStringMap[Name];
1110 // Remember the index into the string table so we can write it
1111 // into the sh_name field of the section header table.
1112 SectionStringTableIndex[&Section] = Index;
1113 SecStringMap[Name] = Index;
1115 Index += Name.size() + 1;
1116 F->getContents() += Name;
1117 F->getContents() += '\x00';
1120 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1123 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1124 const MCValue Target,
1126 const MCFragment *DF) const {
1127 // If this is a PCrel relocation, find the section this fixup value is
1129 const MCSection *BaseSection = 0;
1131 BaseSection = &DF->getParent()->getSection();
1132 assert(BaseSection);
1135 const MCSection *SectionA = 0;
1136 const MCSymbol *SymbolA = 0;
1137 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1138 SymbolA = &A->getSymbol();
1139 SectionA = &SymbolA->AliasedSymbol().getSection();
1142 const MCSection *SectionB = 0;
1143 const MCSymbol *SymbolB = 0;
1144 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1145 SymbolB = &B->getSymbol();
1146 SectionB = &SymbolB->AliasedSymbol().getSection();
1150 return SectionA == SectionB;
1155 // Absolute address but PCrel instruction, so we need a relocation.
1159 // FIXME: This is in here just to match gnu as output. If the two ends
1160 // are in the same section, there is nothing that the linker can do to
1162 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1163 if (DataA.isExternal())
1166 return BaseSection == SectionA;
1169 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1170 MCAsmLayout &Layout,
1171 GroupMapTy &GroupMap,
1172 RevGroupMapTy &RevGroupMap) {
1174 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1176 const MCSectionELF &Section =
1177 static_cast<const MCSectionELF&>(it->getSection());
1178 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1181 const MCSymbol *SignatureSymbol = Section.getGroup();
1182 Asm.getOrCreateSymbolData(*SignatureSymbol);
1183 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1185 Group = Asm.getContext().CreateELFGroupSection();
1186 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1187 Data.setAlignment(4);
1188 MCDataFragment *F = new MCDataFragment(&Data);
1189 String32(*F, ELF::GRP_COMDAT);
1191 GroupMap[Group] = SignatureSymbol;
1194 // Add sections to the groups
1196 unsigned NumGroups = RevGroupMap.size();
1197 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1198 it != ie; ++it, ++Index) {
1199 const MCSectionELF &Section =
1200 static_cast<const MCSectionELF&>(it->getSection());
1201 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1203 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1204 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1205 // FIXME: we could use the previous fragment
1206 MCDataFragment *F = new MCDataFragment(&Data);
1207 String32(*F, NumGroups + Index);
1210 for (RevGroupMapTy::const_iterator i = RevGroupMap.begin(),
1211 e = RevGroupMap.end(); i != e; ++i) {
1212 const MCSectionELF *Group = i->second;
1213 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1214 Asm.AddSectionToTheEnd(*this, Data, Layout);
1218 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1219 const SectionIndexMapTy &SectionIndexMap,
1220 uint32_t GroupSymbolIndex,
1221 uint64_t Offset, uint64_t Size,
1223 const MCSectionELF &Section) {
1224 uint64_t sh_link = 0;
1225 uint64_t sh_info = 0;
1227 switch(Section.getType()) {
1228 case ELF::SHT_DYNAMIC:
1229 sh_link = SectionStringTableIndex[&Section];
1234 case ELF::SHT_RELA: {
1235 const MCSectionELF *SymtabSection;
1236 const MCSectionELF *InfoSection;
1237 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1239 SectionKind::getReadOnly());
1240 sh_link = SectionIndexMap.lookup(SymtabSection);
1241 assert(sh_link && ".symtab not found");
1243 // Remove ".rel" and ".rela" prefixes.
1244 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1245 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1247 InfoSection = Asm.getContext().getELFSection(SectionName,
1248 ELF::SHT_PROGBITS, 0,
1249 SectionKind::getReadOnly());
1250 sh_info = SectionIndexMap.lookup(InfoSection);
1254 case ELF::SHT_SYMTAB:
1255 case ELF::SHT_DYNSYM:
1256 sh_link = StringTableIndex;
1257 sh_info = LastLocalSymbolIndex;
1260 case ELF::SHT_SYMTAB_SHNDX:
1261 sh_link = SymbolTableIndex;
1264 case ELF::SHT_PROGBITS:
1265 case ELF::SHT_STRTAB:
1266 case ELF::SHT_NOBITS:
1268 case ELF::SHT_ARM_ATTRIBUTES:
1272 case ELF::SHT_GROUP: {
1273 sh_link = SymbolTableIndex;
1274 sh_info = GroupSymbolIndex;
1279 assert(0 && "FIXME: sh_type value not supported!");
1283 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1284 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1285 Alignment, Section.getEntrySize());
1288 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1289 const MCAsmLayout &Layout) {
1290 GroupMapTy GroupMap;
1291 RevGroupMapTy RevGroupMap;
1292 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1295 SectionIndexMapTy SectionIndexMap;
1297 ComputeIndexMap(Asm, SectionIndexMap);
1299 // Compute symbol table information.
1300 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1302 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1303 const_cast<MCAsmLayout&>(Layout),
1306 // Update to include the metadata sections.
1307 ComputeIndexMap(Asm, SectionIndexMap);
1309 // Add 1 for the null section.
1310 unsigned NumSections = Asm.size() + 1;
1311 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1312 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1313 uint64_t FileOff = HeaderSize;
1315 std::vector<const MCSectionELF*> Sections;
1316 Sections.resize(NumSections);
1318 for (SectionIndexMapTy::const_iterator i=
1319 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1320 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1321 Sections[p.second] = p.first;
1324 for (unsigned i = 1; i < NumSections; ++i) {
1325 const MCSectionELF &Section = *Sections[i];
1326 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1328 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1330 // Get the size of the section in the output file (including padding).
1331 uint64_t Size = Layout.getSectionFileSize(&SD);
1336 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1338 // Write out the ELF header ...
1339 WriteHeader(FileOff - HeaderSize, NumSections);
1341 FileOff = HeaderSize;
1343 // ... then all of the sections ...
1344 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1346 for (unsigned i = 1; i < NumSections; ++i) {
1347 const MCSectionELF &Section = *Sections[i];
1348 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1350 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1351 WriteZeros(Padding);
1354 // Remember the offset into the file for this section.
1355 SectionOffsetMap[&Section] = FileOff;
1357 FileOff += Layout.getSectionFileSize(&SD);
1359 Asm.WriteSectionData(&SD, Layout, this);
1362 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1363 WriteZeros(Padding);
1366 // ... and then the section header table.
1367 // Should we align the section header table?
1369 // Null section first.
1370 uint64_t FirstSectionSize =
1371 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1372 uint32_t FirstSectionLink =
1373 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1374 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1376 for (unsigned i = 1; i < NumSections; ++i) {
1377 const MCSectionELF &Section = *Sections[i];
1378 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1379 uint32_t GroupSymbolIndex;
1380 if (Section.getType() != ELF::SHT_GROUP)
1381 GroupSymbolIndex = 0;
1383 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1385 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1386 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1387 SD.getAlignment(), Section);
1391 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1393 Triple::OSType OSType,
1395 bool IsLittleEndian,
1396 bool HasRelocationAddend) {
1399 case ELF::EM_X86_64:
1400 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1401 HasRelocationAddend, OSType); break;
1403 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1404 HasRelocationAddend, OSType); break;
1405 case ELF::EM_MBLAZE:
1406 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1407 HasRelocationAddend, OSType); break;
1408 default: llvm_unreachable("Unsupported architecture"); break;
1413 /// START OF SUBCLASSES for ELFObjectWriter
1414 //===- ARMELFObjectWriter -------------------------------------------===//
1416 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1417 bool _IsLittleEndian,
1418 uint16_t _EMachine, bool _HasRelocationAddend,
1419 Triple::OSType _OSType)
1420 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1421 _HasRelocationAddend, _OSType)
1424 ARMELFObjectWriter::~ARMELFObjectWriter()
1427 void ARMELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1428 const MCAsmLayout &Layout,
1429 const MCFragment *Fragment,
1430 const MCFixup &Fixup,
1432 uint64_t &FixedValue) {
1433 assert(0 && "ARMELFObjectWriter::RecordRelocation() unimplemented");
1436 //===- MBlazeELFObjectWriter -------------------------------------------===//
1438 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1439 bool _IsLittleEndian,
1441 bool _HasRelocationAddend,
1442 Triple::OSType _OSType)
1443 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1444 _HasRelocationAddend, _OSType) {
1447 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1450 void MBlazeELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1451 const MCAsmLayout &Layout,
1452 const MCFragment *Fragment,
1453 const MCFixup &Fixup,
1455 uint64_t &FixedValue) {
1458 int64_t Value = Target.getConstant();
1459 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1460 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1461 const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1463 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1464 if (!Target.isAbsolute()) {
1465 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1466 const MCSymbol &SymbolB = RefB->getSymbol();
1467 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1469 MCSectionData *Sec = Fragment->getParent();
1471 // Offset of the symbol in the section
1472 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1474 // Ofeset of the relocation in the section
1475 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1480 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1481 MCFragment *F = SD.getFragment();
1483 Index = F->getParent()->getOrdinal();
1485 MCSectionData *FSD = F->getParent();
1486 // Offset of the symbol in the section
1487 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1489 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1490 WeakrefUsedInReloc.insert(RelocSymbol);
1492 UsedInReloc.insert(RelocSymbol);
1500 // determine the type of the relocation
1503 switch ((unsigned)Fixup.getKind()) {
1505 llvm_unreachable("Unimplemented");
1506 case MBlaze::reloc_pcrel_4byte:
1507 Type = ELF::R_MICROBLAZE_64_PCREL;
1509 case MBlaze::reloc_pcrel_2byte:
1510 Type = ELF::R_MICROBLAZE_32_PCREL;
1514 switch ((unsigned)Fixup.getKind()) {
1515 default: llvm_unreachable("invalid fixup kind!");
1517 Type = (RelocSymbol || Addend !=0) ? ELF::R_MICROBLAZE_32
1518 : ELF::R_MICROBLAZE_64;
1521 Type = ELF::R_MICROBLAZE_32;
1526 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
1527 if (RelocNeedsGOT(Modifier))
1530 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1533 if (!HasRelocationAddend) Addend = 0;
1534 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1535 Relocations[Fragment->getParent()].push_back(ERE);
1538 //===- X86ELFObjectWriter -------------------------------------------===//
1541 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1542 bool _IsLittleEndian,
1543 uint16_t _EMachine, bool _HasRelocationAddend,
1544 Triple::OSType _OSType)
1545 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1546 _HasRelocationAddend, _OSType)
1549 X86ELFObjectWriter::~X86ELFObjectWriter()
1552 void X86ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1553 const MCAsmLayout &Layout,
1554 const MCFragment *Fragment,
1555 const MCFixup &Fixup,
1557 uint64_t &FixedValue) {
1560 int64_t Value = Target.getConstant();
1561 const MCSymbol *RelocSymbol = NULL;
1563 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1564 if (!Target.isAbsolute()) {
1565 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1566 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1567 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1569 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1570 const MCSymbol &SymbolB = RefB->getSymbol();
1571 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1573 MCSectionData *Sec = Fragment->getParent();
1575 // Offset of the symbol in the section
1576 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1578 // Ofeset of the relocation in the section
1579 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1584 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1585 MCFragment *F = SD.getFragment();
1587 Index = F->getParent()->getOrdinal() + 1;
1589 MCSectionData *FSD = F->getParent();
1590 // Offset of the symbol in the section
1591 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1593 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1594 WeakrefUsedInReloc.insert(RelocSymbol);
1596 UsedInReloc.insert(RelocSymbol);
1600 // Compensate for the addend on i386.
1607 // determine the type of the relocation
1609 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1610 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1616 llvm_unreachable("Unimplemented");
1617 case MCSymbolRefExpr::VK_None:
1618 Type = ELF::R_X86_64_PC32;
1620 case MCSymbolRefExpr::VK_PLT:
1621 Type = ELF::R_X86_64_PLT32;
1623 case MCSymbolRefExpr::VK_GOTPCREL:
1624 Type = ELF::R_X86_64_GOTPCREL;
1626 case MCSymbolRefExpr::VK_GOTTPOFF:
1627 Type = ELF::R_X86_64_GOTTPOFF;
1629 case MCSymbolRefExpr::VK_TLSGD:
1630 Type = ELF::R_X86_64_TLSGD;
1632 case MCSymbolRefExpr::VK_TLSLD:
1633 Type = ELF::R_X86_64_TLSLD;
1637 switch ((unsigned)Fixup.getKind()) {
1638 default: llvm_unreachable("invalid fixup kind!");
1639 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1640 case X86::reloc_signed_4byte:
1641 case X86::reloc_pcrel_4byte:
1642 assert(isInt<32>(Target.getConstant()));
1645 llvm_unreachable("Unimplemented");
1646 case MCSymbolRefExpr::VK_None:
1647 Type = ELF::R_X86_64_32S;
1649 case MCSymbolRefExpr::VK_GOT:
1650 Type = ELF::R_X86_64_GOT32;
1652 case MCSymbolRefExpr::VK_GOTPCREL:
1653 Type = ELF::R_X86_64_GOTPCREL;
1655 case MCSymbolRefExpr::VK_TPOFF:
1656 Type = ELF::R_X86_64_TPOFF32;
1658 case MCSymbolRefExpr::VK_DTPOFF:
1659 Type = ELF::R_X86_64_DTPOFF32;
1664 Type = ELF::R_X86_64_32;
1666 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1667 case X86::reloc_pcrel_1byte:
1668 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1675 llvm_unreachable("Unimplemented");
1676 case MCSymbolRefExpr::VK_None:
1677 Type = ELF::R_386_PC32;
1679 case MCSymbolRefExpr::VK_PLT:
1680 Type = ELF::R_386_PLT32;
1684 switch ((unsigned)Fixup.getKind()) {
1685 default: llvm_unreachable("invalid fixup kind!");
1687 case X86::reloc_global_offset_table:
1688 Type = ELF::R_386_GOTPC;
1691 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1693 case X86::reloc_signed_4byte:
1694 case X86::reloc_pcrel_4byte:
1698 llvm_unreachable("Unimplemented");
1699 case MCSymbolRefExpr::VK_None:
1700 Type = ELF::R_386_32;
1702 case MCSymbolRefExpr::VK_GOT:
1703 Type = ELF::R_386_GOT32;
1705 case MCSymbolRefExpr::VK_GOTOFF:
1706 Type = ELF::R_386_GOTOFF;
1708 case MCSymbolRefExpr::VK_TLSGD:
1709 Type = ELF::R_386_TLS_GD;
1711 case MCSymbolRefExpr::VK_TPOFF:
1712 Type = ELF::R_386_TLS_LE_32;
1714 case MCSymbolRefExpr::VK_INDNTPOFF:
1715 Type = ELF::R_386_TLS_IE;
1717 case MCSymbolRefExpr::VK_NTPOFF:
1718 Type = ELF::R_386_TLS_LE;
1720 case MCSymbolRefExpr::VK_GOTNTPOFF:
1721 Type = ELF::R_386_TLS_GOTIE;
1723 case MCSymbolRefExpr::VK_TLSLDM:
1724 Type = ELF::R_386_TLS_LDM;
1726 case MCSymbolRefExpr::VK_DTPOFF:
1727 Type = ELF::R_386_TLS_LDO_32;
1731 case FK_Data_2: Type = ELF::R_386_16; break;
1732 case X86::reloc_pcrel_1byte:
1733 case FK_Data_1: Type = ELF::R_386_8; break;
1738 if (RelocNeedsGOT(Modifier))
1742 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1745 if (!HasRelocationAddend) Addend = 0;
1746 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1747 Relocations[Fragment->getParent()].push_back(ERE);