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/OwningPtr.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCELFObjectWriter.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Target/TargetAsmBackend.h"
34 #include "../Target/X86/X86FixupKinds.h"
35 #include "../Target/ARM/ARMFixupKinds.h"
40 static unsigned GetType(const MCSymbolData &SD) {
41 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
42 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
43 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
44 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
45 Type == ELF::STT_TLS);
49 static unsigned GetBinding(const MCSymbolData &SD) {
50 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
51 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
52 Binding == ELF::STB_WEAK);
56 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
57 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
58 Binding == ELF::STB_WEAK);
59 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
60 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
63 static unsigned GetVisibility(MCSymbolData &SD) {
65 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
66 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
67 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
72 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
76 case MCSymbolRefExpr::VK_GOT:
77 case MCSymbolRefExpr::VK_PLT:
78 case MCSymbolRefExpr::VK_GOTPCREL:
79 case MCSymbolRefExpr::VK_TPOFF:
80 case MCSymbolRefExpr::VK_TLSGD:
81 case MCSymbolRefExpr::VK_GOTTPOFF:
82 case MCSymbolRefExpr::VK_INDNTPOFF:
83 case MCSymbolRefExpr::VK_NTPOFF:
84 case MCSymbolRefExpr::VK_GOTNTPOFF:
85 case MCSymbolRefExpr::VK_TLSLDM:
86 case MCSymbolRefExpr::VK_DTPOFF:
87 case MCSymbolRefExpr::VK_TLSLD:
92 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
93 const MCFixupKindInfo &FKI =
94 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
96 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
100 class ELFObjectWriter : public MCObjectWriter {
102 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
103 return Kind == X86::reloc_riprel_4byte ||
104 Kind == X86::reloc_riprel_4byte_movq_load;
108 /// ELFSymbolData - Helper struct for containing some precomputed information
110 struct ELFSymbolData {
111 MCSymbolData *SymbolData;
112 uint64_t StringIndex;
113 uint32_t SectionIndex;
115 // Support lexicographic sorting.
116 bool operator<(const ELFSymbolData &RHS) const {
117 if (GetType(*SymbolData) == ELF::STT_FILE)
119 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
121 return SymbolData->getSymbol().getName() <
122 RHS.SymbolData->getSymbol().getName();
126 /// @name Relocation Data
129 struct ELFRelocationEntry {
130 // Make these big enough for both 32-bit and 64-bit
134 const MCSymbol *Symbol;
138 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
140 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
141 unsigned RelType, const MCSymbol *Sym,
143 : r_offset(RelocOffset), Index(Idx), Type(RelType),
144 Symbol(Sym), r_addend(Addend) {}
146 // Support lexicographic sorting.
147 bool operator<(const ELFRelocationEntry &RE) const {
148 return RE.r_offset < r_offset;
152 /// The target specific ELF writer instance.
153 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
155 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
156 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
157 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
159 llvm::DenseMap<const MCSectionData*,
160 std::vector<ELFRelocationEntry> > Relocations;
161 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
164 /// @name Symbol Table Data
167 SmallString<256> StringTable;
168 std::vector<ELFSymbolData> LocalSymbolData;
169 std::vector<ELFSymbolData> ExternalSymbolData;
170 std::vector<ELFSymbolData> UndefinedSymbolData;
176 bool NeedsSymtabShndx;
178 // This holds the symbol table index of the last local symbol.
179 unsigned LastLocalSymbolIndex;
180 // This holds the .strtab section index.
181 unsigned StringTableIndex;
182 // This holds the .symtab section index.
183 unsigned SymbolTableIndex;
185 unsigned ShstrtabIndex;
188 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
189 const MCValue &Target,
190 const MCFragment &F) const;
192 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
193 bool hasRelocationAddend() const {
194 return TargetObjectWriter->hasRelocationAddend();
198 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
199 raw_ostream &_OS, bool IsLittleEndian)
200 : MCObjectWriter(_OS, IsLittleEndian),
201 TargetObjectWriter(MOTW),
202 NeedsGOT(false), NeedsSymtabShndx(false){
205 virtual ~ELFObjectWriter();
207 void WriteWord(uint64_t W) {
214 void StringLE16(char *buf, uint16_t Value) {
215 buf[0] = char(Value >> 0);
216 buf[1] = char(Value >> 8);
219 void StringLE32(char *buf, uint32_t Value) {
220 StringLE16(buf, uint16_t(Value >> 0));
221 StringLE16(buf + 2, uint16_t(Value >> 16));
224 void StringLE64(char *buf, uint64_t Value) {
225 StringLE32(buf, uint32_t(Value >> 0));
226 StringLE32(buf + 4, uint32_t(Value >> 32));
229 void StringBE16(char *buf ,uint16_t Value) {
230 buf[0] = char(Value >> 8);
231 buf[1] = char(Value >> 0);
234 void StringBE32(char *buf, uint32_t Value) {
235 StringBE16(buf, uint16_t(Value >> 16));
236 StringBE16(buf + 2, uint16_t(Value >> 0));
239 void StringBE64(char *buf, uint64_t Value) {
240 StringBE32(buf, uint32_t(Value >> 32));
241 StringBE32(buf + 4, uint32_t(Value >> 0));
244 void String8(MCDataFragment &F, uint8_t Value) {
247 F.getContents() += StringRef(buf, 1);
250 void String16(MCDataFragment &F, uint16_t Value) {
252 if (isLittleEndian())
253 StringLE16(buf, Value);
255 StringBE16(buf, Value);
256 F.getContents() += StringRef(buf, 2);
259 void String32(MCDataFragment &F, uint32_t Value) {
261 if (isLittleEndian())
262 StringLE32(buf, Value);
264 StringBE32(buf, Value);
265 F.getContents() += StringRef(buf, 4);
268 void String64(MCDataFragment &F, uint64_t Value) {
270 if (isLittleEndian())
271 StringLE64(buf, Value);
273 StringBE64(buf, Value);
274 F.getContents() += StringRef(buf, 8);
277 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
279 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
280 uint64_t name, uint8_t info,
281 uint64_t value, uint64_t size,
282 uint8_t other, uint32_t shndx,
285 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
287 const MCAsmLayout &Layout);
289 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
290 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
291 const MCAssembler &Asm,
292 const MCAsmLayout &Layout,
293 const SectionIndexMapTy &SectionIndexMap);
295 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
296 const MCFragment *Fragment, const MCFixup &Fixup,
297 MCValue Target, uint64_t &FixedValue);
299 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
302 // Map from a group section to the signature symbol
303 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
304 // Map from a signature symbol to the group section
305 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
307 /// ComputeSymbolTable - Compute the symbol table data
309 /// \param StringTable [out] - The string table data.
310 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
312 virtual void ComputeSymbolTable(MCAssembler &Asm,
313 const SectionIndexMapTy &SectionIndexMap,
314 RevGroupMapTy RevGroupMap);
316 virtual void ComputeIndexMap(MCAssembler &Asm,
317 SectionIndexMapTy &SectionIndexMap);
319 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
320 const MCSectionData &SD);
322 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
323 for (MCAssembler::const_iterator it = Asm.begin(),
324 ie = Asm.end(); it != ie; ++it) {
325 WriteRelocation(Asm, Layout, *it);
329 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
330 const SectionIndexMapTy &SectionIndexMap);
332 virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
333 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
335 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
336 const MCAsmLayout &Layout);
338 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
339 uint64_t Address, uint64_t Offset,
340 uint64_t Size, uint32_t Link, uint32_t Info,
341 uint64_t Alignment, uint64_t EntrySize);
343 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
345 const MCSectionData *SD);
348 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
349 const MCSymbolData &DataA,
350 const MCFragment &FB,
354 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
355 virtual void WriteSection(MCAssembler &Asm,
356 const SectionIndexMapTy &SectionIndexMap,
357 uint32_t GroupSymbolIndex,
358 uint64_t Offset, uint64_t Size, uint64_t Alignment,
359 const MCSectionELF &Section);
362 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
363 bool IsPCRel, bool IsRelocWithSymbol,
367 //===- X86ELFObjectWriter -------------------------------------------===//
369 class X86ELFObjectWriter : public ELFObjectWriter {
371 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
373 bool IsLittleEndian);
375 virtual ~X86ELFObjectWriter();
377 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
378 bool IsPCRel, bool IsRelocWithSymbol,
383 //===- ARMELFObjectWriter -------------------------------------------===//
385 class ARMELFObjectWriter : public ELFObjectWriter {
387 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
389 bool IsLittleEndian);
391 virtual ~ARMELFObjectWriter();
393 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
394 bool IsPCRel, bool IsRelocWithSymbol,
398 //===- MBlazeELFObjectWriter -------------------------------------------===//
400 class MBlazeELFObjectWriter : public ELFObjectWriter {
402 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
404 bool IsLittleEndian);
406 virtual ~MBlazeELFObjectWriter();
408 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
409 bool IsPCRel, bool IsRelocWithSymbol,
414 ELFObjectWriter::~ELFObjectWriter()
417 // Emit the ELF header.
418 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
419 unsigned NumberOfSections) {
425 // emitWord method behaves differently for ELF32 and ELF64, writing
426 // 4 bytes in the former and 8 in the latter.
428 Write8(0x7f); // e_ident[EI_MAG0]
429 Write8('E'); // e_ident[EI_MAG1]
430 Write8('L'); // e_ident[EI_MAG2]
431 Write8('F'); // e_ident[EI_MAG3]
433 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
436 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
438 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
440 switch (TargetObjectWriter->getOSType()) {
441 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
442 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
443 default: Write8(ELF::ELFOSABI_NONE); break;
445 Write8(0); // e_ident[EI_ABIVERSION]
447 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
449 Write16(ELF::ET_REL); // e_type
451 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
453 Write32(ELF::EV_CURRENT); // e_version
454 WriteWord(0); // e_entry, no entry point in .o file
455 WriteWord(0); // e_phoff, no program header for .o
456 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
457 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
459 // FIXME: Make this configurable.
460 Write32(0); // e_flags = whatever the target wants
462 // e_ehsize = ELF header size
463 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
465 Write16(0); // e_phentsize = prog header entry size
466 Write16(0); // e_phnum = # prog header entries = 0
468 // e_shentsize = Section header entry size
469 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
471 // e_shnum = # of section header ents
472 if (NumberOfSections >= ELF::SHN_LORESERVE)
475 Write16(NumberOfSections);
477 // e_shstrndx = Section # of '.shstrtab'
478 if (NumberOfSections >= ELF::SHN_LORESERVE)
479 Write16(ELF::SHN_XINDEX);
481 Write16(ShstrtabIndex);
484 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
485 MCDataFragment *ShndxF,
487 uint8_t info, uint64_t value,
488 uint64_t size, uint8_t other,
492 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
493 String32(*ShndxF, shndx);
495 String32(*ShndxF, 0);
498 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
499 uint16_t(ELF::SHN_XINDEX) : shndx;
502 String32(*SymtabF, name); // st_name
503 String8(*SymtabF, info); // st_info
504 String8(*SymtabF, other); // st_other
505 String16(*SymtabF, Index); // st_shndx
506 String64(*SymtabF, value); // st_value
507 String64(*SymtabF, size); // st_size
509 String32(*SymtabF, name); // st_name
510 String32(*SymtabF, value); // st_value
511 String32(*SymtabF, size); // st_size
512 String8(*SymtabF, info); // st_info
513 String8(*SymtabF, other); // st_other
514 String16(*SymtabF, Index); // st_shndx
518 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
519 if (Data.isCommon() && Data.isExternal())
520 return Data.getCommonAlignment();
522 const MCSymbol &Symbol = Data.getSymbol();
524 if (Symbol.isAbsolute() && Symbol.isVariable()) {
525 if (const MCExpr *Value = Symbol.getVariableValue()) {
527 if (Value->EvaluateAsAbsolute(IntValue, Layout))
528 return (uint64_t)IntValue;
532 if (!Symbol.isInSection())
535 if (Data.getFragment())
536 return Layout.getSymbolOffset(&Data);
541 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
542 const MCAsmLayout &Layout) {
543 // The presence of symbol versions causes undefined symbols and
544 // versions declared with @@@ to be renamed.
546 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
547 ie = Asm.symbol_end(); it != ie; ++it) {
548 const MCSymbol &Alias = it->getSymbol();
549 const MCSymbol &Symbol = Alias.AliasedSymbol();
550 MCSymbolData &SD = Asm.getSymbolData(Symbol);
553 if (&Symbol == &Alias)
556 StringRef AliasName = Alias.getName();
557 size_t Pos = AliasName.find('@');
558 if (Pos == StringRef::npos)
561 // Aliases defined with .symvar copy the binding from the symbol they alias.
562 // This is the first place we are able to copy this information.
563 it->setExternal(SD.isExternal());
564 SetBinding(*it, GetBinding(SD));
566 StringRef Rest = AliasName.substr(Pos);
567 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
570 // FIXME: produce a better error message.
571 if (Symbol.isUndefined() && Rest.startswith("@@") &&
572 !Rest.startswith("@@@"))
573 report_fatal_error("A @@ version cannot be undefined");
575 Renames.insert(std::make_pair(&Symbol, &Alias));
579 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
580 MCDataFragment *ShndxF,
582 const MCAsmLayout &Layout) {
583 MCSymbolData &OrigData = *MSD.SymbolData;
585 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
587 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
588 Data.getSymbol().isVariable();
590 uint8_t Binding = GetBinding(OrigData);
591 uint8_t Visibility = GetVisibility(OrigData);
592 uint8_t Type = GetType(Data);
594 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
595 uint8_t Other = Visibility;
597 uint64_t Value = SymbolValue(Data, Layout);
600 assert(!(Data.isCommon() && !Data.isExternal()));
602 const MCExpr *ESize = Data.getSize();
605 if (!ESize->EvaluateAsAbsolute(Res, Layout))
606 report_fatal_error("Size expression must be absolute.");
610 // Write out the symbol table entry
611 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
612 Size, Other, MSD.SectionIndex, IsReserved);
615 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
616 MCDataFragment *ShndxF,
617 const MCAssembler &Asm,
618 const MCAsmLayout &Layout,
619 const SectionIndexMapTy &SectionIndexMap) {
620 // The string table must be emitted first because we need the index
621 // into the string table for all the symbol names.
622 assert(StringTable.size() && "Missing string table");
624 // FIXME: Make sure the start of the symbol table is aligned.
626 // The first entry is the undefined symbol entry.
627 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
629 // Write the symbol table entries.
630 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
631 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
632 ELFSymbolData &MSD = LocalSymbolData[i];
633 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
636 // Write out a symbol table entry for each regular section.
637 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
639 const MCSectionELF &Section =
640 static_cast<const MCSectionELF&>(i->getSection());
641 if (Section.getType() == ELF::SHT_RELA ||
642 Section.getType() == ELF::SHT_REL ||
643 Section.getType() == ELF::SHT_STRTAB ||
644 Section.getType() == ELF::SHT_SYMTAB)
646 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
647 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
648 LastLocalSymbolIndex++;
651 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
652 ELFSymbolData &MSD = ExternalSymbolData[i];
653 MCSymbolData &Data = *MSD.SymbolData;
654 assert(((Data.getFlags() & ELF_STB_Global) ||
655 (Data.getFlags() & ELF_STB_Weak)) &&
656 "External symbol requires STB_GLOBAL or STB_WEAK flag");
657 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
658 if (GetBinding(Data) == ELF::STB_LOCAL)
659 LastLocalSymbolIndex++;
662 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
663 ELFSymbolData &MSD = UndefinedSymbolData[i];
664 MCSymbolData &Data = *MSD.SymbolData;
665 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
666 if (GetBinding(Data) == ELF::STB_LOCAL)
667 LastLocalSymbolIndex++;
671 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
672 const MCValue &Target,
673 const MCFragment &F) const {
674 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
675 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
676 const MCSymbol *Renamed = Renames.lookup(&Symbol);
677 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
679 if (ASymbol.isUndefined()) {
685 if (SD.isExternal()) {
691 const MCSectionELF &Section =
692 static_cast<const MCSectionELF&>(ASymbol.getSection());
693 const SectionKind secKind = Section.getKind();
698 if (secKind.isThreadLocal()) {
704 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
705 const MCSectionELF &Sec2 =
706 static_cast<const MCSectionELF&>(F.getParent()->getSection());
708 if (&Sec2 != &Section &&
709 (Kind == MCSymbolRefExpr::VK_PLT ||
710 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
711 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
717 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
718 if (Target.getConstant() == 0)
729 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
730 const MCAsmLayout &Layout,
731 const MCFragment *Fragment,
732 const MCFixup &Fixup,
734 uint64_t &FixedValue) {
737 int64_t Value = Target.getConstant();
738 const MCSymbol *RelocSymbol = NULL;
740 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
741 if (!Target.isAbsolute()) {
742 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
743 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
744 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
746 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
747 const MCSymbol &SymbolB = RefB->getSymbol();
748 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
751 // Offset of the symbol in the section
752 int64_t a = Layout.getSymbolOffset(&SDB);
754 // Ofeset of the relocation in the section
755 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
760 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
761 MCFragment *F = SD.getFragment();
763 Index = F->getParent()->getOrdinal() + 1;
765 // Offset of the symbol in the section
766 Value += Layout.getSymbolOffset(&SD);
768 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
769 WeakrefUsedInReloc.insert(RelocSymbol);
771 UsedInReloc.insert(RelocSymbol);
775 // Compensate for the addend on i386.
781 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
782 (RelocSymbol != 0), Addend);
784 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
787 if (!hasRelocationAddend())
789 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
790 Relocations[Fragment->getParent()].push_back(ERE);
795 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
797 MCSymbolData &SD = Asm.getSymbolData(*S);
798 return SD.getIndex();
801 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
802 bool Used, bool Renamed) {
803 if (Data.getFlags() & ELF_Other_Weakref)
812 const MCSymbol &Symbol = Data.getSymbol();
814 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
817 const MCSymbol &A = Symbol.AliasedSymbol();
818 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
821 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
824 if (Symbol.isTemporary())
830 static bool isLocal(const MCSymbolData &Data, bool isSignature,
831 bool isUsedInReloc) {
832 if (Data.isExternal())
835 const MCSymbol &Symbol = Data.getSymbol();
836 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
838 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
839 if (isSignature && !isUsedInReloc)
848 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
849 SectionIndexMapTy &SectionIndexMap) {
851 for (MCAssembler::iterator it = Asm.begin(),
852 ie = Asm.end(); it != ie; ++it) {
853 const MCSectionELF &Section =
854 static_cast<const MCSectionELF &>(it->getSection());
855 if (Section.getType() != ELF::SHT_GROUP)
857 SectionIndexMap[&Section] = Index++;
860 for (MCAssembler::iterator it = Asm.begin(),
861 ie = Asm.end(); it != ie; ++it) {
862 const MCSectionELF &Section =
863 static_cast<const MCSectionELF &>(it->getSection());
864 if (Section.getType() == ELF::SHT_GROUP)
866 SectionIndexMap[&Section] = Index++;
870 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
871 const SectionIndexMapTy &SectionIndexMap,
872 RevGroupMapTy RevGroupMap) {
873 // FIXME: Is this the correct place to do this?
875 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
876 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
877 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
878 Data.setExternal(true);
879 SetBinding(Data, ELF::STB_GLOBAL);
882 // Build section lookup table.
883 int NumRegularSections = Asm.size();
885 // Index 0 is always the empty string.
886 StringMap<uint64_t> StringIndexMap;
887 StringTable += '\x00';
889 // Add the data for the symbols.
890 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
891 ie = Asm.symbol_end(); it != ie; ++it) {
892 const MCSymbol &Symbol = it->getSymbol();
894 bool Used = UsedInReloc.count(&Symbol);
895 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
896 bool isSignature = RevGroupMap.count(&Symbol);
898 if (!isInSymtab(Asm, *it,
899 Used || WeakrefUsed || isSignature,
900 Renames.count(&Symbol)))
905 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
907 // Undefined symbols are global, but this is the first place we
908 // are able to set it.
909 bool Local = isLocal(*it, isSignature, Used);
910 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
911 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
912 SetBinding(*it, ELF::STB_GLOBAL);
913 SetBinding(SD, ELF::STB_GLOBAL);
916 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
917 SetBinding(*it, ELF::STB_WEAK);
919 if (it->isCommon()) {
921 MSD.SectionIndex = ELF::SHN_COMMON;
922 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
923 MSD.SectionIndex = ELF::SHN_ABS;
924 } else if (RefSymbol.isUndefined()) {
925 if (isSignature && !Used)
926 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
928 MSD.SectionIndex = ELF::SHN_UNDEF;
930 const MCSectionELF &Section =
931 static_cast<const MCSectionELF&>(RefSymbol.getSection());
932 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
933 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
934 NeedsSymtabShndx = true;
935 assert(MSD.SectionIndex && "Invalid section index!");
938 // The @@@ in symbol version is replaced with @ in undefined symbols and
939 // @@ in defined ones.
940 StringRef Name = Symbol.getName();
943 size_t Pos = Name.find("@@@");
944 if (Pos != StringRef::npos) {
945 Buf += Name.substr(0, Pos);
946 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
947 Buf += Name.substr(Pos + Skip);
951 uint64_t &Entry = StringIndexMap[Name];
953 Entry = StringTable.size();
955 StringTable += '\x00';
957 MSD.StringIndex = Entry;
958 if (MSD.SectionIndex == ELF::SHN_UNDEF)
959 UndefinedSymbolData.push_back(MSD);
961 LocalSymbolData.push_back(MSD);
963 ExternalSymbolData.push_back(MSD);
966 // Symbols are required to be in lexicographic order.
967 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
968 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
969 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
971 // Set the symbol indices. Local symbols must come before all other
972 // symbols with non-local bindings.
974 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
975 LocalSymbolData[i].SymbolData->setIndex(Index++);
977 Index += NumRegularSections;
979 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
980 ExternalSymbolData[i].SymbolData->setIndex(Index++);
981 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
982 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
985 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
986 const MCSectionData &SD) {
987 if (!Relocations[&SD].empty()) {
988 MCContext &Ctx = Asm.getContext();
989 const MCSectionELF *RelaSection;
990 const MCSectionELF &Section =
991 static_cast<const MCSectionELF&>(SD.getSection());
993 const StringRef SectionName = Section.getSectionName();
994 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
995 RelaSectionName += SectionName;
998 if (hasRelocationAddend())
999 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1001 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1003 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1004 ELF::SHT_RELA : ELF::SHT_REL, 0,
1005 SectionKind::getReadOnly(),
1008 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1009 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1011 MCDataFragment *F = new MCDataFragment(&RelaSD);
1013 WriteRelocationsFragment(Asm, F, &SD);
1017 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1018 uint64_t Flags, uint64_t Address,
1019 uint64_t Offset, uint64_t Size,
1020 uint32_t Link, uint32_t Info,
1022 uint64_t EntrySize) {
1023 Write32(Name); // sh_name: index into string table
1024 Write32(Type); // sh_type
1025 WriteWord(Flags); // sh_flags
1026 WriteWord(Address); // sh_addr
1027 WriteWord(Offset); // sh_offset
1028 WriteWord(Size); // sh_size
1029 Write32(Link); // sh_link
1030 Write32(Info); // sh_info
1031 WriteWord(Alignment); // sh_addralign
1032 WriteWord(EntrySize); // sh_entsize
1035 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1037 const MCSectionData *SD) {
1038 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1039 // sort by the r_offset just like gnu as does
1040 array_pod_sort(Relocs.begin(), Relocs.end());
1042 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1043 ELFRelocationEntry entry = Relocs[e - i - 1];
1047 else if (entry.Index < 0)
1048 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1050 entry.Index += LocalSymbolData.size();
1052 String64(*F, entry.r_offset);
1054 struct ELF::Elf64_Rela ERE64;
1055 ERE64.setSymbolAndType(entry.Index, entry.Type);
1056 String64(*F, ERE64.r_info);
1058 if (hasRelocationAddend())
1059 String64(*F, entry.r_addend);
1061 String32(*F, entry.r_offset);
1063 struct ELF::Elf32_Rela ERE32;
1064 ERE32.setSymbolAndType(entry.Index, entry.Type);
1065 String32(*F, ERE32.r_info);
1067 if (hasRelocationAddend())
1068 String32(*F, entry.r_addend);
1073 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1074 MCAsmLayout &Layout,
1075 const SectionIndexMapTy &SectionIndexMap) {
1076 MCContext &Ctx = Asm.getContext();
1079 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1081 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1082 const MCSectionELF *ShstrtabSection =
1083 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1084 SectionKind::getReadOnly());
1085 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1086 ShstrtabSD.setAlignment(1);
1087 ShstrtabIndex = Asm.size();
1089 const MCSectionELF *SymtabSection =
1090 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1091 SectionKind::getReadOnly(),
1093 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1094 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1095 SymbolTableIndex = Asm.size();
1097 MCSectionData *SymtabShndxSD = NULL;
1099 if (NeedsSymtabShndx) {
1100 const MCSectionELF *SymtabShndxSection =
1101 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1102 SectionKind::getReadOnly(), 4, "");
1103 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1104 SymtabShndxSD->setAlignment(4);
1107 const MCSection *StrtabSection;
1108 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1109 SectionKind::getReadOnly());
1110 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1111 StrtabSD.setAlignment(1);
1112 StringTableIndex = Asm.size();
1114 WriteRelocations(Asm, Layout);
1117 F = new MCDataFragment(&SymtabSD);
1118 MCDataFragment *ShndxF = NULL;
1119 if (NeedsSymtabShndx) {
1120 ShndxF = new MCDataFragment(SymtabShndxSD);
1122 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1124 F = new MCDataFragment(&StrtabSD);
1125 F->getContents().append(StringTable.begin(), StringTable.end());
1127 F = new MCDataFragment(&ShstrtabSD);
1129 // Section header string table.
1131 // The first entry of a string table holds a null character so skip
1134 F->getContents() += '\x00';
1136 StringMap<uint64_t> SecStringMap;
1137 for (MCAssembler::const_iterator it = Asm.begin(),
1138 ie = Asm.end(); it != ie; ++it) {
1139 const MCSectionELF &Section =
1140 static_cast<const MCSectionELF&>(it->getSection());
1141 // FIXME: We could merge suffixes like in .text and .rela.text.
1143 StringRef Name = Section.getSectionName();
1144 if (SecStringMap.count(Name)) {
1145 SectionStringTableIndex[&Section] = SecStringMap[Name];
1148 // Remember the index into the string table so we can write it
1149 // into the sh_name field of the section header table.
1150 SectionStringTableIndex[&Section] = Index;
1151 SecStringMap[Name] = Index;
1153 Index += Name.size() + 1;
1154 F->getContents() += Name;
1155 F->getContents() += '\x00';
1160 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1161 const MCSymbolData &DataA,
1162 const MCFragment &FB,
1164 bool IsPCRel) const {
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 if (DataA.isExternal())
1171 const MCSection &SecA = DataA.getSymbol().AliasedSymbol().getSection();
1172 const MCSection &SecB = FB.getParent()->getSection();
1173 // On ELF A - B is absolute if A and B are in the same section.
1174 return &SecA == &SecB;
1177 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1178 MCAsmLayout &Layout,
1179 GroupMapTy &GroupMap,
1180 RevGroupMapTy &RevGroupMap) {
1182 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1184 const MCSectionELF &Section =
1185 static_cast<const MCSectionELF&>(it->getSection());
1186 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1189 const MCSymbol *SignatureSymbol = Section.getGroup();
1190 Asm.getOrCreateSymbolData(*SignatureSymbol);
1191 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1193 Group = Asm.getContext().CreateELFGroupSection();
1194 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1195 Data.setAlignment(4);
1196 MCDataFragment *F = new MCDataFragment(&Data);
1197 String32(*F, ELF::GRP_COMDAT);
1199 GroupMap[Group] = SignatureSymbol;
1202 // Add sections to the groups
1204 unsigned NumGroups = RevGroupMap.size();
1205 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1206 it != ie; ++it, ++Index) {
1207 const MCSectionELF &Section =
1208 static_cast<const MCSectionELF&>(it->getSection());
1209 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1211 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1212 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1213 // FIXME: we could use the previous fragment
1214 MCDataFragment *F = new MCDataFragment(&Data);
1215 String32(*F, NumGroups + Index);
1219 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1220 const SectionIndexMapTy &SectionIndexMap,
1221 uint32_t GroupSymbolIndex,
1222 uint64_t Offset, uint64_t Size,
1224 const MCSectionELF &Section) {
1225 uint64_t sh_link = 0;
1226 uint64_t sh_info = 0;
1228 switch(Section.getType()) {
1229 case ELF::SHT_DYNAMIC:
1230 sh_link = SectionStringTableIndex[&Section];
1235 case ELF::SHT_RELA: {
1236 const MCSectionELF *SymtabSection;
1237 const MCSectionELF *InfoSection;
1238 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1240 SectionKind::getReadOnly());
1241 sh_link = SectionIndexMap.lookup(SymtabSection);
1242 assert(sh_link && ".symtab not found");
1244 // Remove ".rel" and ".rela" prefixes.
1245 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1246 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1248 InfoSection = Asm.getContext().getELFSection(SectionName,
1249 ELF::SHT_PROGBITS, 0,
1250 SectionKind::getReadOnly());
1251 sh_info = SectionIndexMap.lookup(InfoSection);
1255 case ELF::SHT_SYMTAB:
1256 case ELF::SHT_DYNSYM:
1257 sh_link = StringTableIndex;
1258 sh_info = LastLocalSymbolIndex;
1261 case ELF::SHT_SYMTAB_SHNDX:
1262 sh_link = SymbolTableIndex;
1265 case ELF::SHT_PROGBITS:
1266 case ELF::SHT_STRTAB:
1267 case ELF::SHT_NOBITS:
1270 case ELF::SHT_ARM_ATTRIBUTES:
1271 case ELF::SHT_INIT_ARRAY:
1272 case ELF::SHT_FINI_ARRAY:
1273 case ELF::SHT_PREINIT_ARRAY:
1277 case ELF::SHT_GROUP: {
1278 sh_link = SymbolTableIndex;
1279 sh_info = GroupSymbolIndex;
1284 assert(0 && "FIXME: sh_type value not supported!");
1288 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1289 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1290 Alignment, Section.getEntrySize());
1293 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1294 return SD.getOrdinal() == ~UINT32_C(0) &&
1295 !SD.getSection().isVirtualSection();
1298 static uint64_t DataSectionSize(const MCSectionData &SD) {
1300 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1302 const MCFragment &F = *i;
1303 assert(F.getKind() == MCFragment::FT_Data);
1304 Ret += cast<MCDataFragment>(F).getContents().size();
1309 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1310 const MCSectionData &SD) {
1311 if (IsELFMetaDataSection(SD))
1312 return DataSectionSize(SD);
1313 return Layout.getSectionFileSize(&SD);
1316 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1317 const MCSectionData &SD) {
1318 if (IsELFMetaDataSection(SD))
1319 return DataSectionSize(SD);
1320 return Layout.getSectionAddressSize(&SD);
1323 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1324 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1326 const MCFragment &F = *i;
1327 assert(F.getKind() == MCFragment::FT_Data);
1328 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1332 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1333 const MCAsmLayout &Layout) {
1334 GroupMapTy GroupMap;
1335 RevGroupMapTy RevGroupMap;
1336 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1339 SectionIndexMapTy SectionIndexMap;
1341 ComputeIndexMap(Asm, SectionIndexMap);
1343 // Compute symbol table information.
1344 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1346 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1347 const_cast<MCAsmLayout&>(Layout),
1350 // Update to include the metadata sections.
1351 ComputeIndexMap(Asm, SectionIndexMap);
1353 // Add 1 for the null section.
1354 unsigned NumSections = Asm.size() + 1;
1355 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1356 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1357 sizeof(ELF::Elf32_Ehdr);
1358 uint64_t FileOff = HeaderSize;
1360 std::vector<const MCSectionELF*> Sections;
1361 Sections.resize(NumSections);
1363 for (SectionIndexMapTy::const_iterator i=
1364 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1365 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1366 Sections[p.second] = p.first;
1369 for (unsigned i = 1; i < NumSections; ++i) {
1370 const MCSectionELF &Section = *Sections[i];
1371 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1373 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1375 // Get the size of the section in the output file (including padding).
1376 FileOff += GetSectionFileSize(Layout, SD);
1379 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1381 // Write out the ELF header ...
1382 WriteHeader(FileOff - HeaderSize, NumSections);
1384 FileOff = HeaderSize;
1386 // ... then all of the sections ...
1387 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1389 for (unsigned i = 1; i < NumSections; ++i) {
1390 const MCSectionELF &Section = *Sections[i];
1391 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1393 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1394 WriteZeros(Padding);
1397 // Remember the offset into the file for this section.
1398 SectionOffsetMap[&Section] = FileOff;
1400 FileOff += GetSectionFileSize(Layout, SD);
1402 if (IsELFMetaDataSection(SD))
1403 WriteDataSectionData(this, SD);
1405 Asm.WriteSectionData(&SD, Layout);
1408 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1409 WriteZeros(Padding);
1412 // ... and then the section header table.
1413 // Should we align the section header table?
1415 // Null section first.
1416 uint64_t FirstSectionSize =
1417 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1418 uint32_t FirstSectionLink =
1419 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1420 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1422 for (unsigned i = 1; i < NumSections; ++i) {
1423 const MCSectionELF &Section = *Sections[i];
1424 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1425 uint32_t GroupSymbolIndex;
1426 if (Section.getType() != ELF::SHT_GROUP)
1427 GroupSymbolIndex = 0;
1429 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1431 uint64_t Size = GetSectionAddressSize(Layout, SD);
1433 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1434 SectionOffsetMap[&Section], Size,
1435 SD.getAlignment(), Section);
1439 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1441 bool IsLittleEndian) {
1442 switch (MOTW->getEMachine()) {
1444 case ELF::EM_X86_64:
1445 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1447 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1448 case ELF::EM_MBLAZE:
1449 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1450 default: llvm_unreachable("Unsupported architecture"); break;
1455 /// START OF SUBCLASSES for ELFObjectWriter
1456 //===- ARMELFObjectWriter -------------------------------------------===//
1458 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1460 bool IsLittleEndian)
1461 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1464 ARMELFObjectWriter::~ARMELFObjectWriter()
1467 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1468 const MCFixup &Fixup,
1470 bool IsRelocWithSymbol,
1472 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1473 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1477 switch ((unsigned)Fixup.getKind()) {
1478 default: assert(0 && "Unimplemented");
1481 default: llvm_unreachable("Unsupported Modifier");
1482 case MCSymbolRefExpr::VK_None:
1483 Type = ELF::R_ARM_BASE_PREL; break;
1484 case MCSymbolRefExpr::VK_ARM_TLSGD:
1485 assert(0 && "unimplemented"); break;
1486 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1487 Type = ELF::R_ARM_TLS_IE32;
1489 case ARM::fixup_arm_branch:
1491 case MCSymbolRefExpr::VK_ARM_PLT:
1492 Type = ELF::R_ARM_PLT32; break;
1494 Type = ELF::R_ARM_CALL; break;
1496 case ARM::fixup_arm_movt_hi16:
1497 case ARM::fixup_arm_movt_hi16_pcrel:
1498 Type = ELF::R_ARM_MOVT_PREL; break;
1499 case ARM::fixup_arm_movw_lo16:
1500 case ARM::fixup_arm_movw_lo16_pcrel:
1501 Type = ELF::R_ARM_MOVW_PREL_NC; break;
1505 switch ((unsigned)Fixup.getKind()) {
1506 default: llvm_unreachable("invalid fixup kind!");
1509 default: llvm_unreachable("Unsupported Modifier"); break;
1510 case MCSymbolRefExpr::VK_ARM_GOT:
1511 Type = ELF::R_ARM_GOT_BREL; break;
1512 case MCSymbolRefExpr::VK_ARM_TLSGD:
1513 Type = ELF::R_ARM_TLS_GD32; break;
1514 case MCSymbolRefExpr::VK_ARM_TPOFF:
1515 Type = ELF::R_ARM_TLS_LE32; break;
1516 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1517 Type = ELF::R_ARM_TLS_IE32; break;
1518 case MCSymbolRefExpr::VK_None:
1519 Type = ELF::R_ARM_ABS32; break;
1520 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1521 Type = ELF::R_ARM_GOTOFF32; break;
1523 case ARM::fixup_arm_ldst_pcrel_12:
1524 case ARM::fixup_arm_pcrel_10:
1525 case ARM::fixup_arm_adr_pcrel_12:
1526 case ARM::fixup_arm_thumb_bl:
1527 case ARM::fixup_arm_thumb_cb:
1528 case ARM::fixup_arm_thumb_cp:
1529 case ARM::fixup_arm_thumb_br:
1530 assert(0 && "Unimplemented"); break;
1531 case ARM::fixup_arm_branch:
1532 // FIXME: Differentiate between R_ARM_CALL and
1533 // R_ARM_JUMP24 (latter used for conditional jumps)
1534 Type = ELF::R_ARM_CALL; break;
1535 case ARM::fixup_arm_movt_hi16:
1536 Type = ELF::R_ARM_MOVT_ABS; break;
1537 case ARM::fixup_arm_movw_lo16:
1538 Type = ELF::R_ARM_MOVW_ABS_NC; break;
1542 if (RelocNeedsGOT(Modifier))
1548 //===- MBlazeELFObjectWriter -------------------------------------------===//
1550 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1552 bool IsLittleEndian)
1553 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1556 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1559 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1560 const MCFixup &Fixup,
1562 bool IsRelocWithSymbol,
1564 // determine the type of the relocation
1567 switch ((unsigned)Fixup.getKind()) {
1569 llvm_unreachable("Unimplemented");
1571 Type = ELF::R_MICROBLAZE_64_PCREL;
1574 Type = ELF::R_MICROBLAZE_32_PCREL;
1578 switch ((unsigned)Fixup.getKind()) {
1579 default: llvm_unreachable("invalid fixup kind!");
1581 Type = ((IsRelocWithSymbol || Addend !=0)
1582 ? ELF::R_MICROBLAZE_32
1583 : ELF::R_MICROBLAZE_64);
1586 Type = ELF::R_MICROBLAZE_32;
1593 //===- X86ELFObjectWriter -------------------------------------------===//
1596 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1598 bool IsLittleEndian)
1599 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1602 X86ELFObjectWriter::~X86ELFObjectWriter()
1605 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1606 const MCFixup &Fixup,
1608 bool IsRelocWithSymbol,
1610 // determine the type of the relocation
1612 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1613 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1617 switch ((unsigned)Fixup.getKind()) {
1618 default: llvm_unreachable("invalid fixup kind!");
1620 assert(Modifier == MCSymbolRefExpr::VK_None);
1621 Type = ELF::R_X86_64_PC64;
1623 case X86::reloc_signed_4byte:
1624 case X86::reloc_riprel_4byte_movq_load:
1625 case FK_Data_4: // FIXME?
1626 case X86::reloc_riprel_4byte:
1630 llvm_unreachable("Unimplemented");
1631 case MCSymbolRefExpr::VK_None:
1632 Type = ELF::R_X86_64_PC32;
1634 case MCSymbolRefExpr::VK_PLT:
1635 Type = ELF::R_X86_64_PLT32;
1637 case MCSymbolRefExpr::VK_GOTPCREL:
1638 Type = ELF::R_X86_64_GOTPCREL;
1640 case MCSymbolRefExpr::VK_GOTTPOFF:
1641 Type = ELF::R_X86_64_GOTTPOFF;
1643 case MCSymbolRefExpr::VK_TLSGD:
1644 Type = ELF::R_X86_64_TLSGD;
1646 case MCSymbolRefExpr::VK_TLSLD:
1647 Type = ELF::R_X86_64_TLSLD;
1652 assert(Modifier == MCSymbolRefExpr::VK_None);
1653 Type = ELF::R_X86_64_PC16;
1657 switch ((unsigned)Fixup.getKind()) {
1658 default: llvm_unreachable("invalid fixup kind!");
1659 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1660 case X86::reloc_signed_4byte:
1661 assert(isInt<32>(Target.getConstant()));
1664 llvm_unreachable("Unimplemented");
1665 case MCSymbolRefExpr::VK_None:
1666 Type = ELF::R_X86_64_32S;
1668 case MCSymbolRefExpr::VK_GOT:
1669 Type = ELF::R_X86_64_GOT32;
1671 case MCSymbolRefExpr::VK_GOTPCREL:
1672 Type = ELF::R_X86_64_GOTPCREL;
1674 case MCSymbolRefExpr::VK_TPOFF:
1675 Type = ELF::R_X86_64_TPOFF32;
1677 case MCSymbolRefExpr::VK_DTPOFF:
1678 Type = ELF::R_X86_64_DTPOFF32;
1683 Type = ELF::R_X86_64_32;
1685 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1687 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1694 llvm_unreachable("Unimplemented");
1695 case MCSymbolRefExpr::VK_None:
1696 Type = ELF::R_386_PC32;
1698 case MCSymbolRefExpr::VK_PLT:
1699 Type = ELF::R_386_PLT32;
1703 switch ((unsigned)Fixup.getKind()) {
1704 default: llvm_unreachable("invalid fixup kind!");
1706 case X86::reloc_global_offset_table:
1707 Type = ELF::R_386_GOTPC;
1710 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1712 case X86::reloc_signed_4byte:
1717 llvm_unreachable("Unimplemented");
1718 case MCSymbolRefExpr::VK_None:
1719 Type = ELF::R_386_32;
1721 case MCSymbolRefExpr::VK_GOT:
1722 Type = ELF::R_386_GOT32;
1724 case MCSymbolRefExpr::VK_GOTOFF:
1725 Type = ELF::R_386_GOTOFF;
1727 case MCSymbolRefExpr::VK_TLSGD:
1728 Type = ELF::R_386_TLS_GD;
1730 case MCSymbolRefExpr::VK_TPOFF:
1731 Type = ELF::R_386_TLS_LE_32;
1733 case MCSymbolRefExpr::VK_INDNTPOFF:
1734 Type = ELF::R_386_TLS_IE;
1736 case MCSymbolRefExpr::VK_NTPOFF:
1737 Type = ELF::R_386_TLS_LE;
1739 case MCSymbolRefExpr::VK_GOTNTPOFF:
1740 Type = ELF::R_386_TLS_GOTIE;
1742 case MCSymbolRefExpr::VK_TLSLDM:
1743 Type = ELF::R_386_TLS_LDM;
1745 case MCSymbolRefExpr::VK_DTPOFF:
1746 Type = ELF::R_386_TLS_LDO_32;
1750 case FK_Data_2: Type = ELF::R_386_16; break;
1752 case FK_Data_1: Type = ELF::R_386_8; break;
1757 if (RelocNeedsGOT(Modifier))