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 MBlaze::reloc_pcrel_2byte:
403 case MBlaze::reloc_pcrel_4byte:
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 ARM::fixup_arm_pcrel_12:
430 case ARM::fixup_arm_vfp_pcrel_12:
431 case ARM::fixup_arm_branch:
438 ELFObjectWriter::~ELFObjectWriter()
441 // Emit the ELF header.
442 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
443 unsigned NumberOfSections) {
449 // emitWord method behaves differently for ELF32 and ELF64, writing
450 // 4 bytes in the former and 8 in the latter.
452 Write8(0x7f); // e_ident[EI_MAG0]
453 Write8('E'); // e_ident[EI_MAG1]
454 Write8('L'); // e_ident[EI_MAG2]
455 Write8('F'); // e_ident[EI_MAG3]
457 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
460 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
462 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
465 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
466 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
467 default: Write8(ELF::ELFOSABI_NONE); break;
469 Write8(0); // e_ident[EI_ABIVERSION]
471 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
473 Write16(ELF::ET_REL); // e_type
475 Write16(EMachine); // e_machine = target
477 Write32(ELF::EV_CURRENT); // e_version
478 WriteWord(0); // e_entry, no entry point in .o file
479 WriteWord(0); // e_phoff, no program header for .o
480 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
481 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
483 // FIXME: Make this configurable.
484 Write32(0); // e_flags = whatever the target wants
486 // e_ehsize = ELF header size
487 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
489 Write16(0); // e_phentsize = prog header entry size
490 Write16(0); // e_phnum = # prog header entries = 0
492 // e_shentsize = Section header entry size
493 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
495 // e_shnum = # of section header ents
496 if (NumberOfSections >= ELF::SHN_LORESERVE)
499 Write16(NumberOfSections);
501 // e_shstrndx = Section # of '.shstrtab'
502 if (NumberOfSections >= ELF::SHN_LORESERVE)
503 Write16(ELF::SHN_XINDEX);
505 Write16(ShstrtabIndex);
508 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
509 MCDataFragment *ShndxF,
511 uint8_t info, uint64_t value,
512 uint64_t size, uint8_t other,
516 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
517 String32(*ShndxF, shndx);
519 String32(*ShndxF, 0);
522 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
523 uint16_t(ELF::SHN_XINDEX) : shndx;
526 String32(*SymtabF, name); // st_name
527 String8(*SymtabF, info); // st_info
528 String8(*SymtabF, other); // st_other
529 String16(*SymtabF, Index); // st_shndx
530 String64(*SymtabF, value); // st_value
531 String64(*SymtabF, size); // st_size
533 String32(*SymtabF, name); // st_name
534 String32(*SymtabF, value); // st_value
535 String32(*SymtabF, size); // st_size
536 String8(*SymtabF, info); // st_info
537 String8(*SymtabF, other); // st_other
538 String16(*SymtabF, Index); // st_shndx
542 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
543 if (Data.isCommon() && Data.isExternal())
544 return Data.getCommonAlignment();
546 const MCSymbol &Symbol = Data.getSymbol();
547 if (!Symbol.isInSection())
550 if (MCFragment *FF = Data.getFragment())
551 return Layout.getSymbolAddress(&Data) -
552 Layout.getSectionAddress(FF->getParent());
557 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
558 // The presence of symbol versions causes undefined symbols and
559 // versions declared with @@@ to be renamed.
561 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
562 ie = Asm.symbol_end(); it != ie; ++it) {
563 const MCSymbol &Alias = it->getSymbol();
564 const MCSymbol &Symbol = Alias.AliasedSymbol();
565 MCSymbolData &SD = Asm.getSymbolData(Symbol);
568 if (&Symbol == &Alias)
571 StringRef AliasName = Alias.getName();
572 size_t Pos = AliasName.find('@');
573 if (Pos == StringRef::npos)
576 // Aliases defined with .symvar copy the binding from the symbol they alias.
577 // This is the first place we are able to copy this information.
578 it->setExternal(SD.isExternal());
579 SetBinding(*it, GetBinding(SD));
581 StringRef Rest = AliasName.substr(Pos);
582 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
585 // FIXME: produce a better error message.
586 if (Symbol.isUndefined() && Rest.startswith("@@") &&
587 !Rest.startswith("@@@"))
588 report_fatal_error("A @@ version cannot be undefined");
590 Renames.insert(std::make_pair(&Symbol, &Alias));
594 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
595 MCDataFragment *ShndxF,
597 const MCAsmLayout &Layout) {
598 MCSymbolData &OrigData = *MSD.SymbolData;
600 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
602 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
603 Data.getSymbol().isVariable();
605 uint8_t Binding = GetBinding(OrigData);
606 uint8_t Visibility = GetVisibility(OrigData);
607 uint8_t Type = GetType(Data);
609 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
610 uint8_t Other = Visibility;
612 uint64_t Value = SymbolValue(Data, Layout);
616 assert(!(Data.isCommon() && !Data.isExternal()));
618 ESize = Data.getSize();
619 if (Data.getSize()) {
621 if (ESize->getKind() == MCExpr::Binary) {
622 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
624 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
625 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
626 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
627 Size = Res.getConstant();
629 } else if (ESize->getKind() == MCExpr::Constant) {
630 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
632 assert(0 && "Unsupported size expression");
636 // Write out the symbol table entry
637 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
638 Size, Other, MSD.SectionIndex, IsReserved);
641 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
642 MCDataFragment *ShndxF,
643 const MCAssembler &Asm,
644 const MCAsmLayout &Layout,
645 const SectionIndexMapTy &SectionIndexMap) {
646 // The string table must be emitted first because we need the index
647 // into the string table for all the symbol names.
648 assert(StringTable.size() && "Missing string table");
650 // FIXME: Make sure the start of the symbol table is aligned.
652 // The first entry is the undefined symbol entry.
653 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
655 // Write the symbol table entries.
656 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
657 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
658 ELFSymbolData &MSD = LocalSymbolData[i];
659 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
662 // Write out a symbol table entry for each regular section.
663 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
665 const MCSectionELF &Section =
666 static_cast<const MCSectionELF&>(i->getSection());
667 if (Section.getType() == ELF::SHT_RELA ||
668 Section.getType() == ELF::SHT_REL ||
669 Section.getType() == ELF::SHT_STRTAB ||
670 Section.getType() == ELF::SHT_SYMTAB)
672 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
673 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
674 LastLocalSymbolIndex++;
677 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
678 ELFSymbolData &MSD = ExternalSymbolData[i];
679 MCSymbolData &Data = *MSD.SymbolData;
680 assert(((Data.getFlags() & ELF_STB_Global) ||
681 (Data.getFlags() & ELF_STB_Weak)) &&
682 "External symbol requires STB_GLOBAL or STB_WEAK flag");
683 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
684 if (GetBinding(Data) == ELF::STB_LOCAL)
685 LastLocalSymbolIndex++;
688 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
689 ELFSymbolData &MSD = UndefinedSymbolData[i];
690 MCSymbolData &Data = *MSD.SymbolData;
691 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
692 if (GetBinding(Data) == ELF::STB_LOCAL)
693 LastLocalSymbolIndex++;
697 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
698 const MCValue &Target,
699 const MCFragment &F) const {
700 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
701 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
702 const MCSymbol *Renamed = Renames.lookup(&Symbol);
703 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
705 if (ASymbol.isUndefined()) {
711 if (SD.isExternal()) {
717 const MCSectionELF &Section =
718 static_cast<const MCSectionELF&>(ASymbol.getSection());
720 if (Section.getKind().isBSS())
723 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
724 const MCSectionELF &Sec2 =
725 static_cast<const MCSectionELF&>(F.getParent()->getSection());
727 if (&Sec2 != &Section &&
728 (Kind == MCSymbolRefExpr::VK_PLT ||
729 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
730 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
736 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
737 if (Target.getConstant() == 0)
749 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
751 MCSymbolData &SD = Asm.getSymbolData(*S);
752 return SD.getIndex();
755 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
756 bool Used, bool Renamed) {
757 if (Data.getFlags() & ELF_Other_Weakref)
766 const MCSymbol &Symbol = Data.getSymbol();
768 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
771 const MCSymbol &A = Symbol.AliasedSymbol();
772 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
775 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
778 if (Symbol.isTemporary())
784 static bool isLocal(const MCSymbolData &Data, bool isSignature,
785 bool isUsedInReloc) {
786 if (Data.isExternal())
789 const MCSymbol &Symbol = Data.getSymbol();
790 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
792 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
793 if (isSignature && !isUsedInReloc)
802 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
803 SectionIndexMapTy &SectionIndexMap) {
805 for (MCAssembler::iterator it = Asm.begin(),
806 ie = Asm.end(); it != ie; ++it) {
807 const MCSectionELF &Section =
808 static_cast<const MCSectionELF &>(it->getSection());
809 if (Section.getType() != ELF::SHT_GROUP)
811 SectionIndexMap[&Section] = Index++;
814 for (MCAssembler::iterator it = Asm.begin(),
815 ie = Asm.end(); it != ie; ++it) {
816 const MCSectionELF &Section =
817 static_cast<const MCSectionELF &>(it->getSection());
818 if (Section.getType() == ELF::SHT_GROUP)
820 SectionIndexMap[&Section] = Index++;
824 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
825 const SectionIndexMapTy &SectionIndexMap,
826 RevGroupMapTy RevGroupMap) {
827 // FIXME: Is this the correct place to do this?
829 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
830 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
831 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
832 Data.setExternal(true);
833 SetBinding(Data, ELF::STB_GLOBAL);
836 // Build section lookup table.
837 int NumRegularSections = Asm.size();
839 // Index 0 is always the empty string.
840 StringMap<uint64_t> StringIndexMap;
841 StringTable += '\x00';
843 // Add the data for the symbols.
844 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
845 ie = Asm.symbol_end(); it != ie; ++it) {
846 const MCSymbol &Symbol = it->getSymbol();
848 bool Used = UsedInReloc.count(&Symbol);
849 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
850 bool isSignature = RevGroupMap.count(&Symbol);
852 if (!isInSymtab(Asm, *it,
853 Used || WeakrefUsed || isSignature,
854 Renames.count(&Symbol)))
859 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
861 // Undefined symbols are global, but this is the first place we
862 // are able to set it.
863 bool Local = isLocal(*it, isSignature, Used);
864 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
865 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
866 SetBinding(*it, ELF::STB_GLOBAL);
867 SetBinding(SD, ELF::STB_GLOBAL);
870 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
871 SetBinding(*it, ELF::STB_WEAK);
873 if (it->isCommon()) {
875 MSD.SectionIndex = ELF::SHN_COMMON;
876 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
877 MSD.SectionIndex = ELF::SHN_ABS;
878 } else if (RefSymbol.isUndefined()) {
879 if (isSignature && !Used)
880 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
882 MSD.SectionIndex = ELF::SHN_UNDEF;
884 const MCSectionELF &Section =
885 static_cast<const MCSectionELF&>(RefSymbol.getSection());
886 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
887 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
888 NeedsSymtabShndx = true;
889 assert(MSD.SectionIndex && "Invalid section index!");
892 // The @@@ in symbol version is replaced with @ in undefined symbols and
893 // @@ in defined ones.
894 StringRef Name = Symbol.getName();
897 size_t Pos = Name.find("@@@");
898 if (Pos != StringRef::npos) {
899 Buf += Name.substr(0, Pos);
900 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
901 Buf += Name.substr(Pos + Skip);
905 uint64_t &Entry = StringIndexMap[Name];
907 Entry = StringTable.size();
909 StringTable += '\x00';
911 MSD.StringIndex = Entry;
912 if (MSD.SectionIndex == ELF::SHN_UNDEF)
913 UndefinedSymbolData.push_back(MSD);
915 LocalSymbolData.push_back(MSD);
917 ExternalSymbolData.push_back(MSD);
920 // Symbols are required to be in lexicographic order.
921 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
922 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
923 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
925 // Set the symbol indices. Local symbols must come before all other
926 // symbols with non-local bindings.
928 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
929 LocalSymbolData[i].SymbolData->setIndex(Index++);
931 Index += NumRegularSections;
933 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
934 ExternalSymbolData[i].SymbolData->setIndex(Index++);
935 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
936 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
939 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
940 const MCSectionData &SD) {
941 if (!Relocations[&SD].empty()) {
942 MCContext &Ctx = Asm.getContext();
943 const MCSectionELF *RelaSection;
944 const MCSectionELF &Section =
945 static_cast<const MCSectionELF&>(SD.getSection());
947 const StringRef SectionName = Section.getSectionName();
948 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
949 RelaSectionName += SectionName;
952 if (HasRelocationAddend)
953 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
955 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
957 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
958 ELF::SHT_RELA : ELF::SHT_REL, 0,
959 SectionKind::getReadOnly(),
962 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
963 RelaSD.setAlignment(Is64Bit ? 8 : 4);
965 MCDataFragment *F = new MCDataFragment(&RelaSD);
967 WriteRelocationsFragment(Asm, F, &SD);
969 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
973 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
974 uint64_t Flags, uint64_t Address,
975 uint64_t Offset, uint64_t Size,
976 uint32_t Link, uint32_t Info,
978 uint64_t EntrySize) {
979 Write32(Name); // sh_name: index into string table
980 Write32(Type); // sh_type
981 WriteWord(Flags); // sh_flags
982 WriteWord(Address); // sh_addr
983 WriteWord(Offset); // sh_offset
984 WriteWord(Size); // sh_size
985 Write32(Link); // sh_link
986 Write32(Info); // sh_info
987 WriteWord(Alignment); // sh_addralign
988 WriteWord(EntrySize); // sh_entsize
991 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
993 const MCSectionData *SD) {
994 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
995 // sort by the r_offset just like gnu as does
996 array_pod_sort(Relocs.begin(), Relocs.end());
998 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
999 ELFRelocationEntry entry = Relocs[e - i - 1];
1003 else if (entry.Index < 0)
1004 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1006 entry.Index += LocalSymbolData.size();
1008 String64(*F, entry.r_offset);
1010 struct ELF::Elf64_Rela ERE64;
1011 ERE64.setSymbolAndType(entry.Index, entry.Type);
1012 String64(*F, ERE64.r_info);
1014 if (HasRelocationAddend)
1015 String64(*F, entry.r_addend);
1017 String32(*F, entry.r_offset);
1019 struct ELF::Elf32_Rela ERE32;
1020 ERE32.setSymbolAndType(entry.Index, entry.Type);
1021 String32(*F, ERE32.r_info);
1023 if (HasRelocationAddend)
1024 String32(*F, entry.r_addend);
1029 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1030 MCAsmLayout &Layout,
1031 const SectionIndexMapTy &SectionIndexMap) {
1032 MCContext &Ctx = Asm.getContext();
1035 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1037 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1038 const MCSectionELF *ShstrtabSection =
1039 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1040 SectionKind::getReadOnly());
1041 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1042 ShstrtabSD.setAlignment(1);
1043 ShstrtabIndex = Asm.size();
1045 const MCSectionELF *SymtabSection =
1046 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1047 SectionKind::getReadOnly(),
1049 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1050 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1051 SymbolTableIndex = Asm.size();
1053 MCSectionData *SymtabShndxSD = NULL;
1055 if (NeedsSymtabShndx) {
1056 const MCSectionELF *SymtabShndxSection =
1057 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1058 SectionKind::getReadOnly(), 4, "");
1059 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1060 SymtabShndxSD->setAlignment(4);
1063 const MCSection *StrtabSection;
1064 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1065 SectionKind::getReadOnly());
1066 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1067 StrtabSD.setAlignment(1);
1068 StringTableIndex = Asm.size();
1070 WriteRelocations(Asm, Layout);
1073 F = new MCDataFragment(&SymtabSD);
1074 MCDataFragment *ShndxF = NULL;
1075 if (NeedsSymtabShndx) {
1076 ShndxF = new MCDataFragment(SymtabShndxSD);
1077 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1079 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1080 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1082 F = new MCDataFragment(&StrtabSD);
1083 F->getContents().append(StringTable.begin(), StringTable.end());
1084 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1086 F = new MCDataFragment(&ShstrtabSD);
1088 // Section header string table.
1090 // The first entry of a string table holds a null character so skip
1093 F->getContents() += '\x00';
1095 StringMap<uint64_t> SecStringMap;
1096 for (MCAssembler::const_iterator it = Asm.begin(),
1097 ie = Asm.end(); it != ie; ++it) {
1098 const MCSectionELF &Section =
1099 static_cast<const MCSectionELF&>(it->getSection());
1100 // FIXME: We could merge suffixes like in .text and .rela.text.
1102 StringRef Name = Section.getSectionName();
1103 if (SecStringMap.count(Name)) {
1104 SectionStringTableIndex[&Section] = SecStringMap[Name];
1107 // Remember the index into the string table so we can write it
1108 // into the sh_name field of the section header table.
1109 SectionStringTableIndex[&Section] = Index;
1110 SecStringMap[Name] = Index;
1112 Index += Name.size() + 1;
1113 F->getContents() += Name;
1114 F->getContents() += '\x00';
1117 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1120 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1121 const MCValue Target,
1123 const MCFragment *DF) const {
1124 // If this is a PCrel relocation, find the section this fixup value is
1126 const MCSection *BaseSection = 0;
1128 BaseSection = &DF->getParent()->getSection();
1129 assert(BaseSection);
1132 const MCSection *SectionA = 0;
1133 const MCSymbol *SymbolA = 0;
1134 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1135 SymbolA = &A->getSymbol();
1136 SectionA = &SymbolA->AliasedSymbol().getSection();
1139 const MCSection *SectionB = 0;
1140 const MCSymbol *SymbolB = 0;
1141 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1142 SymbolB = &B->getSymbol();
1143 SectionB = &SymbolB->AliasedSymbol().getSection();
1147 return SectionA == SectionB;
1152 // Absolute address but PCrel instruction, so we need a relocation.
1156 // FIXME: This is in here just to match gnu as output. If the two ends
1157 // are in the same section, there is nothing that the linker can do to
1159 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1160 if (DataA.isExternal())
1163 return BaseSection == SectionA;
1166 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1167 MCAsmLayout &Layout,
1168 GroupMapTy &GroupMap,
1169 RevGroupMapTy &RevGroupMap) {
1171 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1173 const MCSectionELF &Section =
1174 static_cast<const MCSectionELF&>(it->getSection());
1175 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1178 const MCSymbol *SignatureSymbol = Section.getGroup();
1179 Asm.getOrCreateSymbolData(*SignatureSymbol);
1180 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1182 Group = Asm.getContext().CreateELFGroupSection();
1183 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1184 Data.setAlignment(4);
1185 MCDataFragment *F = new MCDataFragment(&Data);
1186 String32(*F, ELF::GRP_COMDAT);
1188 GroupMap[Group] = SignatureSymbol;
1191 // Add sections to the groups
1193 unsigned NumGroups = RevGroupMap.size();
1194 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1195 it != ie; ++it, ++Index) {
1196 const MCSectionELF &Section =
1197 static_cast<const MCSectionELF&>(it->getSection());
1198 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1200 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1201 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1202 // FIXME: we could use the previous fragment
1203 MCDataFragment *F = new MCDataFragment(&Data);
1204 String32(*F, NumGroups + Index);
1207 for (RevGroupMapTy::const_iterator i = RevGroupMap.begin(),
1208 e = RevGroupMap.end(); i != e; ++i) {
1209 const MCSectionELF *Group = i->second;
1210 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1211 Asm.AddSectionToTheEnd(*this, Data, Layout);
1215 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1216 const SectionIndexMapTy &SectionIndexMap,
1217 uint32_t GroupSymbolIndex,
1218 uint64_t Offset, uint64_t Size,
1220 const MCSectionELF &Section) {
1221 uint64_t sh_link = 0;
1222 uint64_t sh_info = 0;
1224 switch(Section.getType()) {
1225 case ELF::SHT_DYNAMIC:
1226 sh_link = SectionStringTableIndex[&Section];
1231 case ELF::SHT_RELA: {
1232 const MCSectionELF *SymtabSection;
1233 const MCSectionELF *InfoSection;
1234 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1236 SectionKind::getReadOnly());
1237 sh_link = SectionIndexMap.lookup(SymtabSection);
1238 assert(sh_link && ".symtab not found");
1240 // Remove ".rel" and ".rela" prefixes.
1241 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1242 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1244 InfoSection = Asm.getContext().getELFSection(SectionName,
1245 ELF::SHT_PROGBITS, 0,
1246 SectionKind::getReadOnly());
1247 sh_info = SectionIndexMap.lookup(InfoSection);
1251 case ELF::SHT_SYMTAB:
1252 case ELF::SHT_DYNSYM:
1253 sh_link = StringTableIndex;
1254 sh_info = LastLocalSymbolIndex;
1257 case ELF::SHT_SYMTAB_SHNDX:
1258 sh_link = SymbolTableIndex;
1261 case ELF::SHT_PROGBITS:
1262 case ELF::SHT_STRTAB:
1263 case ELF::SHT_NOBITS:
1265 case ELF::SHT_ARM_ATTRIBUTES:
1269 case ELF::SHT_GROUP: {
1270 sh_link = SymbolTableIndex;
1271 sh_info = GroupSymbolIndex;
1276 assert(0 && "FIXME: sh_type value not supported!");
1280 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1281 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1282 Alignment, Section.getEntrySize());
1285 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1286 const MCAsmLayout &Layout) {
1287 GroupMapTy GroupMap;
1288 RevGroupMapTy RevGroupMap;
1289 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1292 SectionIndexMapTy SectionIndexMap;
1294 ComputeIndexMap(Asm, SectionIndexMap);
1296 // Compute symbol table information.
1297 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1299 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1300 const_cast<MCAsmLayout&>(Layout),
1303 // Update to include the metadata sections.
1304 ComputeIndexMap(Asm, SectionIndexMap);
1306 // Add 1 for the null section.
1307 unsigned NumSections = Asm.size() + 1;
1308 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1309 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1310 uint64_t FileOff = HeaderSize;
1312 std::vector<const MCSectionELF*> Sections;
1313 Sections.resize(NumSections);
1315 for (SectionIndexMapTy::const_iterator i=
1316 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1317 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1318 Sections[p.second] = p.first;
1321 for (unsigned i = 1; i < NumSections; ++i) {
1322 const MCSectionELF &Section = *Sections[i];
1323 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1325 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1327 // Get the size of the section in the output file (including padding).
1328 uint64_t Size = Layout.getSectionFileSize(&SD);
1333 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1335 // Write out the ELF header ...
1336 WriteHeader(FileOff - HeaderSize, NumSections);
1338 FileOff = HeaderSize;
1340 // ... then all of the sections ...
1341 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1343 for (unsigned i = 1; i < NumSections; ++i) {
1344 const MCSectionELF &Section = *Sections[i];
1345 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1347 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1348 WriteZeros(Padding);
1351 // Remember the offset into the file for this section.
1352 SectionOffsetMap[&Section] = FileOff;
1354 FileOff += Layout.getSectionFileSize(&SD);
1356 Asm.WriteSectionData(&SD, Layout, this);
1359 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1360 WriteZeros(Padding);
1363 // ... and then the section header table.
1364 // Should we align the section header table?
1366 // Null section first.
1367 uint64_t FirstSectionSize =
1368 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1369 uint32_t FirstSectionLink =
1370 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1371 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1373 for (unsigned i = 1; i < NumSections; ++i) {
1374 const MCSectionELF &Section = *Sections[i];
1375 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1376 uint32_t GroupSymbolIndex;
1377 if (Section.getType() != ELF::SHT_GROUP)
1378 GroupSymbolIndex = 0;
1380 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1382 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1383 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1384 SD.getAlignment(), Section);
1388 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1390 Triple::OSType OSType,
1392 bool IsLittleEndian,
1393 bool HasRelocationAddend) {
1396 case ELF::EM_X86_64:
1397 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1398 HasRelocationAddend, OSType); break;
1400 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1401 HasRelocationAddend, OSType); break;
1402 case ELF::EM_MBLAZE:
1403 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1404 HasRelocationAddend, OSType); break;
1405 default: llvm_unreachable("Unsupported architecture"); break;
1410 /// START OF SUBCLASSES for ELFObjectWriter
1411 //===- ARMELFObjectWriter -------------------------------------------===//
1413 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1414 bool _IsLittleEndian,
1415 uint16_t _EMachine, bool _HasRelocationAddend,
1416 Triple::OSType _OSType)
1417 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1418 _HasRelocationAddend, _OSType)
1421 ARMELFObjectWriter::~ARMELFObjectWriter()
1424 void ARMELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1425 const MCAsmLayout &Layout,
1426 const MCFragment *Fragment,
1427 const MCFixup &Fixup,
1429 uint64_t &FixedValue) {
1430 assert(0 && "ARMELFObjectWriter::RecordRelocation() unimplemented");
1433 //===- MBlazeELFObjectWriter -------------------------------------------===//
1435 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1436 bool _IsLittleEndian,
1438 bool _HasRelocationAddend,
1439 Triple::OSType _OSType)
1440 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1441 _HasRelocationAddend, _OSType) {
1444 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1447 void MBlazeELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1448 const MCAsmLayout &Layout,
1449 const MCFragment *Fragment,
1450 const MCFixup &Fixup,
1452 uint64_t &FixedValue) {
1455 int64_t Value = Target.getConstant();
1456 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1457 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1458 const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1460 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1461 if (!Target.isAbsolute()) {
1462 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1463 const MCSymbol &SymbolB = RefB->getSymbol();
1464 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1466 MCSectionData *Sec = Fragment->getParent();
1468 // Offset of the symbol in the section
1469 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1471 // Ofeset of the relocation in the section
1472 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1477 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1478 MCFragment *F = SD.getFragment();
1480 Index = F->getParent()->getOrdinal();
1482 MCSectionData *FSD = F->getParent();
1483 // Offset of the symbol in the section
1484 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1486 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1487 WeakrefUsedInReloc.insert(RelocSymbol);
1489 UsedInReloc.insert(RelocSymbol);
1497 // determine the type of the relocation
1500 switch ((unsigned)Fixup.getKind()) {
1502 llvm_unreachable("Unimplemented");
1503 case MBlaze::reloc_pcrel_4byte:
1504 Type = ELF::R_MICROBLAZE_64_PCREL;
1506 case MBlaze::reloc_pcrel_2byte:
1507 Type = ELF::R_MICROBLAZE_32_PCREL;
1511 switch ((unsigned)Fixup.getKind()) {
1512 default: llvm_unreachable("invalid fixup kind!");
1514 Type = (RelocSymbol || Addend !=0) ? ELF::R_MICROBLAZE_32
1515 : ELF::R_MICROBLAZE_64;
1518 Type = ELF::R_MICROBLAZE_32;
1523 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
1524 if (RelocNeedsGOT(Modifier))
1527 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1530 if (! HasRelocationAddend) Addend = 0;
1531 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1532 Relocations[Fragment->getParent()].push_back(ERE);
1535 //===- X86ELFObjectWriter -------------------------------------------===//
1538 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1539 bool _IsLittleEndian,
1540 uint16_t _EMachine, bool _HasRelocationAddend,
1541 Triple::OSType _OSType)
1542 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1543 _HasRelocationAddend, _OSType)
1546 X86ELFObjectWriter::~X86ELFObjectWriter()
1549 void X86ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1550 const MCAsmLayout &Layout,
1551 const MCFragment *Fragment,
1552 const MCFixup &Fixup,
1554 uint64_t &FixedValue) {
1557 int64_t Value = Target.getConstant();
1558 const MCSymbol *RelocSymbol = NULL;
1560 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1561 if (!Target.isAbsolute()) {
1562 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1563 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1564 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1566 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1567 const MCSymbol &SymbolB = RefB->getSymbol();
1568 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1570 MCSectionData *Sec = Fragment->getParent();
1572 // Offset of the symbol in the section
1573 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1575 // Ofeset of the relocation in the section
1576 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1581 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1582 MCFragment *F = SD.getFragment();
1584 Index = F->getParent()->getOrdinal() + 1;
1586 MCSectionData *FSD = F->getParent();
1587 // Offset of the symbol in the section
1588 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1590 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1591 WeakrefUsedInReloc.insert(RelocSymbol);
1593 UsedInReloc.insert(RelocSymbol);
1597 // Compensate for the addend on i386.
1604 // determine the type of the relocation
1606 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1607 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1613 llvm_unreachable("Unimplemented");
1614 case MCSymbolRefExpr::VK_None:
1615 Type = ELF::R_X86_64_PC32;
1617 case MCSymbolRefExpr::VK_PLT:
1618 Type = ELF::R_X86_64_PLT32;
1620 case MCSymbolRefExpr::VK_GOTPCREL:
1621 Type = ELF::R_X86_64_GOTPCREL;
1623 case MCSymbolRefExpr::VK_GOTTPOFF:
1624 Type = ELF::R_X86_64_GOTTPOFF;
1626 case MCSymbolRefExpr::VK_TLSGD:
1627 Type = ELF::R_X86_64_TLSGD;
1629 case MCSymbolRefExpr::VK_TLSLD:
1630 Type = ELF::R_X86_64_TLSLD;
1634 switch ((unsigned)Fixup.getKind()) {
1635 default: llvm_unreachable("invalid fixup kind!");
1636 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1637 case X86::reloc_signed_4byte:
1638 case X86::reloc_pcrel_4byte:
1639 assert(isInt<32>(Target.getConstant()));
1642 llvm_unreachable("Unimplemented");
1643 case MCSymbolRefExpr::VK_None:
1644 Type = ELF::R_X86_64_32S;
1646 case MCSymbolRefExpr::VK_GOT:
1647 Type = ELF::R_X86_64_GOT32;
1649 case MCSymbolRefExpr::VK_GOTPCREL:
1650 Type = ELF::R_X86_64_GOTPCREL;
1652 case MCSymbolRefExpr::VK_TPOFF:
1653 Type = ELF::R_X86_64_TPOFF32;
1655 case MCSymbolRefExpr::VK_DTPOFF:
1656 Type = ELF::R_X86_64_DTPOFF32;
1661 Type = ELF::R_X86_64_32;
1663 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1664 case X86::reloc_pcrel_1byte:
1665 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1672 llvm_unreachable("Unimplemented");
1673 case MCSymbolRefExpr::VK_None:
1674 Type = ELF::R_386_PC32;
1676 case MCSymbolRefExpr::VK_PLT:
1677 Type = ELF::R_386_PLT32;
1681 switch ((unsigned)Fixup.getKind()) {
1682 default: llvm_unreachable("invalid fixup kind!");
1684 case X86::reloc_global_offset_table:
1685 Type = ELF::R_386_GOTPC;
1688 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1690 case X86::reloc_signed_4byte:
1691 case X86::reloc_pcrel_4byte:
1695 llvm_unreachable("Unimplemented");
1696 case MCSymbolRefExpr::VK_None:
1697 Type = ELF::R_386_32;
1699 case MCSymbolRefExpr::VK_GOT:
1700 Type = ELF::R_386_GOT32;
1702 case MCSymbolRefExpr::VK_GOTOFF:
1703 Type = ELF::R_386_GOTOFF;
1705 case MCSymbolRefExpr::VK_TLSGD:
1706 Type = ELF::R_386_TLS_GD;
1708 case MCSymbolRefExpr::VK_TPOFF:
1709 Type = ELF::R_386_TLS_LE_32;
1711 case MCSymbolRefExpr::VK_INDNTPOFF:
1712 Type = ELF::R_386_TLS_IE;
1714 case MCSymbolRefExpr::VK_NTPOFF:
1715 Type = ELF::R_386_TLS_LE;
1717 case MCSymbolRefExpr::VK_GOTNTPOFF:
1718 Type = ELF::R_386_TLS_GOTIE;
1720 case MCSymbolRefExpr::VK_TLSLDM:
1721 Type = ELF::R_386_TLS_LDM;
1723 case MCSymbolRefExpr::VK_DTPOFF:
1724 Type = ELF::R_386_TLS_LDO_32;
1728 case FK_Data_2: Type = ELF::R_386_16; break;
1729 case X86::reloc_pcrel_1byte:
1730 case FK_Data_1: Type = ELF::R_386_8; break;
1735 if (RelocNeedsGOT(Modifier))
1739 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1742 if (! HasRelocationAddend) Addend = 0;
1743 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1744 Relocations[Fragment->getParent()].push_back(ERE);