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);
320 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
321 virtual void WriteSection(MCAssembler &Asm,
322 const SectionIndexMapTy &SectionIndexMap,
323 uint32_t GroupSymbolIndex,
324 uint64_t Offset, uint64_t Size, uint64_t Alignment,
325 const MCSectionELF &Section);
328 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
329 bool IsPCRel, bool IsRelocWithSymbol,
333 //===- X86ELFObjectWriter -------------------------------------------===//
335 class X86ELFObjectWriter : public ELFObjectWriter {
337 X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
339 bool IsLittleEndian);
341 virtual ~X86ELFObjectWriter();
343 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
344 bool IsPCRel, bool IsRelocWithSymbol,
349 //===- ARMELFObjectWriter -------------------------------------------===//
351 class ARMELFObjectWriter : public ELFObjectWriter {
353 // FIXME: MCAssembler can't yet return the Subtarget,
354 enum { DefaultEABIVersion = 0x05000000U };
356 ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
358 bool IsLittleEndian);
360 virtual ~ARMELFObjectWriter();
362 virtual void WriteEFlags();
364 virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
365 const MCValue &Target,
369 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
370 bool IsPCRel, bool IsRelocWithSymbol,
374 //===- MBlazeELFObjectWriter -------------------------------------------===//
376 class MBlazeELFObjectWriter : public ELFObjectWriter {
378 MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
380 bool IsLittleEndian);
382 virtual ~MBlazeELFObjectWriter();
384 virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
385 bool IsPCRel, bool IsRelocWithSymbol,
390 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
391 const MCFixupKindInfo &FKI =
392 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
394 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
397 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
401 case MCSymbolRefExpr::VK_GOT:
402 case MCSymbolRefExpr::VK_PLT:
403 case MCSymbolRefExpr::VK_GOTPCREL:
404 case MCSymbolRefExpr::VK_TPOFF:
405 case MCSymbolRefExpr::VK_TLSGD:
406 case MCSymbolRefExpr::VK_GOTTPOFF:
407 case MCSymbolRefExpr::VK_INDNTPOFF:
408 case MCSymbolRefExpr::VK_NTPOFF:
409 case MCSymbolRefExpr::VK_GOTNTPOFF:
410 case MCSymbolRefExpr::VK_TLSLDM:
411 case MCSymbolRefExpr::VK_DTPOFF:
412 case MCSymbolRefExpr::VK_TLSLD:
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 // 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 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
522 const MCAsmLayout &Layout) {
523 if (Data.isCommon() && Data.isExternal())
524 return Data.getCommonAlignment();
526 const MCSymbol &Symbol = Data.getSymbol();
528 if (Symbol.isAbsolute() && Symbol.isVariable()) {
529 if (const MCExpr *Value = Symbol.getVariableValue()) {
531 if (Value->EvaluateAsAbsolute(IntValue, Layout))
532 return (uint64_t)IntValue;
536 if (!Symbol.isInSection())
539 if (Data.getFragment())
540 return Layout.getSymbolOffset(&Data);
545 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
546 const MCAsmLayout &Layout) {
547 // The presence of symbol versions causes undefined symbols and
548 // versions declared with @@@ to be renamed.
550 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
551 ie = Asm.symbol_end(); it != ie; ++it) {
552 const MCSymbol &Alias = it->getSymbol();
553 const MCSymbol &Symbol = Alias.AliasedSymbol();
554 MCSymbolData &SD = Asm.getSymbolData(Symbol);
557 if (&Symbol == &Alias)
560 StringRef AliasName = Alias.getName();
561 size_t Pos = AliasName.find('@');
562 if (Pos == StringRef::npos)
565 // Aliases defined with .symvar copy the binding from the symbol they alias.
566 // This is the first place we are able to copy this information.
567 it->setExternal(SD.isExternal());
568 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
570 StringRef Rest = AliasName.substr(Pos);
571 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
574 // FIXME: produce a better error message.
575 if (Symbol.isUndefined() && Rest.startswith("@@") &&
576 !Rest.startswith("@@@"))
577 report_fatal_error("A @@ version cannot be undefined");
579 Renames.insert(std::make_pair(&Symbol, &Alias));
583 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
584 MCDataFragment *ShndxF,
586 const MCAsmLayout &Layout) {
587 MCSymbolData &OrigData = *MSD.SymbolData;
589 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
591 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
592 Data.getSymbol().isVariable();
594 uint8_t Binding = MCELF::GetBinding(OrigData);
595 uint8_t Visibility = MCELF::GetVisibility(OrigData);
596 uint8_t Type = MCELF::GetType(Data);
598 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
599 uint8_t Other = Visibility;
601 uint64_t Value = SymbolValue(Data, Layout);
604 assert(!(Data.isCommon() && !Data.isExternal()));
606 const MCExpr *ESize = Data.getSize();
609 if (!ESize->EvaluateAsAbsolute(Res, Layout))
610 report_fatal_error("Size expression must be absolute.");
614 // Write out the symbol table entry
615 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
616 Size, Other, MSD.SectionIndex, IsReserved);
619 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
620 MCDataFragment *ShndxF,
621 const MCAssembler &Asm,
622 const MCAsmLayout &Layout,
623 const SectionIndexMapTy &SectionIndexMap) {
624 // The string table must be emitted first because we need the index
625 // into the string table for all the symbol names.
626 assert(StringTable.size() && "Missing string table");
628 // FIXME: Make sure the start of the symbol table is aligned.
630 // The first entry is the undefined symbol entry.
631 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
633 // Write the symbol table entries.
634 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
635 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
636 ELFSymbolData &MSD = LocalSymbolData[i];
637 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
640 // Write out a symbol table entry for each regular section.
641 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
643 const MCSectionELF &Section =
644 static_cast<const MCSectionELF&>(i->getSection());
645 if (Section.getType() == ELF::SHT_RELA ||
646 Section.getType() == ELF::SHT_REL ||
647 Section.getType() == ELF::SHT_STRTAB ||
648 Section.getType() == ELF::SHT_SYMTAB)
650 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
651 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
652 LastLocalSymbolIndex++;
655 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
656 ELFSymbolData &MSD = ExternalSymbolData[i];
657 MCSymbolData &Data = *MSD.SymbolData;
658 assert(((Data.getFlags() & ELF_STB_Global) ||
659 (Data.getFlags() & ELF_STB_Weak)) &&
660 "External symbol requires STB_GLOBAL or STB_WEAK flag");
661 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
662 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
663 LastLocalSymbolIndex++;
666 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
667 ELFSymbolData &MSD = UndefinedSymbolData[i];
668 MCSymbolData &Data = *MSD.SymbolData;
669 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
670 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
671 LastLocalSymbolIndex++;
675 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
676 const MCValue &Target,
677 const MCFragment &F) const {
678 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
679 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
680 const MCSymbol *Renamed = Renames.lookup(&Symbol);
681 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
683 if (ASymbol.isUndefined()) {
689 if (SD.isExternal()) {
695 const MCSectionELF &Section =
696 static_cast<const MCSectionELF&>(ASymbol.getSection());
697 const SectionKind secKind = Section.getKind();
700 return ExplicitRelSym(Asm, Target, F, true);
702 if (secKind.isThreadLocal()) {
708 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
709 const MCSectionELF &Sec2 =
710 static_cast<const MCSectionELF&>(F.getParent()->getSection());
712 if (&Sec2 != &Section &&
713 (Kind == MCSymbolRefExpr::VK_PLT ||
714 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
715 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
721 if (Section.getFlags() & ELF::SHF_MERGE) {
722 if (Target.getConstant() == 0)
729 return ExplicitRelSym(Asm, Target, F, false);
733 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
734 const MCAsmLayout &Layout,
735 const MCFragment *Fragment,
736 const MCFixup &Fixup,
738 uint64_t &FixedValue) {
741 int64_t Value = Target.getConstant();
742 const MCSymbol *RelocSymbol = NULL;
744 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
745 if (!Target.isAbsolute()) {
746 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
747 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
748 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
750 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
751 const MCSymbol &SymbolB = RefB->getSymbol();
752 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
755 // Offset of the symbol in the section
756 int64_t a = Layout.getSymbolOffset(&SDB);
758 // Ofeset of the relocation in the section
759 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
764 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
765 MCFragment *F = SD.getFragment();
767 Index = F->getParent()->getOrdinal() + 1;
769 // Offset of the symbol in the section
770 Value += Layout.getSymbolOffset(&SD);
772 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
773 WeakrefUsedInReloc.insert(RelocSymbol);
775 UsedInReloc.insert(RelocSymbol);
779 // Compensate for the addend on i386.
785 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
786 (RelocSymbol != 0), Addend);
788 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
791 if (!hasRelocationAddend())
793 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
794 Relocations[Fragment->getParent()].push_back(ERE);
799 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
801 MCSymbolData &SD = Asm.getSymbolData(*S);
802 return SD.getIndex();
805 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
806 const MCSymbolData &Data,
807 bool Used, bool Renamed) {
808 if (Data.getFlags() & ELF_Other_Weakref)
817 const MCSymbol &Symbol = Data.getSymbol();
819 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
822 const MCSymbol &A = Symbol.AliasedSymbol();
823 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
826 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
827 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
830 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
833 if (Symbol.isTemporary())
839 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
840 bool isUsedInReloc) {
841 if (Data.isExternal())
844 const MCSymbol &Symbol = Data.getSymbol();
845 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
847 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
848 if (isSignature && !isUsedInReloc)
857 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
858 SectionIndexMapTy &SectionIndexMap) {
860 for (MCAssembler::iterator it = Asm.begin(),
861 ie = Asm.end(); it != ie; ++it) {
862 const MCSectionELF &Section =
863 static_cast<const MCSectionELF &>(it->getSection());
864 if (Section.getType() != ELF::SHT_GROUP)
866 SectionIndexMap[&Section] = Index++;
869 for (MCAssembler::iterator it = Asm.begin(),
870 ie = Asm.end(); it != ie; ++it) {
871 const MCSectionELF &Section =
872 static_cast<const MCSectionELF &>(it->getSection());
873 if (Section.getType() == ELF::SHT_GROUP)
875 SectionIndexMap[&Section] = Index++;
879 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
880 const SectionIndexMapTy &SectionIndexMap,
881 RevGroupMapTy RevGroupMap) {
882 // FIXME: Is this the correct place to do this?
884 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
885 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
886 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
887 Data.setExternal(true);
888 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
891 // Build section lookup table.
892 int NumRegularSections = Asm.size();
894 // Index 0 is always the empty string.
895 StringMap<uint64_t> StringIndexMap;
896 StringTable += '\x00';
898 // Add the data for the symbols.
899 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
900 ie = Asm.symbol_end(); it != ie; ++it) {
901 const MCSymbol &Symbol = it->getSymbol();
903 bool Used = UsedInReloc.count(&Symbol);
904 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
905 bool isSignature = RevGroupMap.count(&Symbol);
907 if (!isInSymtab(Asm, *it,
908 Used || WeakrefUsed || isSignature,
909 Renames.count(&Symbol)))
914 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
916 // Undefined symbols are global, but this is the first place we
917 // are able to set it.
918 bool Local = isLocal(*it, isSignature, Used);
919 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
920 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
921 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
922 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
925 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
926 MCELF::SetBinding(*it, ELF::STB_WEAK);
928 if (it->isCommon()) {
930 MSD.SectionIndex = ELF::SHN_COMMON;
931 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
932 MSD.SectionIndex = ELF::SHN_ABS;
933 } else if (RefSymbol.isUndefined()) {
934 if (isSignature && !Used)
935 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
937 MSD.SectionIndex = ELF::SHN_UNDEF;
939 const MCSectionELF &Section =
940 static_cast<const MCSectionELF&>(RefSymbol.getSection());
941 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
942 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
943 NeedsSymtabShndx = true;
944 assert(MSD.SectionIndex && "Invalid section index!");
947 // The @@@ in symbol version is replaced with @ in undefined symbols and
948 // @@ in defined ones.
949 StringRef Name = Symbol.getName();
952 size_t Pos = Name.find("@@@");
953 if (Pos != StringRef::npos) {
954 Buf += Name.substr(0, Pos);
955 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
956 Buf += Name.substr(Pos + Skip);
960 uint64_t &Entry = StringIndexMap[Name];
962 Entry = StringTable.size();
964 StringTable += '\x00';
966 MSD.StringIndex = Entry;
967 if (MSD.SectionIndex == ELF::SHN_UNDEF)
968 UndefinedSymbolData.push_back(MSD);
970 LocalSymbolData.push_back(MSD);
972 ExternalSymbolData.push_back(MSD);
975 // Symbols are required to be in lexicographic order.
976 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
977 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
978 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
980 // Set the symbol indices. Local symbols must come before all other
981 // symbols with non-local bindings.
983 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
984 LocalSymbolData[i].SymbolData->setIndex(Index++);
986 Index += NumRegularSections;
988 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
989 ExternalSymbolData[i].SymbolData->setIndex(Index++);
990 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
991 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
994 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
995 const MCSectionData &SD) {
996 if (!Relocations[&SD].empty()) {
997 MCContext &Ctx = Asm.getContext();
998 const MCSectionELF *RelaSection;
999 const MCSectionELF &Section =
1000 static_cast<const MCSectionELF&>(SD.getSection());
1002 const StringRef SectionName = Section.getSectionName();
1003 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1004 RelaSectionName += SectionName;
1007 if (hasRelocationAddend())
1008 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1010 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1012 RelaSection = Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1013 ELF::SHT_RELA : ELF::SHT_REL, 0,
1014 SectionKind::getReadOnly(),
1017 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1018 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1020 MCDataFragment *F = new MCDataFragment(&RelaSD);
1022 WriteRelocationsFragment(Asm, F, &SD);
1026 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1027 uint64_t Flags, uint64_t Address,
1028 uint64_t Offset, uint64_t Size,
1029 uint32_t Link, uint32_t Info,
1031 uint64_t EntrySize) {
1032 Write32(Name); // sh_name: index into string table
1033 Write32(Type); // sh_type
1034 WriteWord(Flags); // sh_flags
1035 WriteWord(Address); // sh_addr
1036 WriteWord(Offset); // sh_offset
1037 WriteWord(Size); // sh_size
1038 Write32(Link); // sh_link
1039 Write32(Info); // sh_info
1040 WriteWord(Alignment); // sh_addralign
1041 WriteWord(EntrySize); // sh_entsize
1044 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1046 const MCSectionData *SD) {
1047 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1048 // sort by the r_offset just like gnu as does
1049 array_pod_sort(Relocs.begin(), Relocs.end());
1051 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1052 ELFRelocationEntry entry = Relocs[e - i - 1];
1056 else if (entry.Index < 0)
1057 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1059 entry.Index += LocalSymbolData.size();
1061 String64(*F, entry.r_offset);
1063 struct ELF::Elf64_Rela ERE64;
1064 ERE64.setSymbolAndType(entry.Index, entry.Type);
1065 String64(*F, ERE64.r_info);
1067 if (hasRelocationAddend())
1068 String64(*F, entry.r_addend);
1070 String32(*F, entry.r_offset);
1072 struct ELF::Elf32_Rela ERE32;
1073 ERE32.setSymbolAndType(entry.Index, entry.Type);
1074 String32(*F, ERE32.r_info);
1076 if (hasRelocationAddend())
1077 String32(*F, entry.r_addend);
1082 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1083 MCAsmLayout &Layout,
1084 const SectionIndexMapTy &SectionIndexMap) {
1085 MCContext &Ctx = Asm.getContext();
1088 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1090 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1091 const MCSectionELF *ShstrtabSection =
1092 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1093 SectionKind::getReadOnly());
1094 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1095 ShstrtabSD.setAlignment(1);
1096 ShstrtabIndex = Asm.size();
1098 const MCSectionELF *SymtabSection =
1099 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1100 SectionKind::getReadOnly(),
1102 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1103 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1104 SymbolTableIndex = Asm.size();
1106 MCSectionData *SymtabShndxSD = NULL;
1108 if (NeedsSymtabShndx) {
1109 const MCSectionELF *SymtabShndxSection =
1110 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1111 SectionKind::getReadOnly(), 4, "");
1112 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1113 SymtabShndxSD->setAlignment(4);
1116 const MCSection *StrtabSection;
1117 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1118 SectionKind::getReadOnly());
1119 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1120 StrtabSD.setAlignment(1);
1121 StringTableIndex = Asm.size();
1123 WriteRelocations(Asm, Layout);
1126 F = new MCDataFragment(&SymtabSD);
1127 MCDataFragment *ShndxF = NULL;
1128 if (NeedsSymtabShndx) {
1129 ShndxF = new MCDataFragment(SymtabShndxSD);
1131 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1133 F = new MCDataFragment(&StrtabSD);
1134 F->getContents().append(StringTable.begin(), StringTable.end());
1136 F = new MCDataFragment(&ShstrtabSD);
1138 // Section header string table.
1140 // The first entry of a string table holds a null character so skip
1143 F->getContents() += '\x00';
1145 StringMap<uint64_t> SecStringMap;
1146 for (MCAssembler::const_iterator it = Asm.begin(),
1147 ie = Asm.end(); it != ie; ++it) {
1148 const MCSectionELF &Section =
1149 static_cast<const MCSectionELF&>(it->getSection());
1150 // FIXME: We could merge suffixes like in .text and .rela.text.
1152 StringRef Name = Section.getSectionName();
1153 if (SecStringMap.count(Name)) {
1154 SectionStringTableIndex[&Section] = SecStringMap[Name];
1157 // Remember the index into the string table so we can write it
1158 // into the sh_name field of the section header table.
1159 SectionStringTableIndex[&Section] = Index;
1160 SecStringMap[Name] = Index;
1162 Index += Name.size() + 1;
1163 F->getContents() += Name;
1164 F->getContents() += '\x00';
1168 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1169 MCAsmLayout &Layout,
1170 GroupMapTy &GroupMap,
1171 RevGroupMapTy &RevGroupMap) {
1172 // Create the .note.GNU-stack section if needed.
1173 MCContext &Ctx = Asm.getContext();
1174 if (Asm.getNoExecStack()) {
1175 const MCSectionELF *GnuStackSection =
1176 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1177 SectionKind::getReadOnly());
1178 Asm.getOrCreateSectionData(*GnuStackSection);
1182 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1184 const MCSectionELF &Section =
1185 static_cast<const MCSectionELF&>(it->getSection());
1186 if (!(Section.getFlags() & ELF::SHF_GROUP))
1189 const MCSymbol *SignatureSymbol = Section.getGroup();
1190 Asm.getOrCreateSymbolData(*SignatureSymbol);
1191 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1193 Group = Ctx.CreateELFGroupSection();
1194 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1195 Data.setAlignment(4);
1196 MCDataFragment *F = new MCDataFragment(&Data);
1197 String32(*F, ELF::GRP_COMDAT);
1199 GroupMap[Group] = SignatureSymbol;
1202 // Add sections to the groups
1204 unsigned NumGroups = RevGroupMap.size();
1205 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1206 it != ie; ++it, ++Index) {
1207 const MCSectionELF &Section =
1208 static_cast<const MCSectionELF&>(it->getSection());
1209 if (!(Section.getFlags() & ELF::SHF_GROUP))
1211 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1212 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1213 // FIXME: we could use the previous fragment
1214 MCDataFragment *F = new MCDataFragment(&Data);
1215 String32(*F, NumGroups + Index);
1219 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1220 const SectionIndexMapTy &SectionIndexMap,
1221 uint32_t GroupSymbolIndex,
1222 uint64_t Offset, uint64_t Size,
1224 const MCSectionELF &Section) {
1225 uint64_t sh_link = 0;
1226 uint64_t sh_info = 0;
1228 switch(Section.getType()) {
1229 case ELF::SHT_DYNAMIC:
1230 sh_link = SectionStringTableIndex[&Section];
1235 case ELF::SHT_RELA: {
1236 const MCSectionELF *SymtabSection;
1237 const MCSectionELF *InfoSection;
1238 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1240 SectionKind::getReadOnly());
1241 sh_link = SectionIndexMap.lookup(SymtabSection);
1242 assert(sh_link && ".symtab not found");
1244 // Remove ".rel" and ".rela" prefixes.
1245 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1246 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1248 InfoSection = Asm.getContext().getELFSection(SectionName,
1249 ELF::SHT_PROGBITS, 0,
1250 SectionKind::getReadOnly());
1251 sh_info = SectionIndexMap.lookup(InfoSection);
1255 case ELF::SHT_SYMTAB:
1256 case ELF::SHT_DYNSYM:
1257 sh_link = StringTableIndex;
1258 sh_info = LastLocalSymbolIndex;
1261 case ELF::SHT_SYMTAB_SHNDX:
1262 sh_link = SymbolTableIndex;
1265 case ELF::SHT_PROGBITS:
1266 case ELF::SHT_STRTAB:
1267 case ELF::SHT_NOBITS:
1270 case ELF::SHT_ARM_ATTRIBUTES:
1271 case ELF::SHT_INIT_ARRAY:
1272 case ELF::SHT_FINI_ARRAY:
1273 case ELF::SHT_PREINIT_ARRAY:
1274 case ELF::SHT_X86_64_UNWIND:
1278 case ELF::SHT_GROUP: {
1279 sh_link = SymbolTableIndex;
1280 sh_info = GroupSymbolIndex;
1285 assert(0 && "FIXME: sh_type value not supported!");
1289 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1290 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1291 Alignment, Section.getEntrySize());
1294 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1295 return SD.getOrdinal() == ~UINT32_C(0) &&
1296 !SD.getSection().isVirtualSection();
1299 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1301 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1303 const MCFragment &F = *i;
1304 assert(F.getKind() == MCFragment::FT_Data);
1305 Ret += cast<MCDataFragment>(F).getContents().size();
1310 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1311 const MCSectionData &SD) {
1312 if (IsELFMetaDataSection(SD))
1313 return DataSectionSize(SD);
1314 return Layout.getSectionFileSize(&SD);
1317 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1318 const MCSectionData &SD) {
1319 if (IsELFMetaDataSection(SD))
1320 return DataSectionSize(SD);
1321 return Layout.getSectionAddressSize(&SD);
1324 void ELFObjectWriter::WriteDataSectionData(ELFObjectWriter *W,
1325 const MCSectionData &SD) {
1326 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1328 const MCFragment &F = *i;
1329 assert(F.getKind() == MCFragment::FT_Data);
1330 W->WriteBytes(cast<MCDataFragment>(F).getContents().str());
1334 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1335 const MCAsmLayout &Layout) {
1336 GroupMapTy GroupMap;
1337 RevGroupMapTy RevGroupMap;
1338 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1341 SectionIndexMapTy SectionIndexMap;
1343 ComputeIndexMap(Asm, SectionIndexMap);
1345 // Compute symbol table information.
1346 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1348 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1349 const_cast<MCAsmLayout&>(Layout),
1352 // Update to include the metadata sections.
1353 ComputeIndexMap(Asm, SectionIndexMap);
1355 // Add 1 for the null section.
1356 unsigned NumSections = Asm.size() + 1;
1357 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1358 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1359 sizeof(ELF::Elf32_Ehdr);
1360 uint64_t FileOff = HeaderSize;
1362 std::vector<const MCSectionELF*> Sections;
1363 Sections.resize(NumSections);
1365 for (SectionIndexMapTy::const_iterator i=
1366 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1367 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1368 Sections[p.second] = p.first;
1371 for (unsigned i = 1; i < NumSections; ++i) {
1372 const MCSectionELF &Section = *Sections[i];
1373 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1375 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1377 // Get the size of the section in the output file (including padding).
1378 FileOff += GetSectionFileSize(Layout, SD);
1381 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1383 // Write out the ELF header ...
1384 WriteHeader(FileOff - HeaderSize, NumSections);
1386 FileOff = HeaderSize;
1388 // ... then all of the sections ...
1389 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1391 for (unsigned i = 1; i < NumSections; ++i) {
1392 const MCSectionELF &Section = *Sections[i];
1393 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1395 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1396 WriteZeros(Padding);
1399 // Remember the offset into the file for this section.
1400 SectionOffsetMap[&Section] = FileOff;
1402 FileOff += GetSectionFileSize(Layout, SD);
1404 if (IsELFMetaDataSection(SD))
1405 WriteDataSectionData(this, SD);
1407 Asm.WriteSectionData(&SD, Layout);
1410 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1411 WriteZeros(Padding);
1414 // ... and then the section header table.
1415 // Should we align the section header table?
1417 // Null section first.
1418 uint64_t FirstSectionSize =
1419 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1420 uint32_t FirstSectionLink =
1421 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1422 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1424 for (unsigned i = 1; i < NumSections; ++i) {
1425 const MCSectionELF &Section = *Sections[i];
1426 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1427 uint32_t GroupSymbolIndex;
1428 if (Section.getType() != ELF::SHT_GROUP)
1429 GroupSymbolIndex = 0;
1431 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1433 uint64_t Size = GetSectionAddressSize(Layout, SD);
1435 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1436 SectionOffsetMap[&Section], Size,
1437 SD.getAlignment(), Section);
1441 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1443 bool IsLittleEndian) {
1444 switch (MOTW->getEMachine()) {
1446 case ELF::EM_X86_64:
1447 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1449 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1450 case ELF::EM_MBLAZE:
1451 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1452 default: llvm_unreachable("Unsupported architecture"); break;
1457 /// START OF SUBCLASSES for ELFObjectWriter
1458 //===- ARMELFObjectWriter -------------------------------------------===//
1460 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1462 bool IsLittleEndian)
1463 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1466 ARMELFObjectWriter::~ARMELFObjectWriter()
1469 // FIXME: get the real EABI Version from the Triple.
1470 void ARMELFObjectWriter::WriteEFlags() {
1471 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1474 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1475 // I.e. not as an offset to a section symbol.
1476 // This code is a first-cut approximation of what ARM/gcc does.
1478 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1479 const MCValue &Target,
1480 const MCFragment &F,
1482 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1483 bool EmitThisSym = false;
1486 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1487 .Case("_MergedGlobals", true)
1490 EmitThisSym = StringSwitch<bool>(Symbol.getName())
1491 .Case("_MergedGlobals", true)
1492 .StartsWith(".L.str", true)
1497 if (! Symbol.isTemporary())
1502 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1503 const MCFixup &Fixup,
1505 bool IsRelocWithSymbol,
1507 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1508 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1512 switch ((unsigned)Fixup.getKind()) {
1513 default: assert(0 && "Unimplemented");
1516 default: llvm_unreachable("Unsupported Modifier");
1517 case MCSymbolRefExpr::VK_None:
1518 Type = ELF::R_ARM_BASE_PREL;
1520 case MCSymbolRefExpr::VK_ARM_TLSGD:
1521 assert(0 && "unimplemented");
1523 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1524 Type = ELF::R_ARM_TLS_IE32;
1528 case ARM::fixup_arm_uncondbranch:
1530 case MCSymbolRefExpr::VK_ARM_PLT:
1531 Type = ELF::R_ARM_PLT32;
1534 Type = ELF::R_ARM_CALL;
1538 case ARM::fixup_arm_condbranch:
1539 Type = ELF::R_ARM_JUMP24;
1541 case ARM::fixup_arm_movt_hi16:
1542 case ARM::fixup_arm_movt_hi16_pcrel:
1543 Type = ELF::R_ARM_MOVT_PREL;
1545 case ARM::fixup_arm_movw_lo16:
1546 case ARM::fixup_arm_movw_lo16_pcrel:
1547 Type = ELF::R_ARM_MOVW_PREL_NC;
1549 case ARM::fixup_t2_movt_hi16:
1550 case ARM::fixup_t2_movt_hi16_pcrel:
1551 Type = ELF::R_ARM_THM_MOVT_PREL;
1553 case ARM::fixup_t2_movw_lo16:
1554 case ARM::fixup_t2_movw_lo16_pcrel:
1555 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1559 switch ((unsigned)Fixup.getKind()) {
1560 default: llvm_unreachable("invalid fixup kind!");
1563 default: llvm_unreachable("Unsupported Modifier"); break;
1564 case MCSymbolRefExpr::VK_ARM_GOT:
1565 Type = ELF::R_ARM_GOT_BREL;
1567 case MCSymbolRefExpr::VK_ARM_TLSGD:
1568 Type = ELF::R_ARM_TLS_GD32;
1570 case MCSymbolRefExpr::VK_ARM_TPOFF:
1571 Type = ELF::R_ARM_TLS_LE32;
1573 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1574 Type = ELF::R_ARM_TLS_IE32;
1576 case MCSymbolRefExpr::VK_None:
1577 Type = ELF::R_ARM_ABS32;
1579 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1580 Type = ELF::R_ARM_GOTOFF32;
1584 case ARM::fixup_arm_ldst_pcrel_12:
1585 case ARM::fixup_arm_pcrel_10:
1586 case ARM::fixup_arm_adr_pcrel_12:
1587 case ARM::fixup_arm_thumb_bl:
1588 case ARM::fixup_arm_thumb_cb:
1589 case ARM::fixup_arm_thumb_cp:
1590 case ARM::fixup_arm_thumb_br:
1591 assert(0 && "Unimplemented");
1593 case ARM::fixup_arm_uncondbranch:
1594 Type = ELF::R_ARM_CALL;
1596 case ARM::fixup_arm_condbranch:
1597 Type = ELF::R_ARM_JUMP24;
1599 case ARM::fixup_arm_movt_hi16:
1600 Type = ELF::R_ARM_MOVT_ABS;
1602 case ARM::fixup_arm_movw_lo16:
1603 Type = ELF::R_ARM_MOVW_ABS_NC;
1605 case ARM::fixup_t2_movt_hi16:
1606 Type = ELF::R_ARM_THM_MOVT_ABS;
1608 case ARM::fixup_t2_movw_lo16:
1609 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1614 if (RelocNeedsGOT(Modifier))
1620 //===- MBlazeELFObjectWriter -------------------------------------------===//
1622 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1624 bool IsLittleEndian)
1625 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1628 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1631 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1632 const MCFixup &Fixup,
1634 bool IsRelocWithSymbol,
1636 // determine the type of the relocation
1639 switch ((unsigned)Fixup.getKind()) {
1641 llvm_unreachable("Unimplemented");
1643 Type = ELF::R_MICROBLAZE_64_PCREL;
1646 Type = ELF::R_MICROBLAZE_32_PCREL;
1650 switch ((unsigned)Fixup.getKind()) {
1651 default: llvm_unreachable("invalid fixup kind!");
1653 Type = ((IsRelocWithSymbol || Addend !=0)
1654 ? ELF::R_MICROBLAZE_32
1655 : ELF::R_MICROBLAZE_64);
1658 Type = ELF::R_MICROBLAZE_32;
1665 //===- X86ELFObjectWriter -------------------------------------------===//
1668 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1670 bool IsLittleEndian)
1671 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1674 X86ELFObjectWriter::~X86ELFObjectWriter()
1677 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1678 const MCFixup &Fixup,
1680 bool IsRelocWithSymbol,
1682 // determine the type of the relocation
1684 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1685 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1689 switch ((unsigned)Fixup.getKind()) {
1690 default: llvm_unreachable("invalid fixup kind!");
1692 assert(Modifier == MCSymbolRefExpr::VK_None);
1693 Type = ELF::R_X86_64_PC64;
1695 case X86::reloc_signed_4byte:
1696 case X86::reloc_riprel_4byte_movq_load:
1697 case FK_Data_4: // FIXME?
1698 case X86::reloc_riprel_4byte:
1702 llvm_unreachable("Unimplemented");
1703 case MCSymbolRefExpr::VK_None:
1704 Type = ELF::R_X86_64_PC32;
1706 case MCSymbolRefExpr::VK_PLT:
1707 Type = ELF::R_X86_64_PLT32;
1709 case MCSymbolRefExpr::VK_GOTPCREL:
1710 Type = ELF::R_X86_64_GOTPCREL;
1712 case MCSymbolRefExpr::VK_GOTTPOFF:
1713 Type = ELF::R_X86_64_GOTTPOFF;
1715 case MCSymbolRefExpr::VK_TLSGD:
1716 Type = ELF::R_X86_64_TLSGD;
1718 case MCSymbolRefExpr::VK_TLSLD:
1719 Type = ELF::R_X86_64_TLSLD;
1724 assert(Modifier == MCSymbolRefExpr::VK_None);
1725 Type = ELF::R_X86_64_PC16;
1728 assert(Modifier == MCSymbolRefExpr::VK_None);
1729 Type = ELF::R_X86_64_PC8;
1733 switch ((unsigned)Fixup.getKind()) {
1734 default: llvm_unreachable("invalid fixup kind!");
1735 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1736 case X86::reloc_signed_4byte:
1737 assert(isInt<32>(Target.getConstant()));
1740 llvm_unreachable("Unimplemented");
1741 case MCSymbolRefExpr::VK_None:
1742 Type = ELF::R_X86_64_32S;
1744 case MCSymbolRefExpr::VK_GOT:
1745 Type = ELF::R_X86_64_GOT32;
1747 case MCSymbolRefExpr::VK_GOTPCREL:
1748 Type = ELF::R_X86_64_GOTPCREL;
1750 case MCSymbolRefExpr::VK_TPOFF:
1751 Type = ELF::R_X86_64_TPOFF32;
1753 case MCSymbolRefExpr::VK_DTPOFF:
1754 Type = ELF::R_X86_64_DTPOFF32;
1759 Type = ELF::R_X86_64_32;
1761 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1763 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1770 llvm_unreachable("Unimplemented");
1771 case MCSymbolRefExpr::VK_None:
1772 Type = ELF::R_386_PC32;
1774 case MCSymbolRefExpr::VK_PLT:
1775 Type = ELF::R_386_PLT32;
1779 switch ((unsigned)Fixup.getKind()) {
1780 default: llvm_unreachable("invalid fixup kind!");
1782 case X86::reloc_global_offset_table:
1783 Type = ELF::R_386_GOTPC;
1786 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1788 case X86::reloc_signed_4byte:
1793 llvm_unreachable("Unimplemented");
1794 case MCSymbolRefExpr::VK_None:
1795 Type = ELF::R_386_32;
1797 case MCSymbolRefExpr::VK_GOT:
1798 Type = ELF::R_386_GOT32;
1800 case MCSymbolRefExpr::VK_GOTOFF:
1801 Type = ELF::R_386_GOTOFF;
1803 case MCSymbolRefExpr::VK_TLSGD:
1804 Type = ELF::R_386_TLS_GD;
1806 case MCSymbolRefExpr::VK_TPOFF:
1807 Type = ELF::R_386_TLS_LE_32;
1809 case MCSymbolRefExpr::VK_INDNTPOFF:
1810 Type = ELF::R_386_TLS_IE;
1812 case MCSymbolRefExpr::VK_NTPOFF:
1813 Type = ELF::R_386_TLS_LE;
1815 case MCSymbolRefExpr::VK_GOTNTPOFF:
1816 Type = ELF::R_386_TLS_GOTIE;
1818 case MCSymbolRefExpr::VK_TLSLDM:
1819 Type = ELF::R_386_TLS_LDM;
1821 case MCSymbolRefExpr::VK_DTPOFF:
1822 Type = ELF::R_386_TLS_LDO_32;
1826 case FK_Data_2: Type = ELF::R_386_16; break;
1828 case FK_Data_1: Type = ELF::R_386_8; break;
1833 if (RelocNeedsGOT(Modifier))