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 // Create the sections that show up in the symbol table. Currently
333 // those are the .note.GNU-stack section and the group sections.
334 virtual void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
335 GroupMapTy &GroupMap,
336 RevGroupMapTy &RevGroupMap);
338 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
339 const MCAsmLayout &Layout);
341 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
342 uint64_t Address, uint64_t Offset,
343 uint64_t Size, uint32_t Link, uint32_t Info,
344 uint64_t Alignment, uint64_t EntrySize);
346 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
348 const MCSectionData *SD);
351 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
352 const MCSymbolData &DataA,
353 const MCFragment &FB,
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 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
366 bool IsPCRel, bool IsRelocWithSymbol,
370 //===- X86ELFObjectWriter -------------------------------------------===//
372 class X86ELFObjectWriter : public ELFObjectWriter {
374 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
376 bool IsLittleEndian);
378 virtual ~X86ELFObjectWriter();
380 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
381 bool IsPCRel, bool IsRelocWithSymbol,
386 //===- ARMELFObjectWriter -------------------------------------------===//
388 class ARMELFObjectWriter : public ELFObjectWriter {
390 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
392 bool IsLittleEndian);
394 virtual ~ARMELFObjectWriter();
396 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
397 bool IsPCRel, bool IsRelocWithSymbol,
401 //===- MBlazeELFObjectWriter -------------------------------------------===//
403 class MBlazeELFObjectWriter : public ELFObjectWriter {
405 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
407 bool IsLittleEndian);
409 virtual ~MBlazeELFObjectWriter();
411 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
412 bool IsPCRel, bool IsRelocWithSymbol,
417 ELFObjectWriter::~ELFObjectWriter()
420 // Emit the ELF header.
421 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
422 unsigned NumberOfSections) {
428 // emitWord method behaves differently for ELF32 and ELF64, writing
429 // 4 bytes in the former and 8 in the latter.
431 Write8(0x7f); // e_ident[EI_MAG0]
432 Write8('E'); // e_ident[EI_MAG1]
433 Write8('L'); // e_ident[EI_MAG2]
434 Write8('F'); // e_ident[EI_MAG3]
436 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
439 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
441 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
443 switch (TargetObjectWriter->getOSType()) {
444 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
445 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
446 default: Write8(ELF::ELFOSABI_NONE); break;
448 Write8(0); // e_ident[EI_ABIVERSION]
450 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
452 Write16(ELF::ET_REL); // e_type
454 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
456 Write32(ELF::EV_CURRENT); // e_version
457 WriteWord(0); // e_entry, no entry point in .o file
458 WriteWord(0); // e_phoff, no program header for .o
459 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
460 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
462 // FIXME: Make this configurable.
463 Write32(0); // e_flags = whatever the target wants
465 // e_ehsize = ELF header size
466 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
468 Write16(0); // e_phentsize = prog header entry size
469 Write16(0); // e_phnum = # prog header entries = 0
471 // e_shentsize = Section header entry size
472 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
474 // e_shnum = # of section header ents
475 if (NumberOfSections >= ELF::SHN_LORESERVE)
478 Write16(NumberOfSections);
480 // e_shstrndx = Section # of '.shstrtab'
481 if (NumberOfSections >= ELF::SHN_LORESERVE)
482 Write16(ELF::SHN_XINDEX);
484 Write16(ShstrtabIndex);
487 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
488 MCDataFragment *ShndxF,
490 uint8_t info, uint64_t value,
491 uint64_t size, uint8_t other,
495 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
496 String32(*ShndxF, shndx);
498 String32(*ShndxF, 0);
501 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
502 uint16_t(ELF::SHN_XINDEX) : shndx;
505 String32(*SymtabF, name); // st_name
506 String8(*SymtabF, info); // st_info
507 String8(*SymtabF, other); // st_other
508 String16(*SymtabF, Index); // st_shndx
509 String64(*SymtabF, value); // st_value
510 String64(*SymtabF, size); // st_size
512 String32(*SymtabF, name); // st_name
513 String32(*SymtabF, value); // st_value
514 String32(*SymtabF, size); // st_size
515 String8(*SymtabF, info); // st_info
516 String8(*SymtabF, other); // st_other
517 String16(*SymtabF, Index); // st_shndx
521 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
522 if (Data.isCommon() && Data.isExternal())
523 return Data.getCommonAlignment();
525 const MCSymbol &Symbol = Data.getSymbol();
527 if (Symbol.isAbsolute() && Symbol.isVariable()) {
528 if (const MCExpr *Value = Symbol.getVariableValue()) {
530 if (Value->EvaluateAsAbsolute(IntValue, Layout))
531 return (uint64_t)IntValue;
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);
603 assert(!(Data.isCommon() && !Data.isExternal()));
605 const MCExpr *ESize = Data.getSize();
608 if (!ESize->EvaluateAsAbsolute(Res, Layout))
609 report_fatal_error("Size expression must be absolute.");
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());
696 const SectionKind secKind = Section.getKind();
701 if (secKind.isThreadLocal()) {
707 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
708 const MCSectionELF &Sec2 =
709 static_cast<const MCSectionELF&>(F.getParent()->getSection());
711 if (&Sec2 != &Section &&
712 (Kind == MCSymbolRefExpr::VK_PLT ||
713 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
714 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
720 if (Section.getFlags() & ELF::SHF_MERGE) {
721 if (Target.getConstant() == 0)
732 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
733 const MCAsmLayout &Layout,
734 const MCFragment *Fragment,
735 const MCFixup &Fixup,
737 uint64_t &FixedValue) {
740 int64_t Value = Target.getConstant();
741 const MCSymbol *RelocSymbol = NULL;
743 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
744 if (!Target.isAbsolute()) {
745 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
746 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
747 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
749 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
750 const MCSymbol &SymbolB = RefB->getSymbol();
751 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
754 // Offset of the symbol in the section
755 int64_t a = Layout.getSymbolOffset(&SDB);
757 // Ofeset of the relocation in the section
758 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
763 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
764 MCFragment *F = SD.getFragment();
766 Index = F->getParent()->getOrdinal() + 1;
768 // Offset of the symbol in the section
769 Value += Layout.getSymbolOffset(&SD);
771 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
772 WeakrefUsedInReloc.insert(RelocSymbol);
774 UsedInReloc.insert(RelocSymbol);
778 // Compensate for the addend on i386.
784 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
785 (RelocSymbol != 0), Addend);
787 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
790 if (!hasRelocationAddend())
792 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
793 Relocations[Fragment->getParent()].push_back(ERE);
798 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
800 MCSymbolData &SD = Asm.getSymbolData(*S);
801 return SD.getIndex();
804 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
805 bool Used, bool Renamed) {
806 if (Data.getFlags() & ELF_Other_Weakref)
815 const MCSymbol &Symbol = Data.getSymbol();
817 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
820 const MCSymbol &A = Symbol.AliasedSymbol();
821 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
824 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
827 if (Symbol.isTemporary())
833 static bool isLocal(const MCSymbolData &Data, bool isSignature,
834 bool isUsedInReloc) {
835 if (Data.isExternal())
838 const MCSymbol &Symbol = Data.getSymbol();
839 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
841 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
842 if (isSignature && !isUsedInReloc)
851 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
852 SectionIndexMapTy &SectionIndexMap) {
854 for (MCAssembler::iterator it = Asm.begin(),
855 ie = Asm.end(); it != ie; ++it) {
856 const MCSectionELF &Section =
857 static_cast<const MCSectionELF &>(it->getSection());
858 if (Section.getType() != ELF::SHT_GROUP)
860 SectionIndexMap[&Section] = Index++;
863 for (MCAssembler::iterator it = Asm.begin(),
864 ie = Asm.end(); it != ie; ++it) {
865 const MCSectionELF &Section =
866 static_cast<const MCSectionELF &>(it->getSection());
867 if (Section.getType() == ELF::SHT_GROUP)
869 SectionIndexMap[&Section] = Index++;
873 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
874 const SectionIndexMapTy &SectionIndexMap,
875 RevGroupMapTy RevGroupMap) {
876 // FIXME: Is this the correct place to do this?
878 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
879 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
880 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
881 Data.setExternal(true);
882 SetBinding(Data, ELF::STB_GLOBAL);
885 // Build section lookup table.
886 int NumRegularSections = Asm.size();
888 // Index 0 is always the empty string.
889 StringMap<uint64_t> StringIndexMap;
890 StringTable += '\x00';
892 // Add the data for the symbols.
893 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
894 ie = Asm.symbol_end(); it != ie; ++it) {
895 const MCSymbol &Symbol = it->getSymbol();
897 bool Used = UsedInReloc.count(&Symbol);
898 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
899 bool isSignature = RevGroupMap.count(&Symbol);
901 if (!isInSymtab(Asm, *it,
902 Used || WeakrefUsed || isSignature,
903 Renames.count(&Symbol)))
908 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
910 // Undefined symbols are global, but this is the first place we
911 // are able to set it.
912 bool Local = isLocal(*it, isSignature, Used);
913 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
914 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
915 SetBinding(*it, ELF::STB_GLOBAL);
916 SetBinding(SD, ELF::STB_GLOBAL);
919 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
920 SetBinding(*it, ELF::STB_WEAK);
922 if (it->isCommon()) {
924 MSD.SectionIndex = ELF::SHN_COMMON;
925 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
926 MSD.SectionIndex = ELF::SHN_ABS;
927 } else if (RefSymbol.isUndefined()) {
928 if (isSignature && !Used)
929 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
931 MSD.SectionIndex = ELF::SHN_UNDEF;
933 const MCSectionELF &Section =
934 static_cast<const MCSectionELF&>(RefSymbol.getSection());
935 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
936 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
937 NeedsSymtabShndx = true;
938 assert(MSD.SectionIndex && "Invalid section index!");
941 // The @@@ in symbol version is replaced with @ in undefined symbols and
942 // @@ in defined ones.
943 StringRef Name = Symbol.getName();
946 size_t Pos = Name.find("@@@");
947 if (Pos != StringRef::npos) {
948 Buf += Name.substr(0, Pos);
949 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
950 Buf += Name.substr(Pos + Skip);
954 uint64_t &Entry = StringIndexMap[Name];
956 Entry = StringTable.size();
958 StringTable += '\x00';
960 MSD.StringIndex = Entry;
961 if (MSD.SectionIndex == ELF::SHN_UNDEF)
962 UndefinedSymbolData.push_back(MSD);
964 LocalSymbolData.push_back(MSD);
966 ExternalSymbolData.push_back(MSD);
969 // Symbols are required to be in lexicographic order.
970 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
971 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
972 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
974 // Set the symbol indices. Local symbols must come before all other
975 // symbols with non-local bindings.
977 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
978 LocalSymbolData[i].SymbolData->setIndex(Index++);
980 Index += NumRegularSections;
982 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
983 ExternalSymbolData[i].SymbolData->setIndex(Index++);
984 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
985 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
988 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
989 const MCSectionData &SD) {
990 if (!Relocations[&SD].empty()) {
991 MCContext &Ctx = Asm.getContext();
992 const MCSectionELF *RelaSection;
993 const MCSectionELF &Section =
994 static_cast<const MCSectionELF&>(SD.getSection());
996 const StringRef SectionName = Section.getSectionName();
997 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
998 RelaSectionName += SectionName;
1001 if (hasRelocationAddend())
1002 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1004 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1006 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1007 ELF::SHT_RELA : ELF::SHT_REL, 0,
1008 SectionKind::getReadOnly(),
1011 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1012 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1014 MCDataFragment *F = new MCDataFragment(&RelaSD);
1016 WriteRelocationsFragment(Asm, F, &SD);
1020 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1021 uint64_t Flags, uint64_t Address,
1022 uint64_t Offset, uint64_t Size,
1023 uint32_t Link, uint32_t Info,
1025 uint64_t EntrySize) {
1026 Write32(Name); // sh_name: index into string table
1027 Write32(Type); // sh_type
1028 WriteWord(Flags); // sh_flags
1029 WriteWord(Address); // sh_addr
1030 WriteWord(Offset); // sh_offset
1031 WriteWord(Size); // sh_size
1032 Write32(Link); // sh_link
1033 Write32(Info); // sh_info
1034 WriteWord(Alignment); // sh_addralign
1035 WriteWord(EntrySize); // sh_entsize
1038 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1040 const MCSectionData *SD) {
1041 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1042 // sort by the r_offset just like gnu as does
1043 array_pod_sort(Relocs.begin(), Relocs.end());
1045 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1046 ELFRelocationEntry entry = Relocs[e - i - 1];
1050 else if (entry.Index < 0)
1051 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1053 entry.Index += LocalSymbolData.size();
1055 String64(*F, entry.r_offset);
1057 struct ELF::Elf64_Rela ERE64;
1058 ERE64.setSymbolAndType(entry.Index, entry.Type);
1059 String64(*F, ERE64.r_info);
1061 if (hasRelocationAddend())
1062 String64(*F, entry.r_addend);
1064 String32(*F, entry.r_offset);
1066 struct ELF::Elf32_Rela ERE32;
1067 ERE32.setSymbolAndType(entry.Index, entry.Type);
1068 String32(*F, ERE32.r_info);
1070 if (hasRelocationAddend())
1071 String32(*F, entry.r_addend);
1076 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1077 MCAsmLayout &Layout,
1078 const SectionIndexMapTy &SectionIndexMap) {
1079 MCContext &Ctx = Asm.getContext();
1082 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1084 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1085 const MCSectionELF *ShstrtabSection =
1086 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1087 SectionKind::getReadOnly());
1088 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1089 ShstrtabSD.setAlignment(1);
1090 ShstrtabIndex = Asm.size();
1092 const MCSectionELF *SymtabSection =
1093 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1094 SectionKind::getReadOnly(),
1096 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1097 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1098 SymbolTableIndex = Asm.size();
1100 MCSectionData *SymtabShndxSD = NULL;
1102 if (NeedsSymtabShndx) {
1103 const MCSectionELF *SymtabShndxSection =
1104 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1105 SectionKind::getReadOnly(), 4, "");
1106 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1107 SymtabShndxSD->setAlignment(4);
1110 const MCSection *StrtabSection;
1111 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1112 SectionKind::getReadOnly());
1113 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1114 StrtabSD.setAlignment(1);
1115 StringTableIndex = Asm.size();
1117 WriteRelocations(Asm, Layout);
1120 F = new MCDataFragment(&SymtabSD);
1121 MCDataFragment *ShndxF = NULL;
1122 if (NeedsSymtabShndx) {
1123 ShndxF = new MCDataFragment(SymtabShndxSD);
1125 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1127 F = new MCDataFragment(&StrtabSD);
1128 F->getContents().append(StringTable.begin(), StringTable.end());
1130 F = new MCDataFragment(&ShstrtabSD);
1132 // Section header string table.
1134 // The first entry of a string table holds a null character so skip
1137 F->getContents() += '\x00';
1139 StringMap<uint64_t> SecStringMap;
1140 for (MCAssembler::const_iterator it = Asm.begin(),
1141 ie = Asm.end(); it != ie; ++it) {
1142 const MCSectionELF &Section =
1143 static_cast<const MCSectionELF&>(it->getSection());
1144 // FIXME: We could merge suffixes like in .text and .rela.text.
1146 StringRef Name = Section.getSectionName();
1147 if (SecStringMap.count(Name)) {
1148 SectionStringTableIndex[&Section] = SecStringMap[Name];
1151 // Remember the index into the string table so we can write it
1152 // into the sh_name field of the section header table.
1153 SectionStringTableIndex[&Section] = Index;
1154 SecStringMap[Name] = Index;
1156 Index += Name.size() + 1;
1157 F->getContents() += Name;
1158 F->getContents() += '\x00';
1163 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1164 const MCSymbolData &DataA,
1165 const MCFragment &FB,
1167 bool IsPCRel) const {
1168 // FIXME: This is in here just to match gnu as output. If the two ends
1169 // are in the same section, there is nothing that the linker can do to
1171 if (DataA.isExternal())
1174 const MCSection &SecA = DataA.getSymbol().AliasedSymbol().getSection();
1175 const MCSection &SecB = FB.getParent()->getSection();
1176 // On ELF A - B is absolute if A and B are in the same section.
1177 return &SecA == &SecB;
1180 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1181 MCAsmLayout &Layout,
1182 GroupMapTy &GroupMap,
1183 RevGroupMapTy &RevGroupMap) {
1184 // Create the .note.GNU-stack section if needed.
1185 MCContext &Ctx = Asm.getContext();
1186 if (Asm.getNoExecStack()) {
1187 const MCSectionELF *GnuStackSection =
1188 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1189 SectionKind::getReadOnly());
1190 Asm.getOrCreateSectionData(*GnuStackSection);
1194 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1196 const MCSectionELF &Section =
1197 static_cast<const MCSectionELF&>(it->getSection());
1198 if (!(Section.getFlags() & ELF::SHF_GROUP))
1201 const MCSymbol *SignatureSymbol = Section.getGroup();
1202 Asm.getOrCreateSymbolData(*SignatureSymbol);
1203 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1205 Group = Ctx.CreateELFGroupSection();
1206 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1207 Data.setAlignment(4);
1208 MCDataFragment *F = new MCDataFragment(&Data);
1209 String32(*F, ELF::GRP_COMDAT);
1211 GroupMap[Group] = SignatureSymbol;
1214 // Add sections to the groups
1216 unsigned NumGroups = RevGroupMap.size();
1217 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1218 it != ie; ++it, ++Index) {
1219 const MCSectionELF &Section =
1220 static_cast<const MCSectionELF&>(it->getSection());
1221 if (!(Section.getFlags() & ELF::SHF_GROUP))
1223 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1224 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1225 // FIXME: we could use the previous fragment
1226 MCDataFragment *F = new MCDataFragment(&Data);
1227 String32(*F, NumGroups + Index);
1231 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1232 const SectionIndexMapTy &SectionIndexMap,
1233 uint32_t GroupSymbolIndex,
1234 uint64_t Offset, uint64_t Size,
1236 const MCSectionELF &Section) {
1237 uint64_t sh_link = 0;
1238 uint64_t sh_info = 0;
1240 switch(Section.getType()) {
1241 case ELF::SHT_DYNAMIC:
1242 sh_link = SectionStringTableIndex[&Section];
1247 case ELF::SHT_RELA: {
1248 const MCSectionELF *SymtabSection;
1249 const MCSectionELF *InfoSection;
1250 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1252 SectionKind::getReadOnly());
1253 sh_link = SectionIndexMap.lookup(SymtabSection);
1254 assert(sh_link && ".symtab not found");
1256 // Remove ".rel" and ".rela" prefixes.
1257 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1258 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1260 InfoSection = Asm.getContext().getELFSection(SectionName,
1261 ELF::SHT_PROGBITS, 0,
1262 SectionKind::getReadOnly());
1263 sh_info = SectionIndexMap.lookup(InfoSection);
1267 case ELF::SHT_SYMTAB:
1268 case ELF::SHT_DYNSYM:
1269 sh_link = StringTableIndex;
1270 sh_info = LastLocalSymbolIndex;
1273 case ELF::SHT_SYMTAB_SHNDX:
1274 sh_link = SymbolTableIndex;
1277 case ELF::SHT_PROGBITS:
1278 case ELF::SHT_STRTAB:
1279 case ELF::SHT_NOBITS:
1282 case ELF::SHT_ARM_ATTRIBUTES:
1283 case ELF::SHT_INIT_ARRAY:
1284 case ELF::SHT_FINI_ARRAY:
1285 case ELF::SHT_PREINIT_ARRAY:
1286 case ELF::SHT_X86_64_UNWIND:
1290 case ELF::SHT_GROUP: {
1291 sh_link = SymbolTableIndex;
1292 sh_info = GroupSymbolIndex;
1297 assert(0 && "FIXME: sh_type value not supported!");
1301 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1302 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1303 Alignment, Section.getEntrySize());
1306 static bool IsELFMetaDataSection(const MCSectionData &SD) {
1307 return SD.getOrdinal() == ~UINT32_C(0) &&
1308 !SD.getSection().isVirtualSection();
1311 static uint64_t DataSectionSize(const MCSectionData &SD) {
1313 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1315 const MCFragment &F = *i;
1316 assert(F.getKind() == MCFragment::FT_Data);
1317 Ret += cast<MCDataFragment>(F).getContents().size();
1322 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
1323 const MCSectionData &SD) {
1324 if (IsELFMetaDataSection(SD))
1325 return DataSectionSize(SD);
1326 return Layout.getSectionFileSize(&SD);
1329 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
1330 const MCSectionData &SD) {
1331 if (IsELFMetaDataSection(SD))
1332 return DataSectionSize(SD);
1333 return Layout.getSectionAddressSize(&SD);
1336 static void WriteDataSectionData(ELFObjectWriter *W, const MCSectionData &SD) {
1337 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1339 const MCFragment &F = *i;
1340 assert(F.getKind() == MCFragment::FT_Data);
1341 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1345 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1346 const MCAsmLayout &Layout) {
1347 GroupMapTy GroupMap;
1348 RevGroupMapTy RevGroupMap;
1349 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1352 SectionIndexMapTy SectionIndexMap;
1354 ComputeIndexMap(Asm, SectionIndexMap);
1356 // Compute symbol table information.
1357 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1359 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1360 const_cast<MCAsmLayout&>(Layout),
1363 // Update to include the metadata sections.
1364 ComputeIndexMap(Asm, SectionIndexMap);
1366 // Add 1 for the null section.
1367 unsigned NumSections = Asm.size() + 1;
1368 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1369 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1370 sizeof(ELF::Elf32_Ehdr);
1371 uint64_t FileOff = HeaderSize;
1373 std::vector<const MCSectionELF*> Sections;
1374 Sections.resize(NumSections);
1376 for (SectionIndexMapTy::const_iterator i=
1377 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1378 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1379 Sections[p.second] = p.first;
1382 for (unsigned i = 1; i < NumSections; ++i) {
1383 const MCSectionELF &Section = *Sections[i];
1384 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1386 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1388 // Get the size of the section in the output file (including padding).
1389 FileOff += GetSectionFileSize(Layout, SD);
1392 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1394 // Write out the ELF header ...
1395 WriteHeader(FileOff - HeaderSize, NumSections);
1397 FileOff = HeaderSize;
1399 // ... then all of the sections ...
1400 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1402 for (unsigned i = 1; i < NumSections; ++i) {
1403 const MCSectionELF &Section = *Sections[i];
1404 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1406 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1407 WriteZeros(Padding);
1410 // Remember the offset into the file for this section.
1411 SectionOffsetMap[&Section] = FileOff;
1413 FileOff += GetSectionFileSize(Layout, SD);
1415 if (IsELFMetaDataSection(SD))
1416 WriteDataSectionData(this, SD);
1418 Asm.WriteSectionData(&SD, Layout);
1421 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1422 WriteZeros(Padding);
1425 // ... and then the section header table.
1426 // Should we align the section header table?
1428 // Null section first.
1429 uint64_t FirstSectionSize =
1430 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1431 uint32_t FirstSectionLink =
1432 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1433 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1435 for (unsigned i = 1; i < NumSections; ++i) {
1436 const MCSectionELF &Section = *Sections[i];
1437 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1438 uint32_t GroupSymbolIndex;
1439 if (Section.getType() != ELF::SHT_GROUP)
1440 GroupSymbolIndex = 0;
1442 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1444 uint64_t Size = GetSectionAddressSize(Layout, SD);
1446 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1447 SectionOffsetMap[&Section], Size,
1448 SD.getAlignment(), Section);
1452 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1454 bool IsLittleEndian) {
1455 switch (MOTW->getEMachine()) {
1457 case ELF::EM_X86_64:
1458 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1460 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1461 case ELF::EM_MBLAZE:
1462 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1463 default: llvm_unreachable("Unsupported architecture"); break;
1468 /// START OF SUBCLASSES for ELFObjectWriter
1469 //===- ARMELFObjectWriter -------------------------------------------===//
1471 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1473 bool IsLittleEndian)
1474 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1477 ARMELFObjectWriter::~ARMELFObjectWriter()
1480 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1481 const MCFixup &Fixup,
1483 bool IsRelocWithSymbol,
1485 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1486 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1490 switch ((unsigned)Fixup.getKind()) {
1491 default: assert(0 && "Unimplemented");
1494 default: llvm_unreachable("Unsupported Modifier");
1495 case MCSymbolRefExpr::VK_None:
1496 Type = ELF::R_ARM_BASE_PREL;
1498 case MCSymbolRefExpr::VK_ARM_TLSGD:
1499 assert(0 && "unimplemented");
1501 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1502 Type = ELF::R_ARM_TLS_IE32;
1506 case ARM::fixup_arm_uncondbranch:
1508 case MCSymbolRefExpr::VK_ARM_PLT:
1509 Type = ELF::R_ARM_PLT32;
1512 Type = ELF::R_ARM_CALL;
1516 case ARM::fixup_arm_condbranch:
1517 Type = ELF::R_ARM_JUMP24;
1519 case ARM::fixup_arm_movt_hi16:
1520 case ARM::fixup_arm_movt_hi16_pcrel:
1521 Type = ELF::R_ARM_MOVT_PREL;
1523 case ARM::fixup_arm_movw_lo16:
1524 case ARM::fixup_arm_movw_lo16_pcrel:
1525 Type = ELF::R_ARM_MOVW_PREL_NC;
1527 case ARM::fixup_t2_movt_hi16:
1528 case ARM::fixup_t2_movt_hi16_pcrel:
1529 Type = ELF::R_ARM_THM_MOVT_PREL;
1531 case ARM::fixup_t2_movw_lo16:
1532 case ARM::fixup_t2_movw_lo16_pcrel:
1533 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1537 switch ((unsigned)Fixup.getKind()) {
1538 default: llvm_unreachable("invalid fixup kind!");
1541 default: llvm_unreachable("Unsupported Modifier"); break;
1542 case MCSymbolRefExpr::VK_ARM_GOT:
1543 Type = ELF::R_ARM_GOT_BREL;
1545 case MCSymbolRefExpr::VK_ARM_TLSGD:
1546 Type = ELF::R_ARM_TLS_GD32;
1548 case MCSymbolRefExpr::VK_ARM_TPOFF:
1549 Type = ELF::R_ARM_TLS_LE32;
1551 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1552 Type = ELF::R_ARM_TLS_IE32;
1554 case MCSymbolRefExpr::VK_None:
1555 Type = ELF::R_ARM_ABS32;
1557 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1558 Type = ELF::R_ARM_GOTOFF32;
1562 case ARM::fixup_arm_ldst_pcrel_12:
1563 case ARM::fixup_arm_pcrel_10:
1564 case ARM::fixup_arm_adr_pcrel_12:
1565 case ARM::fixup_arm_thumb_bl:
1566 case ARM::fixup_arm_thumb_cb:
1567 case ARM::fixup_arm_thumb_cp:
1568 case ARM::fixup_arm_thumb_br:
1569 assert(0 && "Unimplemented");
1571 case ARM::fixup_arm_uncondbranch:
1572 Type = ELF::R_ARM_CALL;
1574 case ARM::fixup_arm_condbranch:
1575 Type = ELF::R_ARM_JUMP24;
1577 case ARM::fixup_arm_movt_hi16:
1578 Type = ELF::R_ARM_MOVT_ABS;
1580 case ARM::fixup_arm_movw_lo16:
1581 Type = ELF::R_ARM_MOVW_ABS_NC;
1583 case ARM::fixup_t2_movt_hi16:
1584 Type = ELF::R_ARM_THM_MOVT_ABS;
1586 case ARM::fixup_t2_movw_lo16:
1587 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1592 if (RelocNeedsGOT(Modifier))
1598 //===- MBlazeELFObjectWriter -------------------------------------------===//
1600 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1602 bool IsLittleEndian)
1603 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1606 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1609 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1610 const MCFixup &Fixup,
1612 bool IsRelocWithSymbol,
1614 // determine the type of the relocation
1617 switch ((unsigned)Fixup.getKind()) {
1619 llvm_unreachable("Unimplemented");
1621 Type = ELF::R_MICROBLAZE_64_PCREL;
1624 Type = ELF::R_MICROBLAZE_32_PCREL;
1628 switch ((unsigned)Fixup.getKind()) {
1629 default: llvm_unreachable("invalid fixup kind!");
1631 Type = ((IsRelocWithSymbol || Addend !=0)
1632 ? ELF::R_MICROBLAZE_32
1633 : ELF::R_MICROBLAZE_64);
1636 Type = ELF::R_MICROBLAZE_32;
1643 //===- X86ELFObjectWriter -------------------------------------------===//
1646 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1648 bool IsLittleEndian)
1649 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1652 X86ELFObjectWriter::~X86ELFObjectWriter()
1655 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1656 const MCFixup &Fixup,
1658 bool IsRelocWithSymbol,
1660 // determine the type of the relocation
1662 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1663 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1667 switch ((unsigned)Fixup.getKind()) {
1668 default: llvm_unreachable("invalid fixup kind!");
1670 assert(Modifier == MCSymbolRefExpr::VK_None);
1671 Type = ELF::R_X86_64_PC64;
1673 case X86::reloc_signed_4byte:
1674 case X86::reloc_riprel_4byte_movq_load:
1675 case FK_Data_4: // FIXME?
1676 case X86::reloc_riprel_4byte:
1680 llvm_unreachable("Unimplemented");
1681 case MCSymbolRefExpr::VK_None:
1682 Type = ELF::R_X86_64_PC32;
1684 case MCSymbolRefExpr::VK_PLT:
1685 Type = ELF::R_X86_64_PLT32;
1687 case MCSymbolRefExpr::VK_GOTPCREL:
1688 Type = ELF::R_X86_64_GOTPCREL;
1690 case MCSymbolRefExpr::VK_GOTTPOFF:
1691 Type = ELF::R_X86_64_GOTTPOFF;
1693 case MCSymbolRefExpr::VK_TLSGD:
1694 Type = ELF::R_X86_64_TLSGD;
1696 case MCSymbolRefExpr::VK_TLSLD:
1697 Type = ELF::R_X86_64_TLSLD;
1702 assert(Modifier == MCSymbolRefExpr::VK_None);
1703 Type = ELF::R_X86_64_PC16;
1707 switch ((unsigned)Fixup.getKind()) {
1708 default: llvm_unreachable("invalid fixup kind!");
1709 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1710 case X86::reloc_signed_4byte:
1711 assert(isInt<32>(Target.getConstant()));
1714 llvm_unreachable("Unimplemented");
1715 case MCSymbolRefExpr::VK_None:
1716 Type = ELF::R_X86_64_32S;
1718 case MCSymbolRefExpr::VK_GOT:
1719 Type = ELF::R_X86_64_GOT32;
1721 case MCSymbolRefExpr::VK_GOTPCREL:
1722 Type = ELF::R_X86_64_GOTPCREL;
1724 case MCSymbolRefExpr::VK_TPOFF:
1725 Type = ELF::R_X86_64_TPOFF32;
1727 case MCSymbolRefExpr::VK_DTPOFF:
1728 Type = ELF::R_X86_64_DTPOFF32;
1733 Type = ELF::R_X86_64_32;
1735 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1737 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1744 llvm_unreachable("Unimplemented");
1745 case MCSymbolRefExpr::VK_None:
1746 Type = ELF::R_386_PC32;
1748 case MCSymbolRefExpr::VK_PLT:
1749 Type = ELF::R_386_PLT32;
1753 switch ((unsigned)Fixup.getKind()) {
1754 default: llvm_unreachable("invalid fixup kind!");
1756 case X86::reloc_global_offset_table:
1757 Type = ELF::R_386_GOTPC;
1760 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1762 case X86::reloc_signed_4byte:
1767 llvm_unreachable("Unimplemented");
1768 case MCSymbolRefExpr::VK_None:
1769 Type = ELF::R_386_32;
1771 case MCSymbolRefExpr::VK_GOT:
1772 Type = ELF::R_386_GOT32;
1774 case MCSymbolRefExpr::VK_GOTOFF:
1775 Type = ELF::R_386_GOTOFF;
1777 case MCSymbolRefExpr::VK_TLSGD:
1778 Type = ELF::R_386_TLS_GD;
1780 case MCSymbolRefExpr::VK_TPOFF:
1781 Type = ELF::R_386_TLS_LE_32;
1783 case MCSymbolRefExpr::VK_INDNTPOFF:
1784 Type = ELF::R_386_TLS_IE;
1786 case MCSymbolRefExpr::VK_NTPOFF:
1787 Type = ELF::R_386_TLS_LE;
1789 case MCSymbolRefExpr::VK_GOTNTPOFF:
1790 Type = ELF::R_386_TLS_GOTIE;
1792 case MCSymbolRefExpr::VK_TLSLDM:
1793 Type = ELF::R_386_TLS_LDM;
1795 case MCSymbolRefExpr::VK_DTPOFF:
1796 Type = ELF::R_386_TLS_LDO_32;
1800 case FK_Data_2: Type = ELF::R_386_16; break;
1802 case FK_Data_1: Type = ELF::R_386_8; break;
1807 if (RelocNeedsGOT(Modifier))