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"
38 static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
47 static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
61 static unsigned GetVisibility(MCSymbolData &SD) {
63 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
70 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
74 case MCSymbolRefExpr::VK_GOT:
75 case MCSymbolRefExpr::VK_PLT:
76 case MCSymbolRefExpr::VK_GOTPCREL:
77 case MCSymbolRefExpr::VK_TPOFF:
78 case MCSymbolRefExpr::VK_TLSGD:
79 case MCSymbolRefExpr::VK_GOTTPOFF:
80 case MCSymbolRefExpr::VK_INDNTPOFF:
81 case MCSymbolRefExpr::VK_NTPOFF:
82 case MCSymbolRefExpr::VK_GOTNTPOFF:
83 case MCSymbolRefExpr::VK_TLSLDM:
84 case MCSymbolRefExpr::VK_DTPOFF:
85 case MCSymbolRefExpr::VK_TLSLD:
91 class ELFObjectWriter : public MCObjectWriter {
93 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
94 return Kind == X86::reloc_riprel_4byte ||
95 Kind == X86::reloc_riprel_4byte_movq_load;
99 /// ELFSymbolData - Helper struct for containing some precomputed information
101 struct ELFSymbolData {
102 MCSymbolData *SymbolData;
103 uint64_t StringIndex;
104 uint32_t SectionIndex;
106 // Support lexicographic sorting.
107 bool operator<(const ELFSymbolData &RHS) const {
108 if (GetType(*SymbolData) == ELF::STT_FILE)
110 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
112 return SymbolData->getSymbol().getName() <
113 RHS.SymbolData->getSymbol().getName();
117 /// @name Relocation Data
120 struct ELFRelocationEntry {
121 // Make these big enough for both 32-bit and 64-bit
125 const MCSymbol *Symbol;
129 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
131 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
132 unsigned RelType, const MCSymbol *Sym,
134 : r_offset(RelocOffset), Index(Idx), Type(RelType),
135 Symbol(Sym), r_addend(Addend) {}
137 // Support lexicographic sorting.
138 bool operator<(const ELFRelocationEntry &RE) const {
139 return RE.r_offset < r_offset;
143 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
144 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
145 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
147 llvm::DenseMap<const MCSectionData*,
148 std::vector<ELFRelocationEntry> > Relocations;
149 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
152 /// @name Symbol Table Data
155 SmallString<256> StringTable;
156 std::vector<ELFSymbolData> LocalSymbolData;
157 std::vector<ELFSymbolData> ExternalSymbolData;
158 std::vector<ELFSymbolData> UndefinedSymbolData;
164 bool NeedsSymtabShndx;
166 unsigned Is64Bit : 1;
168 bool HasRelocationAddend;
170 Triple::OSType OSType;
174 // This holds the symbol table index of the last local symbol.
175 unsigned LastLocalSymbolIndex;
176 // This holds the .strtab section index.
177 unsigned StringTableIndex;
178 // This holds the .symtab section index.
179 unsigned SymbolTableIndex;
181 unsigned ShstrtabIndex;
184 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
185 const MCValue &Target,
186 const MCFragment &F) const;
189 ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
190 uint16_t _EMachine, bool _HasRelAddend,
191 Triple::OSType _OSType)
192 : MCObjectWriter(_OS, IsLittleEndian),
193 NeedsGOT(false), NeedsSymtabShndx(false),
194 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
195 OSType(_OSType), EMachine(_EMachine) {
198 virtual ~ELFObjectWriter();
200 void WriteWord(uint64_t W) {
207 void StringLE16(char *buf, uint16_t Value) {
208 buf[0] = char(Value >> 0);
209 buf[1] = char(Value >> 8);
212 void StringLE32(char *buf, uint32_t Value) {
213 StringLE16(buf, uint16_t(Value >> 0));
214 StringLE16(buf + 2, uint16_t(Value >> 16));
217 void StringLE64(char *buf, uint64_t Value) {
218 StringLE32(buf, uint32_t(Value >> 0));
219 StringLE32(buf + 4, uint32_t(Value >> 32));
222 void StringBE16(char *buf ,uint16_t Value) {
223 buf[0] = char(Value >> 8);
224 buf[1] = char(Value >> 0);
227 void StringBE32(char *buf, uint32_t Value) {
228 StringBE16(buf, uint16_t(Value >> 16));
229 StringBE16(buf + 2, uint16_t(Value >> 0));
232 void StringBE64(char *buf, uint64_t Value) {
233 StringBE32(buf, uint32_t(Value >> 32));
234 StringBE32(buf + 4, uint32_t(Value >> 0));
237 void String8(MCDataFragment &F, uint8_t Value) {
240 F.getContents() += StringRef(buf, 1);
243 void String16(MCDataFragment &F, uint16_t Value) {
245 if (isLittleEndian())
246 StringLE16(buf, Value);
248 StringBE16(buf, Value);
249 F.getContents() += StringRef(buf, 2);
252 void String32(MCDataFragment &F, uint32_t Value) {
254 if (isLittleEndian())
255 StringLE32(buf, Value);
257 StringBE32(buf, Value);
258 F.getContents() += StringRef(buf, 4);
261 void String64(MCDataFragment &F, uint64_t Value) {
263 if (isLittleEndian())
264 StringLE64(buf, Value);
266 StringBE64(buf, Value);
267 F.getContents() += StringRef(buf, 8);
270 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
272 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
273 uint64_t name, uint8_t info,
274 uint64_t value, uint64_t size,
275 uint8_t other, uint32_t shndx,
278 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
280 const MCAsmLayout &Layout);
282 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
283 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
284 const MCAssembler &Asm,
285 const MCAsmLayout &Layout,
286 const SectionIndexMapTy &SectionIndexMap);
288 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
289 const MCFragment *Fragment, const MCFixup &Fixup,
290 MCValue Target, uint64_t &FixedValue);
292 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
295 // Map from a group section to the signature symbol
296 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
297 // Map from a signature symbol to the group section
298 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
300 /// ComputeSymbolTable - Compute the symbol table data
302 /// \param StringTable [out] - The string table data.
303 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
305 virtual void ComputeSymbolTable(MCAssembler &Asm,
306 const SectionIndexMapTy &SectionIndexMap,
307 RevGroupMapTy RevGroupMap);
309 virtual void ComputeIndexMap(MCAssembler &Asm,
310 SectionIndexMapTy &SectionIndexMap);
312 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
313 const MCSectionData &SD);
315 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
316 for (MCAssembler::const_iterator it = Asm.begin(),
317 ie = Asm.end(); it != ie; ++it) {
318 WriteRelocation(Asm, Layout, *it);
322 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
323 const SectionIndexMapTy &SectionIndexMap);
325 virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
326 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
328 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
329 const MCAsmLayout &Layout);
331 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
332 uint64_t Address, uint64_t Offset,
333 uint64_t Size, uint32_t Link, uint32_t Info,
334 uint64_t Alignment, uint64_t EntrySize);
336 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
338 const MCSectionData *SD);
341 IsSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
342 const MCSymbolRefExpr *A,
343 const MCSymbolRefExpr *B) const {
344 // FIXME: Implement this!
348 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
349 const MCValue Target,
351 const MCFragment *DF) const;
353 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
354 virtual void WriteSection(MCAssembler &Asm,
355 const SectionIndexMapTy &SectionIndexMap,
356 uint32_t GroupSymbolIndex,
357 uint64_t Offset, uint64_t Size, uint64_t Alignment,
358 const MCSectionELF &Section);
361 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
362 bool IsPCRel, bool IsRelocWithSymbol,
365 virtual bool isFixupKindPCRel(unsigned Kind) const = 0;
368 //===- X86ELFObjectWriter -------------------------------------------===//
370 class X86ELFObjectWriter : public ELFObjectWriter {
372 X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
373 uint16_t _EMachine, bool _HasRelAddend,
374 Triple::OSType _OSType);
376 virtual ~X86ELFObjectWriter();
378 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
379 bool IsPCRel, bool IsRelocWithSymbol,
382 virtual bool isFixupKindPCRel(unsigned Kind) const {
389 case X86::reloc_riprel_4byte:
390 case X86::reloc_riprel_4byte_movq_load:
397 //===- ARMELFObjectWriter -------------------------------------------===//
399 class ARMELFObjectWriter : public ELFObjectWriter {
401 ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
402 uint16_t _EMachine, bool _HasRelAddend,
403 Triple::OSType _OSType);
405 virtual ~ARMELFObjectWriter();
407 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
408 bool IsPCRel, bool IsRelocWithSymbol,
410 virtual bool isFixupKindPCRel(unsigned Kind) const {
417 case ARM::fixup_arm_ldst_pcrel_12:
418 case ARM::fixup_arm_pcrel_10:
419 case ARM::fixup_arm_branch:
425 //===- MBlazeELFObjectWriter -------------------------------------------===//
427 class MBlazeELFObjectWriter : public ELFObjectWriter {
429 MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
430 uint16_t _EMachine, bool _HasRelAddend,
431 Triple::OSType _OSType);
433 virtual ~MBlazeELFObjectWriter();
435 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
436 bool IsPCRel, bool IsRelocWithSymbol,
439 virtual bool isFixupKindPCRel(unsigned Kind) const {
452 ELFObjectWriter::~ELFObjectWriter()
455 // Emit the ELF header.
456 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
457 unsigned NumberOfSections) {
463 // emitWord method behaves differently for ELF32 and ELF64, writing
464 // 4 bytes in the former and 8 in the latter.
466 Write8(0x7f); // e_ident[EI_MAG0]
467 Write8('E'); // e_ident[EI_MAG1]
468 Write8('L'); // e_ident[EI_MAG2]
469 Write8('F'); // e_ident[EI_MAG3]
471 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
474 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
476 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
479 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
480 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
481 default: Write8(ELF::ELFOSABI_NONE); break;
483 Write8(0); // e_ident[EI_ABIVERSION]
485 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
487 Write16(ELF::ET_REL); // e_type
489 Write16(EMachine); // e_machine = target
491 Write32(ELF::EV_CURRENT); // e_version
492 WriteWord(0); // e_entry, no entry point in .o file
493 WriteWord(0); // e_phoff, no program header for .o
494 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
495 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
497 // FIXME: Make this configurable.
498 Write32(0); // e_flags = whatever the target wants
500 // e_ehsize = ELF header size
501 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
503 Write16(0); // e_phentsize = prog header entry size
504 Write16(0); // e_phnum = # prog header entries = 0
506 // e_shentsize = Section header entry size
507 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
509 // e_shnum = # of section header ents
510 if (NumberOfSections >= ELF::SHN_LORESERVE)
513 Write16(NumberOfSections);
515 // e_shstrndx = Section # of '.shstrtab'
516 if (NumberOfSections >= ELF::SHN_LORESERVE)
517 Write16(ELF::SHN_XINDEX);
519 Write16(ShstrtabIndex);
522 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
523 MCDataFragment *ShndxF,
525 uint8_t info, uint64_t value,
526 uint64_t size, uint8_t other,
530 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
531 String32(*ShndxF, shndx);
533 String32(*ShndxF, 0);
536 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
537 uint16_t(ELF::SHN_XINDEX) : shndx;
540 String32(*SymtabF, name); // st_name
541 String8(*SymtabF, info); // st_info
542 String8(*SymtabF, other); // st_other
543 String16(*SymtabF, Index); // st_shndx
544 String64(*SymtabF, value); // st_value
545 String64(*SymtabF, size); // st_size
547 String32(*SymtabF, name); // st_name
548 String32(*SymtabF, value); // st_value
549 String32(*SymtabF, size); // st_size
550 String8(*SymtabF, info); // st_info
551 String8(*SymtabF, other); // st_other
552 String16(*SymtabF, Index); // st_shndx
556 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
557 if (Data.isCommon() && Data.isExternal())
558 return Data.getCommonAlignment();
560 const MCSymbol &Symbol = Data.getSymbol();
561 if (!Symbol.isInSection())
564 if (Data.getFragment())
565 return Layout.getSymbolOffset(&Data);
570 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
571 const MCAsmLayout &Layout) {
572 // The presence of symbol versions causes undefined symbols and
573 // versions declared with @@@ to be renamed.
575 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
576 ie = Asm.symbol_end(); it != ie; ++it) {
577 const MCSymbol &Alias = it->getSymbol();
578 const MCSymbol &Symbol = Alias.AliasedSymbol();
579 MCSymbolData &SD = Asm.getSymbolData(Symbol);
582 if (&Symbol == &Alias)
585 StringRef AliasName = Alias.getName();
586 size_t Pos = AliasName.find('@');
587 if (Pos == StringRef::npos)
590 // Aliases defined with .symvar copy the binding from the symbol they alias.
591 // This is the first place we are able to copy this information.
592 it->setExternal(SD.isExternal());
593 SetBinding(*it, GetBinding(SD));
595 StringRef Rest = AliasName.substr(Pos);
596 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
599 // FIXME: produce a better error message.
600 if (Symbol.isUndefined() && Rest.startswith("@@") &&
601 !Rest.startswith("@@@"))
602 report_fatal_error("A @@ version cannot be undefined");
604 Renames.insert(std::make_pair(&Symbol, &Alias));
608 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
609 MCDataFragment *ShndxF,
611 const MCAsmLayout &Layout) {
612 MCSymbolData &OrigData = *MSD.SymbolData;
614 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
616 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
617 Data.getSymbol().isVariable();
619 uint8_t Binding = GetBinding(OrigData);
620 uint8_t Visibility = GetVisibility(OrigData);
621 uint8_t Type = GetType(Data);
623 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
624 uint8_t Other = Visibility;
626 uint64_t Value = SymbolValue(Data, Layout);
630 assert(!(Data.isCommon() && !Data.isExternal()));
632 ESize = Data.getSize();
633 if (Data.getSize()) {
635 if (ESize->getKind() == MCExpr::Binary) {
636 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
638 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
639 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
640 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
641 Size = Res.getConstant();
643 } else if (ESize->getKind() == MCExpr::Constant) {
644 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
646 assert(0 && "Unsupported size expression");
650 // Write out the symbol table entry
651 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
652 Size, Other, MSD.SectionIndex, IsReserved);
655 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
656 MCDataFragment *ShndxF,
657 const MCAssembler &Asm,
658 const MCAsmLayout &Layout,
659 const SectionIndexMapTy &SectionIndexMap) {
660 // The string table must be emitted first because we need the index
661 // into the string table for all the symbol names.
662 assert(StringTable.size() && "Missing string table");
664 // FIXME: Make sure the start of the symbol table is aligned.
666 // The first entry is the undefined symbol entry.
667 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
669 // Write the symbol table entries.
670 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
671 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
672 ELFSymbolData &MSD = LocalSymbolData[i];
673 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
676 // Write out a symbol table entry for each regular section.
677 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
679 const MCSectionELF &Section =
680 static_cast<const MCSectionELF&>(i->getSection());
681 if (Section.getType() == ELF::SHT_RELA ||
682 Section.getType() == ELF::SHT_REL ||
683 Section.getType() == ELF::SHT_STRTAB ||
684 Section.getType() == ELF::SHT_SYMTAB)
686 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
687 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
688 LastLocalSymbolIndex++;
691 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
692 ELFSymbolData &MSD = ExternalSymbolData[i];
693 MCSymbolData &Data = *MSD.SymbolData;
694 assert(((Data.getFlags() & ELF_STB_Global) ||
695 (Data.getFlags() & ELF_STB_Weak)) &&
696 "External symbol requires STB_GLOBAL or STB_WEAK flag");
697 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
698 if (GetBinding(Data) == ELF::STB_LOCAL)
699 LastLocalSymbolIndex++;
702 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
703 ELFSymbolData &MSD = UndefinedSymbolData[i];
704 MCSymbolData &Data = *MSD.SymbolData;
705 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
706 if (GetBinding(Data) == ELF::STB_LOCAL)
707 LastLocalSymbolIndex++;
711 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
712 const MCValue &Target,
713 const MCFragment &F) const {
714 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
715 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
716 const MCSymbol *Renamed = Renames.lookup(&Symbol);
717 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
719 if (ASymbol.isUndefined()) {
725 if (SD.isExternal()) {
731 const MCSectionELF &Section =
732 static_cast<const MCSectionELF&>(ASymbol.getSection());
733 const SectionKind secKind = Section.getKind();
738 if (secKind.isThreadLocal()) {
744 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
745 const MCSectionELF &Sec2 =
746 static_cast<const MCSectionELF&>(F.getParent()->getSection());
748 if (&Sec2 != &Section &&
749 (Kind == MCSymbolRefExpr::VK_PLT ||
750 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
751 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
757 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
758 if (Target.getConstant() == 0)
769 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
770 const MCAsmLayout &Layout,
771 const MCFragment *Fragment,
772 const MCFixup &Fixup,
774 uint64_t &FixedValue) {
777 int64_t Value = Target.getConstant();
778 const MCSymbol *RelocSymbol = NULL;
780 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
781 if (!Target.isAbsolute()) {
782 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
783 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
784 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
786 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
787 const MCSymbol &SymbolB = RefB->getSymbol();
788 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
791 // Offset of the symbol in the section
792 int64_t a = Layout.getSymbolOffset(&SDB);
794 // Ofeset of the relocation in the section
795 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
800 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
801 MCFragment *F = SD.getFragment();
803 Index = F->getParent()->getOrdinal() + 1;
805 // Offset of the symbol in the section
806 Value += Layout.getSymbolOffset(&SD);
808 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
809 WeakrefUsedInReloc.insert(RelocSymbol);
811 UsedInReloc.insert(RelocSymbol);
815 // Compensate for the addend on i386.
821 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
822 (RelocSymbol != 0), Addend);
824 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
827 if (!HasRelocationAddend) Addend = 0;
828 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
829 Relocations[Fragment->getParent()].push_back(ERE);
834 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
836 MCSymbolData &SD = Asm.getSymbolData(*S);
837 return SD.getIndex();
840 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
841 bool Used, bool Renamed) {
842 if (Data.getFlags() & ELF_Other_Weakref)
851 const MCSymbol &Symbol = Data.getSymbol();
853 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
856 const MCSymbol &A = Symbol.AliasedSymbol();
857 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
860 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
863 if (Symbol.isTemporary())
869 static bool isLocal(const MCSymbolData &Data, bool isSignature,
870 bool isUsedInReloc) {
871 if (Data.isExternal())
874 const MCSymbol &Symbol = Data.getSymbol();
875 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
877 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
878 if (isSignature && !isUsedInReloc)
887 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
888 SectionIndexMapTy &SectionIndexMap) {
890 for (MCAssembler::iterator it = Asm.begin(),
891 ie = Asm.end(); it != ie; ++it) {
892 const MCSectionELF &Section =
893 static_cast<const MCSectionELF &>(it->getSection());
894 if (Section.getType() != ELF::SHT_GROUP)
896 SectionIndexMap[&Section] = Index++;
899 for (MCAssembler::iterator it = Asm.begin(),
900 ie = Asm.end(); it != ie; ++it) {
901 const MCSectionELF &Section =
902 static_cast<const MCSectionELF &>(it->getSection());
903 if (Section.getType() == ELF::SHT_GROUP)
905 SectionIndexMap[&Section] = Index++;
909 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
910 const SectionIndexMapTy &SectionIndexMap,
911 RevGroupMapTy RevGroupMap) {
912 // FIXME: Is this the correct place to do this?
914 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
915 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
916 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
917 Data.setExternal(true);
918 SetBinding(Data, ELF::STB_GLOBAL);
921 // Build section lookup table.
922 int NumRegularSections = Asm.size();
924 // Index 0 is always the empty string.
925 StringMap<uint64_t> StringIndexMap;
926 StringTable += '\x00';
928 // Add the data for the symbols.
929 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
930 ie = Asm.symbol_end(); it != ie; ++it) {
931 const MCSymbol &Symbol = it->getSymbol();
933 bool Used = UsedInReloc.count(&Symbol);
934 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
935 bool isSignature = RevGroupMap.count(&Symbol);
937 if (!isInSymtab(Asm, *it,
938 Used || WeakrefUsed || isSignature,
939 Renames.count(&Symbol)))
944 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
946 // Undefined symbols are global, but this is the first place we
947 // are able to set it.
948 bool Local = isLocal(*it, isSignature, Used);
949 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
950 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
951 SetBinding(*it, ELF::STB_GLOBAL);
952 SetBinding(SD, ELF::STB_GLOBAL);
955 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
956 SetBinding(*it, ELF::STB_WEAK);
958 if (it->isCommon()) {
960 MSD.SectionIndex = ELF::SHN_COMMON;
961 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
962 MSD.SectionIndex = ELF::SHN_ABS;
963 } else if (RefSymbol.isUndefined()) {
964 if (isSignature && !Used)
965 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
967 MSD.SectionIndex = ELF::SHN_UNDEF;
969 const MCSectionELF &Section =
970 static_cast<const MCSectionELF&>(RefSymbol.getSection());
971 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
972 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
973 NeedsSymtabShndx = true;
974 assert(MSD.SectionIndex && "Invalid section index!");
977 // The @@@ in symbol version is replaced with @ in undefined symbols and
978 // @@ in defined ones.
979 StringRef Name = Symbol.getName();
982 size_t Pos = Name.find("@@@");
983 if (Pos != StringRef::npos) {
984 Buf += Name.substr(0, Pos);
985 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
986 Buf += Name.substr(Pos + Skip);
990 uint64_t &Entry = StringIndexMap[Name];
992 Entry = StringTable.size();
994 StringTable += '\x00';
996 MSD.StringIndex = Entry;
997 if (MSD.SectionIndex == ELF::SHN_UNDEF)
998 UndefinedSymbolData.push_back(MSD);
1000 LocalSymbolData.push_back(MSD);
1002 ExternalSymbolData.push_back(MSD);
1005 // Symbols are required to be in lexicographic order.
1006 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1007 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1008 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1010 // Set the symbol indices. Local symbols must come before all other
1011 // symbols with non-local bindings.
1013 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1014 LocalSymbolData[i].SymbolData->setIndex(Index++);
1016 Index += NumRegularSections;
1018 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1019 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1020 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1021 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1024 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1025 const MCSectionData &SD) {
1026 if (!Relocations[&SD].empty()) {
1027 MCContext &Ctx = Asm.getContext();
1028 const MCSectionELF *RelaSection;
1029 const MCSectionELF &Section =
1030 static_cast<const MCSectionELF&>(SD.getSection());
1032 const StringRef SectionName = Section.getSectionName();
1033 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1034 RelaSectionName += SectionName;
1037 if (HasRelocationAddend)
1038 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1040 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1042 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1043 ELF::SHT_RELA : ELF::SHT_REL, 0,
1044 SectionKind::getReadOnly(),
1047 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1048 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1050 MCDataFragment *F = new MCDataFragment(&RelaSD);
1052 WriteRelocationsFragment(Asm, F, &SD);
1056 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1057 uint64_t Flags, uint64_t Address,
1058 uint64_t Offset, uint64_t Size,
1059 uint32_t Link, uint32_t Info,
1061 uint64_t EntrySize) {
1062 Write32(Name); // sh_name: index into string table
1063 Write32(Type); // sh_type
1064 WriteWord(Flags); // sh_flags
1065 WriteWord(Address); // sh_addr
1066 WriteWord(Offset); // sh_offset
1067 WriteWord(Size); // sh_size
1068 Write32(Link); // sh_link
1069 Write32(Info); // sh_info
1070 WriteWord(Alignment); // sh_addralign
1071 WriteWord(EntrySize); // sh_entsize
1074 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1076 const MCSectionData *SD) {
1077 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1078 // sort by the r_offset just like gnu as does
1079 array_pod_sort(Relocs.begin(), Relocs.end());
1081 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1082 ELFRelocationEntry entry = Relocs[e - i - 1];
1086 else if (entry.Index < 0)
1087 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1089 entry.Index += LocalSymbolData.size();
1091 String64(*F, entry.r_offset);
1093 struct ELF::Elf64_Rela ERE64;
1094 ERE64.setSymbolAndType(entry.Index, entry.Type);
1095 String64(*F, ERE64.r_info);
1097 if (HasRelocationAddend)
1098 String64(*F, entry.r_addend);
1100 String32(*F, entry.r_offset);
1102 struct ELF::Elf32_Rela ERE32;
1103 ERE32.setSymbolAndType(entry.Index, entry.Type);
1104 String32(*F, ERE32.r_info);
1106 if (HasRelocationAddend)
1107 String32(*F, entry.r_addend);
1112 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1113 MCAsmLayout &Layout,
1114 const SectionIndexMapTy &SectionIndexMap) {
1115 MCContext &Ctx = Asm.getContext();
1118 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1120 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1121 const MCSectionELF *ShstrtabSection =
1122 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1123 SectionKind::getReadOnly());
1124 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1125 ShstrtabSD.setAlignment(1);
1126 ShstrtabIndex = Asm.size();
1128 const MCSectionELF *SymtabSection =
1129 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1130 SectionKind::getReadOnly(),
1132 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1133 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1134 SymbolTableIndex = Asm.size();
1136 MCSectionData *SymtabShndxSD = NULL;
1138 if (NeedsSymtabShndx) {
1139 const MCSectionELF *SymtabShndxSection =
1140 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1141 SectionKind::getReadOnly(), 4, "");
1142 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1143 SymtabShndxSD->setAlignment(4);
1146 const MCSection *StrtabSection;
1147 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1148 SectionKind::getReadOnly());
1149 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1150 StrtabSD.setAlignment(1);
1151 StringTableIndex = Asm.size();
1153 WriteRelocations(Asm, Layout);
1156 F = new MCDataFragment(&SymtabSD);
1157 MCDataFragment *ShndxF = NULL;
1158 if (NeedsSymtabShndx) {
1159 ShndxF = new MCDataFragment(SymtabShndxSD);
1161 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1163 F = new MCDataFragment(&StrtabSD);
1164 F->getContents().append(StringTable.begin(), StringTable.end());
1166 F = new MCDataFragment(&ShstrtabSD);
1168 // Section header string table.
1170 // The first entry of a string table holds a null character so skip
1173 F->getContents() += '\x00';
1175 StringMap<uint64_t> SecStringMap;
1176 for (MCAssembler::const_iterator it = Asm.begin(),
1177 ie = Asm.end(); it != ie; ++it) {
1178 const MCSectionELF &Section =
1179 static_cast<const MCSectionELF&>(it->getSection());
1180 // FIXME: We could merge suffixes like in .text and .rela.text.
1182 StringRef Name = Section.getSectionName();
1183 if (SecStringMap.count(Name)) {
1184 SectionStringTableIndex[&Section] = SecStringMap[Name];
1187 // Remember the index into the string table so we can write it
1188 // into the sh_name field of the section header table.
1189 SectionStringTableIndex[&Section] = Index;
1190 SecStringMap[Name] = Index;
1192 Index += Name.size() + 1;
1193 F->getContents() += Name;
1194 F->getContents() += '\x00';
1198 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1199 const MCValue Target,
1201 const MCFragment *DF) const {
1202 // If this is a PCrel relocation, find the section this fixup value is
1204 const MCSection *BaseSection = 0;
1206 BaseSection = &DF->getParent()->getSection();
1207 assert(BaseSection);
1210 const MCSection *SectionA = 0;
1211 const MCSymbol *SymbolA = 0;
1212 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1213 SymbolA = &A->getSymbol();
1214 SectionA = &SymbolA->AliasedSymbol().getSection();
1217 const MCSection *SectionB = 0;
1218 const MCSymbol *SymbolB = 0;
1219 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1220 SymbolB = &B->getSymbol();
1221 SectionB = &SymbolB->AliasedSymbol().getSection();
1225 return SectionA == SectionB;
1230 // Absolute address but PCrel instruction, so we need a relocation.
1234 // FIXME: This is in here just to match gnu as output. If the two ends
1235 // are in the same section, there is nothing that the linker can do to
1237 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1238 if (DataA.isExternal())
1241 return BaseSection == SectionA;
1244 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1245 MCAsmLayout &Layout,
1246 GroupMapTy &GroupMap,
1247 RevGroupMapTy &RevGroupMap) {
1249 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1251 const MCSectionELF &Section =
1252 static_cast<const MCSectionELF&>(it->getSection());
1253 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1256 const MCSymbol *SignatureSymbol = Section.getGroup();
1257 Asm.getOrCreateSymbolData(*SignatureSymbol);
1258 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1260 Group = Asm.getContext().CreateELFGroupSection();
1261 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1262 Data.setAlignment(4);
1263 MCDataFragment *F = new MCDataFragment(&Data);
1264 String32(*F, ELF::GRP_COMDAT);
1266 GroupMap[Group] = SignatureSymbol;
1269 // Add sections to the groups
1271 unsigned NumGroups = RevGroupMap.size();
1272 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1273 it != ie; ++it, ++Index) {
1274 const MCSectionELF &Section =
1275 static_cast<const MCSectionELF&>(it->getSection());
1276 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1278 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1279 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1280 // FIXME: we could use the previous fragment
1281 MCDataFragment *F = new MCDataFragment(&Data);
1282 String32(*F, NumGroups + Index);
1286 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1287 const SectionIndexMapTy &SectionIndexMap,
1288 uint32_t GroupSymbolIndex,
1289 uint64_t Offset, uint64_t Size,
1291 const MCSectionELF &Section) {
1292 uint64_t sh_link = 0;
1293 uint64_t sh_info = 0;
1295 switch(Section.getType()) {
1296 case ELF::SHT_DYNAMIC:
1297 sh_link = SectionStringTableIndex[&Section];
1302 case ELF::SHT_RELA: {
1303 const MCSectionELF *SymtabSection;
1304 const MCSectionELF *InfoSection;
1305 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1307 SectionKind::getReadOnly());
1308 sh_link = SectionIndexMap.lookup(SymtabSection);
1309 assert(sh_link && ".symtab not found");
1311 // Remove ".rel" and ".rela" prefixes.
1312 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1313 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1315 InfoSection = Asm.getContext().getELFSection(SectionName,
1316 ELF::SHT_PROGBITS, 0,
1317 SectionKind::getReadOnly());
1318 sh_info = SectionIndexMap.lookup(InfoSection);
1322 case ELF::SHT_SYMTAB:
1323 case ELF::SHT_DYNSYM:
1324 sh_link = StringTableIndex;
1325 sh_info = LastLocalSymbolIndex;
1328 case ELF::SHT_SYMTAB_SHNDX:
1329 sh_link = SymbolTableIndex;
1332 case ELF::SHT_PROGBITS:
1333 case ELF::SHT_STRTAB:
1334 case ELF::SHT_NOBITS:
1336 case ELF::SHT_ARM_ATTRIBUTES:
1340 case ELF::SHT_GROUP: {
1341 sh_link = SymbolTableIndex;
1342 sh_info = GroupSymbolIndex;
1347 assert(0 && "FIXME: sh_type value not supported!");
1351 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1352 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1353 Alignment, Section.getEntrySize());
1356 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1357 return SD.getOrdinal() == ~UINT32_C(0) &&
1358 !SD.getSection().isVirtualSection();
1361 static uint64_t DataSectionSize(const MCSectionData &SD) {
1363 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1365 const MCFragment &F = *i;
1366 assert(F.getKind() == MCFragment::FT_Data);
1367 Ret += cast<MCDataFragment>(F).getContents().size();
1372 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1373 const MCSectionData &SD) {
1374 if (IsELFMetaDataSection(SD))
1375 return DataSectionSize(SD);
1376 return Layout.getSectionFileSize(&SD);
1379 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1380 const MCSectionData &SD) {
1381 if (IsELFMetaDataSection(SD))
1382 return DataSectionSize(SD);
1383 return Layout.getSectionAddressSize(&SD);
1386 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1387 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1389 const MCFragment &F = *i;
1390 assert(F.getKind() == MCFragment::FT_Data);
1391 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1395 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1396 const MCAsmLayout &Layout) {
1397 GroupMapTy GroupMap;
1398 RevGroupMapTy RevGroupMap;
1399 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1402 SectionIndexMapTy SectionIndexMap;
1404 ComputeIndexMap(Asm, SectionIndexMap);
1406 // Compute symbol table information.
1407 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1409 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1410 const_cast<MCAsmLayout&>(Layout),
1413 // Update to include the metadata sections.
1414 ComputeIndexMap(Asm, SectionIndexMap);
1416 // Add 1 for the null section.
1417 unsigned NumSections = Asm.size() + 1;
1418 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1419 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1420 uint64_t FileOff = HeaderSize;
1422 std::vector<const MCSectionELF*> Sections;
1423 Sections.resize(NumSections);
1425 for (SectionIndexMapTy::const_iterator i=
1426 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1427 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1428 Sections[p.second] = p.first;
1431 for (unsigned i = 1; i < NumSections; ++i) {
1432 const MCSectionELF &Section = *Sections[i];
1433 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1435 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1437 // Get the size of the section in the output file (including padding).
1438 FileOff += GetSectionFileSize(Layout, SD);
1441 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1443 // Write out the ELF header ...
1444 WriteHeader(FileOff - HeaderSize, NumSections);
1446 FileOff = HeaderSize;
1448 // ... then all of the sections ...
1449 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1451 for (unsigned i = 1; i < NumSections; ++i) {
1452 const MCSectionELF &Section = *Sections[i];
1453 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1455 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1456 WriteZeros(Padding);
1459 // Remember the offset into the file for this section.
1460 SectionOffsetMap[&Section] = FileOff;
1462 FileOff += GetSectionFileSize(Layout, SD);
1464 if (IsELFMetaDataSection(SD))
1465 WriteDataSectionData(this, SD);
1467 Asm.WriteSectionData(&SD, Layout);
1470 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1471 WriteZeros(Padding);
1474 // ... and then the section header table.
1475 // Should we align the section header table?
1477 // Null section first.
1478 uint64_t FirstSectionSize =
1479 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1480 uint32_t FirstSectionLink =
1481 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1482 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1484 for (unsigned i = 1; i < NumSections; ++i) {
1485 const MCSectionELF &Section = *Sections[i];
1486 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1487 uint32_t GroupSymbolIndex;
1488 if (Section.getType() != ELF::SHT_GROUP)
1489 GroupSymbolIndex = 0;
1491 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1493 uint64_t Size = GetSectionAddressSize(Layout, SD);
1495 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1496 SectionOffsetMap[&Section], Size,
1497 SD.getAlignment(), Section);
1501 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1503 Triple::OSType OSType,
1505 bool IsLittleEndian,
1506 bool HasRelocationAddend) {
1509 case ELF::EM_X86_64:
1510 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1511 HasRelocationAddend, OSType); break;
1513 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1514 HasRelocationAddend, OSType); break;
1515 case ELF::EM_MBLAZE:
1516 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1517 HasRelocationAddend, OSType); break;
1518 default: llvm_unreachable("Unsupported architecture"); break;
1523 /// START OF SUBCLASSES for ELFObjectWriter
1524 //===- ARMELFObjectWriter -------------------------------------------===//
1526 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1527 bool _IsLittleEndian,
1528 uint16_t _EMachine, bool _HasRelocationAddend,
1529 Triple::OSType _OSType)
1530 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1531 _HasRelocationAddend, _OSType)
1534 ARMELFObjectWriter::~ARMELFObjectWriter()
1537 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1538 const MCFixup &Fixup,
1540 bool IsRelocWithSymbol,
1542 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1543 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1547 switch ((unsigned)Fixup.getKind()) {
1548 default: assert(0 && "Unimplemented");
1551 default: llvm_unreachable("Unsupported Modifier");
1552 case MCSymbolRefExpr::VK_None:
1553 Type = ELF::R_ARM_BASE_PREL; break;
1554 case MCSymbolRefExpr::VK_ARM_TLSGD:
1555 assert(0 && "unimplemented"); break;
1556 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1557 Type = ELF::R_ARM_TLS_IE32;
1559 case ARM::fixup_arm_branch:
1561 case MCSymbolRefExpr::VK_ARM_PLT:
1562 Type = ELF::R_ARM_PLT32; break;
1564 Type = ELF::R_ARM_CALL; break;
1568 switch ((unsigned)Fixup.getKind()) {
1569 default: llvm_unreachable("invalid fixup kind!");
1572 default: llvm_unreachable("Unsupported Modifier"); break;
1573 case MCSymbolRefExpr::VK_ARM_GOT:
1574 Type = ELF::R_ARM_GOT_BREL; break;
1575 case MCSymbolRefExpr::VK_ARM_TLSGD:
1576 Type = ELF::R_ARM_TLS_GD32; break;
1577 case MCSymbolRefExpr::VK_ARM_TPOFF:
1578 Type = ELF::R_ARM_TLS_LE32; break;
1579 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1580 Type = ELF::R_ARM_TLS_IE32; break;
1581 case MCSymbolRefExpr::VK_None:
1582 Type = ELF::R_ARM_ABS32; break;
1583 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1584 Type = ELF::R_ARM_GOTOFF32; break;
1586 case ARM::fixup_arm_ldst_pcrel_12:
1587 case ARM::fixup_arm_pcrel_10:
1588 case ARM::fixup_arm_adr_pcrel_12:
1589 case ARM::fixup_arm_thumb_bl:
1590 case ARM::fixup_arm_thumb_cb:
1591 case ARM::fixup_arm_thumb_cp:
1592 case ARM::fixup_arm_thumb_br:
1593 assert(0 && "Unimplemented"); break;
1594 case ARM::fixup_arm_branch:
1595 // FIXME: Differentiate between R_ARM_CALL and
1596 // R_ARM_JUMP24 (latter used for conditional jumps)
1597 Type = ELF::R_ARM_CALL; break;
1598 case ARM::fixup_arm_movt_hi16:
1599 Type = ELF::R_ARM_MOVT_ABS; break;
1600 case ARM::fixup_arm_movw_lo16:
1601 Type = ELF::R_ARM_MOVW_ABS_NC; break;
1605 if (RelocNeedsGOT(Modifier))
1611 //===- MBlazeELFObjectWriter -------------------------------------------===//
1613 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1614 bool _IsLittleEndian,
1616 bool _HasRelocationAddend,
1617 Triple::OSType _OSType)
1618 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1619 _HasRelocationAddend, _OSType) {
1622 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1625 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1626 const MCFixup &Fixup,
1628 bool IsRelocWithSymbol,
1630 // determine the type of the relocation
1633 switch ((unsigned)Fixup.getKind()) {
1635 llvm_unreachable("Unimplemented");
1637 Type = ELF::R_MICROBLAZE_64_PCREL;
1640 Type = ELF::R_MICROBLAZE_32_PCREL;
1644 switch ((unsigned)Fixup.getKind()) {
1645 default: llvm_unreachable("invalid fixup kind!");
1647 Type = ((IsRelocWithSymbol || Addend !=0)
1648 ? ELF::R_MICROBLAZE_32
1649 : ELF::R_MICROBLAZE_64);
1652 Type = ELF::R_MICROBLAZE_32;
1659 //===- X86ELFObjectWriter -------------------------------------------===//
1662 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1663 bool _IsLittleEndian,
1664 uint16_t _EMachine, bool _HasRelocationAddend,
1665 Triple::OSType _OSType)
1666 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1667 _HasRelocationAddend, _OSType)
1670 X86ELFObjectWriter::~X86ELFObjectWriter()
1673 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1674 const MCFixup &Fixup,
1676 bool IsRelocWithSymbol,
1678 // determine the type of the relocation
1680 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1681 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1687 llvm_unreachable("Unimplemented");
1688 case MCSymbolRefExpr::VK_None:
1689 Type = ELF::R_X86_64_PC32;
1691 case MCSymbolRefExpr::VK_PLT:
1692 Type = ELF::R_X86_64_PLT32;
1694 case MCSymbolRefExpr::VK_GOTPCREL:
1695 Type = ELF::R_X86_64_GOTPCREL;
1697 case MCSymbolRefExpr::VK_GOTTPOFF:
1698 Type = ELF::R_X86_64_GOTTPOFF;
1700 case MCSymbolRefExpr::VK_TLSGD:
1701 Type = ELF::R_X86_64_TLSGD;
1703 case MCSymbolRefExpr::VK_TLSLD:
1704 Type = ELF::R_X86_64_TLSLD;
1708 switch ((unsigned)Fixup.getKind()) {
1709 default: llvm_unreachable("invalid fixup kind!");
1710 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1711 case X86::reloc_signed_4byte:
1713 assert(isInt<32>(Target.getConstant()));
1716 llvm_unreachable("Unimplemented");
1717 case MCSymbolRefExpr::VK_None:
1718 Type = ELF::R_X86_64_32S;
1720 case MCSymbolRefExpr::VK_GOT:
1721 Type = ELF::R_X86_64_GOT32;
1723 case MCSymbolRefExpr::VK_GOTPCREL:
1724 Type = ELF::R_X86_64_GOTPCREL;
1726 case MCSymbolRefExpr::VK_TPOFF:
1727 Type = ELF::R_X86_64_TPOFF32;
1729 case MCSymbolRefExpr::VK_DTPOFF:
1730 Type = ELF::R_X86_64_DTPOFF32;
1735 Type = ELF::R_X86_64_32;
1737 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1739 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1746 llvm_unreachable("Unimplemented");
1747 case MCSymbolRefExpr::VK_None:
1748 Type = ELF::R_386_PC32;
1750 case MCSymbolRefExpr::VK_PLT:
1751 Type = ELF::R_386_PLT32;
1755 switch ((unsigned)Fixup.getKind()) {
1756 default: llvm_unreachable("invalid fixup kind!");
1758 case X86::reloc_global_offset_table:
1759 Type = ELF::R_386_GOTPC;
1762 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1764 case X86::reloc_signed_4byte:
1769 llvm_unreachable("Unimplemented");
1770 case MCSymbolRefExpr::VK_None:
1771 Type = ELF::R_386_32;
1773 case MCSymbolRefExpr::VK_GOT:
1774 Type = ELF::R_386_GOT32;
1776 case MCSymbolRefExpr::VK_GOTOFF:
1777 Type = ELF::R_386_GOTOFF;
1779 case MCSymbolRefExpr::VK_TLSGD:
1780 Type = ELF::R_386_TLS_GD;
1782 case MCSymbolRefExpr::VK_TPOFF:
1783 Type = ELF::R_386_TLS_LE_32;
1785 case MCSymbolRefExpr::VK_INDNTPOFF:
1786 Type = ELF::R_386_TLS_IE;
1788 case MCSymbolRefExpr::VK_NTPOFF:
1789 Type = ELF::R_386_TLS_LE;
1791 case MCSymbolRefExpr::VK_GOTNTPOFF:
1792 Type = ELF::R_386_TLS_GOTIE;
1794 case MCSymbolRefExpr::VK_TLSLDM:
1795 Type = ELF::R_386_TLS_LDM;
1797 case MCSymbolRefExpr::VK_DTPOFF:
1798 Type = ELF::R_386_TLS_LDO_32;
1802 case FK_Data_2: Type = ELF::R_386_16; break;
1804 case FK_Data_1: Type = ELF::R_386_8; break;
1809 if (RelocNeedsGOT(Modifier))