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"
33 #include "llvm/ADT/StringSwitch.h"
35 #include "../Target/X86/X86FixupKinds.h"
36 #include "../Target/ARM/ARMFixupKinds.h"
41 static unsigned GetType(const MCSymbolData &SD) {
42 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
43 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
44 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
45 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
46 Type == ELF::STT_TLS);
50 static unsigned GetBinding(const MCSymbolData &SD) {
51 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
52 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
53 Binding == ELF::STB_WEAK);
57 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
58 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
59 Binding == ELF::STB_WEAK);
60 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
61 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
64 static unsigned GetVisibility(MCSymbolData &SD) {
66 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
67 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
68 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
73 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
77 case MCSymbolRefExpr::VK_GOT:
78 case MCSymbolRefExpr::VK_PLT:
79 case MCSymbolRefExpr::VK_GOTPCREL:
80 case MCSymbolRefExpr::VK_TPOFF:
81 case MCSymbolRefExpr::VK_TLSGD:
82 case MCSymbolRefExpr::VK_GOTTPOFF:
83 case MCSymbolRefExpr::VK_INDNTPOFF:
84 case MCSymbolRefExpr::VK_NTPOFF:
85 case MCSymbolRefExpr::VK_GOTNTPOFF:
86 case MCSymbolRefExpr::VK_TLSLDM:
87 case MCSymbolRefExpr::VK_DTPOFF:
88 case MCSymbolRefExpr::VK_TLSLD:
93 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
94 const MCFixupKindInfo &FKI =
95 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
97 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
101 class ELFObjectWriter : public MCObjectWriter {
103 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
104 return Kind == X86::reloc_riprel_4byte ||
105 Kind == X86::reloc_riprel_4byte_movq_load;
109 /// ELFSymbolData - Helper struct for containing some precomputed information
111 struct ELFSymbolData {
112 MCSymbolData *SymbolData;
113 uint64_t StringIndex;
114 uint32_t SectionIndex;
116 // Support lexicographic sorting.
117 bool operator<(const ELFSymbolData &RHS) const {
118 if (GetType(*SymbolData) == ELF::STT_FILE)
120 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
122 return SymbolData->getSymbol().getName() <
123 RHS.SymbolData->getSymbol().getName();
127 /// @name Relocation Data
130 struct ELFRelocationEntry {
131 // Make these big enough for both 32-bit and 64-bit
135 const MCSymbol *Symbol;
139 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
141 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
142 unsigned RelType, const MCSymbol *Sym,
144 : r_offset(RelocOffset), Index(Idx), Type(RelType),
145 Symbol(Sym), r_addend(Addend) {}
147 // Support lexicographic sorting.
148 bool operator<(const ELFRelocationEntry &RE) const {
149 return RE.r_offset < r_offset;
153 /// The target specific ELF writer instance.
154 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
156 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
157 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
158 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
160 llvm::DenseMap<const MCSectionData*,
161 std::vector<ELFRelocationEntry> > Relocations;
162 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
165 /// @name Symbol Table Data
168 SmallString<256> StringTable;
169 std::vector<ELFSymbolData> LocalSymbolData;
170 std::vector<ELFSymbolData> ExternalSymbolData;
171 std::vector<ELFSymbolData> UndefinedSymbolData;
177 bool NeedsSymtabShndx;
179 // This holds the symbol table index of the last local symbol.
180 unsigned LastLocalSymbolIndex;
181 // This holds the .strtab section index.
182 unsigned StringTableIndex;
183 // This holds the .symtab section index.
184 unsigned SymbolTableIndex;
186 unsigned ShstrtabIndex;
189 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
190 const MCValue &Target,
191 const MCFragment &F) const;
193 // For arch-specific emission of explicit reloc symbol
194 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
195 const MCValue &Target,
201 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
202 bool hasRelocationAddend() const {
203 return TargetObjectWriter->hasRelocationAddend();
207 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
208 raw_ostream &_OS, bool IsLittleEndian)
209 : MCObjectWriter(_OS, IsLittleEndian),
210 TargetObjectWriter(MOTW),
211 NeedsGOT(false), NeedsSymtabShndx(false){
214 virtual ~ELFObjectWriter();
216 void WriteWord(uint64_t W) {
223 void StringLE16(char *buf, uint16_t Value) {
224 buf[0] = char(Value >> 0);
225 buf[1] = char(Value >> 8);
228 void StringLE32(char *buf, uint32_t Value) {
229 StringLE16(buf, uint16_t(Value >> 0));
230 StringLE16(buf + 2, uint16_t(Value >> 16));
233 void StringLE64(char *buf, uint64_t Value) {
234 StringLE32(buf, uint32_t(Value >> 0));
235 StringLE32(buf + 4, uint32_t(Value >> 32));
238 void StringBE16(char *buf ,uint16_t Value) {
239 buf[0] = char(Value >> 8);
240 buf[1] = char(Value >> 0);
243 void StringBE32(char *buf, uint32_t Value) {
244 StringBE16(buf, uint16_t(Value >> 16));
245 StringBE16(buf + 2, uint16_t(Value >> 0));
248 void StringBE64(char *buf, uint64_t Value) {
249 StringBE32(buf, uint32_t(Value >> 32));
250 StringBE32(buf + 4, uint32_t(Value >> 0));
253 void String8(MCDataFragment &F, uint8_t Value) {
256 F.getContents() += StringRef(buf, 1);
259 void String16(MCDataFragment &F, uint16_t Value) {
261 if (isLittleEndian())
262 StringLE16(buf, Value);
264 StringBE16(buf, Value);
265 F.getContents() += StringRef(buf, 2);
268 void String32(MCDataFragment &F, uint32_t Value) {
270 if (isLittleEndian())
271 StringLE32(buf, Value);
273 StringBE32(buf, Value);
274 F.getContents() += StringRef(buf, 4);
277 void String64(MCDataFragment &F, uint64_t Value) {
279 if (isLittleEndian())
280 StringLE64(buf, Value);
282 StringBE64(buf, Value);
283 F.getContents() += StringRef(buf, 8);
286 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
288 /// Default e_flags = 0
289 virtual void WriteEFlags() { Write32(0); }
291 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
292 uint64_t name, uint8_t info,
293 uint64_t value, uint64_t size,
294 uint8_t other, uint32_t shndx,
297 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
299 const MCAsmLayout &Layout);
301 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
302 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
303 const MCAssembler &Asm,
304 const MCAsmLayout &Layout,
305 const SectionIndexMapTy &SectionIndexMap);
307 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
308 const MCFragment *Fragment, const MCFixup &Fixup,
309 MCValue Target, uint64_t &FixedValue);
311 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
314 // Map from a group section to the signature symbol
315 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
316 // Map from a signature symbol to the group section
317 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
319 /// ComputeSymbolTable - Compute the symbol table data
321 /// \param StringTable [out] - The string table data.
322 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
324 virtual void ComputeSymbolTable(MCAssembler &Asm,
325 const SectionIndexMapTy &SectionIndexMap,
326 RevGroupMapTy RevGroupMap);
328 virtual void ComputeIndexMap(MCAssembler &Asm,
329 SectionIndexMapTy &SectionIndexMap);
331 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
332 const MCSectionData &SD);
334 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
335 for (MCAssembler::const_iterator it = Asm.begin(),
336 ie = Asm.end(); it != ie; ++it) {
337 WriteRelocation(Asm, Layout, *it);
341 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
342 const SectionIndexMapTy &SectionIndexMap);
344 // Create the sections that show up in the symbol table. Currently
345 // those are the .note.GNU-stack section and the group sections.
346 virtual void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
347 GroupMapTy &GroupMap,
348 RevGroupMapTy &RevGroupMap);
350 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
351 const MCAsmLayout &Layout);
353 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
354 uint64_t Address, uint64_t Offset,
355 uint64_t Size, uint32_t Link, uint32_t Info,
356 uint64_t Alignment, uint64_t EntrySize);
358 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
360 const MCSectionData *SD);
363 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
364 const MCSymbolData &DataA,
365 const MCFragment &FB,
369 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
370 virtual void WriteSection(MCAssembler &Asm,
371 const SectionIndexMapTy &SectionIndexMap,
372 uint32_t GroupSymbolIndex,
373 uint64_t Offset, uint64_t Size, uint64_t Alignment,
374 const MCSectionELF &Section);
377 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
378 bool IsPCRel, bool IsRelocWithSymbol,
382 //===- X86ELFObjectWriter -------------------------------------------===//
384 class X86ELFObjectWriter : public ELFObjectWriter {
386 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
388 bool IsLittleEndian);
390 virtual ~X86ELFObjectWriter();
392 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
393 bool IsPCRel, bool IsRelocWithSymbol,
398 //===- ARMELFObjectWriter -------------------------------------------===//
400 class ARMELFObjectWriter : public ELFObjectWriter {
402 // FIXME: MCAssembler can't yet return the Subtarget,
403 enum { DefaultEABIVersion = 0x05000000U };
405 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
407 bool IsLittleEndian);
409 virtual ~ARMELFObjectWriter();
411 virtual void WriteEFlags();
413 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
414 const MCValue &Target,
418 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
419 bool IsPCRel, bool IsRelocWithSymbol,
423 //===- MBlazeELFObjectWriter -------------------------------------------===//
425 class MBlazeELFObjectWriter : public ELFObjectWriter {
427 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
429 bool IsLittleEndian);
431 virtual ~MBlazeELFObjectWriter();
433 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
434 bool IsPCRel, bool IsRelocWithSymbol,
439 ELFObjectWriter::~ELFObjectWriter()
442 // Emit the ELF header.
443 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
444 unsigned NumberOfSections) {
450 // emitWord method behaves differently for ELF32 and ELF64, writing
451 // 4 bytes in the former and 8 in the latter.
453 Write8(0x7f); // e_ident[EI_MAG0]
454 Write8('E'); // e_ident[EI_MAG1]
455 Write8('L'); // e_ident[EI_MAG2]
456 Write8('F'); // e_ident[EI_MAG3]
458 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
461 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
463 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
465 switch (TargetObjectWriter->getOSType()) {
466 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
467 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
468 default: Write8(ELF::ELFOSABI_NONE); break;
470 Write8(0); // e_ident[EI_ABIVERSION]
472 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
474 Write16(ELF::ET_REL); // e_type
476 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
478 Write32(ELF::EV_CURRENT); // e_version
479 WriteWord(0); // e_entry, no entry point in .o file
480 WriteWord(0); // e_phoff, no program header for .o
481 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
482 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
484 // e_flags = whatever the target wants
487 // e_ehsize = ELF header size
488 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
490 Write16(0); // e_phentsize = prog header entry size
491 Write16(0); // e_phnum = # prog header entries = 0
493 // e_shentsize = Section header entry size
494 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
496 // e_shnum = # of section header ents
497 if (NumberOfSections >= ELF::SHN_LORESERVE)
500 Write16(NumberOfSections);
502 // e_shstrndx = Section # of '.shstrtab'
503 if (NumberOfSections >= ELF::SHN_LORESERVE)
504 Write16(ELF::SHN_XINDEX);
506 Write16(ShstrtabIndex);
509 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
510 MCDataFragment *ShndxF,
512 uint8_t info, uint64_t value,
513 uint64_t size, uint8_t other,
517 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
518 String32(*ShndxF, shndx);
520 String32(*ShndxF, 0);
523 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
524 uint16_t(ELF::SHN_XINDEX) : shndx;
527 String32(*SymtabF, name); // st_name
528 String8(*SymtabF, info); // st_info
529 String8(*SymtabF, other); // st_other
530 String16(*SymtabF, Index); // st_shndx
531 String64(*SymtabF, value); // st_value
532 String64(*SymtabF, size); // st_size
534 String32(*SymtabF, name); // st_name
535 String32(*SymtabF, value); // st_value
536 String32(*SymtabF, size); // st_size
537 String8(*SymtabF, info); // st_info
538 String8(*SymtabF, other); // st_other
539 String16(*SymtabF, Index); // st_shndx
543 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
544 if (Data.isCommon() && Data.isExternal())
545 return Data.getCommonAlignment();
547 const MCSymbol &Symbol = Data.getSymbol();
549 if (Symbol.isAbsolute() && Symbol.isVariable()) {
550 if (const MCExpr *Value = Symbol.getVariableValue()) {
552 if (Value->EvaluateAsAbsolute(IntValue, Layout))
553 return (uint64_t)IntValue;
557 if (!Symbol.isInSection())
560 if (Data.getFragment())
561 return Layout.getSymbolOffset(&Data);
566 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
567 const MCAsmLayout &Layout) {
568 // The presence of symbol versions causes undefined symbols and
569 // versions declared with @@@ to be renamed.
571 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
572 ie = Asm.symbol_end(); it != ie; ++it) {
573 const MCSymbol &Alias = it->getSymbol();
574 const MCSymbol &Symbol = Alias.AliasedSymbol();
575 MCSymbolData &SD = Asm.getSymbolData(Symbol);
578 if (&Symbol == &Alias)
581 StringRef AliasName = Alias.getName();
582 size_t Pos = AliasName.find('@');
583 if (Pos == StringRef::npos)
586 // Aliases defined with .symvar copy the binding from the symbol they alias.
587 // This is the first place we are able to copy this information.
588 it->setExternal(SD.isExternal());
589 SetBinding(*it, GetBinding(SD));
591 StringRef Rest = AliasName.substr(Pos);
592 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
595 // FIXME: produce a better error message.
596 if (Symbol.isUndefined() && Rest.startswith("@@") &&
597 !Rest.startswith("@@@"))
598 report_fatal_error("A @@ version cannot be undefined");
600 Renames.insert(std::make_pair(&Symbol, &Alias));
604 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
605 MCDataFragment *ShndxF,
607 const MCAsmLayout &Layout) {
608 MCSymbolData &OrigData = *MSD.SymbolData;
610 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
612 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
613 Data.getSymbol().isVariable();
615 uint8_t Binding = GetBinding(OrigData);
616 uint8_t Visibility = GetVisibility(OrigData);
617 uint8_t Type = GetType(Data);
619 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
620 uint8_t Other = Visibility;
622 uint64_t Value = SymbolValue(Data, Layout);
625 assert(!(Data.isCommon() && !Data.isExternal()));
627 const MCExpr *ESize = Data.getSize();
630 if (!ESize->EvaluateAsAbsolute(Res, Layout))
631 report_fatal_error("Size expression must be absolute.");
635 // Write out the symbol table entry
636 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
637 Size, Other, MSD.SectionIndex, IsReserved);
640 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
641 MCDataFragment *ShndxF,
642 const MCAssembler &Asm,
643 const MCAsmLayout &Layout,
644 const SectionIndexMapTy &SectionIndexMap) {
645 // The string table must be emitted first because we need the index
646 // into the string table for all the symbol names.
647 assert(StringTable.size() && "Missing string table");
649 // FIXME: Make sure the start of the symbol table is aligned.
651 // The first entry is the undefined symbol entry.
652 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
654 // Write the symbol table entries.
655 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
656 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
657 ELFSymbolData &MSD = LocalSymbolData[i];
658 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
661 // Write out a symbol table entry for each regular section.
662 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
664 const MCSectionELF &Section =
665 static_cast<const MCSectionELF&>(i->getSection());
666 if (Section.getType() == ELF::SHT_RELA ||
667 Section.getType() == ELF::SHT_REL ||
668 Section.getType() == ELF::SHT_STRTAB ||
669 Section.getType() == ELF::SHT_SYMTAB)
671 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
672 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
673 LastLocalSymbolIndex++;
676 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
677 ELFSymbolData &MSD = ExternalSymbolData[i];
678 MCSymbolData &Data = *MSD.SymbolData;
679 assert(((Data.getFlags() & ELF_STB_Global) ||
680 (Data.getFlags() & ELF_STB_Weak)) &&
681 "External symbol requires STB_GLOBAL or STB_WEAK flag");
682 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
683 if (GetBinding(Data) == ELF::STB_LOCAL)
684 LastLocalSymbolIndex++;
687 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
688 ELFSymbolData &MSD = UndefinedSymbolData[i];
689 MCSymbolData &Data = *MSD.SymbolData;
690 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
691 if (GetBinding(Data) == ELF::STB_LOCAL)
692 LastLocalSymbolIndex++;
696 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
697 const MCValue &Target,
698 const MCFragment &F) const {
699 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
700 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
701 const MCSymbol *Renamed = Renames.lookup(&Symbol);
702 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
704 if (ASymbol.isUndefined()) {
710 if (SD.isExternal()) {
716 const MCSectionELF &Section =
717 static_cast<const MCSectionELF&>(ASymbol.getSection());
718 const SectionKind secKind = Section.getKind();
721 return ExplicitRelSym(Asm, Target, F, true);
723 if (secKind.isThreadLocal()) {
729 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
730 const MCSectionELF &Sec2 =
731 static_cast<const MCSectionELF&>(F.getParent()->getSection());
733 if (&Sec2 != &Section &&
734 (Kind == MCSymbolRefExpr::VK_PLT ||
735 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
736 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
742 if (Section.getFlags() & ELF::SHF_MERGE) {
743 if (Target.getConstant() == 0)
750 return ExplicitRelSym(Asm, Target, F, false);
754 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
755 const MCAsmLayout &Layout,
756 const MCFragment *Fragment,
757 const MCFixup &Fixup,
759 uint64_t &FixedValue) {
762 int64_t Value = Target.getConstant();
763 const MCSymbol *RelocSymbol = NULL;
765 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
766 if (!Target.isAbsolute()) {
767 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
768 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
769 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
771 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
772 const MCSymbol &SymbolB = RefB->getSymbol();
773 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
776 // Offset of the symbol in the section
777 int64_t a = Layout.getSymbolOffset(&SDB);
779 // Ofeset of the relocation in the section
780 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
785 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
786 MCFragment *F = SD.getFragment();
788 Index = F->getParent()->getOrdinal() + 1;
790 // Offset of the symbol in the section
791 Value += Layout.getSymbolOffset(&SD);
793 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
794 WeakrefUsedInReloc.insert(RelocSymbol);
796 UsedInReloc.insert(RelocSymbol);
800 // Compensate for the addend on i386.
806 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
807 (RelocSymbol != 0), Addend);
809 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
812 if (!hasRelocationAddend())
814 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
815 Relocations[Fragment->getParent()].push_back(ERE);
820 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
822 MCSymbolData &SD = Asm.getSymbolData(*S);
823 return SD.getIndex();
826 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
827 bool Used, bool Renamed) {
828 if (Data.getFlags() & ELF_Other_Weakref)
837 const MCSymbol &Symbol = Data.getSymbol();
839 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
842 const MCSymbol &A = Symbol.AliasedSymbol();
843 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
846 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
849 if (Symbol.isTemporary())
855 static bool isLocal(const MCSymbolData &Data, bool isSignature,
856 bool isUsedInReloc) {
857 if (Data.isExternal())
860 const MCSymbol &Symbol = Data.getSymbol();
861 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
863 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
864 if (isSignature && !isUsedInReloc)
873 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
874 SectionIndexMapTy &SectionIndexMap) {
876 for (MCAssembler::iterator it = Asm.begin(),
877 ie = Asm.end(); it != ie; ++it) {
878 const MCSectionELF &Section =
879 static_cast<const MCSectionELF &>(it->getSection());
880 if (Section.getType() != ELF::SHT_GROUP)
882 SectionIndexMap[&Section] = Index++;
885 for (MCAssembler::iterator it = Asm.begin(),
886 ie = Asm.end(); it != ie; ++it) {
887 const MCSectionELF &Section =
888 static_cast<const MCSectionELF &>(it->getSection());
889 if (Section.getType() == ELF::SHT_GROUP)
891 SectionIndexMap[&Section] = Index++;
895 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
896 const SectionIndexMapTy &SectionIndexMap,
897 RevGroupMapTy RevGroupMap) {
898 // FIXME: Is this the correct place to do this?
900 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
901 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
902 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
903 Data.setExternal(true);
904 SetBinding(Data, ELF::STB_GLOBAL);
907 // Build section lookup table.
908 int NumRegularSections = Asm.size();
910 // Index 0 is always the empty string.
911 StringMap<uint64_t> StringIndexMap;
912 StringTable += '\x00';
914 // Add the data for the symbols.
915 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
916 ie = Asm.symbol_end(); it != ie; ++it) {
917 const MCSymbol &Symbol = it->getSymbol();
919 bool Used = UsedInReloc.count(&Symbol);
920 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
921 bool isSignature = RevGroupMap.count(&Symbol);
923 if (!isInSymtab(Asm, *it,
924 Used || WeakrefUsed || isSignature,
925 Renames.count(&Symbol)))
930 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
932 // Undefined symbols are global, but this is the first place we
933 // are able to set it.
934 bool Local = isLocal(*it, isSignature, Used);
935 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
936 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
937 SetBinding(*it, ELF::STB_GLOBAL);
938 SetBinding(SD, ELF::STB_GLOBAL);
941 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
942 SetBinding(*it, ELF::STB_WEAK);
944 if (it->isCommon()) {
946 MSD.SectionIndex = ELF::SHN_COMMON;
947 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
948 MSD.SectionIndex = ELF::SHN_ABS;
949 } else if (RefSymbol.isUndefined()) {
950 if (isSignature && !Used)
951 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
953 MSD.SectionIndex = ELF::SHN_UNDEF;
955 const MCSectionELF &Section =
956 static_cast<const MCSectionELF&>(RefSymbol.getSection());
957 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
958 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
959 NeedsSymtabShndx = true;
960 assert(MSD.SectionIndex && "Invalid section index!");
963 // The @@@ in symbol version is replaced with @ in undefined symbols and
964 // @@ in defined ones.
965 StringRef Name = Symbol.getName();
968 size_t Pos = Name.find("@@@");
969 if (Pos != StringRef::npos) {
970 Buf += Name.substr(0, Pos);
971 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
972 Buf += Name.substr(Pos + Skip);
976 uint64_t &Entry = StringIndexMap[Name];
978 Entry = StringTable.size();
980 StringTable += '\x00';
982 MSD.StringIndex = Entry;
983 if (MSD.SectionIndex == ELF::SHN_UNDEF)
984 UndefinedSymbolData.push_back(MSD);
986 LocalSymbolData.push_back(MSD);
988 ExternalSymbolData.push_back(MSD);
991 // Symbols are required to be in lexicographic order.
992 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
993 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
994 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
996 // Set the symbol indices. Local symbols must come before all other
997 // symbols with non-local bindings.
999 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1000 LocalSymbolData[i].SymbolData->setIndex(Index++);
1002 Index += NumRegularSections;
1004 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1005 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1006 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1007 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1010 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1011 const MCSectionData &SD) {
1012 if (!Relocations[&SD].empty()) {
1013 MCContext &Ctx = Asm.getContext();
1014 const MCSectionELF *RelaSection;
1015 const MCSectionELF &Section =
1016 static_cast<const MCSectionELF&>(SD.getSection());
1018 const StringRef SectionName = Section.getSectionName();
1019 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1020 RelaSectionName += SectionName;
1023 if (hasRelocationAddend())
1024 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1026 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1028 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1029 ELF::SHT_RELA : ELF::SHT_REL, 0,
1030 SectionKind::getReadOnly(),
1033 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1034 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1036 MCDataFragment *F = new MCDataFragment(&RelaSD);
1038 WriteRelocationsFragment(Asm, F, &SD);
1042 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1043 uint64_t Flags, uint64_t Address,
1044 uint64_t Offset, uint64_t Size,
1045 uint32_t Link, uint32_t Info,
1047 uint64_t EntrySize) {
1048 Write32(Name); // sh_name: index into string table
1049 Write32(Type); // sh_type
1050 WriteWord(Flags); // sh_flags
1051 WriteWord(Address); // sh_addr
1052 WriteWord(Offset); // sh_offset
1053 WriteWord(Size); // sh_size
1054 Write32(Link); // sh_link
1055 Write32(Info); // sh_info
1056 WriteWord(Alignment); // sh_addralign
1057 WriteWord(EntrySize); // sh_entsize
1060 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1062 const MCSectionData *SD) {
1063 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1064 // sort by the r_offset just like gnu as does
1065 array_pod_sort(Relocs.begin(), Relocs.end());
1067 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1068 ELFRelocationEntry entry = Relocs[e - i - 1];
1072 else if (entry.Index < 0)
1073 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1075 entry.Index += LocalSymbolData.size();
1077 String64(*F, entry.r_offset);
1079 struct ELF::Elf64_Rela ERE64;
1080 ERE64.setSymbolAndType(entry.Index, entry.Type);
1081 String64(*F, ERE64.r_info);
1083 if (hasRelocationAddend())
1084 String64(*F, entry.r_addend);
1086 String32(*F, entry.r_offset);
1088 struct ELF::Elf32_Rela ERE32;
1089 ERE32.setSymbolAndType(entry.Index, entry.Type);
1090 String32(*F, ERE32.r_info);
1092 if (hasRelocationAddend())
1093 String32(*F, entry.r_addend);
1098 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1099 MCAsmLayout &Layout,
1100 const SectionIndexMapTy &SectionIndexMap) {
1101 MCContext &Ctx = Asm.getContext();
1104 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1106 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1107 const MCSectionELF *ShstrtabSection =
1108 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1109 SectionKind::getReadOnly());
1110 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1111 ShstrtabSD.setAlignment(1);
1112 ShstrtabIndex = Asm.size();
1114 const MCSectionELF *SymtabSection =
1115 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1116 SectionKind::getReadOnly(),
1118 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1119 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1120 SymbolTableIndex = Asm.size();
1122 MCSectionData *SymtabShndxSD = NULL;
1124 if (NeedsSymtabShndx) {
1125 const MCSectionELF *SymtabShndxSection =
1126 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1127 SectionKind::getReadOnly(), 4, "");
1128 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1129 SymtabShndxSD->setAlignment(4);
1132 const MCSection *StrtabSection;
1133 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1134 SectionKind::getReadOnly());
1135 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1136 StrtabSD.setAlignment(1);
1137 StringTableIndex = Asm.size();
1139 WriteRelocations(Asm, Layout);
1142 F = new MCDataFragment(&SymtabSD);
1143 MCDataFragment *ShndxF = NULL;
1144 if (NeedsSymtabShndx) {
1145 ShndxF = new MCDataFragment(SymtabShndxSD);
1147 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1149 F = new MCDataFragment(&StrtabSD);
1150 F->getContents().append(StringTable.begin(), StringTable.end());
1152 F = new MCDataFragment(&ShstrtabSD);
1154 // Section header string table.
1156 // The first entry of a string table holds a null character so skip
1159 F->getContents() += '\x00';
1161 StringMap<uint64_t> SecStringMap;
1162 for (MCAssembler::const_iterator it = Asm.begin(),
1163 ie = Asm.end(); it != ie; ++it) {
1164 const MCSectionELF &Section =
1165 static_cast<const MCSectionELF&>(it->getSection());
1166 // FIXME: We could merge suffixes like in .text and .rela.text.
1168 StringRef Name = Section.getSectionName();
1169 if (SecStringMap.count(Name)) {
1170 SectionStringTableIndex[&Section] = SecStringMap[Name];
1173 // Remember the index into the string table so we can write it
1174 // into the sh_name field of the section header table.
1175 SectionStringTableIndex[&Section] = Index;
1176 SecStringMap[Name] = Index;
1178 Index += Name.size() + 1;
1179 F->getContents() += Name;
1180 F->getContents() += '\x00';
1185 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1186 const MCSymbolData &DataA,
1187 const MCFragment &FB,
1189 bool IsPCRel) const {
1190 // FIXME: This is in here just to match gnu as output. If the two ends
1191 // are in the same section, there is nothing that the linker can do to
1193 if (DataA.isExternal())
1196 const MCSection &SecA = DataA.getSymbol().AliasedSymbol().getSection();
1197 const MCSection &SecB = FB.getParent()->getSection();
1198 // On ELF A - B is absolute if A and B are in the same section.
1199 return &SecA == &SecB;
1202 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1203 MCAsmLayout &Layout,
1204 GroupMapTy &GroupMap,
1205 RevGroupMapTy &RevGroupMap) {
1206 // Create the .note.GNU-stack section if needed.
1207 MCContext &Ctx = Asm.getContext();
1208 if (Asm.getNoExecStack()) {
1209 const MCSectionELF *GnuStackSection =
1210 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1211 SectionKind::getReadOnly());
1212 Asm.getOrCreateSectionData(*GnuStackSection);
1216 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1218 const MCSectionELF &Section =
1219 static_cast<const MCSectionELF&>(it->getSection());
1220 if (!(Section.getFlags() & ELF::SHF_GROUP))
1223 const MCSymbol *SignatureSymbol = Section.getGroup();
1224 Asm.getOrCreateSymbolData(*SignatureSymbol);
1225 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1227 Group = Ctx.CreateELFGroupSection();
1228 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1229 Data.setAlignment(4);
1230 MCDataFragment *F = new MCDataFragment(&Data);
1231 String32(*F, ELF::GRP_COMDAT);
1233 GroupMap[Group] = SignatureSymbol;
1236 // Add sections to the groups
1238 unsigned NumGroups = RevGroupMap.size();
1239 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1240 it != ie; ++it, ++Index) {
1241 const MCSectionELF &Section =
1242 static_cast<const MCSectionELF&>(it->getSection());
1243 if (!(Section.getFlags() & ELF::SHF_GROUP))
1245 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1246 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1247 // FIXME: we could use the previous fragment
1248 MCDataFragment *F = new MCDataFragment(&Data);
1249 String32(*F, NumGroups + Index);
1253 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1254 const SectionIndexMapTy &SectionIndexMap,
1255 uint32_t GroupSymbolIndex,
1256 uint64_t Offset, uint64_t Size,
1258 const MCSectionELF &Section) {
1259 uint64_t sh_link = 0;
1260 uint64_t sh_info = 0;
1262 switch(Section.getType()) {
1263 case ELF::SHT_DYNAMIC:
1264 sh_link = SectionStringTableIndex[&Section];
1269 case ELF::SHT_RELA: {
1270 const MCSectionELF *SymtabSection;
1271 const MCSectionELF *InfoSection;
1272 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1274 SectionKind::getReadOnly());
1275 sh_link = SectionIndexMap.lookup(SymtabSection);
1276 assert(sh_link && ".symtab not found");
1278 // Remove ".rel" and ".rela" prefixes.
1279 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1280 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1282 InfoSection = Asm.getContext().getELFSection(SectionName,
1283 ELF::SHT_PROGBITS, 0,
1284 SectionKind::getReadOnly());
1285 sh_info = SectionIndexMap.lookup(InfoSection);
1289 case ELF::SHT_SYMTAB:
1290 case ELF::SHT_DYNSYM:
1291 sh_link = StringTableIndex;
1292 sh_info = LastLocalSymbolIndex;
1295 case ELF::SHT_SYMTAB_SHNDX:
1296 sh_link = SymbolTableIndex;
1299 case ELF::SHT_PROGBITS:
1300 case ELF::SHT_STRTAB:
1301 case ELF::SHT_NOBITS:
1304 case ELF::SHT_ARM_ATTRIBUTES:
1305 case ELF::SHT_INIT_ARRAY:
1306 case ELF::SHT_FINI_ARRAY:
1307 case ELF::SHT_PREINIT_ARRAY:
1308 case ELF::SHT_X86_64_UNWIND:
1312 case ELF::SHT_GROUP: {
1313 sh_link = SymbolTableIndex;
1314 sh_info = GroupSymbolIndex;
1319 assert(0 && "FIXME: sh_type value not supported!");
1323 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1324 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1325 Alignment, Section.getEntrySize());
1328 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1329 return SD.getOrdinal() == ~UINT32_C(0) &&
1330 !SD.getSection().isVirtualSection();
1333 static uint64_t DataSectionSize(const MCSectionData &SD) {
1335 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1337 const MCFragment &F = *i;
1338 assert(F.getKind() == MCFragment::FT_Data);
1339 Ret += cast<MCDataFragment>(F).getContents().size();
1344 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1345 const MCSectionData &SD) {
1346 if (IsELFMetaDataSection(SD))
1347 return DataSectionSize(SD);
1348 return Layout.getSectionFileSize(&SD);
1351 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1352 const MCSectionData &SD) {
1353 if (IsELFMetaDataSection(SD))
1354 return DataSectionSize(SD);
1355 return Layout.getSectionAddressSize(&SD);
1358 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1359 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1361 const MCFragment &F = *i;
1362 assert(F.getKind() == MCFragment::FT_Data);
1363 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1367 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1368 const MCAsmLayout &Layout) {
1369 GroupMapTy GroupMap;
1370 RevGroupMapTy RevGroupMap;
1371 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1374 SectionIndexMapTy SectionIndexMap;
1376 ComputeIndexMap(Asm, SectionIndexMap);
1378 // Compute symbol table information.
1379 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1381 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1382 const_cast<MCAsmLayout&>(Layout),
1385 // Update to include the metadata sections.
1386 ComputeIndexMap(Asm, SectionIndexMap);
1388 // Add 1 for the null section.
1389 unsigned NumSections = Asm.size() + 1;
1390 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1391 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1392 sizeof(ELF::Elf32_Ehdr);
1393 uint64_t FileOff = HeaderSize;
1395 std::vector<const MCSectionELF*> Sections;
1396 Sections.resize(NumSections);
1398 for (SectionIndexMapTy::const_iterator i=
1399 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1400 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1401 Sections[p.second] = p.first;
1404 for (unsigned i = 1; i < NumSections; ++i) {
1405 const MCSectionELF &Section = *Sections[i];
1406 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1408 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1410 // Get the size of the section in the output file (including padding).
1411 FileOff += GetSectionFileSize(Layout, SD);
1414 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1416 // Write out the ELF header ...
1417 WriteHeader(FileOff - HeaderSize, NumSections);
1419 FileOff = HeaderSize;
1421 // ... then all of the sections ...
1422 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1424 for (unsigned i = 1; i < NumSections; ++i) {
1425 const MCSectionELF &Section = *Sections[i];
1426 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1428 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1429 WriteZeros(Padding);
1432 // Remember the offset into the file for this section.
1433 SectionOffsetMap[&Section] = FileOff;
1435 FileOff += GetSectionFileSize(Layout, SD);
1437 if (IsELFMetaDataSection(SD))
1438 WriteDataSectionData(this, SD);
1440 Asm.WriteSectionData(&SD, Layout);
1443 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1444 WriteZeros(Padding);
1447 // ... and then the section header table.
1448 // Should we align the section header table?
1450 // Null section first.
1451 uint64_t FirstSectionSize =
1452 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1453 uint32_t FirstSectionLink =
1454 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1455 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1457 for (unsigned i = 1; i < NumSections; ++i) {
1458 const MCSectionELF &Section = *Sections[i];
1459 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1460 uint32_t GroupSymbolIndex;
1461 if (Section.getType() != ELF::SHT_GROUP)
1462 GroupSymbolIndex = 0;
1464 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1466 uint64_t Size = GetSectionAddressSize(Layout, SD);
1468 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1469 SectionOffsetMap[&Section], Size,
1470 SD.getAlignment(), Section);
1474 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1476 bool IsLittleEndian) {
1477 switch (MOTW->getEMachine()) {
1479 case ELF::EM_X86_64:
1480 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1482 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1483 case ELF::EM_MBLAZE:
1484 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1485 default: llvm_unreachable("Unsupported architecture"); break;
1490 /// START OF SUBCLASSES for ELFObjectWriter
1491 //===- ARMELFObjectWriter -------------------------------------------===//
1493 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1495 bool IsLittleEndian)
1496 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1499 ARMELFObjectWriter::~ARMELFObjectWriter()
1502 // FIXME: get the real EABI Version from the Triple.
1503 void ARMELFObjectWriter::WriteEFlags() {
1504 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1507 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1508 // I.e. not as an offset to a section symbol.
1509 // This code is a first-cut approximation of what ARM/gcc does.
1511 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1512 const MCValue &Target,
1513 const MCFragment &F,
1515 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1516 bool EmitThisSym = false;
1519 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1520 .Case("_MergedGlobals", true)
1523 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1524 .Case("_MergedGlobals", true)
1525 .StartsWith(".L.str", true)
1530 if (! Symbol.isTemporary())
1535 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1536 const MCFixup &Fixup,
1538 bool IsRelocWithSymbol,
1540 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1541 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1545 switch ((unsigned)Fixup.getKind()) {
1546 default: assert(0 && "Unimplemented");
1549 default: llvm_unreachable("Unsupported Modifier");
1550 case MCSymbolRefExpr::VK_None:
1551 Type = ELF::R_ARM_BASE_PREL;
1553 case MCSymbolRefExpr::VK_ARM_TLSGD:
1554 assert(0 && "unimplemented");
1556 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1557 Type = ELF::R_ARM_TLS_IE32;
1561 case ARM::fixup_arm_uncondbranch:
1563 case MCSymbolRefExpr::VK_ARM_PLT:
1564 Type = ELF::R_ARM_PLT32;
1567 Type = ELF::R_ARM_CALL;
1571 case ARM::fixup_arm_condbranch:
1572 Type = ELF::R_ARM_JUMP24;
1574 case ARM::fixup_arm_movt_hi16:
1575 case ARM::fixup_arm_movt_hi16_pcrel:
1576 Type = ELF::R_ARM_MOVT_PREL;
1578 case ARM::fixup_arm_movw_lo16:
1579 case ARM::fixup_arm_movw_lo16_pcrel:
1580 Type = ELF::R_ARM_MOVW_PREL_NC;
1582 case ARM::fixup_t2_movt_hi16:
1583 case ARM::fixup_t2_movt_hi16_pcrel:
1584 Type = ELF::R_ARM_THM_MOVT_PREL;
1586 case ARM::fixup_t2_movw_lo16:
1587 case ARM::fixup_t2_movw_lo16_pcrel:
1588 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1592 switch ((unsigned)Fixup.getKind()) {
1593 default: llvm_unreachable("invalid fixup kind!");
1596 default: llvm_unreachable("Unsupported Modifier"); break;
1597 case MCSymbolRefExpr::VK_ARM_GOT:
1598 Type = ELF::R_ARM_GOT_BREL;
1600 case MCSymbolRefExpr::VK_ARM_TLSGD:
1601 Type = ELF::R_ARM_TLS_GD32;
1603 case MCSymbolRefExpr::VK_ARM_TPOFF:
1604 Type = ELF::R_ARM_TLS_LE32;
1606 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1607 Type = ELF::R_ARM_TLS_IE32;
1609 case MCSymbolRefExpr::VK_None:
1610 Type = ELF::R_ARM_ABS32;
1612 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1613 Type = ELF::R_ARM_GOTOFF32;
1617 case ARM::fixup_arm_ldst_pcrel_12:
1618 case ARM::fixup_arm_pcrel_10:
1619 case ARM::fixup_arm_adr_pcrel_12:
1620 case ARM::fixup_arm_thumb_bl:
1621 case ARM::fixup_arm_thumb_cb:
1622 case ARM::fixup_arm_thumb_cp:
1623 case ARM::fixup_arm_thumb_br:
1624 assert(0 && "Unimplemented");
1626 case ARM::fixup_arm_uncondbranch:
1627 Type = ELF::R_ARM_CALL;
1629 case ARM::fixup_arm_condbranch:
1630 Type = ELF::R_ARM_JUMP24;
1632 case ARM::fixup_arm_movt_hi16:
1633 Type = ELF::R_ARM_MOVT_ABS;
1635 case ARM::fixup_arm_movw_lo16:
1636 Type = ELF::R_ARM_MOVW_ABS_NC;
1638 case ARM::fixup_t2_movt_hi16:
1639 Type = ELF::R_ARM_THM_MOVT_ABS;
1641 case ARM::fixup_t2_movw_lo16:
1642 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1647 if (RelocNeedsGOT(Modifier))
1653 //===- MBlazeELFObjectWriter -------------------------------------------===//
1655 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1657 bool IsLittleEndian)
1658 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1661 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1664 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1665 const MCFixup &Fixup,
1667 bool IsRelocWithSymbol,
1669 // determine the type of the relocation
1672 switch ((unsigned)Fixup.getKind()) {
1674 llvm_unreachable("Unimplemented");
1676 Type = ELF::R_MICROBLAZE_64_PCREL;
1679 Type = ELF::R_MICROBLAZE_32_PCREL;
1683 switch ((unsigned)Fixup.getKind()) {
1684 default: llvm_unreachable("invalid fixup kind!");
1686 Type = ((IsRelocWithSymbol || Addend !=0)
1687 ? ELF::R_MICROBLAZE_32
1688 : ELF::R_MICROBLAZE_64);
1691 Type = ELF::R_MICROBLAZE_32;
1698 //===- X86ELFObjectWriter -------------------------------------------===//
1701 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1703 bool IsLittleEndian)
1704 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1707 X86ELFObjectWriter::~X86ELFObjectWriter()
1710 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1711 const MCFixup &Fixup,
1713 bool IsRelocWithSymbol,
1715 // determine the type of the relocation
1717 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1718 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1722 switch ((unsigned)Fixup.getKind()) {
1723 default: llvm_unreachable("invalid fixup kind!");
1725 assert(Modifier == MCSymbolRefExpr::VK_None);
1726 Type = ELF::R_X86_64_PC64;
1728 case X86::reloc_signed_4byte:
1729 case X86::reloc_riprel_4byte_movq_load:
1730 case FK_Data_4: // FIXME?
1731 case X86::reloc_riprel_4byte:
1735 llvm_unreachable("Unimplemented");
1736 case MCSymbolRefExpr::VK_None:
1737 Type = ELF::R_X86_64_PC32;
1739 case MCSymbolRefExpr::VK_PLT:
1740 Type = ELF::R_X86_64_PLT32;
1742 case MCSymbolRefExpr::VK_GOTPCREL:
1743 Type = ELF::R_X86_64_GOTPCREL;
1745 case MCSymbolRefExpr::VK_GOTTPOFF:
1746 Type = ELF::R_X86_64_GOTTPOFF;
1748 case MCSymbolRefExpr::VK_TLSGD:
1749 Type = ELF::R_X86_64_TLSGD;
1751 case MCSymbolRefExpr::VK_TLSLD:
1752 Type = ELF::R_X86_64_TLSLD;
1757 assert(Modifier == MCSymbolRefExpr::VK_None);
1758 Type = ELF::R_X86_64_PC16;
1762 switch ((unsigned)Fixup.getKind()) {
1763 default: llvm_unreachable("invalid fixup kind!");
1764 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1765 case X86::reloc_signed_4byte:
1766 assert(isInt<32>(Target.getConstant()));
1769 llvm_unreachable("Unimplemented");
1770 case MCSymbolRefExpr::VK_None:
1771 Type = ELF::R_X86_64_32S;
1773 case MCSymbolRefExpr::VK_GOT:
1774 Type = ELF::R_X86_64_GOT32;
1776 case MCSymbolRefExpr::VK_GOTPCREL:
1777 Type = ELF::R_X86_64_GOTPCREL;
1779 case MCSymbolRefExpr::VK_TPOFF:
1780 Type = ELF::R_X86_64_TPOFF32;
1782 case MCSymbolRefExpr::VK_DTPOFF:
1783 Type = ELF::R_X86_64_DTPOFF32;
1788 Type = ELF::R_X86_64_32;
1790 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1792 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1799 llvm_unreachable("Unimplemented");
1800 case MCSymbolRefExpr::VK_None:
1801 Type = ELF::R_386_PC32;
1803 case MCSymbolRefExpr::VK_PLT:
1804 Type = ELF::R_386_PLT32;
1808 switch ((unsigned)Fixup.getKind()) {
1809 default: llvm_unreachable("invalid fixup kind!");
1811 case X86::reloc_global_offset_table:
1812 Type = ELF::R_386_GOTPC;
1815 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1817 case X86::reloc_signed_4byte:
1822 llvm_unreachable("Unimplemented");
1823 case MCSymbolRefExpr::VK_None:
1824 Type = ELF::R_386_32;
1826 case MCSymbolRefExpr::VK_GOT:
1827 Type = ELF::R_386_GOT32;
1829 case MCSymbolRefExpr::VK_GOTOFF:
1830 Type = ELF::R_386_GOTOFF;
1832 case MCSymbolRefExpr::VK_TLSGD:
1833 Type = ELF::R_386_TLS_GD;
1835 case MCSymbolRefExpr::VK_TPOFF:
1836 Type = ELF::R_386_TLS_LE_32;
1838 case MCSymbolRefExpr::VK_INDNTPOFF:
1839 Type = ELF::R_386_TLS_IE;
1841 case MCSymbolRefExpr::VK_NTPOFF:
1842 Type = ELF::R_386_TLS_LE;
1844 case MCSymbolRefExpr::VK_GOTNTPOFF:
1845 Type = ELF::R_386_TLS_GOTIE;
1847 case MCSymbolRefExpr::VK_TLSLDM:
1848 Type = ELF::R_386_TLS_LDM;
1850 case MCSymbolRefExpr::VK_DTPOFF:
1851 Type = ELF::R_386_TLS_LDO_32;
1855 case FK_Data_2: Type = ELF::R_386_16; break;
1857 case FK_Data_1: Type = ELF::R_386_8; break;
1862 if (RelocNeedsGOT(Modifier))