1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Target/TargetAsmBackend.h"
32 #include "../Target/X86/X86FixupKinds.h"
33 #include "../Target/MBlaze/MBlazeFixupKinds.h"
38 static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
47 static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
61 static unsigned GetVisibility(MCSymbolData &SD) {
63 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
69 static bool isFixupKindX86PCRel(unsigned Kind) {
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
76 case X86::reloc_riprel_4byte_movq_load:
81 static bool isFixupKindMBlazePCRel(unsigned Kind) {
85 case MBlaze::reloc_pcrel_2byte:
86 case MBlaze::reloc_pcrel_4byte:
91 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
95 case MCSymbolRefExpr::VK_GOT:
96 case MCSymbolRefExpr::VK_PLT:
97 case MCSymbolRefExpr::VK_GOTPCREL:
98 case MCSymbolRefExpr::VK_TPOFF:
99 case MCSymbolRefExpr::VK_TLSGD:
100 case MCSymbolRefExpr::VK_GOTTPOFF:
101 case MCSymbolRefExpr::VK_INDNTPOFF:
102 case MCSymbolRefExpr::VK_NTPOFF:
103 case MCSymbolRefExpr::VK_GOTNTPOFF:
104 case MCSymbolRefExpr::VK_TLSLDM:
105 case MCSymbolRefExpr::VK_DTPOFF:
106 case MCSymbolRefExpr::VK_TLSLD:
112 class ELFObjectWriter : public MCObjectWriter {
114 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
115 return Kind == X86::reloc_riprel_4byte ||
116 Kind == X86::reloc_riprel_4byte_movq_load;
120 /// ELFSymbolData - Helper struct for containing some precomputed information
122 struct ELFSymbolData {
123 MCSymbolData *SymbolData;
124 uint64_t StringIndex;
125 uint32_t SectionIndex;
127 // Support lexicographic sorting.
128 bool operator<(const ELFSymbolData &RHS) const {
129 if (GetType(*SymbolData) == ELF::STT_FILE)
131 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
133 return SymbolData->getSymbol().getName() <
134 RHS.SymbolData->getSymbol().getName();
138 /// @name Relocation Data
141 struct ELFRelocationEntry {
142 // Make these big enough for both 32-bit and 64-bit
146 const MCSymbol *Symbol;
149 // Support lexicographic sorting.
150 bool operator<(const ELFRelocationEntry &RE) const {
151 return RE.r_offset < r_offset;
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 unsigned Is64Bit : 1;
180 bool HasRelocationAddend;
182 Triple::OSType OSType;
186 // This holds the symbol table index of the last local symbol.
187 unsigned LastLocalSymbolIndex;
188 // This holds the .strtab section index.
189 unsigned StringTableIndex;
190 // This holds the .symtab section index.
191 unsigned SymbolTableIndex;
193 unsigned ShstrtabIndex;
196 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
197 const MCValue &Target,
198 const MCFragment &F) const;
201 ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
202 uint16_t _EMachine, bool _HasRelAddend,
203 Triple::OSType _OSType)
204 : MCObjectWriter(_OS, IsLittleEndian),
205 NeedsGOT(false), NeedsSymtabShndx(false),
206 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
207 OSType(_OSType), EMachine(_EMachine) {
210 virtual ~ELFObjectWriter();
212 void WriteWord(uint64_t W) {
219 void StringLE16(char *buf, uint16_t Value) {
220 buf[0] = char(Value >> 0);
221 buf[1] = char(Value >> 8);
224 void StringLE32(char *buf, uint32_t Value) {
225 StringLE16(buf, uint16_t(Value >> 0));
226 StringLE16(buf + 2, uint16_t(Value >> 16));
229 void StringLE64(char *buf, uint64_t Value) {
230 StringLE32(buf, uint32_t(Value >> 0));
231 StringLE32(buf + 4, uint32_t(Value >> 32));
234 void StringBE16(char *buf ,uint16_t Value) {
235 buf[0] = char(Value >> 8);
236 buf[1] = char(Value >> 0);
239 void StringBE32(char *buf, uint32_t Value) {
240 StringBE16(buf, uint16_t(Value >> 16));
241 StringBE16(buf + 2, uint16_t(Value >> 0));
244 void StringBE64(char *buf, uint64_t Value) {
245 StringBE32(buf, uint32_t(Value >> 32));
246 StringBE32(buf + 4, uint32_t(Value >> 0));
249 void String8(MCDataFragment &F, uint8_t Value) {
252 F.getContents() += StringRef(buf, 1);
255 void String16(MCDataFragment &F, uint16_t Value) {
257 if (isLittleEndian())
258 StringLE16(buf, Value);
260 StringBE16(buf, Value);
261 F.getContents() += StringRef(buf, 2);
264 void String32(MCDataFragment &F, uint32_t Value) {
266 if (isLittleEndian())
267 StringLE32(buf, Value);
269 StringBE32(buf, Value);
270 F.getContents() += StringRef(buf, 4);
273 void String64(MCDataFragment &F, uint64_t Value) {
275 if (isLittleEndian())
276 StringLE64(buf, Value);
278 StringBE64(buf, Value);
279 F.getContents() += StringRef(buf, 8);
282 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
284 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
285 uint64_t name, uint8_t info,
286 uint64_t value, uint64_t size,
287 uint8_t other, uint32_t shndx,
290 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
292 const MCAsmLayout &Layout);
294 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
295 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
296 const MCAssembler &Asm,
297 const MCAsmLayout &Layout,
298 const SectionIndexMapTy &SectionIndexMap);
300 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
301 const MCFragment *Fragment, const MCFixup &Fixup,
302 MCValue Target, uint64_t &FixedValue) {
303 assert(0 && "RecordRelocation is not specific enough");
306 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
309 // Map from a group section to the signature symbol
310 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
311 // Map from a signature symbol to the group section
312 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
314 /// ComputeSymbolTable - Compute the symbol table data
316 /// \param StringTable [out] - The string table data.
317 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
319 virtual void ComputeSymbolTable(MCAssembler &Asm,
320 const SectionIndexMapTy &SectionIndexMap,
321 RevGroupMapTy RevGroupMap);
323 virtual void ComputeIndexMap(MCAssembler &Asm,
324 SectionIndexMapTy &SectionIndexMap);
326 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
327 const MCSectionData &SD);
329 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
330 for (MCAssembler::const_iterator it = Asm.begin(),
331 ie = Asm.end(); it != ie; ++it) {
332 WriteRelocation(Asm, Layout, *it);
336 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
337 const SectionIndexMapTy &SectionIndexMap);
339 virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
340 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
342 virtual void ExecutePostLayoutBinding(MCAssembler &Asm);
344 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
345 uint64_t Address, uint64_t Offset,
346 uint64_t Size, uint32_t Link, uint32_t Info,
347 uint64_t Alignment, uint64_t EntrySize);
349 virtual void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
350 const MCSectionData *SD);
352 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
353 const MCValue Target,
355 const MCFragment *DF) const;
357 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
358 virtual void WriteSection(MCAssembler &Asm,
359 const SectionIndexMapTy &SectionIndexMap,
360 uint32_t GroupSymbolIndex,
361 uint64_t Offset, uint64_t Size, uint64_t Alignment,
362 const MCSectionELF &Section);
365 //===- X86ELFObjectWriter -------------------------------------------===//
367 class X86ELFObjectWriter : public ELFObjectWriter {
369 X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
370 uint16_t _EMachine, bool _HasRelAddend,
371 Triple::OSType _OSType);
373 virtual ~X86ELFObjectWriter();
374 virtual void RecordRelocation(const MCAssembler &Asm,
375 const MCAsmLayout &Layout,
376 const MCFragment *Fragment,
377 const MCFixup &Fixup, MCValue Target,
378 uint64_t &FixedValue);
382 //===- ARMELFObjectWriter -------------------------------------------===//
384 class ARMELFObjectWriter : public ELFObjectWriter {
386 ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
387 uint16_t _EMachine, bool _HasRelAddend,
388 Triple::OSType _OSType);
390 virtual ~ARMELFObjectWriter();
391 virtual void RecordRelocation(const MCAssembler &Asm,
392 const MCAsmLayout &Layout,
393 const MCFragment *Fragment,
394 const MCFixup &Fixup, MCValue Target,
395 uint64_t &FixedValue);
398 //===- MBlazeELFObjectWriter -------------------------------------------===//
400 class MBlazeELFObjectWriter : public ELFObjectWriter {
402 MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
403 uint16_t _EMachine, bool _HasRelAddend,
404 Triple::OSType _OSType);
406 virtual ~MBlazeELFObjectWriter();
407 virtual void RecordRelocation(const MCAssembler &Asm,
408 const MCAsmLayout &Layout,
409 const MCFragment *Fragment,
410 const MCFixup &Fixup, MCValue Target,
411 uint64_t &FixedValue);
415 ELFObjectWriter::~ELFObjectWriter()
418 // Emit the ELF header.
419 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
420 unsigned NumberOfSections) {
426 // emitWord method behaves differently for ELF32 and ELF64, writing
427 // 4 bytes in the former and 8 in the latter.
429 Write8(0x7f); // e_ident[EI_MAG0]
430 Write8('E'); // e_ident[EI_MAG1]
431 Write8('L'); // e_ident[EI_MAG2]
432 Write8('F'); // e_ident[EI_MAG3]
434 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
437 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
439 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
442 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
443 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
444 default: Write8(ELF::ELFOSABI_NONE); break;
446 Write8(0); // e_ident[EI_ABIVERSION]
448 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
450 Write16(ELF::ET_REL); // e_type
452 Write16(EMachine); // e_machine = target
454 Write32(ELF::EV_CURRENT); // e_version
455 WriteWord(0); // e_entry, no entry point in .o file
456 WriteWord(0); // e_phoff, no program header for .o
457 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
458 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
460 // FIXME: Make this configurable.
461 Write32(0); // e_flags = whatever the target wants
463 // e_ehsize = ELF header size
464 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
466 Write16(0); // e_phentsize = prog header entry size
467 Write16(0); // e_phnum = # prog header entries = 0
469 // e_shentsize = Section header entry size
470 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
472 // e_shnum = # of section header ents
473 if (NumberOfSections >= ELF::SHN_LORESERVE)
476 Write16(NumberOfSections);
478 // e_shstrndx = Section # of '.shstrtab'
479 if (NumberOfSections >= ELF::SHN_LORESERVE)
480 Write16(ELF::SHN_XINDEX);
482 Write16(ShstrtabIndex);
485 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
486 MCDataFragment *ShndxF,
488 uint8_t info, uint64_t value,
489 uint64_t size, uint8_t other,
493 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
494 String32(*ShndxF, shndx);
496 String32(*ShndxF, 0);
499 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
500 uint16_t(ELF::SHN_XINDEX) : shndx;
503 String32(*SymtabF, name); // st_name
504 String8(*SymtabF, info); // st_info
505 String8(*SymtabF, other); // st_other
506 String16(*SymtabF, Index); // st_shndx
507 String64(*SymtabF, value); // st_value
508 String64(*SymtabF, size); // st_size
510 String32(*SymtabF, name); // st_name
511 String32(*SymtabF, value); // st_value
512 String32(*SymtabF, size); // st_size
513 String8(*SymtabF, info); // st_info
514 String8(*SymtabF, other); // st_other
515 String16(*SymtabF, Index); // st_shndx
519 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
520 if (Data.isCommon() && Data.isExternal())
521 return Data.getCommonAlignment();
523 const MCSymbol &Symbol = Data.getSymbol();
524 if (!Symbol.isInSection())
527 if (MCFragment *FF = Data.getFragment())
528 return Layout.getSymbolAddress(&Data) -
529 Layout.getSectionAddress(FF->getParent());
534 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
535 // The presence of symbol versions causes undefined symbols and
536 // versions declared with @@@ to be renamed.
538 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
539 ie = Asm.symbol_end(); it != ie; ++it) {
540 const MCSymbol &Alias = it->getSymbol();
541 const MCSymbol &Symbol = Alias.AliasedSymbol();
542 MCSymbolData &SD = Asm.getSymbolData(Symbol);
545 if (&Symbol == &Alias)
548 StringRef AliasName = Alias.getName();
549 size_t Pos = AliasName.find('@');
550 if (Pos == StringRef::npos)
553 // Aliases defined with .symvar copy the binding from the symbol they alias.
554 // This is the first place we are able to copy this information.
555 it->setExternal(SD.isExternal());
556 SetBinding(*it, GetBinding(SD));
558 StringRef Rest = AliasName.substr(Pos);
559 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
562 // FIXME: produce a better error message.
563 if (Symbol.isUndefined() && Rest.startswith("@@") &&
564 !Rest.startswith("@@@"))
565 report_fatal_error("A @@ version cannot be undefined");
567 Renames.insert(std::make_pair(&Symbol, &Alias));
571 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
572 MCDataFragment *ShndxF,
574 const MCAsmLayout &Layout) {
575 MCSymbolData &OrigData = *MSD.SymbolData;
577 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
579 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
580 Data.getSymbol().isVariable();
582 uint8_t Binding = GetBinding(OrigData);
583 uint8_t Visibility = GetVisibility(OrigData);
584 uint8_t Type = GetType(Data);
586 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
587 uint8_t Other = Visibility;
589 uint64_t Value = SymbolValue(Data, Layout);
593 assert(!(Data.isCommon() && !Data.isExternal()));
595 ESize = Data.getSize();
596 if (Data.getSize()) {
598 if (ESize->getKind() == MCExpr::Binary) {
599 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
601 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
602 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
603 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
604 Size = Res.getConstant();
606 } else if (ESize->getKind() == MCExpr::Constant) {
607 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
609 assert(0 && "Unsupported size expression");
613 // Write out the symbol table entry
614 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
615 Size, Other, MSD.SectionIndex, IsReserved);
618 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
619 MCDataFragment *ShndxF,
620 const MCAssembler &Asm,
621 const MCAsmLayout &Layout,
622 const SectionIndexMapTy &SectionIndexMap) {
623 // The string table must be emitted first because we need the index
624 // into the string table for all the symbol names.
625 assert(StringTable.size() && "Missing string table");
627 // FIXME: Make sure the start of the symbol table is aligned.
629 // The first entry is the undefined symbol entry.
630 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
632 // Write the symbol table entries.
633 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
634 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
635 ELFSymbolData &MSD = LocalSymbolData[i];
636 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
639 // Write out a symbol table entry for each regular section.
640 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
642 const MCSectionELF &Section =
643 static_cast<const MCSectionELF&>(i->getSection());
644 if (Section.getType() == ELF::SHT_RELA ||
645 Section.getType() == ELF::SHT_REL ||
646 Section.getType() == ELF::SHT_STRTAB ||
647 Section.getType() == ELF::SHT_SYMTAB)
649 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
650 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
651 LastLocalSymbolIndex++;
654 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
655 ELFSymbolData &MSD = ExternalSymbolData[i];
656 MCSymbolData &Data = *MSD.SymbolData;
657 assert(((Data.getFlags() & ELF_STB_Global) ||
658 (Data.getFlags() & ELF_STB_Weak)) &&
659 "External symbol requires STB_GLOBAL or STB_WEAK flag");
660 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
661 if (GetBinding(Data) == ELF::STB_LOCAL)
662 LastLocalSymbolIndex++;
665 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
666 ELFSymbolData &MSD = UndefinedSymbolData[i];
667 MCSymbolData &Data = *MSD.SymbolData;
668 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
669 if (GetBinding(Data) == ELF::STB_LOCAL)
670 LastLocalSymbolIndex++;
674 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
675 const MCValue &Target,
676 const MCFragment &F) const {
677 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
678 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
679 const MCSymbol *Renamed = Renames.lookup(&Symbol);
680 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
682 if (ASymbol.isUndefined()) {
688 if (SD.isExternal()) {
694 const MCSectionELF &Section =
695 static_cast<const MCSectionELF&>(ASymbol.getSection());
697 if (Section.getKind().isBSS())
700 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
701 const MCSectionELF &Sec2 =
702 static_cast<const MCSectionELF&>(F.getParent()->getSection());
704 if (&Sec2 != &Section &&
705 (Kind == MCSymbolRefExpr::VK_PLT ||
706 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
707 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
713 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
714 if (Target.getConstant() == 0)
726 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
728 MCSymbolData &SD = Asm.getSymbolData(*S);
729 return SD.getIndex();
732 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
733 bool Used, bool Renamed) {
734 if (Data.getFlags() & ELF_Other_Weakref)
743 const MCSymbol &Symbol = Data.getSymbol();
745 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
748 const MCSymbol &A = Symbol.AliasedSymbol();
749 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
752 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
755 if (Symbol.isTemporary())
761 static bool isLocal(const MCSymbolData &Data, bool isSignature,
762 bool isUsedInReloc) {
763 if (Data.isExternal())
766 const MCSymbol &Symbol = Data.getSymbol();
767 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
769 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
770 if (isSignature && !isUsedInReloc)
779 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
780 SectionIndexMapTy &SectionIndexMap) {
782 for (MCAssembler::iterator it = Asm.begin(),
783 ie = Asm.end(); it != ie; ++it) {
784 const MCSectionELF &Section =
785 static_cast<const MCSectionELF &>(it->getSection());
786 if (Section.getType() != ELF::SHT_GROUP)
788 SectionIndexMap[&Section] = Index++;
791 for (MCAssembler::iterator it = Asm.begin(),
792 ie = Asm.end(); it != ie; ++it) {
793 const MCSectionELF &Section =
794 static_cast<const MCSectionELF &>(it->getSection());
795 if (Section.getType() == ELF::SHT_GROUP)
797 SectionIndexMap[&Section] = Index++;
801 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
802 const SectionIndexMapTy &SectionIndexMap,
803 RevGroupMapTy RevGroupMap) {
804 // FIXME: Is this the correct place to do this?
806 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
807 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
808 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
809 Data.setExternal(true);
810 SetBinding(Data, ELF::STB_GLOBAL);
813 // Build section lookup table.
814 int NumRegularSections = Asm.size();
816 // Index 0 is always the empty string.
817 StringMap<uint64_t> StringIndexMap;
818 StringTable += '\x00';
820 // Add the data for the symbols.
821 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
822 ie = Asm.symbol_end(); it != ie; ++it) {
823 const MCSymbol &Symbol = it->getSymbol();
825 bool Used = UsedInReloc.count(&Symbol);
826 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
827 bool isSignature = RevGroupMap.count(&Symbol);
829 if (!isInSymtab(Asm, *it,
830 Used || WeakrefUsed || isSignature,
831 Renames.count(&Symbol)))
836 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
838 // Undefined symbols are global, but this is the first place we
839 // are able to set it.
840 bool Local = isLocal(*it, isSignature, Used);
841 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
842 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
843 SetBinding(*it, ELF::STB_GLOBAL);
844 SetBinding(SD, ELF::STB_GLOBAL);
847 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
848 SetBinding(*it, ELF::STB_WEAK);
850 if (it->isCommon()) {
852 MSD.SectionIndex = ELF::SHN_COMMON;
853 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
854 MSD.SectionIndex = ELF::SHN_ABS;
855 } else if (RefSymbol.isUndefined()) {
856 if (isSignature && !Used)
857 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
859 MSD.SectionIndex = ELF::SHN_UNDEF;
861 const MCSectionELF &Section =
862 static_cast<const MCSectionELF&>(RefSymbol.getSection());
863 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
864 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
865 NeedsSymtabShndx = true;
866 assert(MSD.SectionIndex && "Invalid section index!");
869 // The @@@ in symbol version is replaced with @ in undefined symbols and
870 // @@ in defined ones.
871 StringRef Name = Symbol.getName();
874 size_t Pos = Name.find("@@@");
875 if (Pos != StringRef::npos) {
876 Buf += Name.substr(0, Pos);
877 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
878 Buf += Name.substr(Pos + Skip);
882 uint64_t &Entry = StringIndexMap[Name];
884 Entry = StringTable.size();
886 StringTable += '\x00';
888 MSD.StringIndex = Entry;
889 if (MSD.SectionIndex == ELF::SHN_UNDEF)
890 UndefinedSymbolData.push_back(MSD);
892 LocalSymbolData.push_back(MSD);
894 ExternalSymbolData.push_back(MSD);
897 // Symbols are required to be in lexicographic order.
898 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
899 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
900 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
902 // Set the symbol indices. Local symbols must come before all other
903 // symbols with non-local bindings.
905 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
906 LocalSymbolData[i].SymbolData->setIndex(Index++);
908 Index += NumRegularSections;
910 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
911 ExternalSymbolData[i].SymbolData->setIndex(Index++);
912 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
913 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
916 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
917 const MCSectionData &SD) {
918 if (!Relocations[&SD].empty()) {
919 MCContext &Ctx = Asm.getContext();
920 const MCSectionELF *RelaSection;
921 const MCSectionELF &Section =
922 static_cast<const MCSectionELF&>(SD.getSection());
924 const StringRef SectionName = Section.getSectionName();
925 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
926 RelaSectionName += SectionName;
929 if (HasRelocationAddend)
930 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
932 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
934 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
935 ELF::SHT_RELA : ELF::SHT_REL, 0,
936 SectionKind::getReadOnly(),
939 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
940 RelaSD.setAlignment(Is64Bit ? 8 : 4);
942 MCDataFragment *F = new MCDataFragment(&RelaSD);
944 WriteRelocationsFragment(Asm, F, &SD);
946 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
950 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
951 uint64_t Flags, uint64_t Address,
952 uint64_t Offset, uint64_t Size,
953 uint32_t Link, uint32_t Info,
955 uint64_t EntrySize) {
956 Write32(Name); // sh_name: index into string table
957 Write32(Type); // sh_type
958 WriteWord(Flags); // sh_flags
959 WriteWord(Address); // sh_addr
960 WriteWord(Offset); // sh_offset
961 WriteWord(Size); // sh_size
962 Write32(Link); // sh_link
963 Write32(Info); // sh_info
964 WriteWord(Alignment); // sh_addralign
965 WriteWord(EntrySize); // sh_entsize
968 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
970 const MCSectionData *SD) {
971 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
972 // sort by the r_offset just like gnu as does
973 array_pod_sort(Relocs.begin(), Relocs.end());
975 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
976 ELFRelocationEntry entry = Relocs[e - i - 1];
980 else if (entry.Index < 0)
981 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
983 entry.Index += LocalSymbolData.size();
985 String64(*F, entry.r_offset);
987 struct ELF::Elf64_Rela ERE64;
988 ERE64.setSymbolAndType(entry.Index, entry.Type);
989 String64(*F, ERE64.r_info);
991 if (HasRelocationAddend)
992 String64(*F, entry.r_addend);
994 String32(*F, entry.r_offset);
996 struct ELF::Elf32_Rela ERE32;
997 ERE32.setSymbolAndType(entry.Index, entry.Type);
998 String32(*F, ERE32.r_info);
1000 if (HasRelocationAddend)
1001 String32(*F, entry.r_addend);
1006 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1007 MCAsmLayout &Layout,
1008 const SectionIndexMapTy &SectionIndexMap) {
1009 MCContext &Ctx = Asm.getContext();
1012 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1014 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1015 const MCSectionELF *ShstrtabSection =
1016 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1017 SectionKind::getReadOnly());
1018 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1019 ShstrtabSD.setAlignment(1);
1020 ShstrtabIndex = Asm.size();
1022 const MCSectionELF *SymtabSection =
1023 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1024 SectionKind::getReadOnly(),
1026 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1027 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1028 SymbolTableIndex = Asm.size();
1030 MCSectionData *SymtabShndxSD = NULL;
1032 if (NeedsSymtabShndx) {
1033 const MCSectionELF *SymtabShndxSection =
1034 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1035 SectionKind::getReadOnly(), 4, "");
1036 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1037 SymtabShndxSD->setAlignment(4);
1040 const MCSection *StrtabSection;
1041 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1042 SectionKind::getReadOnly());
1043 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1044 StrtabSD.setAlignment(1);
1045 StringTableIndex = Asm.size();
1047 WriteRelocations(Asm, Layout);
1050 F = new MCDataFragment(&SymtabSD);
1051 MCDataFragment *ShndxF = NULL;
1052 if (NeedsSymtabShndx) {
1053 ShndxF = new MCDataFragment(SymtabShndxSD);
1054 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1056 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1057 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1059 F = new MCDataFragment(&StrtabSD);
1060 F->getContents().append(StringTable.begin(), StringTable.end());
1061 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1063 F = new MCDataFragment(&ShstrtabSD);
1065 // Section header string table.
1067 // The first entry of a string table holds a null character so skip
1070 F->getContents() += '\x00';
1072 StringMap<uint64_t> SecStringMap;
1073 for (MCAssembler::const_iterator it = Asm.begin(),
1074 ie = Asm.end(); it != ie; ++it) {
1075 const MCSectionELF &Section =
1076 static_cast<const MCSectionELF&>(it->getSection());
1077 // FIXME: We could merge suffixes like in .text and .rela.text.
1079 StringRef Name = Section.getSectionName();
1080 if (SecStringMap.count(Name)) {
1081 SectionStringTableIndex[&Section] = SecStringMap[Name];
1084 // Remember the index into the string table so we can write it
1085 // into the sh_name field of the section header table.
1086 SectionStringTableIndex[&Section] = Index;
1087 SecStringMap[Name] = Index;
1089 Index += Name.size() + 1;
1090 F->getContents() += Name;
1091 F->getContents() += '\x00';
1094 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1097 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1098 const MCValue Target,
1100 const MCFragment *DF) const {
1101 // If this is a PCrel relocation, find the section this fixup value is
1103 const MCSection *BaseSection = 0;
1105 BaseSection = &DF->getParent()->getSection();
1106 assert(BaseSection);
1109 const MCSection *SectionA = 0;
1110 const MCSymbol *SymbolA = 0;
1111 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1112 SymbolA = &A->getSymbol();
1113 SectionA = &SymbolA->AliasedSymbol().getSection();
1116 const MCSection *SectionB = 0;
1117 const MCSymbol *SymbolB = 0;
1118 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1119 SymbolB = &B->getSymbol();
1120 SectionB = &SymbolB->AliasedSymbol().getSection();
1124 return SectionA == SectionB;
1129 // Absolute address but PCrel instruction, so we need a relocation.
1133 // FIXME: This is in here just to match gnu as output. If the two ends
1134 // are in the same section, there is nothing that the linker can do to
1136 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1137 if (DataA.isExternal())
1140 return BaseSection == SectionA;
1143 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1144 MCAsmLayout &Layout,
1145 GroupMapTy &GroupMap,
1146 RevGroupMapTy &RevGroupMap) {
1148 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1150 const MCSectionELF &Section =
1151 static_cast<const MCSectionELF&>(it->getSection());
1152 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1155 const MCSymbol *SignatureSymbol = Section.getGroup();
1156 Asm.getOrCreateSymbolData(*SignatureSymbol);
1157 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1159 Group = Asm.getContext().CreateELFGroupSection();
1160 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1161 Data.setAlignment(4);
1162 MCDataFragment *F = new MCDataFragment(&Data);
1163 String32(*F, ELF::GRP_COMDAT);
1165 GroupMap[Group] = SignatureSymbol;
1168 // Add sections to the groups
1170 unsigned NumGroups = RevGroupMap.size();
1171 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1172 it != ie; ++it, ++Index) {
1173 const MCSectionELF &Section =
1174 static_cast<const MCSectionELF&>(it->getSection());
1175 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1177 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1178 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1179 // FIXME: we could use the previous fragment
1180 MCDataFragment *F = new MCDataFragment(&Data);
1181 String32(*F, NumGroups + Index);
1184 for (RevGroupMapTy::const_iterator i = RevGroupMap.begin(),
1185 e = RevGroupMap.end(); i != e; ++i) {
1186 const MCSectionELF *Group = i->second;
1187 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1188 Asm.AddSectionToTheEnd(*this, Data, Layout);
1192 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1193 const SectionIndexMapTy &SectionIndexMap,
1194 uint32_t GroupSymbolIndex,
1195 uint64_t Offset, uint64_t Size,
1197 const MCSectionELF &Section) {
1198 uint64_t sh_link = 0;
1199 uint64_t sh_info = 0;
1201 switch(Section.getType()) {
1202 case ELF::SHT_DYNAMIC:
1203 sh_link = SectionStringTableIndex[&Section];
1208 case ELF::SHT_RELA: {
1209 const MCSectionELF *SymtabSection;
1210 const MCSectionELF *InfoSection;
1211 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1213 SectionKind::getReadOnly());
1214 sh_link = SectionIndexMap.lookup(SymtabSection);
1215 assert(sh_link && ".symtab not found");
1217 // Remove ".rel" and ".rela" prefixes.
1218 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1219 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1221 InfoSection = Asm.getContext().getELFSection(SectionName,
1222 ELF::SHT_PROGBITS, 0,
1223 SectionKind::getReadOnly());
1224 sh_info = SectionIndexMap.lookup(InfoSection);
1228 case ELF::SHT_SYMTAB:
1229 case ELF::SHT_DYNSYM:
1230 sh_link = StringTableIndex;
1231 sh_info = LastLocalSymbolIndex;
1234 case ELF::SHT_SYMTAB_SHNDX:
1235 sh_link = SymbolTableIndex;
1238 case ELF::SHT_PROGBITS:
1239 case ELF::SHT_STRTAB:
1240 case ELF::SHT_NOBITS:
1242 case ELF::SHT_ARM_ATTRIBUTES:
1246 case ELF::SHT_GROUP: {
1247 sh_link = SymbolTableIndex;
1248 sh_info = GroupSymbolIndex;
1253 assert(0 && "FIXME: sh_type value not supported!");
1257 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1258 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1259 Alignment, Section.getEntrySize());
1262 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1263 const MCAsmLayout &Layout) {
1264 GroupMapTy GroupMap;
1265 RevGroupMapTy RevGroupMap;
1266 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1269 SectionIndexMapTy SectionIndexMap;
1271 ComputeIndexMap(Asm, SectionIndexMap);
1273 // Compute symbol table information.
1274 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1276 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1277 const_cast<MCAsmLayout&>(Layout),
1280 // Update to include the metadata sections.
1281 ComputeIndexMap(Asm, SectionIndexMap);
1283 // Add 1 for the null section.
1284 unsigned NumSections = Asm.size() + 1;
1285 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1286 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1287 uint64_t FileOff = HeaderSize;
1289 std::vector<const MCSectionELF*> Sections;
1290 Sections.resize(NumSections);
1292 for (SectionIndexMapTy::const_iterator i=
1293 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1294 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1295 Sections[p.second] = p.first;
1298 for (unsigned i = 1; i < NumSections; ++i) {
1299 const MCSectionELF &Section = *Sections[i];
1300 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1302 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1304 // Get the size of the section in the output file (including padding).
1305 uint64_t Size = Layout.getSectionFileSize(&SD);
1310 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1312 // Write out the ELF header ...
1313 WriteHeader(FileOff - HeaderSize, NumSections);
1315 FileOff = HeaderSize;
1317 // ... then all of the sections ...
1318 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1320 for (unsigned i = 1; i < NumSections; ++i) {
1321 const MCSectionELF &Section = *Sections[i];
1322 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1324 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1325 WriteZeros(Padding);
1328 // Remember the offset into the file for this section.
1329 SectionOffsetMap[&Section] = FileOff;
1331 FileOff += Layout.getSectionFileSize(&SD);
1333 Asm.WriteSectionData(&SD, Layout, this);
1336 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1337 WriteZeros(Padding);
1340 // ... and then the section header table.
1341 // Should we align the section header table?
1343 // Null section first.
1344 uint64_t FirstSectionSize =
1345 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1346 uint32_t FirstSectionLink =
1347 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1348 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1350 for (unsigned i = 1; i < NumSections; ++i) {
1351 const MCSectionELF &Section = *Sections[i];
1352 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1353 uint32_t GroupSymbolIndex;
1354 if (Section.getType() != ELF::SHT_GROUP)
1355 GroupSymbolIndex = 0;
1357 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1359 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1360 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1361 SD.getAlignment(), Section);
1365 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1367 Triple::OSType OSType,
1369 bool IsLittleEndian,
1370 bool HasRelocationAddend) {
1373 case ELF::EM_X86_64:
1374 return new X86ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1375 HasRelocationAddend, OSType); break;
1377 return new ARMELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1378 HasRelocationAddend, OSType); break;
1379 case ELF::EM_MBLAZE:
1380 return new MBlazeELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1381 HasRelocationAddend, OSType); break;
1382 default: llvm_unreachable("Unsupported architecture"); break;
1387 /// START OF SUBCLASSES for ELFObjectWriter
1388 //===- ARMELFObjectWriter -------------------------------------------===//
1390 ARMELFObjectWriter::ARMELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1391 bool _IsLittleEndian,
1392 uint16_t _EMachine, bool _HasRelocationAddend,
1393 Triple::OSType _OSType)
1394 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1395 _HasRelocationAddend, _OSType)
1398 ARMELFObjectWriter::~ARMELFObjectWriter()
1401 void ARMELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1402 const MCAsmLayout &Layout,
1403 const MCFragment *Fragment,
1404 const MCFixup &Fixup,
1406 uint64_t &FixedValue) {
1407 assert(0 && "ARMELFObjectWriter::RecordRelocation() unimplemented");
1410 //===- MBlazeELFObjectWriter -------------------------------------------===//
1412 MBlazeELFObjectWriter::MBlazeELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1413 bool _IsLittleEndian,
1415 bool _HasRelocationAddend,
1416 Triple::OSType _OSType)
1417 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1418 _HasRelocationAddend, _OSType) {
1421 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1424 void MBlazeELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1425 const MCAsmLayout &Layout,
1426 const MCFragment *Fragment,
1427 const MCFixup &Fixup,
1429 uint64_t &FixedValue) {
1432 int64_t Value = Target.getConstant();
1433 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1434 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1435 const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1437 bool IsPCRel = isFixupKindMBlazePCRel(Fixup.getKind());
1438 if (!Target.isAbsolute()) {
1439 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1440 const MCSymbol &SymbolB = RefB->getSymbol();
1441 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1443 MCSectionData *Sec = Fragment->getParent();
1445 // Offset of the symbol in the section
1446 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1448 // Ofeset of the relocation in the section
1449 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1454 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1455 MCFragment *F = SD.getFragment();
1457 Index = F->getParent()->getOrdinal();
1459 MCSectionData *FSD = F->getParent();
1460 // Offset of the symbol in the section
1461 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1463 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1464 WeakrefUsedInReloc.insert(RelocSymbol);
1466 UsedInReloc.insert(RelocSymbol);
1474 // determine the type of the relocation
1477 switch ((unsigned)Fixup.getKind()) {
1479 llvm_unreachable("Unimplemented");
1480 case MBlaze::reloc_pcrel_4byte:
1481 Type = ELF::R_MICROBLAZE_64_PCREL;
1483 case MBlaze::reloc_pcrel_2byte:
1484 Type = ELF::R_MICROBLAZE_32_PCREL;
1488 switch ((unsigned)Fixup.getKind()) {
1489 default: llvm_unreachable("invalid fixup kind!");
1491 Type = (RelocSymbol || Addend !=0) ? ELF::R_MICROBLAZE_32
1492 : ELF::R_MICROBLAZE_64;
1495 Type = ELF::R_MICROBLAZE_32;
1500 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
1501 if (RelocNeedsGOT(Modifier))
1504 ELFRelocationEntry ERE;
1508 ERE.Symbol = RelocSymbol;
1510 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1512 if (HasRelocationAddend)
1513 ERE.r_addend = Addend;
1515 ERE.r_addend = 0; // Silence compiler warning.
1517 Relocations[Fragment->getParent()].push_back(ERE);
1520 //===- X86ELFObjectWriter -------------------------------------------===//
1523 X86ELFObjectWriter::X86ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit,
1524 bool _IsLittleEndian,
1525 uint16_t _EMachine, bool _HasRelocationAddend,
1526 Triple::OSType _OSType)
1527 : ELFObjectWriter(_OS, _Is64Bit, _IsLittleEndian, _EMachine,
1528 _HasRelocationAddend, _OSType)
1531 X86ELFObjectWriter::~X86ELFObjectWriter()
1534 void X86ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1535 const MCAsmLayout &Layout,
1536 const MCFragment *Fragment,
1537 const MCFixup &Fixup,
1539 uint64_t &FixedValue) {
1542 int64_t Value = Target.getConstant();
1543 const MCSymbol *RelocSymbol = NULL;
1545 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
1546 if (!Target.isAbsolute()) {
1547 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1548 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
1549 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
1551 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1552 const MCSymbol &SymbolB = RefB->getSymbol();
1553 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
1555 MCSectionData *Sec = Fragment->getParent();
1557 // Offset of the symbol in the section
1558 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
1560 // Ofeset of the relocation in the section
1561 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1566 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
1567 MCFragment *F = SD.getFragment();
1569 Index = F->getParent()->getOrdinal() + 1;
1571 MCSectionData *FSD = F->getParent();
1572 // Offset of the symbol in the section
1573 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
1575 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
1576 WeakrefUsedInReloc.insert(RelocSymbol);
1578 UsedInReloc.insert(RelocSymbol);
1582 // Compensate for the addend on i386.
1589 // determine the type of the relocation
1591 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1592 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1598 llvm_unreachable("Unimplemented");
1599 case MCSymbolRefExpr::VK_None:
1600 Type = ELF::R_X86_64_PC32;
1602 case MCSymbolRefExpr::VK_PLT:
1603 Type = ELF::R_X86_64_PLT32;
1605 case MCSymbolRefExpr::VK_GOTPCREL:
1606 Type = ELF::R_X86_64_GOTPCREL;
1608 case MCSymbolRefExpr::VK_GOTTPOFF:
1609 Type = ELF::R_X86_64_GOTTPOFF;
1611 case MCSymbolRefExpr::VK_TLSGD:
1612 Type = ELF::R_X86_64_TLSGD;
1614 case MCSymbolRefExpr::VK_TLSLD:
1615 Type = ELF::R_X86_64_TLSLD;
1619 switch ((unsigned)Fixup.getKind()) {
1620 default: llvm_unreachable("invalid fixup kind!");
1621 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1622 case X86::reloc_signed_4byte:
1623 case X86::reloc_pcrel_4byte:
1624 assert(isInt<32>(Target.getConstant()));
1627 llvm_unreachable("Unimplemented");
1628 case MCSymbolRefExpr::VK_None:
1629 Type = ELF::R_X86_64_32S;
1631 case MCSymbolRefExpr::VK_GOT:
1632 Type = ELF::R_X86_64_GOT32;
1634 case MCSymbolRefExpr::VK_GOTPCREL:
1635 Type = ELF::R_X86_64_GOTPCREL;
1637 case MCSymbolRefExpr::VK_TPOFF:
1638 Type = ELF::R_X86_64_TPOFF32;
1640 case MCSymbolRefExpr::VK_DTPOFF:
1641 Type = ELF::R_X86_64_DTPOFF32;
1646 Type = ELF::R_X86_64_32;
1648 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1649 case X86::reloc_pcrel_1byte:
1650 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1657 llvm_unreachable("Unimplemented");
1658 case MCSymbolRefExpr::VK_None:
1659 Type = ELF::R_386_PC32;
1661 case MCSymbolRefExpr::VK_PLT:
1662 Type = ELF::R_386_PLT32;
1666 switch ((unsigned)Fixup.getKind()) {
1667 default: llvm_unreachable("invalid fixup kind!");
1669 case X86::reloc_global_offset_table:
1670 Type = ELF::R_386_GOTPC;
1673 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1675 case X86::reloc_signed_4byte:
1676 case X86::reloc_pcrel_4byte:
1680 llvm_unreachable("Unimplemented");
1681 case MCSymbolRefExpr::VK_None:
1682 Type = ELF::R_386_32;
1684 case MCSymbolRefExpr::VK_GOT:
1685 Type = ELF::R_386_GOT32;
1687 case MCSymbolRefExpr::VK_GOTOFF:
1688 Type = ELF::R_386_GOTOFF;
1690 case MCSymbolRefExpr::VK_TLSGD:
1691 Type = ELF::R_386_TLS_GD;
1693 case MCSymbolRefExpr::VK_TPOFF:
1694 Type = ELF::R_386_TLS_LE_32;
1696 case MCSymbolRefExpr::VK_INDNTPOFF:
1697 Type = ELF::R_386_TLS_IE;
1699 case MCSymbolRefExpr::VK_NTPOFF:
1700 Type = ELF::R_386_TLS_LE;
1702 case MCSymbolRefExpr::VK_GOTNTPOFF:
1703 Type = ELF::R_386_TLS_GOTIE;
1705 case MCSymbolRefExpr::VK_TLSLDM:
1706 Type = ELF::R_386_TLS_LDM;
1708 case MCSymbolRefExpr::VK_DTPOFF:
1709 Type = ELF::R_386_TLS_LDO_32;
1713 case FK_Data_2: Type = ELF::R_386_16; break;
1714 case X86::reloc_pcrel_1byte:
1715 case FK_Data_1: Type = ELF::R_386_8; break;
1720 if (RelocNeedsGOT(Modifier))
1723 ELFRelocationEntry ERE;
1727 ERE.Symbol = RelocSymbol;
1729 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1731 if (HasRelocationAddend)
1732 ERE.r_addend = Addend;
1734 ERE.r_addend = 0; // Silence compiler warning.
1736 Relocations[Fragment->getParent()].push_back(ERE);