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, MCDataFragment *F,
337 const MCSectionData *SD);
339 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
340 const MCValue Target,
342 const MCFragment *DF) const;
344 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
345 virtual void WriteSection(MCAssembler &Asm,
346 const SectionIndexMapTy &SectionIndexMap,
347 uint32_t GroupSymbolIndex,
348 uint64_t Offset, uint64_t Size, uint64_t Alignment,
349 const MCSectionELF &Section);
352 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
353 bool IsPCRel, bool IsRelocWithSymbol,
356 virtual bool isFixupKindPCRel(unsigned Kind) const = 0;
359 //===- X86ELFObjectWriter -------------------------------------------===//
361 class X86ELFObjectWriter : public ELFObjectWriter {
363 X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
364 uint16_t _EMachine, bool _HasRelAddend,
365 Triple::OSType _OSType);
367 virtual ~X86ELFObjectWriter();
369 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
370 bool IsPCRel, bool IsRelocWithSymbol,
373 virtual bool isFixupKindPCRel(unsigned Kind) const {
380 case X86::reloc_riprel_4byte:
381 case X86::reloc_riprel_4byte_movq_load:
388 //===- ARMELFObjectWriter -------------------------------------------===//
390 class ARMELFObjectWriter : public ELFObjectWriter {
392 ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
393 uint16_t _EMachine, bool _HasRelAddend,
394 Triple::OSType _OSType);
396 virtual ~ARMELFObjectWriter();
398 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
399 bool IsPCRel, bool IsRelocWithSymbol,
401 virtual bool isFixupKindPCRel(unsigned Kind) const {
408 case ARM::fixup_arm_ldst_pcrel_12:
409 case ARM::fixup_arm_pcrel_10:
410 case ARM::fixup_arm_branch:
416 //===- MBlazeELFObjectWriter -------------------------------------------===//
418 class MBlazeELFObjectWriter : public ELFObjectWriter {
420 MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
421 uint16_t _EMachine, bool _HasRelAddend,
422 Triple::OSType _OSType);
424 virtual ~MBlazeELFObjectWriter();
426 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
427 bool IsPCRel, bool IsRelocWithSymbol,
430 virtual bool isFixupKindPCRel(unsigned Kind) const {
443 ELFObjectWriter::~ELFObjectWriter()
446 // Emit the ELF header.
447 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
448 unsigned NumberOfSections) {
454 // emitWord method behaves differently for ELF32 and ELF64, writing
455 // 4 bytes in the former and 8 in the latter.
457 Write8(0x7f); // e_ident[EI_MAG0]
458 Write8('E'); // e_ident[EI_MAG1]
459 Write8('L'); // e_ident[EI_MAG2]
460 Write8('F'); // e_ident[EI_MAG3]
462 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
465 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
467 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
470 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
471 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
472 default: Write8(ELF::ELFOSABI_NONE); break;
474 Write8(0); // e_ident[EI_ABIVERSION]
476 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
478 Write16(ELF::ET_REL); // e_type
480 Write16(EMachine); // e_machine = target
482 Write32(ELF::EV_CURRENT); // e_version
483 WriteWord(0); // e_entry, no entry point in .o file
484 WriteWord(0); // e_phoff, no program header for .o
485 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
486 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
488 // FIXME: Make this configurable.
489 Write32(0); // e_flags = whatever the target wants
491 // e_ehsize = ELF header size
492 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
494 Write16(0); // e_phentsize = prog header entry size
495 Write16(0); // e_phnum = # prog header entries = 0
497 // e_shentsize = Section header entry size
498 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
500 // e_shnum = # of section header ents
501 if (NumberOfSections >= ELF::SHN_LORESERVE)
504 Write16(NumberOfSections);
506 // e_shstrndx = Section # of '.shstrtab'
507 if (NumberOfSections >= ELF::SHN_LORESERVE)
508 Write16(ELF::SHN_XINDEX);
510 Write16(ShstrtabIndex);
513 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
514 MCDataFragment *ShndxF,
516 uint8_t info, uint64_t value,
517 uint64_t size, uint8_t other,
521 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
522 String32(*ShndxF, shndx);
524 String32(*ShndxF, 0);
527 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
528 uint16_t(ELF::SHN_XINDEX) : shndx;
531 String32(*SymtabF, name); // st_name
532 String8(*SymtabF, info); // st_info
533 String8(*SymtabF, other); // st_other
534 String16(*SymtabF, Index); // st_shndx
535 String64(*SymtabF, value); // st_value
536 String64(*SymtabF, size); // st_size
538 String32(*SymtabF, name); // st_name
539 String32(*SymtabF, value); // st_value
540 String32(*SymtabF, size); // st_size
541 String8(*SymtabF, info); // st_info
542 String8(*SymtabF, other); // st_other
543 String16(*SymtabF, Index); // st_shndx
547 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
548 if (Data.isCommon() && Data.isExternal())
549 return Data.getCommonAlignment();
551 const MCSymbol &Symbol = Data.getSymbol();
552 if (!Symbol.isInSection())
555 if (Data.getFragment())
556 return Layout.getSymbolOffset(&Data);
561 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
562 const MCAsmLayout &Layout) {
563 // The presence of symbol versions causes undefined symbols and
564 // versions declared with @@@ to be renamed.
566 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
567 ie = Asm.symbol_end(); it != ie; ++it) {
568 const MCSymbol &Alias = it->getSymbol();
569 const MCSymbol &Symbol = Alias.AliasedSymbol();
570 MCSymbolData &SD = Asm.getSymbolData(Symbol);
573 if (&Symbol == &Alias)
576 StringRef AliasName = Alias.getName();
577 size_t Pos = AliasName.find('@');
578 if (Pos == StringRef::npos)
581 // Aliases defined with .symvar copy the binding from the symbol they alias.
582 // This is the first place we are able to copy this information.
583 it->setExternal(SD.isExternal());
584 SetBinding(*it, GetBinding(SD));
586 StringRef Rest = AliasName.substr(Pos);
587 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
590 // FIXME: produce a better error message.
591 if (Symbol.isUndefined() && Rest.startswith("@@") &&
592 !Rest.startswith("@@@"))
593 report_fatal_error("A @@ version cannot be undefined");
595 Renames.insert(std::make_pair(&Symbol, &Alias));
599 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
600 MCDataFragment *ShndxF,
602 const MCAsmLayout &Layout) {
603 MCSymbolData &OrigData = *MSD.SymbolData;
605 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
607 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
608 Data.getSymbol().isVariable();
610 uint8_t Binding = GetBinding(OrigData);
611 uint8_t Visibility = GetVisibility(OrigData);
612 uint8_t Type = GetType(Data);
614 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
615 uint8_t Other = Visibility;
617 uint64_t Value = SymbolValue(Data, Layout);
621 assert(!(Data.isCommon() && !Data.isExternal()));
623 ESize = Data.getSize();
624 if (Data.getSize()) {
626 if (ESize->getKind() == MCExpr::Binary) {
627 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
629 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
630 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
631 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
632 Size = Res.getConstant();
634 } else if (ESize->getKind() == MCExpr::Constant) {
635 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
637 assert(0 && "Unsupported size expression");
641 // Write out the symbol table entry
642 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
643 Size, Other, MSD.SectionIndex, IsReserved);
646 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
647 MCDataFragment *ShndxF,
648 const MCAssembler &Asm,
649 const MCAsmLayout &Layout,
650 const SectionIndexMapTy &SectionIndexMap) {
651 // The string table must be emitted first because we need the index
652 // into the string table for all the symbol names.
653 assert(StringTable.size() && "Missing string table");
655 // FIXME: Make sure the start of the symbol table is aligned.
657 // The first entry is the undefined symbol entry.
658 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
660 // Write the symbol table entries.
661 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
662 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
663 ELFSymbolData &MSD = LocalSymbolData[i];
664 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
667 // Write out a symbol table entry for each regular section.
668 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
670 const MCSectionELF &Section =
671 static_cast<const MCSectionELF&>(i->getSection());
672 if (Section.getType() == ELF::SHT_RELA ||
673 Section.getType() == ELF::SHT_REL ||
674 Section.getType() == ELF::SHT_STRTAB ||
675 Section.getType() == ELF::SHT_SYMTAB)
677 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
678 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
679 LastLocalSymbolIndex++;
682 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
683 ELFSymbolData &MSD = ExternalSymbolData[i];
684 MCSymbolData &Data = *MSD.SymbolData;
685 assert(((Data.getFlags() & ELF_STB_Global) ||
686 (Data.getFlags() & ELF_STB_Weak)) &&
687 "External symbol requires STB_GLOBAL or STB_WEAK flag");
688 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
689 if (GetBinding(Data) == ELF::STB_LOCAL)
690 LastLocalSymbolIndex++;
693 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
694 ELFSymbolData &MSD = UndefinedSymbolData[i];
695 MCSymbolData &Data = *MSD.SymbolData;
696 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
697 if (GetBinding(Data) == ELF::STB_LOCAL)
698 LastLocalSymbolIndex++;
702 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
703 const MCValue &Target,
704 const MCFragment &F) const {
705 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
706 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
707 const MCSymbol *Renamed = Renames.lookup(&Symbol);
708 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
710 if (ASymbol.isUndefined()) {
716 if (SD.isExternal()) {
722 const MCSectionELF &Section =
723 static_cast<const MCSectionELF&>(ASymbol.getSection());
724 const SectionKind secKind = Section.getKind();
729 if (secKind.isThreadLocal()) {
735 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
736 const MCSectionELF &Sec2 =
737 static_cast<const MCSectionELF&>(F.getParent()->getSection());
739 if (&Sec2 != &Section &&
740 (Kind == MCSymbolRefExpr::VK_PLT ||
741 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
742 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
748 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
749 if (Target.getConstant() == 0)
760 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
761 const MCAsmLayout &Layout,
762 const MCFragment *Fragment,
763 const MCFixup &Fixup,
765 uint64_t &FixedValue) {
768 int64_t Value = Target.getConstant();
769 const MCSymbol *RelocSymbol = NULL;
771 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
772 if (!Target.isAbsolute()) {
773 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
774 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
775 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
777 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
778 const MCSymbol &SymbolB = RefB->getSymbol();
779 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
782 // Offset of the symbol in the section
783 int64_t a = Layout.getSymbolOffset(&SDB);
785 // Ofeset of the relocation in the section
786 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
791 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
792 MCFragment *F = SD.getFragment();
794 Index = F->getParent()->getOrdinal() + 1;
796 // Offset of the symbol in the section
797 Value += Layout.getSymbolOffset(&SD);
799 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
800 WeakrefUsedInReloc.insert(RelocSymbol);
802 UsedInReloc.insert(RelocSymbol);
806 // Compensate for the addend on i386.
812 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
813 (RelocSymbol != 0), Addend);
815 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
818 if (!HasRelocationAddend) Addend = 0;
819 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
820 Relocations[Fragment->getParent()].push_back(ERE);
825 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
827 MCSymbolData &SD = Asm.getSymbolData(*S);
828 return SD.getIndex();
831 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
832 bool Used, bool Renamed) {
833 if (Data.getFlags() & ELF_Other_Weakref)
842 const MCSymbol &Symbol = Data.getSymbol();
844 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
847 const MCSymbol &A = Symbol.AliasedSymbol();
848 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
851 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
854 if (Symbol.isTemporary())
860 static bool isLocal(const MCSymbolData &Data, bool isSignature,
861 bool isUsedInReloc) {
862 if (Data.isExternal())
865 const MCSymbol &Symbol = Data.getSymbol();
866 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
868 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
869 if (isSignature && !isUsedInReloc)
878 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
879 SectionIndexMapTy &SectionIndexMap) {
881 for (MCAssembler::iterator it = Asm.begin(),
882 ie = Asm.end(); it != ie; ++it) {
883 const MCSectionELF &Section =
884 static_cast<const MCSectionELF &>(it->getSection());
885 if (Section.getType() != ELF::SHT_GROUP)
887 SectionIndexMap[&Section] = Index++;
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++;
900 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
901 const SectionIndexMapTy &SectionIndexMap,
902 RevGroupMapTy RevGroupMap) {
903 // FIXME: Is this the correct place to do this?
905 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
906 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
907 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
908 Data.setExternal(true);
909 SetBinding(Data, ELF::STB_GLOBAL);
912 // Build section lookup table.
913 int NumRegularSections = Asm.size();
915 // Index 0 is always the empty string.
916 StringMap<uint64_t> StringIndexMap;
917 StringTable += '\x00';
919 // Add the data for the symbols.
920 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
921 ie = Asm.symbol_end(); it != ie; ++it) {
922 const MCSymbol &Symbol = it->getSymbol();
924 bool Used = UsedInReloc.count(&Symbol);
925 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
926 bool isSignature = RevGroupMap.count(&Symbol);
928 if (!isInSymtab(Asm, *it,
929 Used || WeakrefUsed || isSignature,
930 Renames.count(&Symbol)))
935 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
937 // Undefined symbols are global, but this is the first place we
938 // are able to set it.
939 bool Local = isLocal(*it, isSignature, Used);
940 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
941 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
942 SetBinding(*it, ELF::STB_GLOBAL);
943 SetBinding(SD, ELF::STB_GLOBAL);
946 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
947 SetBinding(*it, ELF::STB_WEAK);
949 if (it->isCommon()) {
951 MSD.SectionIndex = ELF::SHN_COMMON;
952 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
953 MSD.SectionIndex = ELF::SHN_ABS;
954 } else if (RefSymbol.isUndefined()) {
955 if (isSignature && !Used)
956 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
958 MSD.SectionIndex = ELF::SHN_UNDEF;
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF&>(RefSymbol.getSection());
962 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
963 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
964 NeedsSymtabShndx = true;
965 assert(MSD.SectionIndex && "Invalid section index!");
968 // The @@@ in symbol version is replaced with @ in undefined symbols and
969 // @@ in defined ones.
970 StringRef Name = Symbol.getName();
973 size_t Pos = Name.find("@@@");
974 if (Pos != StringRef::npos) {
975 Buf += Name.substr(0, Pos);
976 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
977 Buf += Name.substr(Pos + Skip);
981 uint64_t &Entry = StringIndexMap[Name];
983 Entry = StringTable.size();
985 StringTable += '\x00';
987 MSD.StringIndex = Entry;
988 if (MSD.SectionIndex == ELF::SHN_UNDEF)
989 UndefinedSymbolData.push_back(MSD);
991 LocalSymbolData.push_back(MSD);
993 ExternalSymbolData.push_back(MSD);
996 // Symbols are required to be in lexicographic order.
997 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
998 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
999 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1001 // Set the symbol indices. Local symbols must come before all other
1002 // symbols with non-local bindings.
1004 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1005 LocalSymbolData[i].SymbolData->setIndex(Index++);
1007 Index += NumRegularSections;
1009 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1010 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1011 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1012 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1015 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1016 const MCSectionData &SD) {
1017 if (!Relocations[&SD].empty()) {
1018 MCContext &Ctx = Asm.getContext();
1019 const MCSectionELF *RelaSection;
1020 const MCSectionELF &Section =
1021 static_cast<const MCSectionELF&>(SD.getSection());
1023 const StringRef SectionName = Section.getSectionName();
1024 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1025 RelaSectionName += SectionName;
1028 if (HasRelocationAddend)
1029 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1031 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1033 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1034 ELF::SHT_RELA : ELF::SHT_REL, 0,
1035 SectionKind::getReadOnly(),
1038 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1039 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1041 MCDataFragment *F = new MCDataFragment(&RelaSD);
1043 WriteRelocationsFragment(Asm, F, &SD);
1047 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1048 uint64_t Flags, uint64_t Address,
1049 uint64_t Offset, uint64_t Size,
1050 uint32_t Link, uint32_t Info,
1052 uint64_t EntrySize) {
1053 Write32(Name); // sh_name: index into string table
1054 Write32(Type); // sh_type
1055 WriteWord(Flags); // sh_flags
1056 WriteWord(Address); // sh_addr
1057 WriteWord(Offset); // sh_offset
1058 WriteWord(Size); // sh_size
1059 Write32(Link); // sh_link
1060 Write32(Info); // sh_info
1061 WriteWord(Alignment); // sh_addralign
1062 WriteWord(EntrySize); // sh_entsize
1065 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1067 const MCSectionData *SD) {
1068 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1069 // sort by the r_offset just like gnu as does
1070 array_pod_sort(Relocs.begin(), Relocs.end());
1072 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1073 ELFRelocationEntry entry = Relocs[e - i - 1];
1077 else if (entry.Index < 0)
1078 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1080 entry.Index += LocalSymbolData.size();
1082 String64(*F, entry.r_offset);
1084 struct ELF::Elf64_Rela ERE64;
1085 ERE64.setSymbolAndType(entry.Index, entry.Type);
1086 String64(*F, ERE64.r_info);
1088 if (HasRelocationAddend)
1089 String64(*F, entry.r_addend);
1091 String32(*F, entry.r_offset);
1093 struct ELF::Elf32_Rela ERE32;
1094 ERE32.setSymbolAndType(entry.Index, entry.Type);
1095 String32(*F, ERE32.r_info);
1097 if (HasRelocationAddend)
1098 String32(*F, entry.r_addend);
1103 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1104 MCAsmLayout &Layout,
1105 const SectionIndexMapTy &SectionIndexMap) {
1106 MCContext &Ctx = Asm.getContext();
1109 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1111 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1112 const MCSectionELF *ShstrtabSection =
1113 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1114 SectionKind::getReadOnly());
1115 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1116 ShstrtabSD.setAlignment(1);
1117 ShstrtabIndex = Asm.size();
1119 const MCSectionELF *SymtabSection =
1120 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1121 SectionKind::getReadOnly(),
1123 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1124 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1125 SymbolTableIndex = Asm.size();
1127 MCSectionData *SymtabShndxSD = NULL;
1129 if (NeedsSymtabShndx) {
1130 const MCSectionELF *SymtabShndxSection =
1131 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1132 SectionKind::getReadOnly(), 4, "");
1133 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1134 SymtabShndxSD->setAlignment(4);
1137 const MCSection *StrtabSection;
1138 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1139 SectionKind::getReadOnly());
1140 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1141 StrtabSD.setAlignment(1);
1142 StringTableIndex = Asm.size();
1144 WriteRelocations(Asm, Layout);
1147 F = new MCDataFragment(&SymtabSD);
1148 MCDataFragment *ShndxF = NULL;
1149 if (NeedsSymtabShndx) {
1150 ShndxF = new MCDataFragment(SymtabShndxSD);
1152 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1154 F = new MCDataFragment(&StrtabSD);
1155 F->getContents().append(StringTable.begin(), StringTable.end());
1157 F = new MCDataFragment(&ShstrtabSD);
1159 // Section header string table.
1161 // The first entry of a string table holds a null character so skip
1164 F->getContents() += '\x00';
1166 StringMap<uint64_t> SecStringMap;
1167 for (MCAssembler::const_iterator it = Asm.begin(),
1168 ie = Asm.end(); it != ie; ++it) {
1169 const MCSectionELF &Section =
1170 static_cast<const MCSectionELF&>(it->getSection());
1171 // FIXME: We could merge suffixes like in .text and .rela.text.
1173 StringRef Name = Section.getSectionName();
1174 if (SecStringMap.count(Name)) {
1175 SectionStringTableIndex[&Section] = SecStringMap[Name];
1178 // Remember the index into the string table so we can write it
1179 // into the sh_name field of the section header table.
1180 SectionStringTableIndex[&Section] = Index;
1181 SecStringMap[Name] = Index;
1183 Index += Name.size() + 1;
1184 F->getContents() += Name;
1185 F->getContents() += '\x00';
1189 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1190 const MCValue Target,
1192 const MCFragment *DF) const {
1193 // If this is a PCrel relocation, find the section this fixup value is
1195 const MCSection *BaseSection = 0;
1197 BaseSection = &DF->getParent()->getSection();
1198 assert(BaseSection);
1201 const MCSection *SectionA = 0;
1202 const MCSymbol *SymbolA = 0;
1203 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1204 SymbolA = &A->getSymbol();
1205 SectionA = &SymbolA->AliasedSymbol().getSection();
1208 const MCSection *SectionB = 0;
1209 const MCSymbol *SymbolB = 0;
1210 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1211 SymbolB = &B->getSymbol();
1212 SectionB = &SymbolB->AliasedSymbol().getSection();
1216 return SectionA == SectionB;
1221 // Absolute address but PCrel instruction, so we need a relocation.
1225 // FIXME: This is in here just to match gnu as output. If the two ends
1226 // are in the same section, there is nothing that the linker can do to
1228 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1229 if (DataA.isExternal())
1232 return BaseSection == SectionA;
1235 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1236 MCAsmLayout &Layout,
1237 GroupMapTy &GroupMap,
1238 RevGroupMapTy &RevGroupMap) {
1240 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1242 const MCSectionELF &Section =
1243 static_cast<const MCSectionELF&>(it->getSection());
1244 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1247 const MCSymbol *SignatureSymbol = Section.getGroup();
1248 Asm.getOrCreateSymbolData(*SignatureSymbol);
1249 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1251 Group = Asm.getContext().CreateELFGroupSection();
1252 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1253 Data.setAlignment(4);
1254 MCDataFragment *F = new MCDataFragment(&Data);
1255 String32(*F, ELF::GRP_COMDAT);
1257 GroupMap[Group] = SignatureSymbol;
1260 // Add sections to the groups
1262 unsigned NumGroups = RevGroupMap.size();
1263 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1264 it != ie; ++it, ++Index) {
1265 const MCSectionELF &Section =
1266 static_cast<const MCSectionELF&>(it->getSection());
1267 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1269 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1270 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1271 // FIXME: we could use the previous fragment
1272 MCDataFragment *F = new MCDataFragment(&Data);
1273 String32(*F, NumGroups + Index);
1277 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1278 const SectionIndexMapTy &SectionIndexMap,
1279 uint32_t GroupSymbolIndex,
1280 uint64_t Offset, uint64_t Size,
1282 const MCSectionELF &Section) {
1283 uint64_t sh_link = 0;
1284 uint64_t sh_info = 0;
1286 switch(Section.getType()) {
1287 case ELF::SHT_DYNAMIC:
1288 sh_link = SectionStringTableIndex[&Section];
1293 case ELF::SHT_RELA: {
1294 const MCSectionELF *SymtabSection;
1295 const MCSectionELF *InfoSection;
1296 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1298 SectionKind::getReadOnly());
1299 sh_link = SectionIndexMap.lookup(SymtabSection);
1300 assert(sh_link && ".symtab not found");
1302 // Remove ".rel" and ".rela" prefixes.
1303 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1304 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1306 InfoSection = Asm.getContext().getELFSection(SectionName,
1307 ELF::SHT_PROGBITS, 0,
1308 SectionKind::getReadOnly());
1309 sh_info = SectionIndexMap.lookup(InfoSection);
1313 case ELF::SHT_SYMTAB:
1314 case ELF::SHT_DYNSYM:
1315 sh_link = StringTableIndex;
1316 sh_info = LastLocalSymbolIndex;
1319 case ELF::SHT_SYMTAB_SHNDX:
1320 sh_link = SymbolTableIndex;
1323 case ELF::SHT_PROGBITS:
1324 case ELF::SHT_STRTAB:
1325 case ELF::SHT_NOBITS:
1327 case ELF::SHT_ARM_ATTRIBUTES:
1331 case ELF::SHT_GROUP: {
1332 sh_link = SymbolTableIndex;
1333 sh_info = GroupSymbolIndex;
1338 assert(0 && "FIXME: sh_type value not supported!");
1342 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1343 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1344 Alignment, Section.getEntrySize());
1347 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1348 return SD.getOrdinal() == ~UINT32_C(0) &&
1349 !SD.getSection().isVirtualSection();
1352 static uint64_t DataSectionSize(const MCSectionData &SD) {
1354 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1356 const MCFragment &F = *i;
1357 assert(F.getKind() == MCFragment::FT_Data);
1358 Ret += cast<MCDataFragment>(F).getContents().size();
1363 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1364 const MCSectionData &SD) {
1365 if (IsELFMetaDataSection(SD))
1366 return DataSectionSize(SD);
1367 return Layout.getSectionFileSize(&SD);
1370 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1371 const MCSectionData &SD) {
1372 if (IsELFMetaDataSection(SD))
1373 return DataSectionSize(SD);
1374 return Layout.getSectionAddressSize(&SD);
1377 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1378 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1380 const MCFragment &F = *i;
1381 assert(F.getKind() == MCFragment::FT_Data);
1382 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1386 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1387 const MCAsmLayout &Layout) {
1388 GroupMapTy GroupMap;
1389 RevGroupMapTy RevGroupMap;
1390 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1393 SectionIndexMapTy SectionIndexMap;
1395 ComputeIndexMap(Asm, SectionIndexMap);
1397 // Compute symbol table information.
1398 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1400 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1401 const_cast<MCAsmLayout&>(Layout),
1404 // Update to include the metadata sections.
1405 ComputeIndexMap(Asm, SectionIndexMap);
1407 // Add 1 for the null section.
1408 unsigned NumSections = Asm.size() + 1;
1409 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1410 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1411 uint64_t FileOff = HeaderSize;
1413 std::vector<const MCSectionELF*> Sections;
1414 Sections.resize(NumSections);
1416 for (SectionIndexMapTy::const_iterator i=
1417 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1418 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1419 Sections[p.second] = p.first;
1422 for (unsigned i = 1; i < NumSections; ++i) {
1423 const MCSectionELF &Section = *Sections[i];
1424 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1426 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1428 // Get the size of the section in the output file (including padding).
1429 FileOff += GetSectionFileSize(Layout, SD);
1432 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1434 // Write out the ELF header ...
1435 WriteHeader(FileOff - HeaderSize, NumSections);
1437 FileOff = HeaderSize;
1439 // ... then all of the sections ...
1440 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1442 for (unsigned i = 1; i < NumSections; ++i) {
1443 const MCSectionELF &Section = *Sections[i];
1444 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1446 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1447 WriteZeros(Padding);
1450 // Remember the offset into the file for this section.
1451 SectionOffsetMap[&Section] = FileOff;
1453 FileOff += GetSectionFileSize(Layout, SD);
1455 if (IsELFMetaDataSection(SD))
1456 WriteDataSectionData(this, SD);
1458 Asm.WriteSectionData(&SD, Layout, this);
1461 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1462 WriteZeros(Padding);
1465 // ... and then the section header table.
1466 // Should we align the section header table?
1468 // Null section first.
1469 uint64_t FirstSectionSize =
1470 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1471 uint32_t FirstSectionLink =
1472 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1473 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1475 for (unsigned i = 1; i < NumSections; ++i) {
1476 const MCSectionELF &Section = *Sections[i];
1477 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1478 uint32_t GroupSymbolIndex;
1479 if (Section.getType() != ELF::SHT_GROUP)
1480 GroupSymbolIndex = 0;
1482 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1484 uint64_t Size = GetSectionAddressSize(Layout, SD);
1486 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1487 SectionOffsetMap[&Section], Size,
1488 SD.getAlignment(), Section);
1492 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1494 Triple::OSType OSType,
1496 bool IsLittleEndian,
1497 bool HasRelocationAddend) {
1500 case ELF::EM_X86_64:
1501 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1502 HasRelocationAddend, OSType); break;
1504 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1505 HasRelocationAddend, OSType); break;
1506 case ELF::EM_MBLAZE:
1507 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1508 HasRelocationAddend, OSType); break;
1509 default: llvm_unreachable("Unsupported architecture"); break;
1514 /// START OF SUBCLASSES for ELFObjectWriter
1515 //===- ARMELFObjectWriter -------------------------------------------===//
1517 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1518 bool _IsLittleEndian,
1519 uint16_t _EMachine, bool _HasRelocationAddend,
1520 Triple::OSType _OSType)
1521 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1522 _HasRelocationAddend, _OSType)
1525 ARMELFObjectWriter::~ARMELFObjectWriter()
1528 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1529 const MCFixup &Fixup,
1531 bool IsRelocWithSymbol,
1533 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1534 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1539 default: assert(0 && "Unimplemented Modifier");
1540 case MCSymbolRefExpr::VK_None: break;
1542 switch ((unsigned)Fixup.getKind()) {
1543 default: assert(0 && "Unimplemented");
1544 case ARM::fixup_arm_branch: Type = ELF::R_ARM_CALL; break;
1547 switch ((unsigned)Fixup.getKind()) {
1548 default: llvm_unreachable("invalid fixup kind!");
1551 default: llvm_unreachable("Unsupported Modifier");
1552 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1553 Type = ELF::R_ARM_TLS_IE32;
1555 case ARM::fixup_arm_ldst_pcrel_12:
1556 case ARM::fixup_arm_pcrel_10:
1557 case ARM::fixup_arm_adr_pcrel_12:
1558 case ARM::fixup_arm_thumb_bl:
1559 case ARM::fixup_arm_thumb_cb:
1560 case ARM::fixup_arm_thumb_cp:
1561 case ARM::fixup_arm_thumb_br:
1562 assert(0 && "Unimplemented"); break;
1563 case ARM::fixup_arm_branch:
1564 Type = ELF::R_ARM_CALL; break;
1565 case ARM::fixup_arm_movt_hi16:
1566 Type = ELF::R_ARM_MOVT_ABS; break;
1567 case ARM::fixup_arm_movw_lo16:
1568 Type = ELF::R_ARM_MOVW_ABS_NC; break;
1572 if (RelocNeedsGOT(Modifier))
1578 //===- MBlazeELFObjectWriter -------------------------------------------===//
1580 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1581 bool _IsLittleEndian,
1583 bool _HasRelocationAddend,
1584 Triple::OSType _OSType)
1585 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1586 _HasRelocationAddend, _OSType) {
1589 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1592 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1593 const MCFixup &Fixup,
1595 bool IsRelocWithSymbol,
1597 // determine the type of the relocation
1600 switch ((unsigned)Fixup.getKind()) {
1602 llvm_unreachable("Unimplemented");
1604 Type = ELF::R_MICROBLAZE_64_PCREL;
1607 Type = ELF::R_MICROBLAZE_32_PCREL;
1611 switch ((unsigned)Fixup.getKind()) {
1612 default: llvm_unreachable("invalid fixup kind!");
1614 Type = ((IsRelocWithSymbol || Addend !=0)
1615 ? ELF::R_MICROBLAZE_32
1616 : ELF::R_MICROBLAZE_64);
1619 Type = ELF::R_MICROBLAZE_32;
1626 //===- X86ELFObjectWriter -------------------------------------------===//
1629 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1630 bool _IsLittleEndian,
1631 uint16_t _EMachine, bool _HasRelocationAddend,
1632 Triple::OSType _OSType)
1633 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1634 _HasRelocationAddend, _OSType)
1637 X86ELFObjectWriter::~X86ELFObjectWriter()
1640 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1641 const MCFixup &Fixup,
1643 bool IsRelocWithSymbol,
1645 // determine the type of the relocation
1647 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1648 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1654 llvm_unreachable("Unimplemented");
1655 case MCSymbolRefExpr::VK_None:
1656 Type = ELF::R_X86_64_PC32;
1658 case MCSymbolRefExpr::VK_PLT:
1659 Type = ELF::R_X86_64_PLT32;
1661 case MCSymbolRefExpr::VK_GOTPCREL:
1662 Type = ELF::R_X86_64_GOTPCREL;
1664 case MCSymbolRefExpr::VK_GOTTPOFF:
1665 Type = ELF::R_X86_64_GOTTPOFF;
1667 case MCSymbolRefExpr::VK_TLSGD:
1668 Type = ELF::R_X86_64_TLSGD;
1670 case MCSymbolRefExpr::VK_TLSLD:
1671 Type = ELF::R_X86_64_TLSLD;
1675 switch ((unsigned)Fixup.getKind()) {
1676 default: llvm_unreachable("invalid fixup kind!");
1677 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1678 case X86::reloc_signed_4byte:
1680 assert(isInt<32>(Target.getConstant()));
1683 llvm_unreachable("Unimplemented");
1684 case MCSymbolRefExpr::VK_None:
1685 Type = ELF::R_X86_64_32S;
1687 case MCSymbolRefExpr::VK_GOT:
1688 Type = ELF::R_X86_64_GOT32;
1690 case MCSymbolRefExpr::VK_GOTPCREL:
1691 Type = ELF::R_X86_64_GOTPCREL;
1693 case MCSymbolRefExpr::VK_TPOFF:
1694 Type = ELF::R_X86_64_TPOFF32;
1696 case MCSymbolRefExpr::VK_DTPOFF:
1697 Type = ELF::R_X86_64_DTPOFF32;
1702 Type = ELF::R_X86_64_32;
1704 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1706 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1713 llvm_unreachable("Unimplemented");
1714 case MCSymbolRefExpr::VK_None:
1715 Type = ELF::R_386_PC32;
1717 case MCSymbolRefExpr::VK_PLT:
1718 Type = ELF::R_386_PLT32;
1722 switch ((unsigned)Fixup.getKind()) {
1723 default: llvm_unreachable("invalid fixup kind!");
1725 case X86::reloc_global_offset_table:
1726 Type = ELF::R_386_GOTPC;
1729 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1731 case X86::reloc_signed_4byte:
1736 llvm_unreachable("Unimplemented");
1737 case MCSymbolRefExpr::VK_None:
1738 Type = ELF::R_386_32;
1740 case MCSymbolRefExpr::VK_GOT:
1741 Type = ELF::R_386_GOT32;
1743 case MCSymbolRefExpr::VK_GOTOFF:
1744 Type = ELF::R_386_GOTOFF;
1746 case MCSymbolRefExpr::VK_TLSGD:
1747 Type = ELF::R_386_TLS_GD;
1749 case MCSymbolRefExpr::VK_TPOFF:
1750 Type = ELF::R_386_TLS_LE_32;
1752 case MCSymbolRefExpr::VK_INDNTPOFF:
1753 Type = ELF::R_386_TLS_IE;
1755 case MCSymbolRefExpr::VK_NTPOFF:
1756 Type = ELF::R_386_TLS_LE;
1758 case MCSymbolRefExpr::VK_GOTNTPOFF:
1759 Type = ELF::R_386_TLS_GOTIE;
1761 case MCSymbolRefExpr::VK_TLSLDM:
1762 Type = ELF::R_386_TLS_LDM;
1764 case MCSymbolRefExpr::VK_DTPOFF:
1765 Type = ELF::R_386_TLS_LDO_32;
1769 case FK_Data_2: Type = ELF::R_386_16; break;
1771 case FK_Data_1: Type = ELF::R_386_8; break;
1776 if (RelocNeedsGOT(Modifier))