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) {
291 assert(0 && "RecordRelocation is not specific enough");
294 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
297 // Map from a group section to the signature symbol
298 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
299 // Map from a signature symbol to the group section
300 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
302 /// ComputeSymbolTable - Compute the symbol table data
304 /// \param StringTable [out] - The string table data.
305 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
307 virtual void ComputeSymbolTable(MCAssembler &Asm,
308 const SectionIndexMapTy &SectionIndexMap,
309 RevGroupMapTy RevGroupMap);
311 virtual void ComputeIndexMap(MCAssembler &Asm,
312 SectionIndexMapTy &SectionIndexMap);
314 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
315 const MCSectionData &SD);
317 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
318 for (MCAssembler::const_iterator it = Asm.begin(),
319 ie = Asm.end(); it != ie; ++it) {
320 WriteRelocation(Asm, Layout, *it);
324 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
325 const SectionIndexMapTy &SectionIndexMap);
327 virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
328 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
330 virtual void ExecutePostLayoutBinding(MCAssembler &Asm);
332 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
333 uint64_t Address, uint64_t Offset,
334 uint64_t Size, uint32_t Link, uint32_t Info,
335 uint64_t Alignment, uint64_t EntrySize);
337 virtual void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
338 const MCSectionData *SD);
340 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
341 const MCValue Target,
343 const MCFragment *DF) const;
345 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
346 virtual void WriteSection(MCAssembler &Asm,
347 const SectionIndexMapTy &SectionIndexMap,
348 uint32_t GroupSymbolIndex,
349 uint64_t Offset, uint64_t Size, uint64_t Alignment,
350 const MCSectionELF &Section);
353 //===- X86ELFObjectWriter -------------------------------------------===//
355 class X86ELFObjectWriter : public ELFObjectWriter {
357 X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
358 uint16_t _EMachine, bool _HasRelAddend,
359 Triple::OSType _OSType);
361 virtual ~X86ELFObjectWriter();
362 virtual void RecordRelocation(const MCAssembler &Asm,
363 const MCAsmLayout &Layout,
364 const MCFragment *Fragment,
365 const MCFixup &Fixup, MCValue Target,
366 uint64_t &FixedValue);
369 static bool isFixupKindPCRel(unsigned Kind) {
376 case X86::reloc_riprel_4byte:
377 case X86::reloc_riprel_4byte_movq_load:
384 //===- ARMELFObjectWriter -------------------------------------------===//
386 class ARMELFObjectWriter : public ELFObjectWriter {
388 ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
389 uint16_t _EMachine, bool _HasRelAddend,
390 Triple::OSType _OSType);
392 virtual ~ARMELFObjectWriter();
393 virtual void RecordRelocation(const MCAssembler &Asm,
394 const MCAsmLayout &Layout,
395 const MCFragment *Fragment,
396 const MCFixup &Fixup, MCValue Target,
397 uint64_t &FixedValue);
400 // Fixme: pull up to ELFObjectWriter
401 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
404 static bool isFixupKindPCRel(unsigned Kind) {
411 case ARM::fixup_arm_ldst_pcrel_12:
412 case ARM::fixup_arm_pcrel_10:
413 case ARM::fixup_arm_branch:
419 //===- MBlazeELFObjectWriter -------------------------------------------===//
421 class MBlazeELFObjectWriter : public ELFObjectWriter {
423 MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
424 uint16_t _EMachine, bool _HasRelAddend,
425 Triple::OSType _OSType);
427 virtual ~MBlazeELFObjectWriter();
428 virtual void RecordRelocation(const MCAssembler &Asm,
429 const MCAsmLayout &Layout,
430 const MCFragment *Fragment,
431 const MCFixup &Fixup, MCValue Target,
432 uint64_t &FixedValue);
435 static bool isFixupKindPCRel(unsigned Kind) {
448 ELFObjectWriter::~ELFObjectWriter()
451 // Emit the ELF header.
452 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
453 unsigned NumberOfSections) {
459 // emitWord method behaves differently for ELF32 and ELF64, writing
460 // 4 bytes in the former and 8 in the latter.
462 Write8(0x7f); // e_ident[EI_MAG0]
463 Write8('E'); // e_ident[EI_MAG1]
464 Write8('L'); // e_ident[EI_MAG2]
465 Write8('F'); // e_ident[EI_MAG3]
467 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
470 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
472 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
475 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
476 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
477 default: Write8(ELF::ELFOSABI_NONE); break;
479 Write8(0); // e_ident[EI_ABIVERSION]
481 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
483 Write16(ELF::ET_REL); // e_type
485 Write16(EMachine); // e_machine = target
487 Write32(ELF::EV_CURRENT); // e_version
488 WriteWord(0); // e_entry, no entry point in .o file
489 WriteWord(0); // e_phoff, no program header for .o
490 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
491 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
493 // FIXME: Make this configurable.
494 Write32(0); // e_flags = whatever the target wants
496 // e_ehsize = ELF header size
497 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
499 Write16(0); // e_phentsize = prog header entry size
500 Write16(0); // e_phnum = # prog header entries = 0
502 // e_shentsize = Section header entry size
503 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
505 // e_shnum = # of section header ents
506 if (NumberOfSections >= ELF::SHN_LORESERVE)
509 Write16(NumberOfSections);
511 // e_shstrndx = Section # of '.shstrtab'
512 if (NumberOfSections >= ELF::SHN_LORESERVE)
513 Write16(ELF::SHN_XINDEX);
515 Write16(ShstrtabIndex);
518 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
519 MCDataFragment *ShndxF,
521 uint8_t info, uint64_t value,
522 uint64_t size, uint8_t other,
526 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
527 String32(*ShndxF, shndx);
529 String32(*ShndxF, 0);
532 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
533 uint16_t(ELF::SHN_XINDEX) : shndx;
536 String32(*SymtabF, name); // st_name
537 String8(*SymtabF, info); // st_info
538 String8(*SymtabF, other); // st_other
539 String16(*SymtabF, Index); // st_shndx
540 String64(*SymtabF, value); // st_value
541 String64(*SymtabF, size); // st_size
543 String32(*SymtabF, name); // st_name
544 String32(*SymtabF, value); // st_value
545 String32(*SymtabF, size); // st_size
546 String8(*SymtabF, info); // st_info
547 String8(*SymtabF, other); // st_other
548 String16(*SymtabF, Index); // st_shndx
552 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
553 if (Data.isCommon() && Data.isExternal())
554 return Data.getCommonAlignment();
556 const MCSymbol &Symbol = Data.getSymbol();
557 if (!Symbol.isInSection())
560 if (Data.getFragment())
561 return Layout.getSymbolOffset(&Data);
566 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
567 // The presence of symbol versions causes undefined symbols and
568 // versions declared with @@@ to be renamed.
570 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
571 ie = Asm.symbol_end(); it != ie; ++it) {
572 const MCSymbol &Alias = it->getSymbol();
573 const MCSymbol &Symbol = Alias.AliasedSymbol();
574 MCSymbolData &SD = Asm.getSymbolData(Symbol);
577 if (&Symbol == &Alias)
580 StringRef AliasName = Alias.getName();
581 size_t Pos = AliasName.find('@');
582 if (Pos == StringRef::npos)
585 // Aliases defined with .symvar copy the binding from the symbol they alias.
586 // This is the first place we are able to copy this information.
587 it->setExternal(SD.isExternal());
588 SetBinding(*it, GetBinding(SD));
590 StringRef Rest = AliasName.substr(Pos);
591 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
594 // FIXME: produce a better error message.
595 if (Symbol.isUndefined() && Rest.startswith("@@") &&
596 !Rest.startswith("@@@"))
597 report_fatal_error("A @@ version cannot be undefined");
599 Renames.insert(std::make_pair(&Symbol, &Alias));
603 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
604 MCDataFragment *ShndxF,
606 const MCAsmLayout &Layout) {
607 MCSymbolData &OrigData = *MSD.SymbolData;
609 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
611 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
612 Data.getSymbol().isVariable();
614 uint8_t Binding = GetBinding(OrigData);
615 uint8_t Visibility = GetVisibility(OrigData);
616 uint8_t Type = GetType(Data);
618 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
619 uint8_t Other = Visibility;
621 uint64_t Value = SymbolValue(Data, Layout);
625 assert(!(Data.isCommon() && !Data.isExternal()));
627 ESize = Data.getSize();
628 if (Data.getSize()) {
630 if (ESize->getKind() == MCExpr::Binary) {
631 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
633 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
634 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
635 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
636 Size = Res.getConstant();
638 } else if (ESize->getKind() == MCExpr::Constant) {
639 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
641 assert(0 && "Unsupported size expression");
645 // Write out the symbol table entry
646 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
647 Size, Other, MSD.SectionIndex, IsReserved);
650 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
651 MCDataFragment *ShndxF,
652 const MCAssembler &Asm,
653 const MCAsmLayout &Layout,
654 const SectionIndexMapTy &SectionIndexMap) {
655 // The string table must be emitted first because we need the index
656 // into the string table for all the symbol names.
657 assert(StringTable.size() && "Missing string table");
659 // FIXME: Make sure the start of the symbol table is aligned.
661 // The first entry is the undefined symbol entry.
662 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
664 // Write the symbol table entries.
665 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
666 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
667 ELFSymbolData &MSD = LocalSymbolData[i];
668 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
671 // Write out a symbol table entry for each regular section.
672 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
674 const MCSectionELF &Section =
675 static_cast<const MCSectionELF&>(i->getSection());
676 if (Section.getType() == ELF::SHT_RELA ||
677 Section.getType() == ELF::SHT_REL ||
678 Section.getType() == ELF::SHT_STRTAB ||
679 Section.getType() == ELF::SHT_SYMTAB)
681 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
682 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
683 LastLocalSymbolIndex++;
686 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
687 ELFSymbolData &MSD = ExternalSymbolData[i];
688 MCSymbolData &Data = *MSD.SymbolData;
689 assert(((Data.getFlags() & ELF_STB_Global) ||
690 (Data.getFlags() & ELF_STB_Weak)) &&
691 "External symbol requires STB_GLOBAL or STB_WEAK flag");
692 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
693 if (GetBinding(Data) == ELF::STB_LOCAL)
694 LastLocalSymbolIndex++;
697 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
698 ELFSymbolData &MSD = UndefinedSymbolData[i];
699 MCSymbolData &Data = *MSD.SymbolData;
700 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
701 if (GetBinding(Data) == ELF::STB_LOCAL)
702 LastLocalSymbolIndex++;
706 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
707 const MCValue &Target,
708 const MCFragment &F) const {
709 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
710 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
711 const MCSymbol *Renamed = Renames.lookup(&Symbol);
712 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
714 if (ASymbol.isUndefined()) {
720 if (SD.isExternal()) {
726 const MCSectionELF &Section =
727 static_cast<const MCSectionELF&>(ASymbol.getSection());
728 const SectionKind secKind = Section.getKind();
733 if (secKind.isThreadLocal()) {
739 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
740 const MCSectionELF &Sec2 =
741 static_cast<const MCSectionELF&>(F.getParent()->getSection());
743 if (&Sec2 != &Section &&
744 (Kind == MCSymbolRefExpr::VK_PLT ||
745 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
746 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
752 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
753 if (Target.getConstant() == 0)
765 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
767 MCSymbolData &SD = Asm.getSymbolData(*S);
768 return SD.getIndex();
771 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
772 bool Used, bool Renamed) {
773 if (Data.getFlags() & ELF_Other_Weakref)
782 const MCSymbol &Symbol = Data.getSymbol();
784 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
787 const MCSymbol &A = Symbol.AliasedSymbol();
788 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
791 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
794 if (Symbol.isTemporary())
800 static bool isLocal(const MCSymbolData &Data, bool isSignature,
801 bool isUsedInReloc) {
802 if (Data.isExternal())
805 const MCSymbol &Symbol = Data.getSymbol();
806 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
808 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
809 if (isSignature && !isUsedInReloc)
818 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
819 SectionIndexMapTy &SectionIndexMap) {
821 for (MCAssembler::iterator it = Asm.begin(),
822 ie = Asm.end(); it != ie; ++it) {
823 const MCSectionELF &Section =
824 static_cast<const MCSectionELF &>(it->getSection());
825 if (Section.getType() != ELF::SHT_GROUP)
827 SectionIndexMap[&Section] = Index++;
830 for (MCAssembler::iterator it = Asm.begin(),
831 ie = Asm.end(); it != ie; ++it) {
832 const MCSectionELF &Section =
833 static_cast<const MCSectionELF &>(it->getSection());
834 if (Section.getType() == ELF::SHT_GROUP)
836 SectionIndexMap[&Section] = Index++;
840 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
841 const SectionIndexMapTy &SectionIndexMap,
842 RevGroupMapTy RevGroupMap) {
843 // FIXME: Is this the correct place to do this?
845 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
846 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
847 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
848 Data.setExternal(true);
849 SetBinding(Data, ELF::STB_GLOBAL);
852 // Build section lookup table.
853 int NumRegularSections = Asm.size();
855 // Index 0 is always the empty string.
856 StringMap<uint64_t> StringIndexMap;
857 StringTable += '\x00';
859 // Add the data for the symbols.
860 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
861 ie = Asm.symbol_end(); it != ie; ++it) {
862 const MCSymbol &Symbol = it->getSymbol();
864 bool Used = UsedInReloc.count(&Symbol);
865 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
866 bool isSignature = RevGroupMap.count(&Symbol);
868 if (!isInSymtab(Asm, *it,
869 Used || WeakrefUsed || isSignature,
870 Renames.count(&Symbol)))
875 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
877 // Undefined symbols are global, but this is the first place we
878 // are able to set it.
879 bool Local = isLocal(*it, isSignature, Used);
880 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
881 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
882 SetBinding(*it, ELF::STB_GLOBAL);
883 SetBinding(SD, ELF::STB_GLOBAL);
886 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
887 SetBinding(*it, ELF::STB_WEAK);
889 if (it->isCommon()) {
891 MSD.SectionIndex = ELF::SHN_COMMON;
892 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
893 MSD.SectionIndex = ELF::SHN_ABS;
894 } else if (RefSymbol.isUndefined()) {
895 if (isSignature && !Used)
896 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
898 MSD.SectionIndex = ELF::SHN_UNDEF;
900 const MCSectionELF &Section =
901 static_cast<const MCSectionELF&>(RefSymbol.getSection());
902 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
903 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
904 NeedsSymtabShndx = true;
905 assert(MSD.SectionIndex && "Invalid section index!");
908 // The @@@ in symbol version is replaced with @ in undefined symbols and
909 // @@ in defined ones.
910 StringRef Name = Symbol.getName();
913 size_t Pos = Name.find("@@@");
914 if (Pos != StringRef::npos) {
915 Buf += Name.substr(0, Pos);
916 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
917 Buf += Name.substr(Pos + Skip);
921 uint64_t &Entry = StringIndexMap[Name];
923 Entry = StringTable.size();
925 StringTable += '\x00';
927 MSD.StringIndex = Entry;
928 if (MSD.SectionIndex == ELF::SHN_UNDEF)
929 UndefinedSymbolData.push_back(MSD);
931 LocalSymbolData.push_back(MSD);
933 ExternalSymbolData.push_back(MSD);
936 // Symbols are required to be in lexicographic order.
937 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
938 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
939 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
941 // Set the symbol indices. Local symbols must come before all other
942 // symbols with non-local bindings.
944 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
945 LocalSymbolData[i].SymbolData->setIndex(Index++);
947 Index += NumRegularSections;
949 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
950 ExternalSymbolData[i].SymbolData->setIndex(Index++);
951 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
952 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
955 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
956 const MCSectionData &SD) {
957 if (!Relocations[&SD].empty()) {
958 MCContext &Ctx = Asm.getContext();
959 const MCSectionELF *RelaSection;
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF&>(SD.getSection());
963 const StringRef SectionName = Section.getSectionName();
964 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
965 RelaSectionName += SectionName;
968 if (HasRelocationAddend)
969 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
971 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
973 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
974 ELF::SHT_RELA : ELF::SHT_REL, 0,
975 SectionKind::getReadOnly(),
978 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
979 RelaSD.setAlignment(Is64Bit ? 8 : 4);
981 MCDataFragment *F = new MCDataFragment(&RelaSD);
983 WriteRelocationsFragment(Asm, F, &SD);
987 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
988 uint64_t Flags, uint64_t Address,
989 uint64_t Offset, uint64_t Size,
990 uint32_t Link, uint32_t Info,
992 uint64_t EntrySize) {
993 Write32(Name); // sh_name: index into string table
994 Write32(Type); // sh_type
995 WriteWord(Flags); // sh_flags
996 WriteWord(Address); // sh_addr
997 WriteWord(Offset); // sh_offset
998 WriteWord(Size); // sh_size
999 Write32(Link); // sh_link
1000 Write32(Info); // sh_info
1001 WriteWord(Alignment); // sh_addralign
1002 WriteWord(EntrySize); // sh_entsize
1005 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1007 const MCSectionData *SD) {
1008 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1009 // sort by the r_offset just like gnu as does
1010 array_pod_sort(Relocs.begin(), Relocs.end());
1012 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1013 ELFRelocationEntry entry = Relocs[e - i - 1];
1017 else if (entry.Index < 0)
1018 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1020 entry.Index += LocalSymbolData.size();
1022 String64(*F, entry.r_offset);
1024 struct ELF::Elf64_Rela ERE64;
1025 ERE64.setSymbolAndType(entry.Index, entry.Type);
1026 String64(*F, ERE64.r_info);
1028 if (HasRelocationAddend)
1029 String64(*F, entry.r_addend);
1031 String32(*F, entry.r_offset);
1033 struct ELF::Elf32_Rela ERE32;
1034 ERE32.setSymbolAndType(entry.Index, entry.Type);
1035 String32(*F, ERE32.r_info);
1037 if (HasRelocationAddend)
1038 String32(*F, entry.r_addend);
1043 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1044 MCAsmLayout &Layout,
1045 const SectionIndexMapTy &SectionIndexMap) {
1046 MCContext &Ctx = Asm.getContext();
1049 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1051 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1052 const MCSectionELF *ShstrtabSection =
1053 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1054 SectionKind::getReadOnly());
1055 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1056 ShstrtabSD.setAlignment(1);
1057 ShstrtabIndex = Asm.size();
1059 const MCSectionELF *SymtabSection =
1060 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1061 SectionKind::getReadOnly(),
1063 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1064 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1065 SymbolTableIndex = Asm.size();
1067 MCSectionData *SymtabShndxSD = NULL;
1069 if (NeedsSymtabShndx) {
1070 const MCSectionELF *SymtabShndxSection =
1071 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1072 SectionKind::getReadOnly(), 4, "");
1073 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1074 SymtabShndxSD->setAlignment(4);
1077 const MCSection *StrtabSection;
1078 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1079 SectionKind::getReadOnly());
1080 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1081 StrtabSD.setAlignment(1);
1082 StringTableIndex = Asm.size();
1084 WriteRelocations(Asm, Layout);
1087 F = new MCDataFragment(&SymtabSD);
1088 MCDataFragment *ShndxF = NULL;
1089 if (NeedsSymtabShndx) {
1090 ShndxF = new MCDataFragment(SymtabShndxSD);
1092 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1094 F = new MCDataFragment(&StrtabSD);
1095 F->getContents().append(StringTable.begin(), StringTable.end());
1097 F = new MCDataFragment(&ShstrtabSD);
1099 // Section header string table.
1101 // The first entry of a string table holds a null character so skip
1104 F->getContents() += '\x00';
1106 StringMap<uint64_t> SecStringMap;
1107 for (MCAssembler::const_iterator it = Asm.begin(),
1108 ie = Asm.end(); it != ie; ++it) {
1109 const MCSectionELF &Section =
1110 static_cast<const MCSectionELF&>(it->getSection());
1111 // FIXME: We could merge suffixes like in .text and .rela.text.
1113 StringRef Name = Section.getSectionName();
1114 if (SecStringMap.count(Name)) {
1115 SectionStringTableIndex[&Section] = SecStringMap[Name];
1118 // Remember the index into the string table so we can write it
1119 // into the sh_name field of the section header table.
1120 SectionStringTableIndex[&Section] = Index;
1121 SecStringMap[Name] = Index;
1123 Index += Name.size() + 1;
1124 F->getContents() += Name;
1125 F->getContents() += '\x00';
1129 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1130 const MCValue Target,
1132 const MCFragment *DF) const {
1133 // If this is a PCrel relocation, find the section this fixup value is
1135 const MCSection *BaseSection = 0;
1137 BaseSection = &DF->getParent()->getSection();
1138 assert(BaseSection);
1141 const MCSection *SectionA = 0;
1142 const MCSymbol *SymbolA = 0;
1143 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1144 SymbolA = &A->getSymbol();
1145 SectionA = &SymbolA->AliasedSymbol().getSection();
1148 const MCSection *SectionB = 0;
1149 const MCSymbol *SymbolB = 0;
1150 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1151 SymbolB = &B->getSymbol();
1152 SectionB = &SymbolB->AliasedSymbol().getSection();
1156 return SectionA == SectionB;
1161 // Absolute address but PCrel instruction, so we need a relocation.
1165 // FIXME: This is in here just to match gnu as output. If the two ends
1166 // are in the same section, there is nothing that the linker can do to
1168 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1169 if (DataA.isExternal())
1172 return BaseSection == SectionA;
1175 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1176 MCAsmLayout &Layout,
1177 GroupMapTy &GroupMap,
1178 RevGroupMapTy &RevGroupMap) {
1180 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1182 const MCSectionELF &Section =
1183 static_cast<const MCSectionELF&>(it->getSection());
1184 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1187 const MCSymbol *SignatureSymbol = Section.getGroup();
1188 Asm.getOrCreateSymbolData(*SignatureSymbol);
1189 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1191 Group = Asm.getContext().CreateELFGroupSection();
1192 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1193 Data.setAlignment(4);
1194 MCDataFragment *F = new MCDataFragment(&Data);
1195 String32(*F, ELF::GRP_COMDAT);
1197 GroupMap[Group] = SignatureSymbol;
1200 // Add sections to the groups
1202 unsigned NumGroups = RevGroupMap.size();
1203 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1204 it != ie; ++it, ++Index) {
1205 const MCSectionELF &Section =
1206 static_cast<const MCSectionELF&>(it->getSection());
1207 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1209 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1210 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1211 // FIXME: we could use the previous fragment
1212 MCDataFragment *F = new MCDataFragment(&Data);
1213 String32(*F, NumGroups + Index);
1217 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1218 const SectionIndexMapTy &SectionIndexMap,
1219 uint32_t GroupSymbolIndex,
1220 uint64_t Offset, uint64_t Size,
1222 const MCSectionELF &Section) {
1223 uint64_t sh_link = 0;
1224 uint64_t sh_info = 0;
1226 switch(Section.getType()) {
1227 case ELF::SHT_DYNAMIC:
1228 sh_link = SectionStringTableIndex[&Section];
1233 case ELF::SHT_RELA: {
1234 const MCSectionELF *SymtabSection;
1235 const MCSectionELF *InfoSection;
1236 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1238 SectionKind::getReadOnly());
1239 sh_link = SectionIndexMap.lookup(SymtabSection);
1240 assert(sh_link && ".symtab not found");
1242 // Remove ".rel" and ".rela" prefixes.
1243 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1244 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1246 InfoSection = Asm.getContext().getELFSection(SectionName,
1247 ELF::SHT_PROGBITS, 0,
1248 SectionKind::getReadOnly());
1249 sh_info = SectionIndexMap.lookup(InfoSection);
1253 case ELF::SHT_SYMTAB:
1254 case ELF::SHT_DYNSYM:
1255 sh_link = StringTableIndex;
1256 sh_info = LastLocalSymbolIndex;
1259 case ELF::SHT_SYMTAB_SHNDX:
1260 sh_link = SymbolTableIndex;
1263 case ELF::SHT_PROGBITS:
1264 case ELF::SHT_STRTAB:
1265 case ELF::SHT_NOBITS:
1267 case ELF::SHT_ARM_ATTRIBUTES:
1271 case ELF::SHT_GROUP: {
1272 sh_link = SymbolTableIndex;
1273 sh_info = GroupSymbolIndex;
1278 assert(0 && "FIXME: sh_type value not supported!");
1282 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1283 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1284 Alignment, Section.getEntrySize());
1287 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1288 return SD.getAddress() == ~UINT64_C(0) &&
1289 !SD.getSection().isVirtualSection();
1292 static uint64_t DataSectionSize(const MCSectionData &SD) {
1294 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1296 const MCFragment &F = *i;
1297 assert(F.getKind() == MCFragment::FT_Data);
1298 Ret += cast<MCDataFragment>(F).getContents().size();
1303 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1304 const MCSectionData &SD) {
1305 if (IsELFMetaDataSection(SD))
1306 return DataSectionSize(SD);
1307 return Layout.getSectionFileSize(&SD);
1310 static uint64_t GetSectionSize(const MCAsmLayout &Layout,
1311 const MCSectionData &SD) {
1312 if (IsELFMetaDataSection(SD))
1313 return DataSectionSize(SD);
1314 return Layout.getSectionSize(&SD);
1317 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1318 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1320 const MCFragment &F = *i;
1321 assert(F.getKind() == MCFragment::FT_Data);
1322 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1326 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1327 const MCAsmLayout &Layout) {
1328 GroupMapTy GroupMap;
1329 RevGroupMapTy RevGroupMap;
1330 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1333 SectionIndexMapTy SectionIndexMap;
1335 ComputeIndexMap(Asm, SectionIndexMap);
1337 // Compute symbol table information.
1338 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1340 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1341 const_cast<MCAsmLayout&>(Layout),
1344 // Update to include the metadata sections.
1345 ComputeIndexMap(Asm, SectionIndexMap);
1347 // Add 1 for the null section.
1348 unsigned NumSections = Asm.size() + 1;
1349 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1350 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1351 uint64_t FileOff = HeaderSize;
1353 std::vector<const MCSectionELF*> Sections;
1354 Sections.resize(NumSections);
1356 for (SectionIndexMapTy::const_iterator i=
1357 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1358 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1359 Sections[p.second] = p.first;
1362 for (unsigned i = 1; i < NumSections; ++i) {
1363 const MCSectionELF &Section = *Sections[i];
1364 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1366 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1368 // Get the size of the section in the output file (including padding).
1369 FileOff += GetSectionFileSize(Layout, SD);
1372 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1374 // Write out the ELF header ...
1375 WriteHeader(FileOff - HeaderSize, NumSections);
1377 FileOff = HeaderSize;
1379 // ... then all of the sections ...
1380 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1382 for (unsigned i = 1; i < NumSections; ++i) {
1383 const MCSectionELF &Section = *Sections[i];
1384 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1386 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1387 WriteZeros(Padding);
1390 // Remember the offset into the file for this section.
1391 SectionOffsetMap[&Section] = FileOff;
1393 FileOff += GetSectionFileSize(Layout, SD);
1395 if (IsELFMetaDataSection(SD))
1396 WriteDataSectionData(this, SD);
1398 Asm.WriteSectionData(&SD, Layout, this);
1401 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1402 WriteZeros(Padding);
1405 // ... and then the section header table.
1406 // Should we align the section header table?
1408 // Null section first.
1409 uint64_t FirstSectionSize =
1410 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1411 uint32_t FirstSectionLink =
1412 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1413 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1415 for (unsigned i = 1; i < NumSections; ++i) {
1416 const MCSectionELF &Section = *Sections[i];
1417 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1418 uint32_t GroupSymbolIndex;
1419 if (Section.getType() != ELF::SHT_GROUP)
1420 GroupSymbolIndex = 0;
1422 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1424 uint64_t Size = GetSectionSize(Layout, SD);
1426 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1427 SectionOffsetMap[&Section], Size,
1428 SD.getAlignment(), Section);
1432 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1434 Triple::OSType OSType,
1436 bool IsLittleEndian,
1437 bool HasRelocationAddend) {
1440 case ELF::EM_X86_64:
1441 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1442 HasRelocationAddend, OSType); break;
1444 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1445 HasRelocationAddend, OSType); break;
1446 case ELF::EM_MBLAZE:
1447 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1448 HasRelocationAddend, OSType); break;
1449 default: llvm_unreachable("Unsupported architecture"); break;
1454 /// START OF SUBCLASSES for ELFObjectWriter
1455 //===- ARMELFObjectWriter -------------------------------------------===//
1457 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1458 bool _IsLittleEndian,
1459 uint16_t _EMachine, bool _HasRelocationAddend,
1460 Triple::OSType _OSType)
1461 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1462 _HasRelocationAddend, _OSType)
1465 ARMELFObjectWriter::~ARMELFObjectWriter()
1468 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1469 const MCFixup &Fixup,
1471 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1472 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1476 default: assert(0 && "Unimplemented Modifier");
1477 case MCSymbolRefExpr::VK_None: break;
1479 switch ((unsigned)Fixup.getKind()) {
1480 default: assert(0 && "Unimplemented");
1481 case ARM::fixup_arm_branch: return ELF::R_ARM_CALL; break;
1484 switch ((unsigned)Fixup.getKind()) {
1485 default: llvm_unreachable("invalid fixup kind!");
1486 case ARM::fixup_arm_ldst_pcrel_12:
1487 case ARM::fixup_arm_pcrel_10:
1488 case ARM::fixup_arm_adr_pcrel_12:
1489 assert(0 && "Unimplemented"); break;
1490 case ARM::fixup_arm_branch:
1491 return ELF::R_ARM_CALL; break;
1492 case ARM::fixup_arm_movt_hi16:
1493 return ELF::R_ARM_MOVT_ABS; break;
1494 case ARM::fixup_arm_movw_lo16:
1495 return ELF::R_ARM_MOVW_ABS_NC; break;
1499 if (RelocNeedsGOT(Modifier))
1504 void ARMELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1505 const MCAsmLayout &Layout,
1506 const MCFragment *Fragment,
1507 const MCFixup &Fixup,
1509 uint64_t &FixedValue) {
1512 int64_t Value = Target.getConstant();
1513 const MCSymbol *RelocSymbol = NULL;
1515 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1516 if (!Target.isAbsolute()) {
1517 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1518 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1519 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1521 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1522 const MCSymbol &SymbolB = RefB->getSymbol();
1523 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1526 // Offset of the symbol in the section
1527 int64_t a = Layout.getSymbolOffset(&SDB);
1529 // Ofeset of the relocation in the section
1530 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1535 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1536 MCFragment *F = SD.getFragment();
1538 Index = F->getParent()->getOrdinal() + 1;
1540 // Offset of the symbol in the section
1541 Value += Layout.getSymbolOffset(&SD);
1543 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1544 WeakrefUsedInReloc.insert(RelocSymbol);
1546 UsedInReloc.insert(RelocSymbol);
1550 // Compensate for the addend on i386.
1557 // determine the type of the relocation
1558 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
1560 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1563 if (!HasRelocationAddend) Addend = 0;
1564 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1565 Relocations[Fragment->getParent()].push_back(ERE);
1568 //===- MBlazeELFObjectWriter -------------------------------------------===//
1570 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1571 bool _IsLittleEndian,
1573 bool _HasRelocationAddend,
1574 Triple::OSType _OSType)
1575 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1576 _HasRelocationAddend, _OSType) {
1579 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1582 void MBlazeELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1583 const MCAsmLayout &Layout,
1584 const MCFragment *Fragment,
1585 const MCFixup &Fixup,
1587 uint64_t &FixedValue) {
1590 int64_t Value = Target.getConstant();
1591 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1592 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1593 const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1595 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1596 if (!Target.isAbsolute()) {
1597 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1598 const MCSymbol &SymbolB = RefB->getSymbol();
1599 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1602 // Offset of the symbol in the section
1603 int64_t a = Layout.getSymbolOffset(&SDB);
1605 // Ofeset of the relocation in the section
1606 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1611 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1612 MCFragment *F = SD.getFragment();
1614 Index = F->getParent()->getOrdinal();
1616 // Offset of the symbol in the section
1617 Value += Layout.getSymbolOffset(&SD);
1619 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1620 WeakrefUsedInReloc.insert(RelocSymbol);
1622 UsedInReloc.insert(RelocSymbol);
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 = (RelocSymbol || Addend !=0) ? ELF::R_MICROBLAZE_32
1648 : ELF::R_MICROBLAZE_64;
1651 Type = ELF::R_MICROBLAZE_32;
1656 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
1657 if (RelocNeedsGOT(Modifier))
1660 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1663 if (!HasRelocationAddend) Addend = 0;
1664 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1665 Relocations[Fragment->getParent()].push_back(ERE);
1668 //===- X86ELFObjectWriter -------------------------------------------===//
1671 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1672 bool _IsLittleEndian,
1673 uint16_t _EMachine, bool _HasRelocationAddend,
1674 Triple::OSType _OSType)
1675 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1676 _HasRelocationAddend, _OSType)
1679 X86ELFObjectWriter::~X86ELFObjectWriter()
1682 void X86ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1683 const MCAsmLayout &Layout,
1684 const MCFragment *Fragment,
1685 const MCFixup &Fixup,
1687 uint64_t &FixedValue) {
1690 int64_t Value = Target.getConstant();
1691 const MCSymbol *RelocSymbol = NULL;
1693 bool IsPCRel = isFixupKindPCRel(Fixup.getKind());
1694 if (!Target.isAbsolute()) {
1695 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1696 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1697 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1699 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1700 const MCSymbol &SymbolB = RefB->getSymbol();
1701 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1704 // Offset of the symbol in the section
1705 int64_t a = Layout.getSymbolOffset(&SDB);
1707 // Ofeset of the relocation in the section
1708 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1713 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1714 MCFragment *F = SD.getFragment();
1716 Index = F->getParent()->getOrdinal() + 1;
1718 // Offset of the symbol in the section
1719 Value += Layout.getSymbolOffset(&SD);
1721 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1722 WeakrefUsedInReloc.insert(RelocSymbol);
1724 UsedInReloc.insert(RelocSymbol);
1728 // Compensate for the addend on i386.
1735 // determine the type of the relocation
1737 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1738 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1744 llvm_unreachable("Unimplemented");
1745 case MCSymbolRefExpr::VK_None:
1746 Type = ELF::R_X86_64_PC32;
1748 case MCSymbolRefExpr::VK_PLT:
1749 Type = ELF::R_X86_64_PLT32;
1751 case MCSymbolRefExpr::VK_GOTPCREL:
1752 Type = ELF::R_X86_64_GOTPCREL;
1754 case MCSymbolRefExpr::VK_GOTTPOFF:
1755 Type = ELF::R_X86_64_GOTTPOFF;
1757 case MCSymbolRefExpr::VK_TLSGD:
1758 Type = ELF::R_X86_64_TLSGD;
1760 case MCSymbolRefExpr::VK_TLSLD:
1761 Type = ELF::R_X86_64_TLSLD;
1765 switch ((unsigned)Fixup.getKind()) {
1766 default: llvm_unreachable("invalid fixup kind!");
1767 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1768 case X86::reloc_signed_4byte:
1770 assert(isInt<32>(Target.getConstant()));
1773 llvm_unreachable("Unimplemented");
1774 case MCSymbolRefExpr::VK_None:
1775 Type = ELF::R_X86_64_32S;
1777 case MCSymbolRefExpr::VK_GOT:
1778 Type = ELF::R_X86_64_GOT32;
1780 case MCSymbolRefExpr::VK_GOTPCREL:
1781 Type = ELF::R_X86_64_GOTPCREL;
1783 case MCSymbolRefExpr::VK_TPOFF:
1784 Type = ELF::R_X86_64_TPOFF32;
1786 case MCSymbolRefExpr::VK_DTPOFF:
1787 Type = ELF::R_X86_64_DTPOFF32;
1792 Type = ELF::R_X86_64_32;
1794 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1796 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1803 llvm_unreachable("Unimplemented");
1804 case MCSymbolRefExpr::VK_None:
1805 Type = ELF::R_386_PC32;
1807 case MCSymbolRefExpr::VK_PLT:
1808 Type = ELF::R_386_PLT32;
1812 switch ((unsigned)Fixup.getKind()) {
1813 default: llvm_unreachable("invalid fixup kind!");
1815 case X86::reloc_global_offset_table:
1816 Type = ELF::R_386_GOTPC;
1819 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1821 case X86::reloc_signed_4byte:
1826 llvm_unreachable("Unimplemented");
1827 case MCSymbolRefExpr::VK_None:
1828 Type = ELF::R_386_32;
1830 case MCSymbolRefExpr::VK_GOT:
1831 Type = ELF::R_386_GOT32;
1833 case MCSymbolRefExpr::VK_GOTOFF:
1834 Type = ELF::R_386_GOTOFF;
1836 case MCSymbolRefExpr::VK_TLSGD:
1837 Type = ELF::R_386_TLS_GD;
1839 case MCSymbolRefExpr::VK_TPOFF:
1840 Type = ELF::R_386_TLS_LE_32;
1842 case MCSymbolRefExpr::VK_INDNTPOFF:
1843 Type = ELF::R_386_TLS_IE;
1845 case MCSymbolRefExpr::VK_NTPOFF:
1846 Type = ELF::R_386_TLS_LE;
1848 case MCSymbolRefExpr::VK_GOTNTPOFF:
1849 Type = ELF::R_386_TLS_GOTIE;
1851 case MCSymbolRefExpr::VK_TLSLDM:
1852 Type = ELF::R_386_TLS_LDM;
1854 case MCSymbolRefExpr::VK_DTPOFF:
1855 Type = ELF::R_386_TLS_LDO_32;
1859 case FK_Data_2: Type = ELF::R_386_16; break;
1861 case FK_Data_1: Type = ELF::R_386_8; break;
1866 if (RelocNeedsGOT(Modifier))
1870 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
1873 if (!HasRelocationAddend) Addend = 0;
1874 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
1875 Relocations[Fragment->getParent()].push_back(ERE);