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);
347 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
348 const MCValue Target,
350 const MCFragment *DF) const;
352 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
353 virtual void WriteSection(MCAssembler &Asm,
354 const SectionIndexMapTy &SectionIndexMap,
355 uint32_t GroupSymbolIndex,
356 uint64_t Offset, uint64_t Size, uint64_t Alignment,
357 const MCSectionELF &Section);
360 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
361 bool IsPCRel, bool IsRelocWithSymbol,
365 //===- X86ELFObjectWriter -------------------------------------------===//
367 class X86ELFObjectWriter : public ELFObjectWriter {
369 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
371 bool IsLittleEndian);
373 virtual ~X86ELFObjectWriter();
375 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
376 bool IsPCRel, bool IsRelocWithSymbol,
381 //===- ARMELFObjectWriter -------------------------------------------===//
383 class ARMELFObjectWriter : public ELFObjectWriter {
385 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
387 bool IsLittleEndian);
389 virtual ~ARMELFObjectWriter();
391 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
392 bool IsPCRel, bool IsRelocWithSymbol,
396 //===- MBlazeELFObjectWriter -------------------------------------------===//
398 class MBlazeELFObjectWriter : public ELFObjectWriter {
400 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
402 bool IsLittleEndian);
404 virtual ~MBlazeELFObjectWriter();
406 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
407 bool IsPCRel, bool IsRelocWithSymbol,
412 ELFObjectWriter::~ELFObjectWriter()
415 // Emit the ELF header.
416 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
417 unsigned NumberOfSections) {
423 // emitWord method behaves differently for ELF32 and ELF64, writing
424 // 4 bytes in the former and 8 in the latter.
426 Write8(0x7f); // e_ident[EI_MAG0]
427 Write8('E'); // e_ident[EI_MAG1]
428 Write8('L'); // e_ident[EI_MAG2]
429 Write8('F'); // e_ident[EI_MAG3]
431 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
434 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
436 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
438 switch (TargetObjectWriter->getOSType()) {
439 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
440 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
441 default: Write8(ELF::ELFOSABI_NONE); break;
443 Write8(0); // e_ident[EI_ABIVERSION]
445 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
447 Write16(ELF::ET_REL); // e_type
449 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
451 Write32(ELF::EV_CURRENT); // e_version
452 WriteWord(0); // e_entry, no entry point in .o file
453 WriteWord(0); // e_phoff, no program header for .o
454 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
455 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
457 // FIXME: Make this configurable.
458 Write32(0); // e_flags = whatever the target wants
460 // e_ehsize = ELF header size
461 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
463 Write16(0); // e_phentsize = prog header entry size
464 Write16(0); // e_phnum = # prog header entries = 0
466 // e_shentsize = Section header entry size
467 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
469 // e_shnum = # of section header ents
470 if (NumberOfSections >= ELF::SHN_LORESERVE)
473 Write16(NumberOfSections);
475 // e_shstrndx = Section # of '.shstrtab'
476 if (NumberOfSections >= ELF::SHN_LORESERVE)
477 Write16(ELF::SHN_XINDEX);
479 Write16(ShstrtabIndex);
482 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
483 MCDataFragment *ShndxF,
485 uint8_t info, uint64_t value,
486 uint64_t size, uint8_t other,
490 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
491 String32(*ShndxF, shndx);
493 String32(*ShndxF, 0);
496 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
497 uint16_t(ELF::SHN_XINDEX) : shndx;
500 String32(*SymtabF, name); // st_name
501 String8(*SymtabF, info); // st_info
502 String8(*SymtabF, other); // st_other
503 String16(*SymtabF, Index); // st_shndx
504 String64(*SymtabF, value); // st_value
505 String64(*SymtabF, size); // st_size
507 String32(*SymtabF, name); // st_name
508 String32(*SymtabF, value); // st_value
509 String32(*SymtabF, size); // st_size
510 String8(*SymtabF, info); // st_info
511 String8(*SymtabF, other); // st_other
512 String16(*SymtabF, Index); // st_shndx
516 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
517 if (Data.isCommon() && Data.isExternal())
518 return Data.getCommonAlignment();
520 const MCSymbol &Symbol = Data.getSymbol();
522 if (Symbol.isAbsolute() && Symbol.isVariable()) {
523 if (const MCExpr *Value = Symbol.getVariableValue()) {
525 if (Value->EvaluateAsAbsolute(IntValue, Layout))
526 return (uint64_t)IntValue;
530 if (!Symbol.isInSection())
533 if (Data.getFragment())
534 return Layout.getSymbolOffset(&Data);
539 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
540 const MCAsmLayout &Layout) {
541 // The presence of symbol versions causes undefined symbols and
542 // versions declared with @@@ to be renamed.
544 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
545 ie = Asm.symbol_end(); it != ie; ++it) {
546 const MCSymbol &Alias = it->getSymbol();
547 const MCSymbol &Symbol = Alias.AliasedSymbol();
548 MCSymbolData &SD = Asm.getSymbolData(Symbol);
551 if (&Symbol == &Alias)
554 StringRef AliasName = Alias.getName();
555 size_t Pos = AliasName.find('@');
556 if (Pos == StringRef::npos)
559 // Aliases defined with .symvar copy the binding from the symbol they alias.
560 // This is the first place we are able to copy this information.
561 it->setExternal(SD.isExternal());
562 SetBinding(*it, GetBinding(SD));
564 StringRef Rest = AliasName.substr(Pos);
565 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
568 // FIXME: produce a better error message.
569 if (Symbol.isUndefined() && Rest.startswith("@@") &&
570 !Rest.startswith("@@@"))
571 report_fatal_error("A @@ version cannot be undefined");
573 Renames.insert(std::make_pair(&Symbol, &Alias));
577 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
578 MCDataFragment *ShndxF,
580 const MCAsmLayout &Layout) {
581 MCSymbolData &OrigData = *MSD.SymbolData;
583 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
585 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
586 Data.getSymbol().isVariable();
588 uint8_t Binding = GetBinding(OrigData);
589 uint8_t Visibility = GetVisibility(OrigData);
590 uint8_t Type = GetType(Data);
592 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
593 uint8_t Other = Visibility;
595 uint64_t Value = SymbolValue(Data, Layout);
598 assert(!(Data.isCommon() && !Data.isExternal()));
600 const MCExpr *ESize = Data.getSize();
603 if (!ESize->EvaluateAsAbsolute(Res, Layout))
604 report_fatal_error("Size expression must be absolute.");
608 // Write out the symbol table entry
609 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
610 Size, Other, MSD.SectionIndex, IsReserved);
613 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
614 MCDataFragment *ShndxF,
615 const MCAssembler &Asm,
616 const MCAsmLayout &Layout,
617 const SectionIndexMapTy &SectionIndexMap) {
618 // The string table must be emitted first because we need the index
619 // into the string table for all the symbol names.
620 assert(StringTable.size() && "Missing string table");
622 // FIXME: Make sure the start of the symbol table is aligned.
624 // The first entry is the undefined symbol entry.
625 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
627 // Write the symbol table entries.
628 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
629 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
630 ELFSymbolData &MSD = LocalSymbolData[i];
631 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
634 // Write out a symbol table entry for each regular section.
635 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
637 const MCSectionELF &Section =
638 static_cast<const MCSectionELF&>(i->getSection());
639 if (Section.getType() == ELF::SHT_RELA ||
640 Section.getType() == ELF::SHT_REL ||
641 Section.getType() == ELF::SHT_STRTAB ||
642 Section.getType() == ELF::SHT_SYMTAB)
644 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
645 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
646 LastLocalSymbolIndex++;
649 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
650 ELFSymbolData &MSD = ExternalSymbolData[i];
651 MCSymbolData &Data = *MSD.SymbolData;
652 assert(((Data.getFlags() & ELF_STB_Global) ||
653 (Data.getFlags() & ELF_STB_Weak)) &&
654 "External symbol requires STB_GLOBAL or STB_WEAK flag");
655 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
656 if (GetBinding(Data) == ELF::STB_LOCAL)
657 LastLocalSymbolIndex++;
660 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
661 ELFSymbolData &MSD = UndefinedSymbolData[i];
662 MCSymbolData &Data = *MSD.SymbolData;
663 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
664 if (GetBinding(Data) == ELF::STB_LOCAL)
665 LastLocalSymbolIndex++;
669 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
670 const MCValue &Target,
671 const MCFragment &F) const {
672 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
673 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
674 const MCSymbol *Renamed = Renames.lookup(&Symbol);
675 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
677 if (ASymbol.isUndefined()) {
683 if (SD.isExternal()) {
689 const MCSectionELF &Section =
690 static_cast<const MCSectionELF&>(ASymbol.getSection());
691 const SectionKind secKind = Section.getKind();
696 if (secKind.isThreadLocal()) {
702 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
703 const MCSectionELF &Sec2 =
704 static_cast<const MCSectionELF&>(F.getParent()->getSection());
706 if (&Sec2 != &Section &&
707 (Kind == MCSymbolRefExpr::VK_PLT ||
708 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
709 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
715 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
716 if (Target.getConstant() == 0)
727 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
728 const MCAsmLayout &Layout,
729 const MCFragment *Fragment,
730 const MCFixup &Fixup,
732 uint64_t &FixedValue) {
735 int64_t Value = Target.getConstant();
736 const MCSymbol *RelocSymbol = NULL;
738 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
739 if (!Target.isAbsolute()) {
740 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
741 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
742 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
744 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
745 const MCSymbol &SymbolB = RefB->getSymbol();
746 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
749 // Offset of the symbol in the section
750 int64_t a = Layout.getSymbolOffset(&SDB);
752 // Ofeset of the relocation in the section
753 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
758 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
759 MCFragment *F = SD.getFragment();
761 Index = F->getParent()->getOrdinal() + 1;
763 // Offset of the symbol in the section
764 Value += Layout.getSymbolOffset(&SD);
766 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
767 WeakrefUsedInReloc.insert(RelocSymbol);
769 UsedInReloc.insert(RelocSymbol);
773 // Compensate for the addend on i386.
779 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
780 (RelocSymbol != 0), Addend);
782 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
785 if (!hasRelocationAddend())
787 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
788 Relocations[Fragment->getParent()].push_back(ERE);
793 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
795 MCSymbolData &SD = Asm.getSymbolData(*S);
796 return SD.getIndex();
799 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
800 bool Used, bool Renamed) {
801 if (Data.getFlags() & ELF_Other_Weakref)
810 const MCSymbol &Symbol = Data.getSymbol();
812 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
815 const MCSymbol &A = Symbol.AliasedSymbol();
816 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
819 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
822 if (Symbol.isTemporary())
828 static bool isLocal(const MCSymbolData &Data, bool isSignature,
829 bool isUsedInReloc) {
830 if (Data.isExternal())
833 const MCSymbol &Symbol = Data.getSymbol();
834 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
836 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
837 if (isSignature && !isUsedInReloc)
846 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
847 SectionIndexMapTy &SectionIndexMap) {
849 for (MCAssembler::iterator it = Asm.begin(),
850 ie = Asm.end(); it != ie; ++it) {
851 const MCSectionELF &Section =
852 static_cast<const MCSectionELF &>(it->getSection());
853 if (Section.getType() != ELF::SHT_GROUP)
855 SectionIndexMap[&Section] = Index++;
858 for (MCAssembler::iterator it = Asm.begin(),
859 ie = Asm.end(); it != ie; ++it) {
860 const MCSectionELF &Section =
861 static_cast<const MCSectionELF &>(it->getSection());
862 if (Section.getType() == ELF::SHT_GROUP)
864 SectionIndexMap[&Section] = Index++;
868 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
869 const SectionIndexMapTy &SectionIndexMap,
870 RevGroupMapTy RevGroupMap) {
871 // FIXME: Is this the correct place to do this?
873 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
874 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
875 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
876 Data.setExternal(true);
877 SetBinding(Data, ELF::STB_GLOBAL);
880 // Build section lookup table.
881 int NumRegularSections = Asm.size();
883 // Index 0 is always the empty string.
884 StringMap<uint64_t> StringIndexMap;
885 StringTable += '\x00';
887 // Add the data for the symbols.
888 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
889 ie = Asm.symbol_end(); it != ie; ++it) {
890 const MCSymbol &Symbol = it->getSymbol();
892 bool Used = UsedInReloc.count(&Symbol);
893 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
894 bool isSignature = RevGroupMap.count(&Symbol);
896 if (!isInSymtab(Asm, *it,
897 Used || WeakrefUsed || isSignature,
898 Renames.count(&Symbol)))
903 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
905 // Undefined symbols are global, but this is the first place we
906 // are able to set it.
907 bool Local = isLocal(*it, isSignature, Used);
908 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
909 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
910 SetBinding(*it, ELF::STB_GLOBAL);
911 SetBinding(SD, ELF::STB_GLOBAL);
914 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
915 SetBinding(*it, ELF::STB_WEAK);
917 if (it->isCommon()) {
919 MSD.SectionIndex = ELF::SHN_COMMON;
920 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
921 MSD.SectionIndex = ELF::SHN_ABS;
922 } else if (RefSymbol.isUndefined()) {
923 if (isSignature && !Used)
924 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
926 MSD.SectionIndex = ELF::SHN_UNDEF;
928 const MCSectionELF &Section =
929 static_cast<const MCSectionELF&>(RefSymbol.getSection());
930 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
931 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
932 NeedsSymtabShndx = true;
933 assert(MSD.SectionIndex && "Invalid section index!");
936 // The @@@ in symbol version is replaced with @ in undefined symbols and
937 // @@ in defined ones.
938 StringRef Name = Symbol.getName();
941 size_t Pos = Name.find("@@@");
942 if (Pos != StringRef::npos) {
943 Buf += Name.substr(0, Pos);
944 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
945 Buf += Name.substr(Pos + Skip);
949 uint64_t &Entry = StringIndexMap[Name];
951 Entry = StringTable.size();
953 StringTable += '\x00';
955 MSD.StringIndex = Entry;
956 if (MSD.SectionIndex == ELF::SHN_UNDEF)
957 UndefinedSymbolData.push_back(MSD);
959 LocalSymbolData.push_back(MSD);
961 ExternalSymbolData.push_back(MSD);
964 // Symbols are required to be in lexicographic order.
965 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
966 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
967 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
969 // Set the symbol indices. Local symbols must come before all other
970 // symbols with non-local bindings.
972 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
973 LocalSymbolData[i].SymbolData->setIndex(Index++);
975 Index += NumRegularSections;
977 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
978 ExternalSymbolData[i].SymbolData->setIndex(Index++);
979 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
980 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
983 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
984 const MCSectionData &SD) {
985 if (!Relocations[&SD].empty()) {
986 MCContext &Ctx = Asm.getContext();
987 const MCSectionELF *RelaSection;
988 const MCSectionELF &Section =
989 static_cast<const MCSectionELF&>(SD.getSection());
991 const StringRef SectionName = Section.getSectionName();
992 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
993 RelaSectionName += SectionName;
996 if (hasRelocationAddend())
997 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
999 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1001 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1002 ELF::SHT_RELA : ELF::SHT_REL, 0,
1003 SectionKind::getReadOnly(),
1006 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1007 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1009 MCDataFragment *F = new MCDataFragment(&RelaSD);
1011 WriteRelocationsFragment(Asm, F, &SD);
1015 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1016 uint64_t Flags, uint64_t Address,
1017 uint64_t Offset, uint64_t Size,
1018 uint32_t Link, uint32_t Info,
1020 uint64_t EntrySize) {
1021 Write32(Name); // sh_name: index into string table
1022 Write32(Type); // sh_type
1023 WriteWord(Flags); // sh_flags
1024 WriteWord(Address); // sh_addr
1025 WriteWord(Offset); // sh_offset
1026 WriteWord(Size); // sh_size
1027 Write32(Link); // sh_link
1028 Write32(Info); // sh_info
1029 WriteWord(Alignment); // sh_addralign
1030 WriteWord(EntrySize); // sh_entsize
1033 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1035 const MCSectionData *SD) {
1036 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1037 // sort by the r_offset just like gnu as does
1038 array_pod_sort(Relocs.begin(), Relocs.end());
1040 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1041 ELFRelocationEntry entry = Relocs[e - i - 1];
1045 else if (entry.Index < 0)
1046 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1048 entry.Index += LocalSymbolData.size();
1050 String64(*F, entry.r_offset);
1052 struct ELF::Elf64_Rela ERE64;
1053 ERE64.setSymbolAndType(entry.Index, entry.Type);
1054 String64(*F, ERE64.r_info);
1056 if (hasRelocationAddend())
1057 String64(*F, entry.r_addend);
1059 String32(*F, entry.r_offset);
1061 struct ELF::Elf32_Rela ERE32;
1062 ERE32.setSymbolAndType(entry.Index, entry.Type);
1063 String32(*F, ERE32.r_info);
1065 if (hasRelocationAddend())
1066 String32(*F, entry.r_addend);
1071 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1072 MCAsmLayout &Layout,
1073 const SectionIndexMapTy &SectionIndexMap) {
1074 MCContext &Ctx = Asm.getContext();
1077 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1079 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1080 const MCSectionELF *ShstrtabSection =
1081 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1082 SectionKind::getReadOnly());
1083 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1084 ShstrtabSD.setAlignment(1);
1085 ShstrtabIndex = Asm.size();
1087 const MCSectionELF *SymtabSection =
1088 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1089 SectionKind::getReadOnly(),
1091 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1092 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1093 SymbolTableIndex = Asm.size();
1095 MCSectionData *SymtabShndxSD = NULL;
1097 if (NeedsSymtabShndx) {
1098 const MCSectionELF *SymtabShndxSection =
1099 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1100 SectionKind::getReadOnly(), 4, "");
1101 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1102 SymtabShndxSD->setAlignment(4);
1105 const MCSection *StrtabSection;
1106 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1107 SectionKind::getReadOnly());
1108 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1109 StrtabSD.setAlignment(1);
1110 StringTableIndex = Asm.size();
1112 WriteRelocations(Asm, Layout);
1115 F = new MCDataFragment(&SymtabSD);
1116 MCDataFragment *ShndxF = NULL;
1117 if (NeedsSymtabShndx) {
1118 ShndxF = new MCDataFragment(SymtabShndxSD);
1120 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1122 F = new MCDataFragment(&StrtabSD);
1123 F->getContents().append(StringTable.begin(), StringTable.end());
1125 F = new MCDataFragment(&ShstrtabSD);
1127 // Section header string table.
1129 // The first entry of a string table holds a null character so skip
1132 F->getContents() += '\x00';
1134 StringMap<uint64_t> SecStringMap;
1135 for (MCAssembler::const_iterator it = Asm.begin(),
1136 ie = Asm.end(); it != ie; ++it) {
1137 const MCSectionELF &Section =
1138 static_cast<const MCSectionELF&>(it->getSection());
1139 // FIXME: We could merge suffixes like in .text and .rela.text.
1141 StringRef Name = Section.getSectionName();
1142 if (SecStringMap.count(Name)) {
1143 SectionStringTableIndex[&Section] = SecStringMap[Name];
1146 // Remember the index into the string table so we can write it
1147 // into the sh_name field of the section header table.
1148 SectionStringTableIndex[&Section] = Index;
1149 SecStringMap[Name] = Index;
1151 Index += Name.size() + 1;
1152 F->getContents() += Name;
1153 F->getContents() += '\x00';
1157 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1158 const MCValue Target,
1160 const MCFragment *DF) const {
1161 // If this is a PCrel relocation, find the section this fixup value is
1163 const MCSection *BaseSection = 0;
1165 BaseSection = &DF->getParent()->getSection();
1166 assert(BaseSection);
1169 const MCSection *SectionA = 0;
1170 const MCSymbol *SymbolA = 0;
1171 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1172 SymbolA = &A->getSymbol();
1173 SectionA = &SymbolA->AliasedSymbol().getSection();
1176 const MCSection *SectionB = 0;
1177 const MCSymbol *SymbolB = 0;
1178 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1179 SymbolB = &B->getSymbol();
1180 SectionB = &SymbolB->AliasedSymbol().getSection();
1184 return SectionA == SectionB;
1189 // Absolute address but PCrel instruction, so we need a relocation.
1193 // FIXME: This is in here just to match gnu as output. If the two ends
1194 // are in the same section, there is nothing that the linker can do to
1196 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1197 if (DataA.isExternal())
1200 return BaseSection == SectionA;
1203 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1204 MCAsmLayout &Layout,
1205 GroupMapTy &GroupMap,
1206 RevGroupMapTy &RevGroupMap) {
1208 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1210 const MCSectionELF &Section =
1211 static_cast<const MCSectionELF&>(it->getSection());
1212 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1215 const MCSymbol *SignatureSymbol = Section.getGroup();
1216 Asm.getOrCreateSymbolData(*SignatureSymbol);
1217 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1219 Group = Asm.getContext().CreateELFGroupSection();
1220 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1221 Data.setAlignment(4);
1222 MCDataFragment *F = new MCDataFragment(&Data);
1223 String32(*F, ELF::GRP_COMDAT);
1225 GroupMap[Group] = SignatureSymbol;
1228 // Add sections to the groups
1230 unsigned NumGroups = RevGroupMap.size();
1231 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1232 it != ie; ++it, ++Index) {
1233 const MCSectionELF &Section =
1234 static_cast<const MCSectionELF&>(it->getSection());
1235 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1237 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1238 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1239 // FIXME: we could use the previous fragment
1240 MCDataFragment *F = new MCDataFragment(&Data);
1241 String32(*F, NumGroups + Index);
1245 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1246 const SectionIndexMapTy &SectionIndexMap,
1247 uint32_t GroupSymbolIndex,
1248 uint64_t Offset, uint64_t Size,
1250 const MCSectionELF &Section) {
1251 uint64_t sh_link = 0;
1252 uint64_t sh_info = 0;
1254 switch(Section.getType()) {
1255 case ELF::SHT_DYNAMIC:
1256 sh_link = SectionStringTableIndex[&Section];
1261 case ELF::SHT_RELA: {
1262 const MCSectionELF *SymtabSection;
1263 const MCSectionELF *InfoSection;
1264 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1266 SectionKind::getReadOnly());
1267 sh_link = SectionIndexMap.lookup(SymtabSection);
1268 assert(sh_link && ".symtab not found");
1270 // Remove ".rel" and ".rela" prefixes.
1271 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1272 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1274 InfoSection = Asm.getContext().getELFSection(SectionName,
1275 ELF::SHT_PROGBITS, 0,
1276 SectionKind::getReadOnly());
1277 sh_info = SectionIndexMap.lookup(InfoSection);
1281 case ELF::SHT_SYMTAB:
1282 case ELF::SHT_DYNSYM:
1283 sh_link = StringTableIndex;
1284 sh_info = LastLocalSymbolIndex;
1287 case ELF::SHT_SYMTAB_SHNDX:
1288 sh_link = SymbolTableIndex;
1291 case ELF::SHT_PROGBITS:
1292 case ELF::SHT_STRTAB:
1293 case ELF::SHT_NOBITS:
1295 case ELF::SHT_ARM_ATTRIBUTES:
1299 case ELF::SHT_GROUP: {
1300 sh_link = SymbolTableIndex;
1301 sh_info = GroupSymbolIndex;
1306 assert(0 && "FIXME: sh_type value not supported!");
1310 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1311 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1312 Alignment, Section.getEntrySize());
1315 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1316 return SD.getOrdinal() == ~UINT32_C(0) &&
1317 !SD.getSection().isVirtualSection();
1320 static uint64_t DataSectionSize(const MCSectionData &SD) {
1322 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1324 const MCFragment &F = *i;
1325 assert(F.getKind() == MCFragment::FT_Data);
1326 Ret += cast<MCDataFragment>(F).getContents().size();
1331 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1332 const MCSectionData &SD) {
1333 if (IsELFMetaDataSection(SD))
1334 return DataSectionSize(SD);
1335 return Layout.getSectionFileSize(&SD);
1338 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1339 const MCSectionData &SD) {
1340 if (IsELFMetaDataSection(SD))
1341 return DataSectionSize(SD);
1342 return Layout.getSectionAddressSize(&SD);
1345 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1346 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1348 const MCFragment &F = *i;
1349 assert(F.getKind() == MCFragment::FT_Data);
1350 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1354 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1355 const MCAsmLayout &Layout) {
1356 GroupMapTy GroupMap;
1357 RevGroupMapTy RevGroupMap;
1358 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1361 SectionIndexMapTy SectionIndexMap;
1363 ComputeIndexMap(Asm, SectionIndexMap);
1365 // Compute symbol table information.
1366 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1368 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1369 const_cast<MCAsmLayout&>(Layout),
1372 // Update to include the metadata sections.
1373 ComputeIndexMap(Asm, SectionIndexMap);
1375 // Add 1 for the null section.
1376 unsigned NumSections = Asm.size() + 1;
1377 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1378 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1379 sizeof(ELF::Elf32_Ehdr);
1380 uint64_t FileOff = HeaderSize;
1382 std::vector<const MCSectionELF*> Sections;
1383 Sections.resize(NumSections);
1385 for (SectionIndexMapTy::const_iterator i=
1386 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1387 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1388 Sections[p.second] = p.first;
1391 for (unsigned i = 1; i < NumSections; ++i) {
1392 const MCSectionELF &Section = *Sections[i];
1393 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1395 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1397 // Get the size of the section in the output file (including padding).
1398 FileOff += GetSectionFileSize(Layout, SD);
1401 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1403 // Write out the ELF header ...
1404 WriteHeader(FileOff - HeaderSize, NumSections);
1406 FileOff = HeaderSize;
1408 // ... then all of the sections ...
1409 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1411 for (unsigned i = 1; i < NumSections; ++i) {
1412 const MCSectionELF &Section = *Sections[i];
1413 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1415 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1416 WriteZeros(Padding);
1419 // Remember the offset into the file for this section.
1420 SectionOffsetMap[&Section] = FileOff;
1422 FileOff += GetSectionFileSize(Layout, SD);
1424 if (IsELFMetaDataSection(SD))
1425 WriteDataSectionData(this, SD);
1427 Asm.WriteSectionData(&SD, Layout);
1430 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1431 WriteZeros(Padding);
1434 // ... and then the section header table.
1435 // Should we align the section header table?
1437 // Null section first.
1438 uint64_t FirstSectionSize =
1439 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1440 uint32_t FirstSectionLink =
1441 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1442 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1444 for (unsigned i = 1; i < NumSections; ++i) {
1445 const MCSectionELF &Section = *Sections[i];
1446 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1447 uint32_t GroupSymbolIndex;
1448 if (Section.getType() != ELF::SHT_GROUP)
1449 GroupSymbolIndex = 0;
1451 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1453 uint64_t Size = GetSectionAddressSize(Layout, SD);
1455 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1456 SectionOffsetMap[&Section], Size,
1457 SD.getAlignment(), Section);
1461 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1463 bool IsLittleEndian) {
1464 switch (MOTW->getEMachine()) {
1466 case ELF::EM_X86_64:
1467 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1469 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1470 case ELF::EM_MBLAZE:
1471 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1472 default: llvm_unreachable("Unsupported architecture"); break;
1477 /// START OF SUBCLASSES for ELFObjectWriter
1478 //===- ARMELFObjectWriter -------------------------------------------===//
1480 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1482 bool IsLittleEndian)
1483 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1486 ARMELFObjectWriter::~ARMELFObjectWriter()
1489 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1490 const MCFixup &Fixup,
1492 bool IsRelocWithSymbol,
1494 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1495 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1499 switch ((unsigned)Fixup.getKind()) {
1500 default: assert(0 && "Unimplemented");
1503 default: llvm_unreachable("Unsupported Modifier");
1504 case MCSymbolRefExpr::VK_None:
1505 Type = ELF::R_ARM_BASE_PREL; break;
1506 case MCSymbolRefExpr::VK_ARM_TLSGD:
1507 assert(0 && "unimplemented"); break;
1508 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1509 Type = ELF::R_ARM_TLS_IE32;
1511 case ARM::fixup_arm_branch:
1513 case MCSymbolRefExpr::VK_ARM_PLT:
1514 Type = ELF::R_ARM_PLT32; break;
1516 Type = ELF::R_ARM_CALL; break;
1520 switch ((unsigned)Fixup.getKind()) {
1521 default: llvm_unreachable("invalid fixup kind!");
1524 default: llvm_unreachable("Unsupported Modifier"); break;
1525 case MCSymbolRefExpr::VK_ARM_GOT:
1526 Type = ELF::R_ARM_GOT_BREL; break;
1527 case MCSymbolRefExpr::VK_ARM_TLSGD:
1528 Type = ELF::R_ARM_TLS_GD32; break;
1529 case MCSymbolRefExpr::VK_ARM_TPOFF:
1530 Type = ELF::R_ARM_TLS_LE32; break;
1531 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1532 Type = ELF::R_ARM_TLS_IE32; break;
1533 case MCSymbolRefExpr::VK_None:
1534 Type = ELF::R_ARM_ABS32; break;
1535 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1536 Type = ELF::R_ARM_GOTOFF32; break;
1538 case ARM::fixup_arm_ldst_pcrel_12:
1539 case ARM::fixup_arm_pcrel_10:
1540 case ARM::fixup_arm_adr_pcrel_12:
1541 case ARM::fixup_arm_thumb_bl:
1542 case ARM::fixup_arm_thumb_cb:
1543 case ARM::fixup_arm_thumb_cp:
1544 case ARM::fixup_arm_thumb_br:
1545 assert(0 && "Unimplemented"); break;
1546 case ARM::fixup_arm_branch:
1547 // FIXME: Differentiate between R_ARM_CALL and
1548 // R_ARM_JUMP24 (latter used for conditional jumps)
1549 Type = ELF::R_ARM_CALL; break;
1550 case ARM::fixup_arm_movt_hi16:
1551 Type = ELF::R_ARM_MOVT_ABS; break;
1552 case ARM::fixup_arm_movw_lo16:
1553 Type = ELF::R_ARM_MOVW_ABS_NC; break;
1557 if (RelocNeedsGOT(Modifier))
1563 //===- MBlazeELFObjectWriter -------------------------------------------===//
1565 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1567 bool IsLittleEndian)
1568 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1571 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1574 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1575 const MCFixup &Fixup,
1577 bool IsRelocWithSymbol,
1579 // determine the type of the relocation
1582 switch ((unsigned)Fixup.getKind()) {
1584 llvm_unreachable("Unimplemented");
1586 Type = ELF::R_MICROBLAZE_64_PCREL;
1589 Type = ELF::R_MICROBLAZE_32_PCREL;
1593 switch ((unsigned)Fixup.getKind()) {
1594 default: llvm_unreachable("invalid fixup kind!");
1596 Type = ((IsRelocWithSymbol || Addend !=0)
1597 ? ELF::R_MICROBLAZE_32
1598 : ELF::R_MICROBLAZE_64);
1601 Type = ELF::R_MICROBLAZE_32;
1608 //===- X86ELFObjectWriter -------------------------------------------===//
1611 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1613 bool IsLittleEndian)
1614 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1617 X86ELFObjectWriter::~X86ELFObjectWriter()
1620 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1621 const MCFixup &Fixup,
1623 bool IsRelocWithSymbol,
1625 // determine the type of the relocation
1627 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1628 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1634 llvm_unreachable("Unimplemented");
1635 case MCSymbolRefExpr::VK_None:
1636 Type = ELF::R_X86_64_PC32;
1638 case MCSymbolRefExpr::VK_PLT:
1639 Type = ELF::R_X86_64_PLT32;
1641 case MCSymbolRefExpr::VK_GOTPCREL:
1642 Type = ELF::R_X86_64_GOTPCREL;
1644 case MCSymbolRefExpr::VK_GOTTPOFF:
1645 Type = ELF::R_X86_64_GOTTPOFF;
1647 case MCSymbolRefExpr::VK_TLSGD:
1648 Type = ELF::R_X86_64_TLSGD;
1650 case MCSymbolRefExpr::VK_TLSLD:
1651 Type = ELF::R_X86_64_TLSLD;
1655 switch ((unsigned)Fixup.getKind()) {
1656 default: llvm_unreachable("invalid fixup kind!");
1657 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1658 case X86::reloc_signed_4byte:
1660 assert(isInt<32>(Target.getConstant()));
1663 llvm_unreachable("Unimplemented");
1664 case MCSymbolRefExpr::VK_None:
1665 Type = ELF::R_X86_64_32S;
1667 case MCSymbolRefExpr::VK_GOT:
1668 Type = ELF::R_X86_64_GOT32;
1670 case MCSymbolRefExpr::VK_GOTPCREL:
1671 Type = ELF::R_X86_64_GOTPCREL;
1673 case MCSymbolRefExpr::VK_TPOFF:
1674 Type = ELF::R_X86_64_TPOFF32;
1676 case MCSymbolRefExpr::VK_DTPOFF:
1677 Type = ELF::R_X86_64_DTPOFF32;
1682 Type = ELF::R_X86_64_32;
1684 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1686 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1693 llvm_unreachable("Unimplemented");
1694 case MCSymbolRefExpr::VK_None:
1695 Type = ELF::R_386_PC32;
1697 case MCSymbolRefExpr::VK_PLT:
1698 Type = ELF::R_386_PLT32;
1702 switch ((unsigned)Fixup.getKind()) {
1703 default: llvm_unreachable("invalid fixup kind!");
1705 case X86::reloc_global_offset_table:
1706 Type = ELF::R_386_GOTPC;
1709 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1711 case X86::reloc_signed_4byte:
1716 llvm_unreachable("Unimplemented");
1717 case MCSymbolRefExpr::VK_None:
1718 Type = ELF::R_386_32;
1720 case MCSymbolRefExpr::VK_GOT:
1721 Type = ELF::R_386_GOT32;
1723 case MCSymbolRefExpr::VK_GOTOFF:
1724 Type = ELF::R_386_GOTOFF;
1726 case MCSymbolRefExpr::VK_TLSGD:
1727 Type = ELF::R_386_TLS_GD;
1729 case MCSymbolRefExpr::VK_TPOFF:
1730 Type = ELF::R_386_TLS_LE_32;
1732 case MCSymbolRefExpr::VK_INDNTPOFF:
1733 Type = ELF::R_386_TLS_IE;
1735 case MCSymbolRefExpr::VK_NTPOFF:
1736 Type = ELF::R_386_TLS_LE;
1738 case MCSymbolRefExpr::VK_GOTNTPOFF:
1739 Type = ELF::R_386_TLS_GOTIE;
1741 case MCSymbolRefExpr::VK_TLSLDM:
1742 Type = ELF::R_386_TLS_LDM;
1744 case MCSymbolRefExpr::VK_DTPOFF:
1745 Type = ELF::R_386_TLS_LDO_32;
1749 case FK_Data_2: Type = ELF::R_386_16; break;
1751 case FK_Data_1: Type = ELF::R_386_8; break;
1756 if (RelocNeedsGOT(Modifier))