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 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELFSymbolFlags.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCELFObjectWriter.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSectionELF.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Target/TargetAsmBackend.h"
34 #include "llvm/ADT/StringSwitch.h"
36 #include "../Target/X86/X86FixupKinds.h"
37 #include "../Target/ARM/ARMFixupKinds.h"
43 class ELFObjectWriter : public MCObjectWriter {
46 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
47 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
48 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
49 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
50 bool Used, bool Renamed);
51 static bool isLocal(const MCSymbolData &Data, bool isSignature,
53 static bool IsELFMetaDataSection(const MCSectionData &SD);
54 static uint64_t DataSectionSize(const MCSectionData &SD);
55 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
56 const MCSectionData &SD);
57 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
58 const MCSectionData &SD);
59 static void WriteDataSectionData(ELFObjectWriter *W,
60 const MCSectionData &SD);
62 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
63 return Kind == X86::reloc_riprel_4byte ||
64 Kind == X86::reloc_riprel_4byte_movq_load;
67 /// ELFSymbolData - Helper struct for containing some precomputed
68 /// information on symbols.
69 struct ELFSymbolData {
70 MCSymbolData *SymbolData;
72 uint32_t SectionIndex;
74 // Support lexicographic sorting.
75 bool operator<(const ELFSymbolData &RHS) const {
76 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
78 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
80 return SymbolData->getSymbol().getName() <
81 RHS.SymbolData->getSymbol().getName();
85 /// @name Relocation Data
88 struct ELFRelocationEntry {
89 // Make these big enough for both 32-bit and 64-bit
93 const MCSymbol *Symbol;
97 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
99 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
100 unsigned RelType, const MCSymbol *Sym,
102 : r_offset(RelocOffset), Index(Idx), Type(RelType),
103 Symbol(Sym), r_addend(Addend) {}
105 // Support lexicographic sorting.
106 bool operator<(const ELFRelocationEntry &RE) const {
107 return RE.r_offset < r_offset;
111 /// The target specific ELF writer instance.
112 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
114 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
115 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
116 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
118 llvm::DenseMap<const MCSectionData*,
119 std::vector<ELFRelocationEntry> > Relocations;
120 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
123 /// @name Symbol Table Data
126 SmallString<256> StringTable;
127 std::vector<ELFSymbolData> LocalSymbolData;
128 std::vector<ELFSymbolData> ExternalSymbolData;
129 std::vector<ELFSymbolData> UndefinedSymbolData;
135 bool NeedsSymtabShndx;
137 // This holds the symbol table index of the last local symbol.
138 unsigned LastLocalSymbolIndex;
139 // This holds the .strtab section index.
140 unsigned StringTableIndex;
141 // This holds the .symtab section index.
142 unsigned SymbolTableIndex;
144 unsigned ShstrtabIndex;
147 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
148 const MCValue &Target,
149 const MCFragment &F) const;
151 // For arch-specific emission of explicit reloc symbol
152 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
153 const MCValue &Target,
159 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
160 bool hasRelocationAddend() const {
161 return TargetObjectWriter->hasRelocationAddend();
165 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
166 raw_ostream &_OS, bool IsLittleEndian)
167 : MCObjectWriter(_OS, IsLittleEndian),
168 TargetObjectWriter(MOTW),
169 NeedsGOT(false), NeedsSymtabShndx(false){
172 virtual ~ELFObjectWriter();
174 void WriteWord(uint64_t W) {
181 void StringLE16(char *buf, uint16_t Value) {
182 buf[0] = char(Value >> 0);
183 buf[1] = char(Value >> 8);
186 void StringLE32(char *buf, uint32_t Value) {
187 StringLE16(buf, uint16_t(Value >> 0));
188 StringLE16(buf + 2, uint16_t(Value >> 16));
191 void StringLE64(char *buf, uint64_t Value) {
192 StringLE32(buf, uint32_t(Value >> 0));
193 StringLE32(buf + 4, uint32_t(Value >> 32));
196 void StringBE16(char *buf ,uint16_t Value) {
197 buf[0] = char(Value >> 8);
198 buf[1] = char(Value >> 0);
201 void StringBE32(char *buf, uint32_t Value) {
202 StringBE16(buf, uint16_t(Value >> 16));
203 StringBE16(buf + 2, uint16_t(Value >> 0));
206 void StringBE64(char *buf, uint64_t Value) {
207 StringBE32(buf, uint32_t(Value >> 32));
208 StringBE32(buf + 4, uint32_t(Value >> 0));
211 void String8(MCDataFragment &F, uint8_t Value) {
214 F.getContents() += StringRef(buf, 1);
217 void String16(MCDataFragment &F, uint16_t Value) {
219 if (isLittleEndian())
220 StringLE16(buf, Value);
222 StringBE16(buf, Value);
223 F.getContents() += StringRef(buf, 2);
226 void String32(MCDataFragment &F, uint32_t Value) {
228 if (isLittleEndian())
229 StringLE32(buf, Value);
231 StringBE32(buf, Value);
232 F.getContents() += StringRef(buf, 4);
235 void String64(MCDataFragment &F, uint64_t Value) {
237 if (isLittleEndian())
238 StringLE64(buf, Value);
240 StringBE64(buf, Value);
241 F.getContents() += StringRef(buf, 8);
244 virtual void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
246 /// Default e_flags = 0
247 virtual void WriteEFlags() { Write32(0); }
249 virtual void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
250 uint64_t name, uint8_t info,
251 uint64_t value, uint64_t size,
252 uint8_t other, uint32_t shndx,
255 virtual void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
257 const MCAsmLayout &Layout);
259 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
260 virtual void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
261 const MCAssembler &Asm,
262 const MCAsmLayout &Layout,
263 const SectionIndexMapTy &SectionIndexMap);
265 virtual void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
266 const MCFragment *Fragment, const MCFixup &Fixup,
267 MCValue Target, uint64_t &FixedValue);
269 virtual uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
272 // Map from a group section to the signature symbol
273 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
274 // Map from a signature symbol to the group section
275 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
277 /// ComputeSymbolTable - Compute the symbol table data
279 /// \param StringTable [out] - The string table data.
280 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
282 virtual void ComputeSymbolTable(MCAssembler &Asm,
283 const SectionIndexMapTy &SectionIndexMap,
284 RevGroupMapTy RevGroupMap);
286 virtual void ComputeIndexMap(MCAssembler &Asm,
287 SectionIndexMapTy &SectionIndexMap);
289 virtual void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
290 const MCSectionData &SD);
292 virtual void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
293 for (MCAssembler::const_iterator it = Asm.begin(),
294 ie = Asm.end(); it != ie; ++it) {
295 WriteRelocation(Asm, Layout, *it);
299 virtual void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
300 const SectionIndexMapTy &SectionIndexMap);
302 // Create the sections that show up in the symbol table. Currently
303 // those are the .note.GNU-stack section and the group sections.
304 virtual void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
305 GroupMapTy &GroupMap,
306 RevGroupMapTy &RevGroupMap);
308 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
309 const MCAsmLayout &Layout);
311 virtual void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
312 uint64_t Address, uint64_t Offset,
313 uint64_t Size, uint32_t Link, uint32_t Info,
314 uint64_t Alignment, uint64_t EntrySize);
316 virtual void WriteRelocationsFragment(const MCAssembler &Asm,
318 const MCSectionData *SD);
321 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
322 const MCSymbolData &DataA,
323 const MCFragment &FB,
327 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
328 virtual void WriteSection(MCAssembler &Asm,
329 const SectionIndexMapTy &SectionIndexMap,
330 uint32_t GroupSymbolIndex,
331 uint64_t Offset, uint64_t Size, uint64_t Alignment,
332 const MCSectionELF &Section);
335 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
336 bool IsPCRel, bool IsRelocWithSymbol,
340 //===- X86ELFObjectWriter -------------------------------------------===//
342 class X86ELFObjectWriter : public ELFObjectWriter {
344 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
346 bool IsLittleEndian);
348 virtual ~X86ELFObjectWriter();
350 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
351 bool IsPCRel, bool IsRelocWithSymbol,
356 //===- ARMELFObjectWriter -------------------------------------------===//
358 class ARMELFObjectWriter : public ELFObjectWriter {
360 // FIXME: MCAssembler can't yet return the Subtarget,
361 enum { DefaultEABIVersion = 0x05000000U };
363 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
365 bool IsLittleEndian);
367 virtual ~ARMELFObjectWriter();
369 virtual void WriteEFlags();
371 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
372 const MCValue &Target,
376 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
377 bool IsPCRel, bool IsRelocWithSymbol,
381 //===- MBlazeELFObjectWriter -------------------------------------------===//
383 class MBlazeELFObjectWriter : public ELFObjectWriter {
385 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
387 bool IsLittleEndian);
389 virtual ~MBlazeELFObjectWriter();
391 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
392 bool IsPCRel, bool IsRelocWithSymbol,
397 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
398 const MCFixupKindInfo &FKI =
399 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
401 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
404 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
408 case MCSymbolRefExpr::VK_GOT:
409 case MCSymbolRefExpr::VK_PLT:
410 case MCSymbolRefExpr::VK_GOTPCREL:
411 case MCSymbolRefExpr::VK_TPOFF:
412 case MCSymbolRefExpr::VK_TLSGD:
413 case MCSymbolRefExpr::VK_GOTTPOFF:
414 case MCSymbolRefExpr::VK_INDNTPOFF:
415 case MCSymbolRefExpr::VK_NTPOFF:
416 case MCSymbolRefExpr::VK_GOTNTPOFF:
417 case MCSymbolRefExpr::VK_TLSLDM:
418 case MCSymbolRefExpr::VK_DTPOFF:
419 case MCSymbolRefExpr::VK_TLSLD:
424 ELFObjectWriter::~ELFObjectWriter()
427 // Emit the ELF header.
428 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
429 unsigned NumberOfSections) {
435 // emitWord method behaves differently for ELF32 and ELF64, writing
436 // 4 bytes in the former and 8 in the latter.
438 Write8(0x7f); // e_ident[EI_MAG0]
439 Write8('E'); // e_ident[EI_MAG1]
440 Write8('L'); // e_ident[EI_MAG2]
441 Write8('F'); // e_ident[EI_MAG3]
443 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
446 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
448 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
450 switch (TargetObjectWriter->getOSType()) {
451 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
452 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
453 default: Write8(ELF::ELFOSABI_NONE); break;
455 Write8(0); // e_ident[EI_ABIVERSION]
457 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
459 Write16(ELF::ET_REL); // e_type
461 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
463 Write32(ELF::EV_CURRENT); // e_version
464 WriteWord(0); // e_entry, no entry point in .o file
465 WriteWord(0); // e_phoff, no program header for .o
466 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
467 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
469 // e_flags = whatever the target wants
472 // e_ehsize = ELF header size
473 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
475 Write16(0); // e_phentsize = prog header entry size
476 Write16(0); // e_phnum = # prog header entries = 0
478 // e_shentsize = Section header entry size
479 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
481 // e_shnum = # of section header ents
482 if (NumberOfSections >= ELF::SHN_LORESERVE)
485 Write16(NumberOfSections);
487 // e_shstrndx = Section # of '.shstrtab'
488 if (NumberOfSections >= ELF::SHN_LORESERVE)
489 Write16(ELF::SHN_XINDEX);
491 Write16(ShstrtabIndex);
494 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
495 MCDataFragment *ShndxF,
497 uint8_t info, uint64_t value,
498 uint64_t size, uint8_t other,
502 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
503 String32(*ShndxF, shndx);
505 String32(*ShndxF, 0);
508 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
509 uint16_t(ELF::SHN_XINDEX) : shndx;
512 String32(*SymtabF, name); // st_name
513 String8(*SymtabF, info); // st_info
514 String8(*SymtabF, other); // st_other
515 String16(*SymtabF, Index); // st_shndx
516 String64(*SymtabF, value); // st_value
517 String64(*SymtabF, size); // st_size
519 String32(*SymtabF, name); // st_name
520 String32(*SymtabF, value); // st_value
521 String32(*SymtabF, size); // st_size
522 String8(*SymtabF, info); // st_info
523 String8(*SymtabF, other); // st_other
524 String16(*SymtabF, Index); // st_shndx
528 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
529 const MCAsmLayout &Layout) {
530 if (Data.isCommon() && Data.isExternal())
531 return Data.getCommonAlignment();
533 const MCSymbol &Symbol = Data.getSymbol();
535 if (Symbol.isAbsolute() && Symbol.isVariable()) {
536 if (const MCExpr *Value = Symbol.getVariableValue()) {
538 if (Value->EvaluateAsAbsolute(IntValue, Layout))
539 return (uint64_t)IntValue;
543 if (!Symbol.isInSection())
546 if (Data.getFragment())
547 return Layout.getSymbolOffset(&Data);
552 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
553 const MCAsmLayout &Layout) {
554 // The presence of symbol versions causes undefined symbols and
555 // versions declared with @@@ to be renamed.
557 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
558 ie = Asm.symbol_end(); it != ie; ++it) {
559 const MCSymbol &Alias = it->getSymbol();
560 const MCSymbol &Symbol = Alias.AliasedSymbol();
561 MCSymbolData &SD = Asm.getSymbolData(Symbol);
564 if (&Symbol == &Alias)
567 StringRef AliasName = Alias.getName();
568 size_t Pos = AliasName.find('@');
569 if (Pos == StringRef::npos)
572 // Aliases defined with .symvar copy the binding from the symbol they alias.
573 // This is the first place we are able to copy this information.
574 it->setExternal(SD.isExternal());
575 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
577 StringRef Rest = AliasName.substr(Pos);
578 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
581 // FIXME: produce a better error message.
582 if (Symbol.isUndefined() && Rest.startswith("@@") &&
583 !Rest.startswith("@@@"))
584 report_fatal_error("A @@ version cannot be undefined");
586 Renames.insert(std::make_pair(&Symbol, &Alias));
590 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
591 MCDataFragment *ShndxF,
593 const MCAsmLayout &Layout) {
594 MCSymbolData &OrigData = *MSD.SymbolData;
596 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
598 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
599 Data.getSymbol().isVariable();
601 uint8_t Binding = MCELF::GetBinding(OrigData);
602 uint8_t Visibility = MCELF::GetVisibility(OrigData);
603 uint8_t Type = MCELF::GetType(Data);
605 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
606 uint8_t Other = Visibility;
608 uint64_t Value = SymbolValue(Data, Layout);
611 assert(!(Data.isCommon() && !Data.isExternal()));
613 const MCExpr *ESize = Data.getSize();
616 if (!ESize->EvaluateAsAbsolute(Res, Layout))
617 report_fatal_error("Size expression must be absolute.");
621 // Write out the symbol table entry
622 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
623 Size, Other, MSD.SectionIndex, IsReserved);
626 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
627 MCDataFragment *ShndxF,
628 const MCAssembler &Asm,
629 const MCAsmLayout &Layout,
630 const SectionIndexMapTy &SectionIndexMap) {
631 // The string table must be emitted first because we need the index
632 // into the string table for all the symbol names.
633 assert(StringTable.size() && "Missing string table");
635 // FIXME: Make sure the start of the symbol table is aligned.
637 // The first entry is the undefined symbol entry.
638 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
640 // Write the symbol table entries.
641 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
642 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
643 ELFSymbolData &MSD = LocalSymbolData[i];
644 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
647 // Write out a symbol table entry for each regular section.
648 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
650 const MCSectionELF &Section =
651 static_cast<const MCSectionELF&>(i->getSection());
652 if (Section.getType() == ELF::SHT_RELA ||
653 Section.getType() == ELF::SHT_REL ||
654 Section.getType() == ELF::SHT_STRTAB ||
655 Section.getType() == ELF::SHT_SYMTAB)
657 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
658 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
659 LastLocalSymbolIndex++;
662 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
663 ELFSymbolData &MSD = ExternalSymbolData[i];
664 MCSymbolData &Data = *MSD.SymbolData;
665 assert(((Data.getFlags() & ELF_STB_Global) ||
666 (Data.getFlags() & ELF_STB_Weak)) &&
667 "External symbol requires STB_GLOBAL or STB_WEAK flag");
668 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
669 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
670 LastLocalSymbolIndex++;
673 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
674 ELFSymbolData &MSD = UndefinedSymbolData[i];
675 MCSymbolData &Data = *MSD.SymbolData;
676 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
677 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
678 LastLocalSymbolIndex++;
682 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
683 const MCValue &Target,
684 const MCFragment &F) const {
685 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
686 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
687 const MCSymbol *Renamed = Renames.lookup(&Symbol);
688 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
690 if (ASymbol.isUndefined()) {
696 if (SD.isExternal()) {
702 const MCSectionELF &Section =
703 static_cast<const MCSectionELF&>(ASymbol.getSection());
704 const SectionKind secKind = Section.getKind();
707 return ExplicitRelSym(Asm, Target, F, true);
709 if (secKind.isThreadLocal()) {
715 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
716 const MCSectionELF &Sec2 =
717 static_cast<const MCSectionELF&>(F.getParent()->getSection());
719 if (&Sec2 != &Section &&
720 (Kind == MCSymbolRefExpr::VK_PLT ||
721 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
722 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
728 if (Section.getFlags() & ELF::SHF_MERGE) {
729 if (Target.getConstant() == 0)
736 return ExplicitRelSym(Asm, Target, F, false);
740 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
741 const MCAsmLayout &Layout,
742 const MCFragment *Fragment,
743 const MCFixup &Fixup,
745 uint64_t &FixedValue) {
748 int64_t Value = Target.getConstant();
749 const MCSymbol *RelocSymbol = NULL;
751 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
752 if (!Target.isAbsolute()) {
753 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
754 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
755 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
757 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
758 const MCSymbol &SymbolB = RefB->getSymbol();
759 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
762 // Offset of the symbol in the section
763 int64_t a = Layout.getSymbolOffset(&SDB);
765 // Ofeset of the relocation in the section
766 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
771 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
772 MCFragment *F = SD.getFragment();
774 Index = F->getParent()->getOrdinal() + 1;
776 // Offset of the symbol in the section
777 Value += Layout.getSymbolOffset(&SD);
779 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
780 WeakrefUsedInReloc.insert(RelocSymbol);
782 UsedInReloc.insert(RelocSymbol);
786 // Compensate for the addend on i386.
792 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
793 (RelocSymbol != 0), Addend);
795 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
798 if (!hasRelocationAddend())
800 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
801 Relocations[Fragment->getParent()].push_back(ERE);
806 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
808 MCSymbolData &SD = Asm.getSymbolData(*S);
809 return SD.getIndex();
812 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
813 const MCSymbolData &Data,
814 bool Used, bool Renamed) {
815 if (Data.getFlags() & ELF_Other_Weakref)
824 const MCSymbol &Symbol = Data.getSymbol();
826 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
829 const MCSymbol &A = Symbol.AliasedSymbol();
830 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
833 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
834 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
837 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
840 if (Symbol.isTemporary())
846 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
847 bool isUsedInReloc) {
848 if (Data.isExternal())
851 const MCSymbol &Symbol = Data.getSymbol();
852 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
854 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
855 if (isSignature && !isUsedInReloc)
864 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
865 SectionIndexMapTy &SectionIndexMap) {
867 for (MCAssembler::iterator it = Asm.begin(),
868 ie = Asm.end(); it != ie; ++it) {
869 const MCSectionELF &Section =
870 static_cast<const MCSectionELF &>(it->getSection());
871 if (Section.getType() != ELF::SHT_GROUP)
873 SectionIndexMap[&Section] = Index++;
876 for (MCAssembler::iterator it = Asm.begin(),
877 ie = Asm.end(); it != ie; ++it) {
878 const MCSectionELF &Section =
879 static_cast<const MCSectionELF &>(it->getSection());
880 if (Section.getType() == ELF::SHT_GROUP)
882 SectionIndexMap[&Section] = Index++;
886 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
887 const SectionIndexMapTy &SectionIndexMap,
888 RevGroupMapTy RevGroupMap) {
889 // FIXME: Is this the correct place to do this?
891 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
892 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
893 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
894 Data.setExternal(true);
895 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
898 // Build section lookup table.
899 int NumRegularSections = Asm.size();
901 // Index 0 is always the empty string.
902 StringMap<uint64_t> StringIndexMap;
903 StringTable += '\x00';
905 // Add the data for the symbols.
906 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
907 ie = Asm.symbol_end(); it != ie; ++it) {
908 const MCSymbol &Symbol = it->getSymbol();
910 bool Used = UsedInReloc.count(&Symbol);
911 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
912 bool isSignature = RevGroupMap.count(&Symbol);
914 if (!isInSymtab(Asm, *it,
915 Used || WeakrefUsed || isSignature,
916 Renames.count(&Symbol)))
921 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
923 // Undefined symbols are global, but this is the first place we
924 // are able to set it.
925 bool Local = isLocal(*it, isSignature, Used);
926 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
927 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
928 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
929 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
932 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
933 MCELF::SetBinding(*it, ELF::STB_WEAK);
935 if (it->isCommon()) {
937 MSD.SectionIndex = ELF::SHN_COMMON;
938 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
939 MSD.SectionIndex = ELF::SHN_ABS;
940 } else if (RefSymbol.isUndefined()) {
941 if (isSignature && !Used)
942 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
944 MSD.SectionIndex = ELF::SHN_UNDEF;
946 const MCSectionELF &Section =
947 static_cast<const MCSectionELF&>(RefSymbol.getSection());
948 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
949 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
950 NeedsSymtabShndx = true;
951 assert(MSD.SectionIndex && "Invalid section index!");
954 // The @@@ in symbol version is replaced with @ in undefined symbols and
955 // @@ in defined ones.
956 StringRef Name = Symbol.getName();
959 size_t Pos = Name.find("@@@");
960 if (Pos != StringRef::npos) {
961 Buf += Name.substr(0, Pos);
962 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
963 Buf += Name.substr(Pos + Skip);
967 uint64_t &Entry = StringIndexMap[Name];
969 Entry = StringTable.size();
971 StringTable += '\x00';
973 MSD.StringIndex = Entry;
974 if (MSD.SectionIndex == ELF::SHN_UNDEF)
975 UndefinedSymbolData.push_back(MSD);
977 LocalSymbolData.push_back(MSD);
979 ExternalSymbolData.push_back(MSD);
982 // Symbols are required to be in lexicographic order.
983 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
984 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
985 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
987 // Set the symbol indices. Local symbols must come before all other
988 // symbols with non-local bindings.
990 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
991 LocalSymbolData[i].SymbolData->setIndex(Index++);
993 Index += NumRegularSections;
995 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
996 ExternalSymbolData[i].SymbolData->setIndex(Index++);
997 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
998 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1001 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1002 const MCSectionData &SD) {
1003 if (!Relocations[&SD].empty()) {
1004 MCContext &Ctx = Asm.getContext();
1005 const MCSectionELF *RelaSection;
1006 const MCSectionELF &Section =
1007 static_cast<const MCSectionELF&>(SD.getSection());
1009 const StringRef SectionName = Section.getSectionName();
1010 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1011 RelaSectionName += SectionName;
1014 if (hasRelocationAddend())
1015 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1017 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1019 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1020 ELF::SHT_RELA : ELF::SHT_REL, 0,
1021 SectionKind::getReadOnly(),
1024 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1025 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1027 MCDataFragment *F = new MCDataFragment(&RelaSD);
1029 WriteRelocationsFragment(Asm, F, &SD);
1033 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1034 uint64_t Flags, uint64_t Address,
1035 uint64_t Offset, uint64_t Size,
1036 uint32_t Link, uint32_t Info,
1038 uint64_t EntrySize) {
1039 Write32(Name); // sh_name: index into string table
1040 Write32(Type); // sh_type
1041 WriteWord(Flags); // sh_flags
1042 WriteWord(Address); // sh_addr
1043 WriteWord(Offset); // sh_offset
1044 WriteWord(Size); // sh_size
1045 Write32(Link); // sh_link
1046 Write32(Info); // sh_info
1047 WriteWord(Alignment); // sh_addralign
1048 WriteWord(EntrySize); // sh_entsize
1051 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1053 const MCSectionData *SD) {
1054 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1055 // sort by the r_offset just like gnu as does
1056 array_pod_sort(Relocs.begin(), Relocs.end());
1058 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1059 ELFRelocationEntry entry = Relocs[e - i - 1];
1063 else if (entry.Index < 0)
1064 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1066 entry.Index += LocalSymbolData.size();
1068 String64(*F, entry.r_offset);
1070 struct ELF::Elf64_Rela ERE64;
1071 ERE64.setSymbolAndType(entry.Index, entry.Type);
1072 String64(*F, ERE64.r_info);
1074 if (hasRelocationAddend())
1075 String64(*F, entry.r_addend);
1077 String32(*F, entry.r_offset);
1079 struct ELF::Elf32_Rela ERE32;
1080 ERE32.setSymbolAndType(entry.Index, entry.Type);
1081 String32(*F, ERE32.r_info);
1083 if (hasRelocationAddend())
1084 String32(*F, entry.r_addend);
1089 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1090 MCAsmLayout &Layout,
1091 const SectionIndexMapTy &SectionIndexMap) {
1092 MCContext &Ctx = Asm.getContext();
1095 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1097 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1098 const MCSectionELF *ShstrtabSection =
1099 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1100 SectionKind::getReadOnly());
1101 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1102 ShstrtabSD.setAlignment(1);
1103 ShstrtabIndex = Asm.size();
1105 const MCSectionELF *SymtabSection =
1106 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1107 SectionKind::getReadOnly(),
1109 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1110 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1111 SymbolTableIndex = Asm.size();
1113 MCSectionData *SymtabShndxSD = NULL;
1115 if (NeedsSymtabShndx) {
1116 const MCSectionELF *SymtabShndxSection =
1117 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1118 SectionKind::getReadOnly(), 4, "");
1119 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1120 SymtabShndxSD->setAlignment(4);
1123 const MCSection *StrtabSection;
1124 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1125 SectionKind::getReadOnly());
1126 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1127 StrtabSD.setAlignment(1);
1128 StringTableIndex = Asm.size();
1130 WriteRelocations(Asm, Layout);
1133 F = new MCDataFragment(&SymtabSD);
1134 MCDataFragment *ShndxF = NULL;
1135 if (NeedsSymtabShndx) {
1136 ShndxF = new MCDataFragment(SymtabShndxSD);
1138 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1140 F = new MCDataFragment(&StrtabSD);
1141 F->getContents().append(StringTable.begin(), StringTable.end());
1143 F = new MCDataFragment(&ShstrtabSD);
1145 // Section header string table.
1147 // The first entry of a string table holds a null character so skip
1150 F->getContents() += '\x00';
1152 StringMap<uint64_t> SecStringMap;
1153 for (MCAssembler::const_iterator it = Asm.begin(),
1154 ie = Asm.end(); it != ie; ++it) {
1155 const MCSectionELF &Section =
1156 static_cast<const MCSectionELF&>(it->getSection());
1157 // FIXME: We could merge suffixes like in .text and .rela.text.
1159 StringRef Name = Section.getSectionName();
1160 if (SecStringMap.count(Name)) {
1161 SectionStringTableIndex[&Section] = SecStringMap[Name];
1164 // Remember the index into the string table so we can write it
1165 // into the sh_name field of the section header table.
1166 SectionStringTableIndex[&Section] = Index;
1167 SecStringMap[Name] = Index;
1169 Index += Name.size() + 1;
1170 F->getContents() += Name;
1171 F->getContents() += '\x00';
1175 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1176 MCAsmLayout &Layout,
1177 GroupMapTy &GroupMap,
1178 RevGroupMapTy &RevGroupMap) {
1179 // Create the .note.GNU-stack section if needed.
1180 MCContext &Ctx = Asm.getContext();
1181 if (Asm.getNoExecStack()) {
1182 const MCSectionELF *GnuStackSection =
1183 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1184 SectionKind::getReadOnly());
1185 Asm.getOrCreateSectionData(*GnuStackSection);
1189 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1191 const MCSectionELF &Section =
1192 static_cast<const MCSectionELF&>(it->getSection());
1193 if (!(Section.getFlags() & ELF::SHF_GROUP))
1196 const MCSymbol *SignatureSymbol = Section.getGroup();
1197 Asm.getOrCreateSymbolData(*SignatureSymbol);
1198 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1200 Group = Ctx.CreateELFGroupSection();
1201 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1202 Data.setAlignment(4);
1203 MCDataFragment *F = new MCDataFragment(&Data);
1204 String32(*F, ELF::GRP_COMDAT);
1206 GroupMap[Group] = SignatureSymbol;
1209 // Add sections to the groups
1211 unsigned NumGroups = RevGroupMap.size();
1212 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1213 it != ie; ++it, ++Index) {
1214 const MCSectionELF &Section =
1215 static_cast<const MCSectionELF&>(it->getSection());
1216 if (!(Section.getFlags() & ELF::SHF_GROUP))
1218 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1219 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1220 // FIXME: we could use the previous fragment
1221 MCDataFragment *F = new MCDataFragment(&Data);
1222 String32(*F, NumGroups + Index);
1226 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1227 const SectionIndexMapTy &SectionIndexMap,
1228 uint32_t GroupSymbolIndex,
1229 uint64_t Offset, uint64_t Size,
1231 const MCSectionELF &Section) {
1232 uint64_t sh_link = 0;
1233 uint64_t sh_info = 0;
1235 switch(Section.getType()) {
1236 case ELF::SHT_DYNAMIC:
1237 sh_link = SectionStringTableIndex[&Section];
1242 case ELF::SHT_RELA: {
1243 const MCSectionELF *SymtabSection;
1244 const MCSectionELF *InfoSection;
1245 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1247 SectionKind::getReadOnly());
1248 sh_link = SectionIndexMap.lookup(SymtabSection);
1249 assert(sh_link && ".symtab not found");
1251 // Remove ".rel" and ".rela" prefixes.
1252 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1253 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1255 InfoSection = Asm.getContext().getELFSection(SectionName,
1256 ELF::SHT_PROGBITS, 0,
1257 SectionKind::getReadOnly());
1258 sh_info = SectionIndexMap.lookup(InfoSection);
1262 case ELF::SHT_SYMTAB:
1263 case ELF::SHT_DYNSYM:
1264 sh_link = StringTableIndex;
1265 sh_info = LastLocalSymbolIndex;
1268 case ELF::SHT_SYMTAB_SHNDX:
1269 sh_link = SymbolTableIndex;
1272 case ELF::SHT_PROGBITS:
1273 case ELF::SHT_STRTAB:
1274 case ELF::SHT_NOBITS:
1277 case ELF::SHT_ARM_ATTRIBUTES:
1278 case ELF::SHT_INIT_ARRAY:
1279 case ELF::SHT_FINI_ARRAY:
1280 case ELF::SHT_PREINIT_ARRAY:
1281 case ELF::SHT_X86_64_UNWIND:
1285 case ELF::SHT_GROUP: {
1286 sh_link = SymbolTableIndex;
1287 sh_info = GroupSymbolIndex;
1292 assert(0 && "FIXME: sh_type value not supported!");
1296 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1297 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1298 Alignment, Section.getEntrySize());
1301 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1302 return SD.getOrdinal() == ~UINT32_C(0) &&
1303 !SD.getSection().isVirtualSection();
1306 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1308 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1310 const MCFragment &F = *i;
1311 assert(F.getKind() == MCFragment::FT_Data);
1312 Ret += cast<MCDataFragment>(F).getContents().size();
1317 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1318 const MCSectionData &SD) {
1319 if (IsELFMetaDataSection(SD))
1320 return DataSectionSize(SD);
1321 return Layout.getSectionFileSize(&SD);
1324 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1325 const MCSectionData &SD) {
1326 if (IsELFMetaDataSection(SD))
1327 return DataSectionSize(SD);
1328 return Layout.getSectionAddressSize(&SD);
1331 void ELFObjectWriter::WriteDataSectionData(ELFObjectWriter *W,
1332 const MCSectionData &SD) {
1333 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1335 const MCFragment &F = *i;
1336 assert(F.getKind() == MCFragment::FT_Data);
1337 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1341 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1342 const MCAsmLayout &Layout) {
1343 GroupMapTy GroupMap;
1344 RevGroupMapTy RevGroupMap;
1345 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1348 SectionIndexMapTy SectionIndexMap;
1350 ComputeIndexMap(Asm, SectionIndexMap);
1352 // Compute symbol table information.
1353 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1355 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1356 const_cast<MCAsmLayout&>(Layout),
1359 // Update to include the metadata sections.
1360 ComputeIndexMap(Asm, SectionIndexMap);
1362 // Add 1 for the null section.
1363 unsigned NumSections = Asm.size() + 1;
1364 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1365 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1366 sizeof(ELF::Elf32_Ehdr);
1367 uint64_t FileOff = HeaderSize;
1369 std::vector<const MCSectionELF*> Sections;
1370 Sections.resize(NumSections);
1372 for (SectionIndexMapTy::const_iterator i=
1373 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1374 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1375 Sections[p.second] = p.first;
1378 for (unsigned i = 1; i < NumSections; ++i) {
1379 const MCSectionELF &Section = *Sections[i];
1380 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1382 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1384 // Get the size of the section in the output file (including padding).
1385 FileOff += GetSectionFileSize(Layout, SD);
1388 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1390 // Write out the ELF header ...
1391 WriteHeader(FileOff - HeaderSize, NumSections);
1393 FileOff = HeaderSize;
1395 // ... then all of the sections ...
1396 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1398 for (unsigned i = 1; i < NumSections; ++i) {
1399 const MCSectionELF &Section = *Sections[i];
1400 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1402 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1403 WriteZeros(Padding);
1406 // Remember the offset into the file for this section.
1407 SectionOffsetMap[&Section] = FileOff;
1409 FileOff += GetSectionFileSize(Layout, SD);
1411 if (IsELFMetaDataSection(SD))
1412 WriteDataSectionData(this, SD);
1414 Asm.WriteSectionData(&SD, Layout);
1417 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1418 WriteZeros(Padding);
1421 // ... and then the section header table.
1422 // Should we align the section header table?
1424 // Null section first.
1425 uint64_t FirstSectionSize =
1426 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1427 uint32_t FirstSectionLink =
1428 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1429 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1431 for (unsigned i = 1; i < NumSections; ++i) {
1432 const MCSectionELF &Section = *Sections[i];
1433 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1434 uint32_t GroupSymbolIndex;
1435 if (Section.getType() != ELF::SHT_GROUP)
1436 GroupSymbolIndex = 0;
1438 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1440 uint64_t Size = GetSectionAddressSize(Layout, SD);
1442 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1443 SectionOffsetMap[&Section], Size,
1444 SD.getAlignment(), Section);
1449 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1450 const MCSymbolData &DataA,
1451 const MCFragment &FB,
1453 bool IsPCRel) const {
1454 if (DataA.getFlags() & ELF_STB_Weak)
1456 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1457 Asm, DataA, FB,InSet, IsPCRel);
1460 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1462 bool IsLittleEndian) {
1463 switch (MOTW->getEMachine()) {
1465 case ELF::EM_X86_64:
1466 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1468 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1469 case ELF::EM_MBLAZE:
1470 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1471 default: llvm_unreachable("Unsupported architecture"); break;
1476 /// START OF SUBCLASSES for ELFObjectWriter
1477 //===- ARMELFObjectWriter -------------------------------------------===//
1479 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1481 bool IsLittleEndian)
1482 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1485 ARMELFObjectWriter::~ARMELFObjectWriter()
1488 // FIXME: get the real EABI Version from the Triple.
1489 void ARMELFObjectWriter::WriteEFlags() {
1490 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1493 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1494 // I.e. not as an offset to a section symbol.
1495 // This code is a first-cut approximation of what ARM/gcc does.
1497 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1498 const MCValue &Target,
1499 const MCFragment &F,
1501 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1502 bool EmitThisSym = false;
1505 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1506 .Case("_MergedGlobals", true)
1509 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1510 .Case("_MergedGlobals", true)
1511 .StartsWith(".L.str", true)
1516 if (! Symbol.isTemporary())
1521 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1522 const MCFixup &Fixup,
1524 bool IsRelocWithSymbol,
1526 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1527 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1531 switch ((unsigned)Fixup.getKind()) {
1532 default: assert(0 && "Unimplemented");
1535 default: llvm_unreachable("Unsupported Modifier");
1536 case MCSymbolRefExpr::VK_None:
1537 Type = ELF::R_ARM_BASE_PREL;
1539 case MCSymbolRefExpr::VK_ARM_TLSGD:
1540 assert(0 && "unimplemented");
1542 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1543 Type = ELF::R_ARM_TLS_IE32;
1547 case ARM::fixup_arm_uncondbranch:
1549 case MCSymbolRefExpr::VK_ARM_PLT:
1550 Type = ELF::R_ARM_PLT32;
1553 Type = ELF::R_ARM_CALL;
1557 case ARM::fixup_arm_condbranch:
1558 Type = ELF::R_ARM_JUMP24;
1560 case ARM::fixup_arm_movt_hi16:
1561 case ARM::fixup_arm_movt_hi16_pcrel:
1562 Type = ELF::R_ARM_MOVT_PREL;
1564 case ARM::fixup_arm_movw_lo16:
1565 case ARM::fixup_arm_movw_lo16_pcrel:
1566 Type = ELF::R_ARM_MOVW_PREL_NC;
1568 case ARM::fixup_t2_movt_hi16:
1569 case ARM::fixup_t2_movt_hi16_pcrel:
1570 Type = ELF::R_ARM_THM_MOVT_PREL;
1572 case ARM::fixup_t2_movw_lo16:
1573 case ARM::fixup_t2_movw_lo16_pcrel:
1574 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1578 switch ((unsigned)Fixup.getKind()) {
1579 default: llvm_unreachable("invalid fixup kind!");
1582 default: llvm_unreachable("Unsupported Modifier"); break;
1583 case MCSymbolRefExpr::VK_ARM_GOT:
1584 Type = ELF::R_ARM_GOT_BREL;
1586 case MCSymbolRefExpr::VK_ARM_TLSGD:
1587 Type = ELF::R_ARM_TLS_GD32;
1589 case MCSymbolRefExpr::VK_ARM_TPOFF:
1590 Type = ELF::R_ARM_TLS_LE32;
1592 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1593 Type = ELF::R_ARM_TLS_IE32;
1595 case MCSymbolRefExpr::VK_None:
1596 Type = ELF::R_ARM_ABS32;
1598 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1599 Type = ELF::R_ARM_GOTOFF32;
1603 case ARM::fixup_arm_ldst_pcrel_12:
1604 case ARM::fixup_arm_pcrel_10:
1605 case ARM::fixup_arm_adr_pcrel_12:
1606 case ARM::fixup_arm_thumb_bl:
1607 case ARM::fixup_arm_thumb_cb:
1608 case ARM::fixup_arm_thumb_cp:
1609 case ARM::fixup_arm_thumb_br:
1610 assert(0 && "Unimplemented");
1612 case ARM::fixup_arm_uncondbranch:
1613 Type = ELF::R_ARM_CALL;
1615 case ARM::fixup_arm_condbranch:
1616 Type = ELF::R_ARM_JUMP24;
1618 case ARM::fixup_arm_movt_hi16:
1619 Type = ELF::R_ARM_MOVT_ABS;
1621 case ARM::fixup_arm_movw_lo16:
1622 Type = ELF::R_ARM_MOVW_ABS_NC;
1624 case ARM::fixup_t2_movt_hi16:
1625 Type = ELF::R_ARM_THM_MOVT_ABS;
1627 case ARM::fixup_t2_movw_lo16:
1628 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1633 if (RelocNeedsGOT(Modifier))
1639 //===- MBlazeELFObjectWriter -------------------------------------------===//
1641 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1643 bool IsLittleEndian)
1644 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1647 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1650 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1651 const MCFixup &Fixup,
1653 bool IsRelocWithSymbol,
1655 // determine the type of the relocation
1658 switch ((unsigned)Fixup.getKind()) {
1660 llvm_unreachable("Unimplemented");
1662 Type = ELF::R_MICROBLAZE_64_PCREL;
1665 Type = ELF::R_MICROBLAZE_32_PCREL;
1669 switch ((unsigned)Fixup.getKind()) {
1670 default: llvm_unreachable("invalid fixup kind!");
1672 Type = ((IsRelocWithSymbol || Addend !=0)
1673 ? ELF::R_MICROBLAZE_32
1674 : ELF::R_MICROBLAZE_64);
1677 Type = ELF::R_MICROBLAZE_32;
1684 //===- X86ELFObjectWriter -------------------------------------------===//
1687 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1689 bool IsLittleEndian)
1690 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1693 X86ELFObjectWriter::~X86ELFObjectWriter()
1696 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1697 const MCFixup &Fixup,
1699 bool IsRelocWithSymbol,
1701 // determine the type of the relocation
1703 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1704 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1708 switch ((unsigned)Fixup.getKind()) {
1709 default: llvm_unreachable("invalid fixup kind!");
1711 assert(Modifier == MCSymbolRefExpr::VK_None);
1712 Type = ELF::R_X86_64_PC64;
1714 case X86::reloc_signed_4byte:
1715 case X86::reloc_riprel_4byte_movq_load:
1716 case FK_Data_4: // FIXME?
1717 case X86::reloc_riprel_4byte:
1721 llvm_unreachable("Unimplemented");
1722 case MCSymbolRefExpr::VK_None:
1723 Type = ELF::R_X86_64_PC32;
1725 case MCSymbolRefExpr::VK_PLT:
1726 Type = ELF::R_X86_64_PLT32;
1728 case MCSymbolRefExpr::VK_GOTPCREL:
1729 Type = ELF::R_X86_64_GOTPCREL;
1731 case MCSymbolRefExpr::VK_GOTTPOFF:
1732 Type = ELF::R_X86_64_GOTTPOFF;
1734 case MCSymbolRefExpr::VK_TLSGD:
1735 Type = ELF::R_X86_64_TLSGD;
1737 case MCSymbolRefExpr::VK_TLSLD:
1738 Type = ELF::R_X86_64_TLSLD;
1743 assert(Modifier == MCSymbolRefExpr::VK_None);
1744 Type = ELF::R_X86_64_PC16;
1747 assert(Modifier == MCSymbolRefExpr::VK_None);
1748 Type = ELF::R_X86_64_PC8;
1752 switch ((unsigned)Fixup.getKind()) {
1753 default: llvm_unreachable("invalid fixup kind!");
1754 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1755 case X86::reloc_signed_4byte:
1756 assert(isInt<32>(Target.getConstant()));
1759 llvm_unreachable("Unimplemented");
1760 case MCSymbolRefExpr::VK_None:
1761 Type = ELF::R_X86_64_32S;
1763 case MCSymbolRefExpr::VK_GOT:
1764 Type = ELF::R_X86_64_GOT32;
1766 case MCSymbolRefExpr::VK_GOTPCREL:
1767 Type = ELF::R_X86_64_GOTPCREL;
1769 case MCSymbolRefExpr::VK_TPOFF:
1770 Type = ELF::R_X86_64_TPOFF32;
1772 case MCSymbolRefExpr::VK_DTPOFF:
1773 Type = ELF::R_X86_64_DTPOFF32;
1778 Type = ELF::R_X86_64_32;
1780 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1782 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1789 llvm_unreachable("Unimplemented");
1790 case MCSymbolRefExpr::VK_None:
1791 Type = ELF::R_386_PC32;
1793 case MCSymbolRefExpr::VK_PLT:
1794 Type = ELF::R_386_PLT32;
1798 switch ((unsigned)Fixup.getKind()) {
1799 default: llvm_unreachable("invalid fixup kind!");
1801 case X86::reloc_global_offset_table:
1802 Type = ELF::R_386_GOTPC;
1805 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1807 case X86::reloc_signed_4byte:
1812 llvm_unreachable("Unimplemented");
1813 case MCSymbolRefExpr::VK_None:
1814 Type = ELF::R_386_32;
1816 case MCSymbolRefExpr::VK_GOT:
1817 Type = ELF::R_386_GOT32;
1819 case MCSymbolRefExpr::VK_GOTOFF:
1820 Type = ELF::R_386_GOTOFF;
1822 case MCSymbolRefExpr::VK_TLSGD:
1823 Type = ELF::R_386_TLS_GD;
1825 case MCSymbolRefExpr::VK_TPOFF:
1826 Type = ELF::R_386_TLS_LE_32;
1828 case MCSymbolRefExpr::VK_INDNTPOFF:
1829 Type = ELF::R_386_TLS_IE;
1831 case MCSymbolRefExpr::VK_NTPOFF:
1832 Type = ELF::R_386_TLS_LE;
1834 case MCSymbolRefExpr::VK_GOTNTPOFF:
1835 Type = ELF::R_386_TLS_GOTIE;
1837 case MCSymbolRefExpr::VK_TLSLDM:
1838 Type = ELF::R_386_TLS_LDM;
1840 case MCSymbolRefExpr::VK_DTPOFF:
1841 Type = ELF::R_386_TLS_LDO_32;
1845 case FK_Data_2: Type = ELF::R_386_16; break;
1847 case FK_Data_1: Type = ELF::R_386_8; break;
1852 if (RelocNeedsGOT(Modifier))