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 _Index,
133 unsigned _Type, const MCSymbol *_Symbol,
135 : r_offset(RelocOffset), Index(_Index), Type(_Type),
136 Symbol(_Symbol), 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);
369 static bool isFixupKindPCRel(unsigned Kind) {
373 case X86::reloc_pcrel_1byte:
374 case X86::reloc_pcrel_4byte:
375 case X86::reloc_riprel_4byte:
376 case X86::reloc_riprel_4byte_movq_load:
383 //===- ARMELFObjectWriter -------------------------------------------===//
385 class ARMELFObjectWriter : public ELFObjectWriter {
387 ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
388 uint16_t _EMachine, bool _HasRelAddend,
389 Triple::OSType _OSType);
391 virtual ~ARMELFObjectWriter();
392 virtual void RecordRelocation(const MCAssembler &Asm,
393 const MCAsmLayout &Layout,
394 const MCFragment *Fragment,
395 const MCFixup &Fixup, MCValue Target,
396 uint64_t &FixedValue);
398 static bool isFixupKindPCRel(unsigned Kind) {
402 case ARM::fixup_arm_pcrel_12:
403 case ARM::fixup_arm_vfp_pcrel_12:
404 case ARM::fixup_arm_branch:
410 //===- MBlazeELFObjectWriter -------------------------------------------===//
412 class MBlazeELFObjectWriter : public ELFObjectWriter {
414 MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
415 uint16_t _EMachine, bool _HasRelAddend,
416 Triple::OSType _OSType);
418 virtual ~MBlazeELFObjectWriter();
419 virtual void RecordRelocation(const MCAssembler &Asm,
420 const MCAsmLayout &Layout,
421 const MCFragment *Fragment,
422 const MCFixup &Fixup, MCValue Target,
423 uint64_t &FixedValue);
425 static bool isFixupKindPCRel(unsigned Kind) {
429 case MBlaze::reloc_pcrel_2byte:
430 case MBlaze::reloc_pcrel_4byte:
437 ELFObjectWriter::~ELFObjectWriter()
440 // Emit the ELF header.
441 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
442 unsigned NumberOfSections) {
448 // emitWord method behaves differently for ELF32 and ELF64, writing
449 // 4 bytes in the former and 8 in the latter.
451 Write8(0x7f); // e_ident[EI_MAG0]
452 Write8('E'); // e_ident[EI_MAG1]
453 Write8('L'); // e_ident[EI_MAG2]
454 Write8('F'); // e_ident[EI_MAG3]
456 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
459 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
461 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
464 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
465 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
466 default: Write8(ELF::ELFOSABI_NONE); break;
468 Write8(0); // e_ident[EI_ABIVERSION]
470 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
472 Write16(ELF::ET_REL); // e_type
474 Write16(EMachine); // e_machine = target
476 Write32(ELF::EV_CURRENT); // e_version
477 WriteWord(0); // e_entry, no entry point in .o file
478 WriteWord(0); // e_phoff, no program header for .o
479 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
480 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
482 // FIXME: Make this configurable.
483 Write32(0); // e_flags = whatever the target wants
485 // e_ehsize = ELF header size
486 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
488 Write16(0); // e_phentsize = prog header entry size
489 Write16(0); // e_phnum = # prog header entries = 0
491 // e_shentsize = Section header entry size
492 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
494 // e_shnum = # of section header ents
495 if (NumberOfSections >= ELF::SHN_LORESERVE)
498 Write16(NumberOfSections);
500 // e_shstrndx = Section # of '.shstrtab'
501 if (NumberOfSections >= ELF::SHN_LORESERVE)
502 Write16(ELF::SHN_XINDEX);
504 Write16(ShstrtabIndex);
507 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
508 MCDataFragment *ShndxF,
510 uint8_t info, uint64_t value,
511 uint64_t size, uint8_t other,
515 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
516 String32(*ShndxF, shndx);
518 String32(*ShndxF, 0);
521 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
522 uint16_t(ELF::SHN_XINDEX) : shndx;
525 String32(*SymtabF, name); // st_name
526 String8(*SymtabF, info); // st_info
527 String8(*SymtabF, other); // st_other
528 String16(*SymtabF, Index); // st_shndx
529 String64(*SymtabF, value); // st_value
530 String64(*SymtabF, size); // st_size
532 String32(*SymtabF, name); // st_name
533 String32(*SymtabF, value); // st_value
534 String32(*SymtabF, size); // st_size
535 String8(*SymtabF, info); // st_info
536 String8(*SymtabF, other); // st_other
537 String16(*SymtabF, Index); // st_shndx
541 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
542 if (Data.isCommon() && Data.isExternal())
543 return Data.getCommonAlignment();
545 const MCSymbol &Symbol = Data.getSymbol();
546 if (!Symbol.isInSection())
549 if (MCFragment *FF = Data.getFragment())
550 return Layout.getSymbolAddress(&Data) -
551 Layout.getSectionAddress(FF->getParent());
556 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
557 // The presence of symbol versions causes undefined symbols and
558 // versions declared with @@@ to be renamed.
560 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
561 ie = Asm.symbol_end(); it != ie; ++it) {
562 const MCSymbol &Alias = it->getSymbol();
563 const MCSymbol &Symbol = Alias.AliasedSymbol();
564 MCSymbolData &SD = Asm.getSymbolData(Symbol);
567 if (&Symbol == &Alias)
570 StringRef AliasName = Alias.getName();
571 size_t Pos = AliasName.find('@');
572 if (Pos == StringRef::npos)
575 // Aliases defined with .symvar copy the binding from the symbol they alias.
576 // This is the first place we are able to copy this information.
577 it->setExternal(SD.isExternal());
578 SetBinding(*it, GetBinding(SD));
580 StringRef Rest = AliasName.substr(Pos);
581 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
584 // FIXME: produce a better error message.
585 if (Symbol.isUndefined() && Rest.startswith("@@") &&
586 !Rest.startswith("@@@"))
587 report_fatal_error("A @@ version cannot be undefined");
589 Renames.insert(std::make_pair(&Symbol, &Alias));
593 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
594 MCDataFragment *ShndxF,
596 const MCAsmLayout &Layout) {
597 MCSymbolData &OrigData = *MSD.SymbolData;
599 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
601 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
602 Data.getSymbol().isVariable();
604 uint8_t Binding = GetBinding(OrigData);
605 uint8_t Visibility = GetVisibility(OrigData);
606 uint8_t Type = GetType(Data);
608 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
609 uint8_t Other = Visibility;
611 uint64_t Value = SymbolValue(Data, Layout);
615 assert(!(Data.isCommon() && !Data.isExternal()));
617 ESize = Data.getSize();
618 if (Data.getSize()) {
620 if (ESize->getKind() == MCExpr::Binary) {
621 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
623 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
624 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
625 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
626 Size = Res.getConstant();
628 } else if (ESize->getKind() == MCExpr::Constant) {
629 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
631 assert(0 && "Unsupported size expression");
635 // Write out the symbol table entry
636 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
637 Size, Other, MSD.SectionIndex, IsReserved);
640 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
641 MCDataFragment *ShndxF,
642 const MCAssembler &Asm,
643 const MCAsmLayout &Layout,
644 const SectionIndexMapTy &SectionIndexMap) {
645 // The string table must be emitted first because we need the index
646 // into the string table for all the symbol names.
647 assert(StringTable.size() && "Missing string table");
649 // FIXME: Make sure the start of the symbol table is aligned.
651 // The first entry is the undefined symbol entry.
652 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
654 // Write the symbol table entries.
655 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
656 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
657 ELFSymbolData &MSD = LocalSymbolData[i];
658 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
661 // Write out a symbol table entry for each regular section.
662 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
664 const MCSectionELF &Section =
665 static_cast<const MCSectionELF&>(i->getSection());
666 if (Section.getType() == ELF::SHT_RELA ||
667 Section.getType() == ELF::SHT_REL ||
668 Section.getType() == ELF::SHT_STRTAB ||
669 Section.getType() == ELF::SHT_SYMTAB)
671 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
672 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
673 LastLocalSymbolIndex++;
676 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
677 ELFSymbolData &MSD = ExternalSymbolData[i];
678 MCSymbolData &Data = *MSD.SymbolData;
679 assert(((Data.getFlags() & ELF_STB_Global) ||
680 (Data.getFlags() & ELF_STB_Weak)) &&
681 "External symbol requires STB_GLOBAL or STB_WEAK flag");
682 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
683 if (GetBinding(Data) == ELF::STB_LOCAL)
684 LastLocalSymbolIndex++;
687 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
688 ELFSymbolData &MSD = UndefinedSymbolData[i];
689 MCSymbolData &Data = *MSD.SymbolData;
690 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
691 if (GetBinding(Data) == ELF::STB_LOCAL)
692 LastLocalSymbolIndex++;
696 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
697 const MCValue &Target,
698 const MCFragment &F) const {
699 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
700 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
701 const MCSymbol *Renamed = Renames.lookup(&Symbol);
702 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
704 if (ASymbol.isUndefined()) {
710 if (SD.isExternal()) {
716 const MCSectionELF &Section =
717 static_cast<const MCSectionELF&>(ASymbol.getSection());
719 if (Section.getKind().isBSS())
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() & MCSectionELF::SHF_MERGE) {
736 if (Target.getConstant() == 0)
748 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
750 MCSymbolData &SD = Asm.getSymbolData(*S);
751 return SD.getIndex();
754 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
755 bool Used, bool Renamed) {
756 if (Data.getFlags() & ELF_Other_Weakref)
765 const MCSymbol &Symbol = Data.getSymbol();
767 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
770 const MCSymbol &A = Symbol.AliasedSymbol();
771 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
774 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
777 if (Symbol.isTemporary())
783 static bool isLocal(const MCSymbolData &Data, bool isSignature,
784 bool isUsedInReloc) {
785 if (Data.isExternal())
788 const MCSymbol &Symbol = Data.getSymbol();
789 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
791 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
792 if (isSignature && !isUsedInReloc)
801 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
802 SectionIndexMapTy &SectionIndexMap) {
804 for (MCAssembler::iterator it = Asm.begin(),
805 ie = Asm.end(); it != ie; ++it) {
806 const MCSectionELF &Section =
807 static_cast<const MCSectionELF &>(it->getSection());
808 if (Section.getType() != ELF::SHT_GROUP)
810 SectionIndexMap[&Section] = Index++;
813 for (MCAssembler::iterator it = Asm.begin(),
814 ie = Asm.end(); it != ie; ++it) {
815 const MCSectionELF &Section =
816 static_cast<const MCSectionELF &>(it->getSection());
817 if (Section.getType() == ELF::SHT_GROUP)
819 SectionIndexMap[&Section] = Index++;
823 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
824 const SectionIndexMapTy &SectionIndexMap,
825 RevGroupMapTy RevGroupMap) {
826 // FIXME: Is this the correct place to do this?
828 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
829 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
830 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
831 Data.setExternal(true);
832 SetBinding(Data, ELF::STB_GLOBAL);
835 // Build section lookup table.
836 int NumRegularSections = Asm.size();
838 // Index 0 is always the empty string.
839 StringMap<uint64_t> StringIndexMap;
840 StringTable += '\x00';
842 // Add the data for the symbols.
843 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
844 ie = Asm.symbol_end(); it != ie; ++it) {
845 const MCSymbol &Symbol = it->getSymbol();
847 bool Used = UsedInReloc.count(&Symbol);
848 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
849 bool isSignature = RevGroupMap.count(&Symbol);
851 if (!isInSymtab(Asm, *it,
852 Used || WeakrefUsed || isSignature,
853 Renames.count(&Symbol)))
858 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
860 // Undefined symbols are global, but this is the first place we
861 // are able to set it.
862 bool Local = isLocal(*it, isSignature, Used);
863 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
864 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
865 SetBinding(*it, ELF::STB_GLOBAL);
866 SetBinding(SD, ELF::STB_GLOBAL);
869 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
870 SetBinding(*it, ELF::STB_WEAK);
872 if (it->isCommon()) {
874 MSD.SectionIndex = ELF::SHN_COMMON;
875 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
876 MSD.SectionIndex = ELF::SHN_ABS;
877 } else if (RefSymbol.isUndefined()) {
878 if (isSignature && !Used)
879 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
881 MSD.SectionIndex = ELF::SHN_UNDEF;
883 const MCSectionELF &Section =
884 static_cast<const MCSectionELF&>(RefSymbol.getSection());
885 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
886 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
887 NeedsSymtabShndx = true;
888 assert(MSD.SectionIndex && "Invalid section index!");
891 // The @@@ in symbol version is replaced with @ in undefined symbols and
892 // @@ in defined ones.
893 StringRef Name = Symbol.getName();
896 size_t Pos = Name.find("@@@");
897 if (Pos != StringRef::npos) {
898 Buf += Name.substr(0, Pos);
899 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
900 Buf += Name.substr(Pos + Skip);
904 uint64_t &Entry = StringIndexMap[Name];
906 Entry = StringTable.size();
908 StringTable += '\x00';
910 MSD.StringIndex = Entry;
911 if (MSD.SectionIndex == ELF::SHN_UNDEF)
912 UndefinedSymbolData.push_back(MSD);
914 LocalSymbolData.push_back(MSD);
916 ExternalSymbolData.push_back(MSD);
919 // Symbols are required to be in lexicographic order.
920 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
921 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
922 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
924 // Set the symbol indices. Local symbols must come before all other
925 // symbols with non-local bindings.
927 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
928 LocalSymbolData[i].SymbolData->setIndex(Index++);
930 Index += NumRegularSections;
932 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
933 ExternalSymbolData[i].SymbolData->setIndex(Index++);
934 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
935 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
938 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
939 const MCSectionData &SD) {
940 if (!Relocations[&SD].empty()) {
941 MCContext &Ctx = Asm.getContext();
942 const MCSectionELF *RelaSection;
943 const MCSectionELF &Section =
944 static_cast<const MCSectionELF&>(SD.getSection());
946 const StringRef SectionName = Section.getSectionName();
947 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
948 RelaSectionName += SectionName;
951 if (HasRelocationAddend)
952 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
954 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
956 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
957 ELF::SHT_RELA : ELF::SHT_REL, 0,
958 SectionKind::getReadOnly(),
961 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
962 RelaSD.setAlignment(Is64Bit ? 8 : 4);
964 MCDataFragment *F = new MCDataFragment(&RelaSD);
966 WriteRelocationsFragment(Asm, F, &SD);
968 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
972 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
973 uint64_t Flags, uint64_t Address,
974 uint64_t Offset, uint64_t Size,
975 uint32_t Link, uint32_t Info,
977 uint64_t EntrySize) {
978 Write32(Name); // sh_name: index into string table
979 Write32(Type); // sh_type
980 WriteWord(Flags); // sh_flags
981 WriteWord(Address); // sh_addr
982 WriteWord(Offset); // sh_offset
983 WriteWord(Size); // sh_size
984 Write32(Link); // sh_link
985 Write32(Info); // sh_info
986 WriteWord(Alignment); // sh_addralign
987 WriteWord(EntrySize); // sh_entsize
990 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
992 const MCSectionData *SD) {
993 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
994 // sort by the r_offset just like gnu as does
995 array_pod_sort(Relocs.begin(), Relocs.end());
997 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
998 ELFRelocationEntry entry = Relocs[e - i - 1];
1002 else if (entry.Index < 0)
1003 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1005 entry.Index += LocalSymbolData.size();
1007 String64(*F, entry.r_offset);
1009 struct ELF::Elf64_Rela ERE64;
1010 ERE64.setSymbolAndType(entry.Index, entry.Type);
1011 String64(*F, ERE64.r_info);
1013 if (HasRelocationAddend)
1014 String64(*F, entry.r_addend);
1016 String32(*F, entry.r_offset);
1018 struct ELF::Elf32_Rela ERE32;
1019 ERE32.setSymbolAndType(entry.Index, entry.Type);
1020 String32(*F, ERE32.r_info);
1022 if (HasRelocationAddend)
1023 String32(*F, entry.r_addend);
1028 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1029 MCAsmLayout &Layout,
1030 const SectionIndexMapTy &SectionIndexMap) {
1031 MCContext &Ctx = Asm.getContext();
1034 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1036 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1037 const MCSectionELF *ShstrtabSection =
1038 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1039 SectionKind::getReadOnly());
1040 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1041 ShstrtabSD.setAlignment(1);
1042 ShstrtabIndex = Asm.size();
1044 const MCSectionELF *SymtabSection =
1045 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1046 SectionKind::getReadOnly(),
1048 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1049 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1050 SymbolTableIndex = Asm.size();
1052 MCSectionData *SymtabShndxSD = NULL;
1054 if (NeedsSymtabShndx) {
1055 const MCSectionELF *SymtabShndxSection =
1056 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1057 SectionKind::getReadOnly(), 4, "");
1058 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1059 SymtabShndxSD->setAlignment(4);
1062 const MCSection *StrtabSection;
1063 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1064 SectionKind::getReadOnly());
1065 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1066 StrtabSD.setAlignment(1);
1067 StringTableIndex = Asm.size();
1069 WriteRelocations(Asm, Layout);
1072 F = new MCDataFragment(&SymtabSD);
1073 MCDataFragment *ShndxF = NULL;
1074 if (NeedsSymtabShndx) {
1075 ShndxF = new MCDataFragment(SymtabShndxSD);
1076 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1078 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1079 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1081 F = new MCDataFragment(&StrtabSD);
1082 F->getContents().append(StringTable.begin(), StringTable.end());
1083 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1085 F = new MCDataFragment(&ShstrtabSD);
1087 // Section header string table.
1089 // The first entry of a string table holds a null character so skip
1092 F->getContents() += '\x00';
1094 StringMap<uint64_t> SecStringMap;
1095 for (MCAssembler::const_iterator it = Asm.begin(),
1096 ie = Asm.end(); it != ie; ++it) {
1097 const MCSectionELF &Section =
1098 static_cast<const MCSectionELF&>(it->getSection());
1099 // FIXME: We could merge suffixes like in .text and .rela.text.
1101 StringRef Name = Section.getSectionName();
1102 if (SecStringMap.count(Name)) {
1103 SectionStringTableIndex[&Section] = SecStringMap[Name];
1106 // Remember the index into the string table so we can write it
1107 // into the sh_name field of the section header table.
1108 SectionStringTableIndex[&Section] = Index;
1109 SecStringMap[Name] = Index;
1111 Index += Name.size() + 1;
1112 F->getContents() += Name;
1113 F->getContents() += '\x00';
1116 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1119 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1120 const MCValue Target,
1122 const MCFragment *DF) const {
1123 // If this is a PCrel relocation, find the section this fixup value is
1125 const MCSection *BaseSection = 0;
1127 BaseSection = &DF->getParent()->getSection();
1128 assert(BaseSection);
1131 const MCSection *SectionA = 0;
1132 const MCSymbol *SymbolA = 0;
1133 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1134 SymbolA = &A->getSymbol();
1135 SectionA = &SymbolA->AliasedSymbol().getSection();
1138 const MCSection *SectionB = 0;
1139 const MCSymbol *SymbolB = 0;
1140 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1141 SymbolB = &B->getSymbol();
1142 SectionB = &SymbolB->AliasedSymbol().getSection();
1146 return SectionA == SectionB;
1151 // Absolute address but PCrel instruction, so we need a relocation.
1155 // FIXME: This is in here just to match gnu as output. If the two ends
1156 // are in the same section, there is nothing that the linker can do to
1158 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1159 if (DataA.isExternal())
1162 return BaseSection == SectionA;
1165 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1166 MCAsmLayout &Layout,
1167 GroupMapTy &GroupMap,
1168 RevGroupMapTy &RevGroupMap) {
1170 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1172 const MCSectionELF &Section =
1173 static_cast<const MCSectionELF&>(it->getSection());
1174 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1177 const MCSymbol *SignatureSymbol = Section.getGroup();
1178 Asm.getOrCreateSymbolData(*SignatureSymbol);
1179 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1181 Group = Asm.getContext().CreateELFGroupSection();
1182 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1183 Data.setAlignment(4);
1184 MCDataFragment *F = new MCDataFragment(&Data);
1185 String32(*F, ELF::GRP_COMDAT);
1187 GroupMap[Group] = SignatureSymbol;
1190 // Add sections to the groups
1192 unsigned NumGroups = RevGroupMap.size();
1193 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1194 it != ie; ++it, ++Index) {
1195 const MCSectionELF &Section =
1196 static_cast<const MCSectionELF&>(it->getSection());
1197 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1199 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1200 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1201 // FIXME: we could use the previous fragment
1202 MCDataFragment *F = new MCDataFragment(&Data);
1203 String32(*F, NumGroups + Index);
1206 for (RevGroupMapTy::const_iterator i = RevGroupMap.begin(),
1207 e = RevGroupMap.end(); i != e; ++i) {
1208 const MCSectionELF *Group = i->second;
1209 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1210 Asm.AddSectionToTheEnd(*this, Data, Layout);
1214 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1215 const SectionIndexMapTy &SectionIndexMap,
1216 uint32_t GroupSymbolIndex,
1217 uint64_t Offset, uint64_t Size,
1219 const MCSectionELF &Section) {
1220 uint64_t sh_link = 0;
1221 uint64_t sh_info = 0;
1223 switch(Section.getType()) {
1224 case ELF::SHT_DYNAMIC:
1225 sh_link = SectionStringTableIndex[&Section];
1230 case ELF::SHT_RELA: {
1231 const MCSectionELF *SymtabSection;
1232 const MCSectionELF *InfoSection;
1233 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1235 SectionKind::getReadOnly());
1236 sh_link = SectionIndexMap.lookup(SymtabSection);
1237 assert(sh_link && ".symtab not found");
1239 // Remove ".rel" and ".rela" prefixes.
1240 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1241 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1243 InfoSection = Asm.getContext().getELFSection(SectionName,
1244 ELF::SHT_PROGBITS, 0,
1245 SectionKind::getReadOnly());
1246 sh_info = SectionIndexMap.lookup(InfoSection);
1250 case ELF::SHT_SYMTAB:
1251 case ELF::SHT_DYNSYM:
1252 sh_link = StringTableIndex;
1253 sh_info = LastLocalSymbolIndex;
1256 case ELF::SHT_SYMTAB_SHNDX:
1257 sh_link = SymbolTableIndex;
1260 case ELF::SHT_PROGBITS:
1261 case ELF::SHT_STRTAB:
1262 case ELF::SHT_NOBITS:
1264 case ELF::SHT_ARM_ATTRIBUTES:
1268 case ELF::SHT_GROUP: {
1269 sh_link = SymbolTableIndex;
1270 sh_info = GroupSymbolIndex;
1275 assert(0 && "FIXME: sh_type value not supported!");
1279 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1280 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1281 Alignment, Section.getEntrySize());
1284 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1285 const MCAsmLayout &Layout) {
1286 GroupMapTy GroupMap;
1287 RevGroupMapTy RevGroupMap;
1288 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1291 SectionIndexMapTy SectionIndexMap;
1293 ComputeIndexMap(Asm, SectionIndexMap);
1295 // Compute symbol table information.
1296 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1298 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1299 const_cast<MCAsmLayout&>(Layout),
1302 // Update to include the metadata sections.
1303 ComputeIndexMap(Asm, SectionIndexMap);
1305 // Add 1 for the null section.
1306 unsigned NumSections = Asm.size() + 1;
1307 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1308 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1309 uint64_t FileOff = HeaderSize;
1311 std::vector<const MCSectionELF*> Sections;
1312 Sections.resize(NumSections);
1314 for (SectionIndexMapTy::const_iterator i=
1315 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1316 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1317 Sections[p.second] = p.first;
1320 for (unsigned i = 1; i < NumSections; ++i) {
1321 const MCSectionELF &Section = *Sections[i];
1322 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1324 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1326 // Get the size of the section in the output file (including padding).
1327 uint64_t Size = Layout.getSectionFileSize(&SD);
1332 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1334 // Write out the ELF header ...
1335 WriteHeader(FileOff - HeaderSize, NumSections);
1337 FileOff = HeaderSize;
1339 // ... then all of the sections ...
1340 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1342 for (unsigned i = 1; i < NumSections; ++i) {
1343 const MCSectionELF &Section = *Sections[i];
1344 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1346 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1347 WriteZeros(Padding);
1350 // Remember the offset into the file for this section.
1351 SectionOffsetMap[&Section] = FileOff;
1353 FileOff += Layout.getSectionFileSize(&SD);
1355 Asm.WriteSectionData(&SD, Layout, this);
1358 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1359 WriteZeros(Padding);
1362 // ... and then the section header table.
1363 // Should we align the section header table?
1365 // Null section first.
1366 uint64_t FirstSectionSize =
1367 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1368 uint32_t FirstSectionLink =
1369 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1370 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1372 for (unsigned i = 1; i < NumSections; ++i) {
1373 const MCSectionELF &Section = *Sections[i];
1374 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1375 uint32_t GroupSymbolIndex;
1376 if (Section.getType() != ELF::SHT_GROUP)
1377 GroupSymbolIndex = 0;
1379 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1381 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1382 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1383 SD.getAlignment(), Section);
1387 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1389 Triple::OSType OSType,
1391 bool IsLittleEndian,
1392 bool HasRelocationAddend) {
1395 case ELF::EM_X86_64:
1396 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1397 HasRelocationAddend, OSType); break;
1399 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1400 HasRelocationAddend, OSType); break;
1401 case ELF::EM_MBLAZE:
1402 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1403 HasRelocationAddend, OSType); break;
1404 default: llvm_unreachable("Unsupported architecture"); break;
1409 /// START OF SUBCLASSES for ELFObjectWriter
1410 //===- ARMELFObjectWriter -------------------------------------------===//
1412 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1413 bool _IsLittleEndian,
1414 uint16_t _EMachine, bool _HasRelocationAddend,
1415 Triple::OSType _OSType)
1416 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1417 _HasRelocationAddend, _OSType)
1420 ARMELFObjectWriter::~ARMELFObjectWriter()
1423 void ARMELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1424 const MCAsmLayout &Layout,
1425 const MCFragment *Fragment,
1426 const MCFixup &Fixup,
1428 uint64_t &FixedValue) {
1429 assert(0 && "ARMELFObjectWriter::RecordRelocation() unimplemented");
1432 //===- MBlazeELFObjectWriter -------------------------------------------===//
1434 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1435 bool _IsLittleEndian,
1437 bool _HasRelocationAddend,
1438 Triple::OSType _OSType)
1439 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1440 _HasRelocationAddend, _OSType) {
1443 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1446 void MBlazeELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1447 const MCAsmLayout &Layout,
1448 const MCFragment *Fragment,
1449 const MCFixup &Fixup,
1451 uint64_t &FixedValue) {
1454 int64_t Value = Target.getConstant();
1455 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1456 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1457 const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1459 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1460 if (!Target.isAbsolute()) {
1461 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1462 const MCSymbol &SymbolB = RefB->getSymbol();
1463 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1465 MCSectionData *Sec = Fragment->getParent();
1467 // Offset of the symbol in the section
1468 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1470 // Ofeset of the relocation in the section
1471 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1476 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1477 MCFragment *F = SD.getFragment();
1479 Index = F->getParent()->getOrdinal();
1481 MCSectionData *FSD = F->getParent();
1482 // Offset of the symbol in the section
1483 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1485 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1486 WeakrefUsedInReloc.insert(RelocSymbol);
1488 UsedInReloc.insert(RelocSymbol);
1496 // determine the type of the relocation
1499 switch ((unsigned)Fixup.getKind()) {
1501 llvm_unreachable("Unimplemented");
1502 case MBlaze::reloc_pcrel_4byte:
1503 Type = ELF::R_MICROBLAZE_64_PCREL;
1505 case MBlaze::reloc_pcrel_2byte:
1506 Type = ELF::R_MICROBLAZE_32_PCREL;
1510 switch ((unsigned)Fixup.getKind()) {
1511 default: llvm_unreachable("invalid fixup kind!");
1513 Type = (RelocSymbol || Addend !=0) ? ELF::R_MICROBLAZE_32
1514 : ELF::R_MICROBLAZE_64;
1517 Type = ELF::R_MICROBLAZE_32;
1522 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
1523 if (RelocNeedsGOT(Modifier))
1526 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1529 if (! HasRelocationAddend) Addend = 0;
1530 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1531 Relocations[Fragment->getParent()].push_back(ERE);
1534 //===- X86ELFObjectWriter -------------------------------------------===//
1537 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1538 bool _IsLittleEndian,
1539 uint16_t _EMachine, bool _HasRelocationAddend,
1540 Triple::OSType _OSType)
1541 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1542 _HasRelocationAddend, _OSType)
1545 X86ELFObjectWriter::~X86ELFObjectWriter()
1548 void X86ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1549 const MCAsmLayout &Layout,
1550 const MCFragment *Fragment,
1551 const MCFixup &Fixup,
1553 uint64_t &FixedValue) {
1556 int64_t Value = Target.getConstant();
1557 const MCSymbol *RelocSymbol = NULL;
1559 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1560 if (!Target.isAbsolute()) {
1561 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1562 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1563 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1565 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1566 const MCSymbol &SymbolB = RefB->getSymbol();
1567 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1569 MCSectionData *Sec = Fragment->getParent();
1571 // Offset of the symbol in the section
1572 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1574 // Ofeset of the relocation in the section
1575 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1580 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1581 MCFragment *F = SD.getFragment();
1583 Index = F->getParent()->getOrdinal() + 1;
1585 MCSectionData *FSD = F->getParent();
1586 // Offset of the symbol in the section
1587 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1589 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1590 WeakrefUsedInReloc.insert(RelocSymbol);
1592 UsedInReloc.insert(RelocSymbol);
1596 // Compensate for the addend on i386.
1603 // determine the type of the relocation
1605 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1606 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1612 llvm_unreachable("Unimplemented");
1613 case MCSymbolRefExpr::VK_None:
1614 Type = ELF::R_X86_64_PC32;
1616 case MCSymbolRefExpr::VK_PLT:
1617 Type = ELF::R_X86_64_PLT32;
1619 case MCSymbolRefExpr::VK_GOTPCREL:
1620 Type = ELF::R_X86_64_GOTPCREL;
1622 case MCSymbolRefExpr::VK_GOTTPOFF:
1623 Type = ELF::R_X86_64_GOTTPOFF;
1625 case MCSymbolRefExpr::VK_TLSGD:
1626 Type = ELF::R_X86_64_TLSGD;
1628 case MCSymbolRefExpr::VK_TLSLD:
1629 Type = ELF::R_X86_64_TLSLD;
1633 switch ((unsigned)Fixup.getKind()) {
1634 default: llvm_unreachable("invalid fixup kind!");
1635 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1636 case X86::reloc_signed_4byte:
1637 case X86::reloc_pcrel_4byte:
1638 assert(isInt<32>(Target.getConstant()));
1641 llvm_unreachable("Unimplemented");
1642 case MCSymbolRefExpr::VK_None:
1643 Type = ELF::R_X86_64_32S;
1645 case MCSymbolRefExpr::VK_GOT:
1646 Type = ELF::R_X86_64_GOT32;
1648 case MCSymbolRefExpr::VK_GOTPCREL:
1649 Type = ELF::R_X86_64_GOTPCREL;
1651 case MCSymbolRefExpr::VK_TPOFF:
1652 Type = ELF::R_X86_64_TPOFF32;
1654 case MCSymbolRefExpr::VK_DTPOFF:
1655 Type = ELF::R_X86_64_DTPOFF32;
1660 Type = ELF::R_X86_64_32;
1662 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1663 case X86::reloc_pcrel_1byte:
1664 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1671 llvm_unreachable("Unimplemented");
1672 case MCSymbolRefExpr::VK_None:
1673 Type = ELF::R_386_PC32;
1675 case MCSymbolRefExpr::VK_PLT:
1676 Type = ELF::R_386_PLT32;
1680 switch ((unsigned)Fixup.getKind()) {
1681 default: llvm_unreachable("invalid fixup kind!");
1683 case X86::reloc_global_offset_table:
1684 Type = ELF::R_386_GOTPC;
1687 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1689 case X86::reloc_signed_4byte:
1690 case X86::reloc_pcrel_4byte:
1694 llvm_unreachable("Unimplemented");
1695 case MCSymbolRefExpr::VK_None:
1696 Type = ELF::R_386_32;
1698 case MCSymbolRefExpr::VK_GOT:
1699 Type = ELF::R_386_GOT32;
1701 case MCSymbolRefExpr::VK_GOTOFF:
1702 Type = ELF::R_386_GOTOFF;
1704 case MCSymbolRefExpr::VK_TLSGD:
1705 Type = ELF::R_386_TLS_GD;
1707 case MCSymbolRefExpr::VK_TPOFF:
1708 Type = ELF::R_386_TLS_LE_32;
1710 case MCSymbolRefExpr::VK_INDNTPOFF:
1711 Type = ELF::R_386_TLS_IE;
1713 case MCSymbolRefExpr::VK_NTPOFF:
1714 Type = ELF::R_386_TLS_LE;
1716 case MCSymbolRefExpr::VK_GOTNTPOFF:
1717 Type = ELF::R_386_TLS_GOTIE;
1719 case MCSymbolRefExpr::VK_TLSLDM:
1720 Type = ELF::R_386_TLS_LDM;
1722 case MCSymbolRefExpr::VK_DTPOFF:
1723 Type = ELF::R_386_TLS_LDO_32;
1727 case FK_Data_2: Type = ELF::R_386_16; break;
1728 case X86::reloc_pcrel_1byte:
1729 case FK_Data_1: Type = ELF::R_386_8; break;
1734 if (RelocNeedsGOT(Modifier))
1738 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1741 if (! HasRelocationAddend) Addend = 0;
1742 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1743 Relocations[Fragment->getParent()].push_back(ERE);