1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/OwningPtr.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCELFObjectWriter.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSectionELF.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCValue.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ELF.h"
32 #include "llvm/Target/TargetAsmBackend.h"
34 #include "../Target/X86/X86FixupKinds.h"
35 #include "../Target/ARM/ARMFixupKinds.h"
40 static unsigned GetType(const MCSymbolData &SD) {
41 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
42 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
43 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
44 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
45 Type == ELF::STT_TLS);
49 static unsigned GetBinding(const MCSymbolData &SD) {
50 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
51 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
52 Binding == ELF::STB_WEAK);
56 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
57 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
58 Binding == ELF::STB_WEAK);
59 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
60 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
63 static unsigned GetVisibility(MCSymbolData &SD) {
65 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
66 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
67 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
72 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
76 case MCSymbolRefExpr::VK_GOT:
77 case MCSymbolRefExpr::VK_PLT:
78 case MCSymbolRefExpr::VK_GOTPCREL:
79 case MCSymbolRefExpr::VK_TPOFF:
80 case MCSymbolRefExpr::VK_TLSGD:
81 case MCSymbolRefExpr::VK_GOTTPOFF:
82 case MCSymbolRefExpr::VK_INDNTPOFF:
83 case MCSymbolRefExpr::VK_NTPOFF:
84 case MCSymbolRefExpr::VK_GOTNTPOFF:
85 case MCSymbolRefExpr::VK_TLSLDM:
86 case MCSymbolRefExpr::VK_DTPOFF:
87 case MCSymbolRefExpr::VK_TLSLD:
92 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
93 const MCFixupKindInfo &FKI =
94 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
96 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
100 class ELFObjectWriter : public MCObjectWriter {
102 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
103 return Kind == X86::reloc_riprel_4byte ||
104 Kind == X86::reloc_riprel_4byte_movq_load;
108 /// ELFSymbolData - Helper struct for containing some precomputed information
110 struct ELFSymbolData {
111 MCSymbolData *SymbolData;
112 uint64_t StringIndex;
113 uint32_t SectionIndex;
115 // Support lexicographic sorting.
116 bool operator<(const ELFSymbolData &RHS) const {
117 if (GetType(*SymbolData) == ELF::STT_FILE)
119 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
121 return SymbolData->getSymbol().getName() <
122 RHS.SymbolData->getSymbol().getName();
126 /// @name Relocation Data
129 struct ELFRelocationEntry {
130 // Make these big enough for both 32-bit and 64-bit
134 const MCSymbol *Symbol;
138 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
140 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
141 unsigned RelType, const MCSymbol *Sym,
143 : r_offset(RelocOffset), Index(Idx), Type(RelType),
144 Symbol(Sym), r_addend(Addend) {}
146 // Support lexicographic sorting.
147 bool operator<(const ELFRelocationEntry &RE) const {
148 return RE.r_offset < r_offset;
152 /// The target specific ELF writer instance.
153 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
155 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
156 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
157 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
159 llvm::DenseMap<const MCSectionData*,
160 std::vector<ELFRelocationEntry> > Relocations;
161 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
164 /// @name Symbol Table Data
167 SmallString<256> StringTable;
168 std::vector<ELFSymbolData> LocalSymbolData;
169 std::vector<ELFSymbolData> ExternalSymbolData;
170 std::vector<ELFSymbolData> UndefinedSymbolData;
176 bool NeedsSymtabShndx;
178 // This holds the symbol table index of the last local symbol.
179 unsigned LastLocalSymbolIndex;
180 // This holds the .strtab section index.
181 unsigned StringTableIndex;
182 // This holds the .symtab section index.
183 unsigned SymbolTableIndex;
185 unsigned ShstrtabIndex;
188 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
189 const MCValue &Target,
190 const MCFragment &F) const;
192 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
193 bool hasRelocationAddend() const {
194 return TargetObjectWriter->hasRelocationAddend();
198 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
199 raw_ostream &_OS, bool IsLittleEndian)
200 : MCObjectWriter(_OS, IsLittleEndian),
201 TargetObjectWriter(MOTW),
202 NeedsGOT(false), NeedsSymtabShndx(false){
205 virtual ~ELFObjectWriter();
207 void WriteWord(uint64_t W) {
214 void StringLE16(char *buf, uint16_t Value) {
215 buf[0] = char(Value >> 0);
216 buf[1] = char(Value >> 8);
219 void StringLE32(char *buf, uint32_t Value) {
220 StringLE16(buf, uint16_t(Value >> 0));
221 StringLE16(buf + 2, uint16_t(Value >> 16));
224 void StringLE64(char *buf, uint64_t Value) {
225 StringLE32(buf, uint32_t(Value >> 0));
226 StringLE32(buf + 4, uint32_t(Value >> 32));
229 void StringBE16(char *buf ,uint16_t Value) {
230 buf[0] = char(Value >> 8);
231 buf[1] = char(Value >> 0);
234 void StringBE32(char *buf, uint32_t Value) {
235 StringBE16(buf, uint16_t(Value >> 16));
236 StringBE16(buf + 2, uint16_t(Value >> 0));
239 void StringBE64(char *buf, uint64_t Value) {
240 StringBE32(buf, uint32_t(Value >> 32));
241 StringBE32(buf + 4, uint32_t(Value >> 0));
244 void String8(MCDataFragment &F, uint8_t Value) {
247 F.getContents() += StringRef(buf, 1);
250 void String16(MCDataFragment &F, uint16_t Value) {
252 if (isLittleEndian())
253 StringLE16(buf, Value);
255 StringBE16(buf, Value);
256 F.getContents() += StringRef(buf, 2);
259 void String32(MCDataFragment &F, uint32_t Value) {
261 if (isLittleEndian())
262 StringLE32(buf, Value);
264 StringBE32(buf, Value);
265 F.getContents() += StringRef(buf, 4);
268 void String64(MCDataFragment &F, uint64_t Value) {
270 if (isLittleEndian())
271 StringLE64(buf, Value);
273 StringBE64(buf, Value);
274 F.getContents() += StringRef(buf, 8);
277 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
279 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
280 uint64_t name, uint8_t info,
281 uint64_t value, uint64_t size,
282 uint8_t other, uint32_t shndx,
285 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
287 const MCAsmLayout &Layout);
289 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
290 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
291 const MCAssembler &Asm,
292 const MCAsmLayout &Layout,
293 const SectionIndexMapTy &SectionIndexMap);
295 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
296 const MCFragment *Fragment, const MCFixup &Fixup,
297 MCValue Target, uint64_t &FixedValue);
299 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
302 // Map from a group section to the signature symbol
303 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
304 // Map from a signature symbol to the group section
305 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
307 /// ComputeSymbolTable - Compute the symbol table data
309 /// \param StringTable [out] - The string table data.
310 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
312 virtual void ComputeSymbolTable(MCAssembler &Asm,
313 const SectionIndexMapTy &SectionIndexMap,
314 RevGroupMapTy RevGroupMap);
316 virtual void ComputeIndexMap(MCAssembler &Asm,
317 SectionIndexMapTy &SectionIndexMap);
319 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
320 const MCSectionData &SD);
322 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
323 for (MCAssembler::const_iterator it = Asm.begin(),
324 ie = Asm.end(); it != ie; ++it) {
325 WriteRelocation(Asm, Layout, *it);
329 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
330 const SectionIndexMapTy &SectionIndexMap);
332 virtual void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
333 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
335 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
336 const MCAsmLayout &Layout);
338 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
339 uint64_t Address, uint64_t Offset,
340 uint64_t Size, uint32_t Link, uint32_t Info,
341 uint64_t Alignment, uint64_t EntrySize);
343 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
345 const MCSectionData *SD);
348 IsSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
349 const MCSymbolRefExpr *A,
350 const MCSymbolRefExpr *B) const {
351 // FIXME: Implement this!
355 virtual bool isAbsolute(bool IsSet, const MCSymbol &A,
356 const MCSymbol &B) const {
357 // On ELF A - B is absolute if A and B are in the same section.
358 return &A.getSection() == &B.getSection();
361 virtual bool IsFixupFullyResolved(const MCAssembler &Asm,
362 const MCValue Target,
364 const MCFragment *DF) const;
366 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
367 virtual void WriteSection(MCAssembler &Asm,
368 const SectionIndexMapTy &SectionIndexMap,
369 uint32_t GroupSymbolIndex,
370 uint64_t Offset, uint64_t Size, uint64_t Alignment,
371 const MCSectionELF &Section);
374 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
375 bool IsPCRel, bool IsRelocWithSymbol,
379 //===- X86ELFObjectWriter -------------------------------------------===//
381 class X86ELFObjectWriter : public ELFObjectWriter {
383 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
385 bool IsLittleEndian);
387 virtual ~X86ELFObjectWriter();
389 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
390 bool IsPCRel, bool IsRelocWithSymbol,
395 //===- ARMELFObjectWriter -------------------------------------------===//
397 class ARMELFObjectWriter : public ELFObjectWriter {
399 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
401 bool IsLittleEndian);
403 virtual ~ARMELFObjectWriter();
405 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
406 bool IsPCRel, bool IsRelocWithSymbol,
410 //===- MBlazeELFObjectWriter -------------------------------------------===//
412 class MBlazeELFObjectWriter : public ELFObjectWriter {
414 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
416 bool IsLittleEndian);
418 virtual ~MBlazeELFObjectWriter();
420 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
421 bool IsPCRel, bool IsRelocWithSymbol,
426 ELFObjectWriter::~ELFObjectWriter()
429 // Emit the ELF header.
430 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
431 unsigned NumberOfSections) {
437 // emitWord method behaves differently for ELF32 and ELF64, writing
438 // 4 bytes in the former and 8 in the latter.
440 Write8(0x7f); // e_ident[EI_MAG0]
441 Write8('E'); // e_ident[EI_MAG1]
442 Write8('L'); // e_ident[EI_MAG2]
443 Write8('F'); // e_ident[EI_MAG3]
445 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
448 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
450 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
452 switch (TargetObjectWriter->getOSType()) {
453 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
454 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
455 default: Write8(ELF::ELFOSABI_NONE); break;
457 Write8(0); // e_ident[EI_ABIVERSION]
459 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
461 Write16(ELF::ET_REL); // e_type
463 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
465 Write32(ELF::EV_CURRENT); // e_version
466 WriteWord(0); // e_entry, no entry point in .o file
467 WriteWord(0); // e_phoff, no program header for .o
468 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
469 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
471 // FIXME: Make this configurable.
472 Write32(0); // e_flags = whatever the target wants
474 // e_ehsize = ELF header size
475 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
477 Write16(0); // e_phentsize = prog header entry size
478 Write16(0); // e_phnum = # prog header entries = 0
480 // e_shentsize = Section header entry size
481 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
483 // e_shnum = # of section header ents
484 if (NumberOfSections >= ELF::SHN_LORESERVE)
487 Write16(NumberOfSections);
489 // e_shstrndx = Section # of '.shstrtab'
490 if (NumberOfSections >= ELF::SHN_LORESERVE)
491 Write16(ELF::SHN_XINDEX);
493 Write16(ShstrtabIndex);
496 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
497 MCDataFragment *ShndxF,
499 uint8_t info, uint64_t value,
500 uint64_t size, uint8_t other,
504 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
505 String32(*ShndxF, shndx);
507 String32(*ShndxF, 0);
510 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
511 uint16_t(ELF::SHN_XINDEX) : shndx;
514 String32(*SymtabF, name); // st_name
515 String8(*SymtabF, info); // st_info
516 String8(*SymtabF, other); // st_other
517 String16(*SymtabF, Index); // st_shndx
518 String64(*SymtabF, value); // st_value
519 String64(*SymtabF, size); // st_size
521 String32(*SymtabF, name); // st_name
522 String32(*SymtabF, value); // st_value
523 String32(*SymtabF, size); // st_size
524 String8(*SymtabF, info); // st_info
525 String8(*SymtabF, other); // st_other
526 String16(*SymtabF, Index); // st_shndx
530 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
531 if (Data.isCommon() && Data.isExternal())
532 return Data.getCommonAlignment();
534 const MCSymbol &Symbol = Data.getSymbol();
535 if (!Symbol.isInSection())
538 if (Data.getFragment())
539 return Layout.getSymbolOffset(&Data);
544 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
545 const MCAsmLayout &Layout) {
546 // The presence of symbol versions causes undefined symbols and
547 // versions declared with @@@ to be renamed.
549 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
550 ie = Asm.symbol_end(); it != ie; ++it) {
551 const MCSymbol &Alias = it->getSymbol();
552 const MCSymbol &Symbol = Alias.AliasedSymbol();
553 MCSymbolData &SD = Asm.getSymbolData(Symbol);
556 if (&Symbol == &Alias)
559 StringRef AliasName = Alias.getName();
560 size_t Pos = AliasName.find('@');
561 if (Pos == StringRef::npos)
564 // Aliases defined with .symvar copy the binding from the symbol they alias.
565 // This is the first place we are able to copy this information.
566 it->setExternal(SD.isExternal());
567 SetBinding(*it, GetBinding(SD));
569 StringRef Rest = AliasName.substr(Pos);
570 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
573 // FIXME: produce a better error message.
574 if (Symbol.isUndefined() && Rest.startswith("@@") &&
575 !Rest.startswith("@@@"))
576 report_fatal_error("A @@ version cannot be undefined");
578 Renames.insert(std::make_pair(&Symbol, &Alias));
582 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
583 MCDataFragment *ShndxF,
585 const MCAsmLayout &Layout) {
586 MCSymbolData &OrigData = *MSD.SymbolData;
588 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
590 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
591 Data.getSymbol().isVariable();
593 uint8_t Binding = GetBinding(OrigData);
594 uint8_t Visibility = GetVisibility(OrigData);
595 uint8_t Type = GetType(Data);
597 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
598 uint8_t Other = Visibility;
600 uint64_t Value = SymbolValue(Data, Layout);
604 assert(!(Data.isCommon() && !Data.isExternal()));
606 ESize = Data.getSize();
607 if (Data.getSize()) {
609 if (ESize->getKind() == MCExpr::Binary) {
610 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
612 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
613 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
614 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
615 Size = Res.getConstant();
617 } else if (ESize->getKind() == MCExpr::Constant) {
618 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
620 assert(0 && "Unsupported size expression");
624 // Write out the symbol table entry
625 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
626 Size, Other, MSD.SectionIndex, IsReserved);
629 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
630 MCDataFragment *ShndxF,
631 const MCAssembler &Asm,
632 const MCAsmLayout &Layout,
633 const SectionIndexMapTy &SectionIndexMap) {
634 // The string table must be emitted first because we need the index
635 // into the string table for all the symbol names.
636 assert(StringTable.size() && "Missing string table");
638 // FIXME: Make sure the start of the symbol table is aligned.
640 // The first entry is the undefined symbol entry.
641 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
643 // Write the symbol table entries.
644 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
645 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
646 ELFSymbolData &MSD = LocalSymbolData[i];
647 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
650 // Write out a symbol table entry for each regular section.
651 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
653 const MCSectionELF &Section =
654 static_cast<const MCSectionELF&>(i->getSection());
655 if (Section.getType() == ELF::SHT_RELA ||
656 Section.getType() == ELF::SHT_REL ||
657 Section.getType() == ELF::SHT_STRTAB ||
658 Section.getType() == ELF::SHT_SYMTAB)
660 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
661 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
662 LastLocalSymbolIndex++;
665 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
666 ELFSymbolData &MSD = ExternalSymbolData[i];
667 MCSymbolData &Data = *MSD.SymbolData;
668 assert(((Data.getFlags() & ELF_STB_Global) ||
669 (Data.getFlags() & ELF_STB_Weak)) &&
670 "External symbol requires STB_GLOBAL or STB_WEAK flag");
671 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
672 if (GetBinding(Data) == ELF::STB_LOCAL)
673 LastLocalSymbolIndex++;
676 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
677 ELFSymbolData &MSD = UndefinedSymbolData[i];
678 MCSymbolData &Data = *MSD.SymbolData;
679 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
680 if (GetBinding(Data) == ELF::STB_LOCAL)
681 LastLocalSymbolIndex++;
685 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
686 const MCValue &Target,
687 const MCFragment &F) const {
688 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
689 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
690 const MCSymbol *Renamed = Renames.lookup(&Symbol);
691 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
693 if (ASymbol.isUndefined()) {
699 if (SD.isExternal()) {
705 const MCSectionELF &Section =
706 static_cast<const MCSectionELF&>(ASymbol.getSection());
707 const SectionKind secKind = Section.getKind();
712 if (secKind.isThreadLocal()) {
718 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
719 const MCSectionELF &Sec2 =
720 static_cast<const MCSectionELF&>(F.getParent()->getSection());
722 if (&Sec2 != &Section &&
723 (Kind == MCSymbolRefExpr::VK_PLT ||
724 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
725 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
731 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
732 if (Target.getConstant() == 0)
743 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
744 const MCAsmLayout &Layout,
745 const MCFragment *Fragment,
746 const MCFixup &Fixup,
748 uint64_t &FixedValue) {
751 int64_t Value = Target.getConstant();
752 const MCSymbol *RelocSymbol = NULL;
754 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
755 if (!Target.isAbsolute()) {
756 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
757 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
758 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
760 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
761 const MCSymbol &SymbolB = RefB->getSymbol();
762 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
765 // Offset of the symbol in the section
766 int64_t a = Layout.getSymbolOffset(&SDB);
768 // Ofeset of the relocation in the section
769 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
774 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
775 MCFragment *F = SD.getFragment();
777 Index = F->getParent()->getOrdinal() + 1;
779 // Offset of the symbol in the section
780 Value += Layout.getSymbolOffset(&SD);
782 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
783 WeakrefUsedInReloc.insert(RelocSymbol);
785 UsedInReloc.insert(RelocSymbol);
789 // Compensate for the addend on i386.
795 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
796 (RelocSymbol != 0), Addend);
798 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
801 if (!hasRelocationAddend())
803 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
804 Relocations[Fragment->getParent()].push_back(ERE);
809 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
811 MCSymbolData &SD = Asm.getSymbolData(*S);
812 return SD.getIndex();
815 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
816 bool Used, bool Renamed) {
817 if (Data.getFlags() & ELF_Other_Weakref)
826 const MCSymbol &Symbol = Data.getSymbol();
828 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
831 const MCSymbol &A = Symbol.AliasedSymbol();
832 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
835 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
838 if (Symbol.isTemporary())
844 static bool isLocal(const MCSymbolData &Data, bool isSignature,
845 bool isUsedInReloc) {
846 if (Data.isExternal())
849 const MCSymbol &Symbol = Data.getSymbol();
850 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
852 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
853 if (isSignature && !isUsedInReloc)
862 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
863 SectionIndexMapTy &SectionIndexMap) {
865 for (MCAssembler::iterator it = Asm.begin(),
866 ie = Asm.end(); it != ie; ++it) {
867 const MCSectionELF &Section =
868 static_cast<const MCSectionELF &>(it->getSection());
869 if (Section.getType() != ELF::SHT_GROUP)
871 SectionIndexMap[&Section] = Index++;
874 for (MCAssembler::iterator it = Asm.begin(),
875 ie = Asm.end(); it != ie; ++it) {
876 const MCSectionELF &Section =
877 static_cast<const MCSectionELF &>(it->getSection());
878 if (Section.getType() == ELF::SHT_GROUP)
880 SectionIndexMap[&Section] = Index++;
884 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
885 const SectionIndexMapTy &SectionIndexMap,
886 RevGroupMapTy RevGroupMap) {
887 // FIXME: Is this the correct place to do this?
889 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
890 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
891 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
892 Data.setExternal(true);
893 SetBinding(Data, ELF::STB_GLOBAL);
896 // Build section lookup table.
897 int NumRegularSections = Asm.size();
899 // Index 0 is always the empty string.
900 StringMap<uint64_t> StringIndexMap;
901 StringTable += '\x00';
903 // Add the data for the symbols.
904 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
905 ie = Asm.symbol_end(); it != ie; ++it) {
906 const MCSymbol &Symbol = it->getSymbol();
908 bool Used = UsedInReloc.count(&Symbol);
909 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
910 bool isSignature = RevGroupMap.count(&Symbol);
912 if (!isInSymtab(Asm, *it,
913 Used || WeakrefUsed || isSignature,
914 Renames.count(&Symbol)))
919 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
921 // Undefined symbols are global, but this is the first place we
922 // are able to set it.
923 bool Local = isLocal(*it, isSignature, Used);
924 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
925 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
926 SetBinding(*it, ELF::STB_GLOBAL);
927 SetBinding(SD, ELF::STB_GLOBAL);
930 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
931 SetBinding(*it, ELF::STB_WEAK);
933 if (it->isCommon()) {
935 MSD.SectionIndex = ELF::SHN_COMMON;
936 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
937 MSD.SectionIndex = ELF::SHN_ABS;
938 } else if (RefSymbol.isUndefined()) {
939 if (isSignature && !Used)
940 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
942 MSD.SectionIndex = ELF::SHN_UNDEF;
944 const MCSectionELF &Section =
945 static_cast<const MCSectionELF&>(RefSymbol.getSection());
946 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
947 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
948 NeedsSymtabShndx = true;
949 assert(MSD.SectionIndex && "Invalid section index!");
952 // The @@@ in symbol version is replaced with @ in undefined symbols and
953 // @@ in defined ones.
954 StringRef Name = Symbol.getName();
957 size_t Pos = Name.find("@@@");
958 if (Pos != StringRef::npos) {
959 Buf += Name.substr(0, Pos);
960 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
961 Buf += Name.substr(Pos + Skip);
965 uint64_t &Entry = StringIndexMap[Name];
967 Entry = StringTable.size();
969 StringTable += '\x00';
971 MSD.StringIndex = Entry;
972 if (MSD.SectionIndex == ELF::SHN_UNDEF)
973 UndefinedSymbolData.push_back(MSD);
975 LocalSymbolData.push_back(MSD);
977 ExternalSymbolData.push_back(MSD);
980 // Symbols are required to be in lexicographic order.
981 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
982 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
983 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
985 // Set the symbol indices. Local symbols must come before all other
986 // symbols with non-local bindings.
988 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
989 LocalSymbolData[i].SymbolData->setIndex(Index++);
991 Index += NumRegularSections;
993 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
994 ExternalSymbolData[i].SymbolData->setIndex(Index++);
995 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
996 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
999 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1000 const MCSectionData &SD) {
1001 if (!Relocations[&SD].empty()) {
1002 MCContext &Ctx = Asm.getContext();
1003 const MCSectionELF *RelaSection;
1004 const MCSectionELF &Section =
1005 static_cast<const MCSectionELF&>(SD.getSection());
1007 const StringRef SectionName = Section.getSectionName();
1008 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1009 RelaSectionName += SectionName;
1012 if (hasRelocationAddend())
1013 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1015 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1017 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1018 ELF::SHT_RELA : ELF::SHT_REL, 0,
1019 SectionKind::getReadOnly(),
1022 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1023 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1025 MCDataFragment *F = new MCDataFragment(&RelaSD);
1027 WriteRelocationsFragment(Asm, F, &SD);
1031 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1032 uint64_t Flags, uint64_t Address,
1033 uint64_t Offset, uint64_t Size,
1034 uint32_t Link, uint32_t Info,
1036 uint64_t EntrySize) {
1037 Write32(Name); // sh_name: index into string table
1038 Write32(Type); // sh_type
1039 WriteWord(Flags); // sh_flags
1040 WriteWord(Address); // sh_addr
1041 WriteWord(Offset); // sh_offset
1042 WriteWord(Size); // sh_size
1043 Write32(Link); // sh_link
1044 Write32(Info); // sh_info
1045 WriteWord(Alignment); // sh_addralign
1046 WriteWord(EntrySize); // sh_entsize
1049 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1051 const MCSectionData *SD) {
1052 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1053 // sort by the r_offset just like gnu as does
1054 array_pod_sort(Relocs.begin(), Relocs.end());
1056 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1057 ELFRelocationEntry entry = Relocs[e - i - 1];
1061 else if (entry.Index < 0)
1062 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1064 entry.Index += LocalSymbolData.size();
1066 String64(*F, entry.r_offset);
1068 struct ELF::Elf64_Rela ERE64;
1069 ERE64.setSymbolAndType(entry.Index, entry.Type);
1070 String64(*F, ERE64.r_info);
1072 if (hasRelocationAddend())
1073 String64(*F, entry.r_addend);
1075 String32(*F, entry.r_offset);
1077 struct ELF::Elf32_Rela ERE32;
1078 ERE32.setSymbolAndType(entry.Index, entry.Type);
1079 String32(*F, ERE32.r_info);
1081 if (hasRelocationAddend())
1082 String32(*F, entry.r_addend);
1087 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1088 MCAsmLayout &Layout,
1089 const SectionIndexMapTy &SectionIndexMap) {
1090 MCContext &Ctx = Asm.getContext();
1093 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1095 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1096 const MCSectionELF *ShstrtabSection =
1097 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1098 SectionKind::getReadOnly());
1099 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1100 ShstrtabSD.setAlignment(1);
1101 ShstrtabIndex = Asm.size();
1103 const MCSectionELF *SymtabSection =
1104 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1105 SectionKind::getReadOnly(),
1107 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1108 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1109 SymbolTableIndex = Asm.size();
1111 MCSectionData *SymtabShndxSD = NULL;
1113 if (NeedsSymtabShndx) {
1114 const MCSectionELF *SymtabShndxSection =
1115 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1116 SectionKind::getReadOnly(), 4, "");
1117 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1118 SymtabShndxSD->setAlignment(4);
1121 const MCSection *StrtabSection;
1122 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1123 SectionKind::getReadOnly());
1124 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1125 StrtabSD.setAlignment(1);
1126 StringTableIndex = Asm.size();
1128 WriteRelocations(Asm, Layout);
1131 F = new MCDataFragment(&SymtabSD);
1132 MCDataFragment *ShndxF = NULL;
1133 if (NeedsSymtabShndx) {
1134 ShndxF = new MCDataFragment(SymtabShndxSD);
1136 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1138 F = new MCDataFragment(&StrtabSD);
1139 F->getContents().append(StringTable.begin(), StringTable.end());
1141 F = new MCDataFragment(&ShstrtabSD);
1143 // Section header string table.
1145 // The first entry of a string table holds a null character so skip
1148 F->getContents() += '\x00';
1150 StringMap<uint64_t> SecStringMap;
1151 for (MCAssembler::const_iterator it = Asm.begin(),
1152 ie = Asm.end(); it != ie; ++it) {
1153 const MCSectionELF &Section =
1154 static_cast<const MCSectionELF&>(it->getSection());
1155 // FIXME: We could merge suffixes like in .text and .rela.text.
1157 StringRef Name = Section.getSectionName();
1158 if (SecStringMap.count(Name)) {
1159 SectionStringTableIndex[&Section] = SecStringMap[Name];
1162 // Remember the index into the string table so we can write it
1163 // into the sh_name field of the section header table.
1164 SectionStringTableIndex[&Section] = Index;
1165 SecStringMap[Name] = Index;
1167 Index += Name.size() + 1;
1168 F->getContents() += Name;
1169 F->getContents() += '\x00';
1173 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1174 const MCValue Target,
1176 const MCFragment *DF) const {
1177 // If this is a PCrel relocation, find the section this fixup value is
1179 const MCSection *BaseSection = 0;
1181 BaseSection = &DF->getParent()->getSection();
1182 assert(BaseSection);
1185 const MCSection *SectionA = 0;
1186 const MCSymbol *SymbolA = 0;
1187 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1188 SymbolA = &A->getSymbol();
1189 SectionA = &SymbolA->AliasedSymbol().getSection();
1192 const MCSection *SectionB = 0;
1193 const MCSymbol *SymbolB = 0;
1194 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1195 SymbolB = &B->getSymbol();
1196 SectionB = &SymbolB->AliasedSymbol().getSection();
1200 return SectionA == SectionB;
1205 // Absolute address but PCrel instruction, so we need a relocation.
1209 // FIXME: This is in here just to match gnu as output. If the two ends
1210 // are in the same section, there is nothing that the linker can do to
1212 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1213 if (DataA.isExternal())
1216 return BaseSection == SectionA;
1219 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1220 MCAsmLayout &Layout,
1221 GroupMapTy &GroupMap,
1222 RevGroupMapTy &RevGroupMap) {
1224 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1226 const MCSectionELF &Section =
1227 static_cast<const MCSectionELF&>(it->getSection());
1228 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1231 const MCSymbol *SignatureSymbol = Section.getGroup();
1232 Asm.getOrCreateSymbolData(*SignatureSymbol);
1233 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1235 Group = Asm.getContext().CreateELFGroupSection();
1236 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1237 Data.setAlignment(4);
1238 MCDataFragment *F = new MCDataFragment(&Data);
1239 String32(*F, ELF::GRP_COMDAT);
1241 GroupMap[Group] = SignatureSymbol;
1244 // Add sections to the groups
1246 unsigned NumGroups = RevGroupMap.size();
1247 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1248 it != ie; ++it, ++Index) {
1249 const MCSectionELF &Section =
1250 static_cast<const MCSectionELF&>(it->getSection());
1251 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1253 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1254 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1255 // FIXME: we could use the previous fragment
1256 MCDataFragment *F = new MCDataFragment(&Data);
1257 String32(*F, NumGroups + Index);
1261 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1262 const SectionIndexMapTy &SectionIndexMap,
1263 uint32_t GroupSymbolIndex,
1264 uint64_t Offset, uint64_t Size,
1266 const MCSectionELF &Section) {
1267 uint64_t sh_link = 0;
1268 uint64_t sh_info = 0;
1270 switch(Section.getType()) {
1271 case ELF::SHT_DYNAMIC:
1272 sh_link = SectionStringTableIndex[&Section];
1277 case ELF::SHT_RELA: {
1278 const MCSectionELF *SymtabSection;
1279 const MCSectionELF *InfoSection;
1280 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1282 SectionKind::getReadOnly());
1283 sh_link = SectionIndexMap.lookup(SymtabSection);
1284 assert(sh_link && ".symtab not found");
1286 // Remove ".rel" and ".rela" prefixes.
1287 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1288 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1290 InfoSection = Asm.getContext().getELFSection(SectionName,
1291 ELF::SHT_PROGBITS, 0,
1292 SectionKind::getReadOnly());
1293 sh_info = SectionIndexMap.lookup(InfoSection);
1297 case ELF::SHT_SYMTAB:
1298 case ELF::SHT_DYNSYM:
1299 sh_link = StringTableIndex;
1300 sh_info = LastLocalSymbolIndex;
1303 case ELF::SHT_SYMTAB_SHNDX:
1304 sh_link = SymbolTableIndex;
1307 case ELF::SHT_PROGBITS:
1308 case ELF::SHT_STRTAB:
1309 case ELF::SHT_NOBITS:
1311 case ELF::SHT_ARM_ATTRIBUTES:
1315 case ELF::SHT_GROUP: {
1316 sh_link = SymbolTableIndex;
1317 sh_info = GroupSymbolIndex;
1322 assert(0 && "FIXME: sh_type value not supported!");
1326 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1327 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1328 Alignment, Section.getEntrySize());
1331 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1332 return SD.getOrdinal() == ~UINT32_C(0) &&
1333 !SD.getSection().isVirtualSection();
1336 static uint64_t DataSectionSize(const MCSectionData &SD) {
1338 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1340 const MCFragment &F = *i;
1341 assert(F.getKind() == MCFragment::FT_Data);
1342 Ret += cast<MCDataFragment>(F).getContents().size();
1347 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1348 const MCSectionData &SD) {
1349 if (IsELFMetaDataSection(SD))
1350 return DataSectionSize(SD);
1351 return Layout.getSectionFileSize(&SD);
1354 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1355 const MCSectionData &SD) {
1356 if (IsELFMetaDataSection(SD))
1357 return DataSectionSize(SD);
1358 return Layout.getSectionAddressSize(&SD);
1361 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1362 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1364 const MCFragment &F = *i;
1365 assert(F.getKind() == MCFragment::FT_Data);
1366 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1370 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1371 const MCAsmLayout &Layout) {
1372 GroupMapTy GroupMap;
1373 RevGroupMapTy RevGroupMap;
1374 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1377 SectionIndexMapTy SectionIndexMap;
1379 ComputeIndexMap(Asm, SectionIndexMap);
1381 // Compute symbol table information.
1382 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1384 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1385 const_cast<MCAsmLayout&>(Layout),
1388 // Update to include the metadata sections.
1389 ComputeIndexMap(Asm, SectionIndexMap);
1391 // Add 1 for the null section.
1392 unsigned NumSections = Asm.size() + 1;
1393 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1394 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1395 sizeof(ELF::Elf32_Ehdr);
1396 uint64_t FileOff = HeaderSize;
1398 std::vector<const MCSectionELF*> Sections;
1399 Sections.resize(NumSections);
1401 for (SectionIndexMapTy::const_iterator i=
1402 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1403 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1404 Sections[p.second] = p.first;
1407 for (unsigned i = 1; i < NumSections; ++i) {
1408 const MCSectionELF &Section = *Sections[i];
1409 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1411 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1413 // Get the size of the section in the output file (including padding).
1414 FileOff += GetSectionFileSize(Layout, SD);
1417 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1419 // Write out the ELF header ...
1420 WriteHeader(FileOff - HeaderSize, NumSections);
1422 FileOff = HeaderSize;
1424 // ... then all of the sections ...
1425 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1427 for (unsigned i = 1; i < NumSections; ++i) {
1428 const MCSectionELF &Section = *Sections[i];
1429 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1431 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1432 WriteZeros(Padding);
1435 // Remember the offset into the file for this section.
1436 SectionOffsetMap[&Section] = FileOff;
1438 FileOff += GetSectionFileSize(Layout, SD);
1440 if (IsELFMetaDataSection(SD))
1441 WriteDataSectionData(this, SD);
1443 Asm.WriteSectionData(&SD, Layout);
1446 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1447 WriteZeros(Padding);
1450 // ... and then the section header table.
1451 // Should we align the section header table?
1453 // Null section first.
1454 uint64_t FirstSectionSize =
1455 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1456 uint32_t FirstSectionLink =
1457 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1458 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1460 for (unsigned i = 1; i < NumSections; ++i) {
1461 const MCSectionELF &Section = *Sections[i];
1462 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1463 uint32_t GroupSymbolIndex;
1464 if (Section.getType() != ELF::SHT_GROUP)
1465 GroupSymbolIndex = 0;
1467 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1469 uint64_t Size = GetSectionAddressSize(Layout, SD);
1471 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1472 SectionOffsetMap[&Section], Size,
1473 SD.getAlignment(), Section);
1477 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1479 bool IsLittleEndian) {
1480 switch (MOTW->getEMachine()) {
1482 case ELF::EM_X86_64:
1483 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1485 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1486 case ELF::EM_MBLAZE:
1487 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1488 default: llvm_unreachable("Unsupported architecture"); break;
1493 /// START OF SUBCLASSES for ELFObjectWriter
1494 //===- ARMELFObjectWriter -------------------------------------------===//
1496 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1498 bool IsLittleEndian)
1499 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1502 ARMELFObjectWriter::~ARMELFObjectWriter()
1505 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1506 const MCFixup &Fixup,
1508 bool IsRelocWithSymbol,
1510 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1511 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1515 switch ((unsigned)Fixup.getKind()) {
1516 default: assert(0 && "Unimplemented");
1519 default: llvm_unreachable("Unsupported Modifier");
1520 case MCSymbolRefExpr::VK_None:
1521 Type = ELF::R_ARM_BASE_PREL; break;
1522 case MCSymbolRefExpr::VK_ARM_TLSGD:
1523 assert(0 && "unimplemented"); break;
1524 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1525 Type = ELF::R_ARM_TLS_IE32;
1527 case ARM::fixup_arm_branch:
1529 case MCSymbolRefExpr::VK_ARM_PLT:
1530 Type = ELF::R_ARM_PLT32; break;
1532 Type = ELF::R_ARM_CALL; break;
1536 switch ((unsigned)Fixup.getKind()) {
1537 default: llvm_unreachable("invalid fixup kind!");
1540 default: llvm_unreachable("Unsupported Modifier"); break;
1541 case MCSymbolRefExpr::VK_ARM_GOT:
1542 Type = ELF::R_ARM_GOT_BREL; break;
1543 case MCSymbolRefExpr::VK_ARM_TLSGD:
1544 Type = ELF::R_ARM_TLS_GD32; break;
1545 case MCSymbolRefExpr::VK_ARM_TPOFF:
1546 Type = ELF::R_ARM_TLS_LE32; break;
1547 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1548 Type = ELF::R_ARM_TLS_IE32; break;
1549 case MCSymbolRefExpr::VK_None:
1550 Type = ELF::R_ARM_ABS32; break;
1551 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1552 Type = ELF::R_ARM_GOTOFF32; break;
1554 case ARM::fixup_arm_ldst_pcrel_12:
1555 case ARM::fixup_arm_pcrel_10:
1556 case ARM::fixup_arm_adr_pcrel_12:
1557 case ARM::fixup_arm_thumb_bl:
1558 case ARM::fixup_arm_thumb_cb:
1559 case ARM::fixup_arm_thumb_cp:
1560 case ARM::fixup_arm_thumb_br:
1561 assert(0 && "Unimplemented"); break;
1562 case ARM::fixup_arm_branch:
1563 // FIXME: Differentiate between R_ARM_CALL and
1564 // R_ARM_JUMP24 (latter used for conditional jumps)
1565 Type = ELF::R_ARM_CALL; break;
1566 case ARM::fixup_arm_movt_hi16:
1567 Type = ELF::R_ARM_MOVT_ABS; break;
1568 case ARM::fixup_arm_movw_lo16:
1569 Type = ELF::R_ARM_MOVW_ABS_NC; break;
1573 if (RelocNeedsGOT(Modifier))
1579 //===- MBlazeELFObjectWriter -------------------------------------------===//
1581 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1583 bool IsLittleEndian)
1584 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1587 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1590 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1591 const MCFixup &Fixup,
1593 bool IsRelocWithSymbol,
1595 // determine the type of the relocation
1598 switch ((unsigned)Fixup.getKind()) {
1600 llvm_unreachable("Unimplemented");
1602 Type = ELF::R_MICROBLAZE_64_PCREL;
1605 Type = ELF::R_MICROBLAZE_32_PCREL;
1609 switch ((unsigned)Fixup.getKind()) {
1610 default: llvm_unreachable("invalid fixup kind!");
1612 Type = ((IsRelocWithSymbol || Addend !=0)
1613 ? ELF::R_MICROBLAZE_32
1614 : ELF::R_MICROBLAZE_64);
1617 Type = ELF::R_MICROBLAZE_32;
1624 //===- X86ELFObjectWriter -------------------------------------------===//
1627 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1629 bool IsLittleEndian)
1630 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1633 X86ELFObjectWriter::~X86ELFObjectWriter()
1636 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1637 const MCFixup &Fixup,
1639 bool IsRelocWithSymbol,
1641 // determine the type of the relocation
1643 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1644 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1650 llvm_unreachable("Unimplemented");
1651 case MCSymbolRefExpr::VK_None:
1652 Type = ELF::R_X86_64_PC32;
1654 case MCSymbolRefExpr::VK_PLT:
1655 Type = ELF::R_X86_64_PLT32;
1657 case MCSymbolRefExpr::VK_GOTPCREL:
1658 Type = ELF::R_X86_64_GOTPCREL;
1660 case MCSymbolRefExpr::VK_GOTTPOFF:
1661 Type = ELF::R_X86_64_GOTTPOFF;
1663 case MCSymbolRefExpr::VK_TLSGD:
1664 Type = ELF::R_X86_64_TLSGD;
1666 case MCSymbolRefExpr::VK_TLSLD:
1667 Type = ELF::R_X86_64_TLSLD;
1671 switch ((unsigned)Fixup.getKind()) {
1672 default: llvm_unreachable("invalid fixup kind!");
1673 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1674 case X86::reloc_signed_4byte:
1676 assert(isInt<32>(Target.getConstant()));
1679 llvm_unreachable("Unimplemented");
1680 case MCSymbolRefExpr::VK_None:
1681 Type = ELF::R_X86_64_32S;
1683 case MCSymbolRefExpr::VK_GOT:
1684 Type = ELF::R_X86_64_GOT32;
1686 case MCSymbolRefExpr::VK_GOTPCREL:
1687 Type = ELF::R_X86_64_GOTPCREL;
1689 case MCSymbolRefExpr::VK_TPOFF:
1690 Type = ELF::R_X86_64_TPOFF32;
1692 case MCSymbolRefExpr::VK_DTPOFF:
1693 Type = ELF::R_X86_64_DTPOFF32;
1698 Type = ELF::R_X86_64_32;
1700 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1702 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1709 llvm_unreachable("Unimplemented");
1710 case MCSymbolRefExpr::VK_None:
1711 Type = ELF::R_386_PC32;
1713 case MCSymbolRefExpr::VK_PLT:
1714 Type = ELF::R_386_PLT32;
1718 switch ((unsigned)Fixup.getKind()) {
1719 default: llvm_unreachable("invalid fixup kind!");
1721 case X86::reloc_global_offset_table:
1722 Type = ELF::R_386_GOTPC;
1725 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1727 case X86::reloc_signed_4byte:
1732 llvm_unreachable("Unimplemented");
1733 case MCSymbolRefExpr::VK_None:
1734 Type = ELF::R_386_32;
1736 case MCSymbolRefExpr::VK_GOT:
1737 Type = ELF::R_386_GOT32;
1739 case MCSymbolRefExpr::VK_GOTOFF:
1740 Type = ELF::R_386_GOTOFF;
1742 case MCSymbolRefExpr::VK_TLSGD:
1743 Type = ELF::R_386_TLS_GD;
1745 case MCSymbolRefExpr::VK_TPOFF:
1746 Type = ELF::R_386_TLS_LE_32;
1748 case MCSymbolRefExpr::VK_INDNTPOFF:
1749 Type = ELF::R_386_TLS_IE;
1751 case MCSymbolRefExpr::VK_NTPOFF:
1752 Type = ELF::R_386_TLS_LE;
1754 case MCSymbolRefExpr::VK_GOTNTPOFF:
1755 Type = ELF::R_386_TLS_GOTIE;
1757 case MCSymbolRefExpr::VK_TLSLDM:
1758 Type = ELF::R_386_TLS_LDM;
1760 case MCSymbolRefExpr::VK_DTPOFF:
1761 Type = ELF::R_386_TLS_LDO_32;
1765 case FK_Data_2: Type = ELF::R_386_16; break;
1767 case FK_Data_1: Type = ELF::R_386_8; break;
1772 if (RelocNeedsGOT(Modifier))