1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "ELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAsmBackend.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCSectionELF.h"
23 #include "llvm/MC/MCValue.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ELF.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringSwitch.h"
31 #include "../Target/Mips/MCTargetDesc/MipsFixupKinds.h"
32 #include "../Target/X86/MCTargetDesc/X86FixupKinds.h"
33 #include "../Target/ARM/MCTargetDesc/ARMFixupKinds.h"
34 #include "../Target/PowerPC/MCTargetDesc/PPCFixupKinds.h"
40 #define DEBUG_TYPE "reloc-info"
42 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
43 const MCFixupKindInfo &FKI =
44 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
46 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
49 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
53 case MCSymbolRefExpr::VK_GOT:
54 case MCSymbolRefExpr::VK_PLT:
55 case MCSymbolRefExpr::VK_GOTPCREL:
56 case MCSymbolRefExpr::VK_GOTOFF:
57 case MCSymbolRefExpr::VK_TPOFF:
58 case MCSymbolRefExpr::VK_TLSGD:
59 case MCSymbolRefExpr::VK_GOTTPOFF:
60 case MCSymbolRefExpr::VK_INDNTPOFF:
61 case MCSymbolRefExpr::VK_NTPOFF:
62 case MCSymbolRefExpr::VK_GOTNTPOFF:
63 case MCSymbolRefExpr::VK_TLSLDM:
64 case MCSymbolRefExpr::VK_DTPOFF:
65 case MCSymbolRefExpr::VK_TLSLD:
70 ELFObjectWriter::~ELFObjectWriter()
73 // Emit the ELF header.
74 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
75 unsigned NumberOfSections) {
81 // emitWord method behaves differently for ELF32 and ELF64, writing
82 // 4 bytes in the former and 8 in the latter.
84 Write8(0x7f); // e_ident[EI_MAG0]
85 Write8('E'); // e_ident[EI_MAG1]
86 Write8('L'); // e_ident[EI_MAG2]
87 Write8('F'); // e_ident[EI_MAG3]
89 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
92 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
94 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
96 switch (TargetObjectWriter->getOSType()) {
97 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
98 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
99 default: Write8(ELF::ELFOSABI_NONE); break;
101 Write8(0); // e_ident[EI_ABIVERSION]
103 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
105 Write16(ELF::ET_REL); // e_type
107 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
109 Write32(ELF::EV_CURRENT); // e_version
110 WriteWord(0); // e_entry, no entry point in .o file
111 WriteWord(0); // e_phoff, no program header for .o
112 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
113 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
115 // e_flags = whatever the target wants
118 // e_ehsize = ELF header size
119 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
121 Write16(0); // e_phentsize = prog header entry size
122 Write16(0); // e_phnum = # prog header entries = 0
124 // e_shentsize = Section header entry size
125 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
127 // e_shnum = # of section header ents
128 if (NumberOfSections >= ELF::SHN_LORESERVE)
129 Write16(ELF::SHN_UNDEF);
131 Write16(NumberOfSections);
133 // e_shstrndx = Section # of '.shstrtab'
134 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
135 Write16(ELF::SHN_XINDEX);
137 Write16(ShstrtabIndex);
140 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
141 MCDataFragment *ShndxF,
143 uint8_t info, uint64_t value,
144 uint64_t size, uint8_t other,
148 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
149 String32(*ShndxF, shndx);
151 String32(*ShndxF, 0);
154 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
155 uint16_t(ELF::SHN_XINDEX) : shndx;
158 String32(*SymtabF, name); // st_name
159 String8(*SymtabF, info); // st_info
160 String8(*SymtabF, other); // st_other
161 String16(*SymtabF, Index); // st_shndx
162 String64(*SymtabF, value); // st_value
163 String64(*SymtabF, size); // st_size
165 String32(*SymtabF, name); // st_name
166 String32(*SymtabF, value); // st_value
167 String32(*SymtabF, size); // st_size
168 String8(*SymtabF, info); // st_info
169 String8(*SymtabF, other); // st_other
170 String16(*SymtabF, Index); // st_shndx
174 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
175 const MCAsmLayout &Layout) {
176 if (Data.isCommon() && Data.isExternal())
177 return Data.getCommonAlignment();
179 const MCSymbol &Symbol = Data.getSymbol();
181 if (Symbol.isAbsolute() && Symbol.isVariable()) {
182 if (const MCExpr *Value = Symbol.getVariableValue()) {
184 if (Value->EvaluateAsAbsolute(IntValue, Layout))
185 return (uint64_t)IntValue;
189 if (!Symbol.isInSection())
193 if (Data.getFragment()) {
194 if (Data.getFlags() & ELF_Other_ThumbFunc)
195 return Layout.getSymbolOffset(&Data)+1;
197 return Layout.getSymbolOffset(&Data);
203 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
204 const MCAsmLayout &Layout) {
205 // The presence of symbol versions causes undefined symbols and
206 // versions declared with @@@ to be renamed.
208 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
209 ie = Asm.symbol_end(); it != ie; ++it) {
210 const MCSymbol &Alias = it->getSymbol();
211 const MCSymbol &Symbol = Alias.AliasedSymbol();
212 MCSymbolData &SD = Asm.getSymbolData(Symbol);
215 if (&Symbol == &Alias)
218 StringRef AliasName = Alias.getName();
219 size_t Pos = AliasName.find('@');
220 if (Pos == StringRef::npos)
223 // Aliases defined with .symvar copy the binding from the symbol they alias.
224 // This is the first place we are able to copy this information.
225 it->setExternal(SD.isExternal());
226 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
228 StringRef Rest = AliasName.substr(Pos);
229 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
232 // FIXME: produce a better error message.
233 if (Symbol.isUndefined() && Rest.startswith("@@") &&
234 !Rest.startswith("@@@"))
235 report_fatal_error("A @@ version cannot be undefined");
237 Renames.insert(std::make_pair(&Symbol, &Alias));
241 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
242 MCDataFragment *ShndxF,
244 const MCAsmLayout &Layout) {
245 MCSymbolData &OrigData = *MSD.SymbolData;
247 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
249 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
250 Data.getSymbol().isVariable();
252 uint8_t Binding = MCELF::GetBinding(OrigData);
253 uint8_t Visibility = MCELF::GetVisibility(OrigData);
254 uint8_t Type = MCELF::GetType(Data);
256 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
257 uint8_t Other = Visibility;
259 uint64_t Value = SymbolValue(Data, Layout);
262 assert(!(Data.isCommon() && !Data.isExternal()));
264 const MCExpr *ESize = Data.getSize();
267 if (!ESize->EvaluateAsAbsolute(Res, Layout))
268 report_fatal_error("Size expression must be absolute.");
272 // Write out the symbol table entry
273 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
274 Size, Other, MSD.SectionIndex, IsReserved);
277 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
278 MCDataFragment *ShndxF,
279 const MCAssembler &Asm,
280 const MCAsmLayout &Layout,
281 const SectionIndexMapTy &SectionIndexMap) {
282 // The string table must be emitted first because we need the index
283 // into the string table for all the symbol names.
284 assert(StringTable.size() && "Missing string table");
286 // FIXME: Make sure the start of the symbol table is aligned.
288 // The first entry is the undefined symbol entry.
289 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
291 // Write the symbol table entries.
292 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
293 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
294 ELFSymbolData &MSD = LocalSymbolData[i];
295 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
298 // Write out a symbol table entry for each regular section.
299 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
301 const MCSectionELF &Section =
302 static_cast<const MCSectionELF&>(i->getSection());
303 if (Section.getType() == ELF::SHT_RELA ||
304 Section.getType() == ELF::SHT_REL ||
305 Section.getType() == ELF::SHT_STRTAB ||
306 Section.getType() == ELF::SHT_SYMTAB ||
307 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
309 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
310 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
312 LastLocalSymbolIndex++;
315 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
316 ELFSymbolData &MSD = ExternalSymbolData[i];
317 MCSymbolData &Data = *MSD.SymbolData;
318 assert(((Data.getFlags() & ELF_STB_Global) ||
319 (Data.getFlags() & ELF_STB_Weak)) &&
320 "External symbol requires STB_GLOBAL or STB_WEAK flag");
321 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
322 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
323 LastLocalSymbolIndex++;
326 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
327 ELFSymbolData &MSD = UndefinedSymbolData[i];
328 MCSymbolData &Data = *MSD.SymbolData;
329 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
330 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
331 LastLocalSymbolIndex++;
335 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
336 const MCValue &Target,
338 const MCFixup &Fixup,
339 bool IsPCRel) const {
340 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
341 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
342 const MCSymbol *Renamed = Renames.lookup(&Symbol);
343 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
345 if (ASymbol.isUndefined()) {
351 if (SD.isExternal()) {
357 const MCSectionELF &Section =
358 static_cast<const MCSectionELF&>(ASymbol.getSection());
359 const SectionKind secKind = Section.getKind();
362 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
364 if (secKind.isThreadLocal()) {
370 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
371 const MCSectionELF &Sec2 =
372 static_cast<const MCSectionELF&>(F.getParent()->getSection());
374 if (&Sec2 != &Section &&
375 (Kind == MCSymbolRefExpr::VK_PLT ||
376 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
377 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
383 if (Section.getFlags() & ELF::SHF_MERGE) {
384 if (Target.getConstant() == 0)
385 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
391 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
396 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
397 const MCAsmLayout &Layout,
398 const MCFragment *Fragment,
399 const MCFixup &Fixup,
401 uint64_t &FixedValue) {
404 int64_t Value = Target.getConstant();
405 const MCSymbol *RelocSymbol = NULL;
407 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
408 if (!Target.isAbsolute()) {
409 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
410 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
411 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
413 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
414 const MCSymbol &SymbolB = RefB->getSymbol();
415 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
418 // Offset of the symbol in the section
419 int64_t a = Layout.getSymbolOffset(&SDB);
421 // Offset of the relocation in the section
422 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
427 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
428 MCFragment *F = SD.getFragment();
430 Index = F->getParent()->getOrdinal() + 1;
432 // Offset of the symbol in the section
433 Value += Layout.getSymbolOffset(&SD);
435 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
436 WeakrefUsedInReloc.insert(RelocSymbol);
438 UsedInReloc.insert(RelocSymbol);
442 // Compensate for the addend on i386.
448 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
449 (RelocSymbol != 0), Addend);
451 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
454 adjustFixupOffset(Fixup, RelocOffset);
456 if (!hasRelocationAddend())
460 assert(isInt<64>(Addend));
462 assert(isInt<32>(Addend));
464 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
465 Relocations[Fragment->getParent()].push_back(ERE);
470 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
472 MCSymbolData &SD = Asm.getSymbolData(*S);
473 return SD.getIndex();
476 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
477 const MCSymbolData &Data,
478 bool Used, bool Renamed) {
479 if (Data.getFlags() & ELF_Other_Weakref)
488 const MCSymbol &Symbol = Data.getSymbol();
490 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
493 const MCSymbol &A = Symbol.AliasedSymbol();
494 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
497 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
498 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
501 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
504 if (Symbol.isTemporary())
510 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
511 bool isUsedInReloc) {
512 if (Data.isExternal())
515 const MCSymbol &Symbol = Data.getSymbol();
516 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
518 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
519 if (isSignature && !isUsedInReloc)
528 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
529 SectionIndexMapTy &SectionIndexMap,
530 const RelMapTy &RelMap) {
532 for (MCAssembler::iterator it = Asm.begin(),
533 ie = Asm.end(); it != ie; ++it) {
534 const MCSectionELF &Section =
535 static_cast<const MCSectionELF &>(it->getSection());
536 if (Section.getType() != ELF::SHT_GROUP)
538 SectionIndexMap[&Section] = Index++;
541 for (MCAssembler::iterator it = Asm.begin(),
542 ie = Asm.end(); it != ie; ++it) {
543 const MCSectionELF &Section =
544 static_cast<const MCSectionELF &>(it->getSection());
545 if (Section.getType() == ELF::SHT_GROUP ||
546 Section.getType() == ELF::SHT_REL ||
547 Section.getType() == ELF::SHT_RELA)
549 SectionIndexMap[&Section] = Index++;
550 const MCSectionELF *RelSection = RelMap.lookup(&Section);
552 SectionIndexMap[RelSection] = Index++;
556 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
557 const SectionIndexMapTy &SectionIndexMap,
558 RevGroupMapTy RevGroupMap,
559 unsigned NumRegularSections) {
560 // FIXME: Is this the correct place to do this?
561 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
563 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
564 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
565 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
566 Data.setExternal(true);
567 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
570 // Index 0 is always the empty string.
571 StringMap<uint64_t> StringIndexMap;
572 StringTable += '\x00';
574 // FIXME: We could optimize suffixes in strtab in the same way we
575 // optimize them in shstrtab.
577 // Add the data for the symbols.
578 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
579 ie = Asm.symbol_end(); it != ie; ++it) {
580 const MCSymbol &Symbol = it->getSymbol();
582 bool Used = UsedInReloc.count(&Symbol);
583 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
584 bool isSignature = RevGroupMap.count(&Symbol);
586 if (!isInSymtab(Asm, *it,
587 Used || WeakrefUsed || isSignature,
588 Renames.count(&Symbol)))
593 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
595 // Undefined symbols are global, but this is the first place we
596 // are able to set it.
597 bool Local = isLocal(*it, isSignature, Used);
598 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
599 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
600 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
601 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
604 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
605 MCELF::SetBinding(*it, ELF::STB_WEAK);
607 if (it->isCommon()) {
609 MSD.SectionIndex = ELF::SHN_COMMON;
610 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
611 MSD.SectionIndex = ELF::SHN_ABS;
612 } else if (RefSymbol.isUndefined()) {
613 if (isSignature && !Used)
614 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
616 MSD.SectionIndex = ELF::SHN_UNDEF;
618 const MCSectionELF &Section =
619 static_cast<const MCSectionELF&>(RefSymbol.getSection());
620 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
621 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
622 NeedsSymtabShndx = true;
623 assert(MSD.SectionIndex && "Invalid section index!");
626 // The @@@ in symbol version is replaced with @ in undefined symbols and
627 // @@ in defined ones.
628 StringRef Name = Symbol.getName();
631 size_t Pos = Name.find("@@@");
632 if (Pos != StringRef::npos) {
633 Buf += Name.substr(0, Pos);
634 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
635 Buf += Name.substr(Pos + Skip);
639 uint64_t &Entry = StringIndexMap[Name];
641 Entry = StringTable.size();
643 StringTable += '\x00';
645 MSD.StringIndex = Entry;
646 if (MSD.SectionIndex == ELF::SHN_UNDEF)
647 UndefinedSymbolData.push_back(MSD);
649 LocalSymbolData.push_back(MSD);
651 ExternalSymbolData.push_back(MSD);
654 // Symbols are required to be in lexicographic order.
655 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
656 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
657 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
659 // Set the symbol indices. Local symbols must come before all other
660 // symbols with non-local bindings.
662 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
663 LocalSymbolData[i].SymbolData->setIndex(Index++);
665 Index += NumRegularSections;
667 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
668 ExternalSymbolData[i].SymbolData->setIndex(Index++);
669 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
670 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
672 if (NumRegularSections > ELF::SHN_LORESERVE)
673 NeedsSymtabShndx = true;
676 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
679 for (MCAssembler::const_iterator it = Asm.begin(),
680 ie = Asm.end(); it != ie; ++it) {
681 const MCSectionData &SD = *it;
682 if (Relocations[&SD].empty())
685 MCContext &Ctx = Asm.getContext();
686 const MCSectionELF &Section =
687 static_cast<const MCSectionELF&>(SD.getSection());
689 const StringRef SectionName = Section.getSectionName();
690 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
691 RelaSectionName += SectionName;
694 if (hasRelocationAddend())
695 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
697 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
699 const MCSectionELF *RelaSection =
700 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
701 ELF::SHT_RELA : ELF::SHT_REL, 0,
702 SectionKind::getReadOnly(),
704 RelMap[&Section] = RelaSection;
705 Asm.getOrCreateSectionData(*RelaSection);
709 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
710 const RelMapTy &RelMap) {
711 for (MCAssembler::const_iterator it = Asm.begin(),
712 ie = Asm.end(); it != ie; ++it) {
713 const MCSectionData &SD = *it;
714 const MCSectionELF &Section =
715 static_cast<const MCSectionELF&>(SD.getSection());
717 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
720 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
721 RelaSD.setAlignment(is64Bit() ? 8 : 4);
723 MCDataFragment *F = new MCDataFragment(&RelaSD);
724 WriteRelocationsFragment(Asm, F, &*it);
728 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
729 uint64_t Flags, uint64_t Address,
730 uint64_t Offset, uint64_t Size,
731 uint32_t Link, uint32_t Info,
733 uint64_t EntrySize) {
734 Write32(Name); // sh_name: index into string table
735 Write32(Type); // sh_type
736 WriteWord(Flags); // sh_flags
737 WriteWord(Address); // sh_addr
738 WriteWord(Offset); // sh_offset
739 WriteWord(Size); // sh_size
740 Write32(Link); // sh_link
741 Write32(Info); // sh_info
742 WriteWord(Alignment); // sh_addralign
743 WriteWord(EntrySize); // sh_entsize
746 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
748 const MCSectionData *SD) {
749 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
750 // sort by the r_offset just like gnu as does
751 array_pod_sort(Relocs.begin(), Relocs.end());
753 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
754 ELFRelocationEntry entry = Relocs[e - i - 1];
758 else if (entry.Index < 0)
759 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
761 entry.Index += LocalSymbolData.size();
763 String64(*F, entry.r_offset);
765 struct ELF::Elf64_Rela ERE64;
766 ERE64.setSymbolAndType(entry.Index, entry.Type);
767 String64(*F, ERE64.r_info);
769 if (hasRelocationAddend())
770 String64(*F, entry.r_addend);
772 String32(*F, entry.r_offset);
774 struct ELF::Elf32_Rela ERE32;
775 ERE32.setSymbolAndType(entry.Index, entry.Type);
776 String32(*F, ERE32.r_info);
778 if (hasRelocationAddend())
779 String32(*F, entry.r_addend);
784 static int compareBySuffix(const void *a, const void *b) {
785 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
786 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
787 const StringRef &NameA = secA->getSectionName();
788 const StringRef &NameB = secB->getSectionName();
789 const unsigned sizeA = NameA.size();
790 const unsigned sizeB = NameB.size();
791 const unsigned len = std::min(sizeA, sizeB);
792 for (unsigned int i = 0; i < len; ++i) {
793 char ca = NameA[sizeA - i - 1];
794 char cb = NameB[sizeB - i - 1];
799 return sizeB - sizeA;
802 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
804 SectionIndexMapTy &SectionIndexMap,
805 const RelMapTy &RelMap) {
806 MCContext &Ctx = Asm.getContext();
809 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
811 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
812 const MCSectionELF *ShstrtabSection =
813 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
814 SectionKind::getReadOnly());
815 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
816 ShstrtabSD.setAlignment(1);
818 const MCSectionELF *SymtabSection =
819 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
820 SectionKind::getReadOnly(),
822 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
823 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
825 MCSectionData *SymtabShndxSD = NULL;
827 if (NeedsSymtabShndx) {
828 const MCSectionELF *SymtabShndxSection =
829 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
830 SectionKind::getReadOnly(), 4, "");
831 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
832 SymtabShndxSD->setAlignment(4);
835 const MCSectionELF *StrtabSection;
836 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
837 SectionKind::getReadOnly());
838 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
839 StrtabSD.setAlignment(1);
841 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
843 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
844 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
845 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
848 F = new MCDataFragment(&SymtabSD);
849 MCDataFragment *ShndxF = NULL;
850 if (NeedsSymtabShndx) {
851 ShndxF = new MCDataFragment(SymtabShndxSD);
853 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
855 F = new MCDataFragment(&StrtabSD);
856 F->getContents().append(StringTable.begin(), StringTable.end());
858 F = new MCDataFragment(&ShstrtabSD);
860 std::vector<const MCSectionELF*> Sections;
861 for (MCAssembler::const_iterator it = Asm.begin(),
862 ie = Asm.end(); it != ie; ++it) {
863 const MCSectionELF &Section =
864 static_cast<const MCSectionELF&>(it->getSection());
865 Sections.push_back(&Section);
867 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
869 // Section header string table.
871 // The first entry of a string table holds a null character so skip
874 F->getContents() += '\x00';
876 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
877 const MCSectionELF &Section = *Sections[I];
879 StringRef Name = Section.getSectionName();
881 StringRef PreviousName = Sections[I - 1]->getSectionName();
882 if (PreviousName.endswith(Name)) {
883 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
887 // Remember the index into the string table so we can write it
888 // into the sh_name field of the section header table.
889 SectionStringTableIndex[&Section] = Index;
891 Index += Name.size() + 1;
892 F->getContents() += Name;
893 F->getContents() += '\x00';
897 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
899 GroupMapTy &GroupMap,
900 RevGroupMapTy &RevGroupMap,
901 SectionIndexMapTy &SectionIndexMap,
902 const RelMapTy &RelMap) {
903 // Create the .note.GNU-stack section if needed.
904 MCContext &Ctx = Asm.getContext();
905 if (Asm.getNoExecStack()) {
906 const MCSectionELF *GnuStackSection =
907 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
908 SectionKind::getReadOnly());
909 Asm.getOrCreateSectionData(*GnuStackSection);
913 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
915 const MCSectionELF &Section =
916 static_cast<const MCSectionELF&>(it->getSection());
917 if (!(Section.getFlags() & ELF::SHF_GROUP))
920 const MCSymbol *SignatureSymbol = Section.getGroup();
921 Asm.getOrCreateSymbolData(*SignatureSymbol);
922 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
924 Group = Ctx.CreateELFGroupSection();
925 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
926 Data.setAlignment(4);
927 MCDataFragment *F = new MCDataFragment(&Data);
928 String32(*F, ELF::GRP_COMDAT);
930 GroupMap[Group] = SignatureSymbol;
933 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
935 // Add sections to the groups
936 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
938 const MCSectionELF &Section =
939 static_cast<const MCSectionELF&>(it->getSection());
940 if (!(Section.getFlags() & ELF::SHF_GROUP))
942 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
943 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
944 // FIXME: we could use the previous fragment
945 MCDataFragment *F = new MCDataFragment(&Data);
946 unsigned Index = SectionIndexMap.lookup(&Section);
951 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
952 const SectionIndexMapTy &SectionIndexMap,
953 uint32_t GroupSymbolIndex,
954 uint64_t Offset, uint64_t Size,
956 const MCSectionELF &Section) {
957 uint64_t sh_link = 0;
958 uint64_t sh_info = 0;
960 switch(Section.getType()) {
961 case ELF::SHT_DYNAMIC:
962 sh_link = SectionStringTableIndex[&Section];
967 case ELF::SHT_RELA: {
968 const MCSectionELF *SymtabSection;
969 const MCSectionELF *InfoSection;
970 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
972 SectionKind::getReadOnly());
973 sh_link = SectionIndexMap.lookup(SymtabSection);
974 assert(sh_link && ".symtab not found");
976 // Remove ".rel" and ".rela" prefixes.
977 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
978 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
980 InfoSection = Asm.getContext().getELFSection(SectionName,
981 ELF::SHT_PROGBITS, 0,
982 SectionKind::getReadOnly());
983 sh_info = SectionIndexMap.lookup(InfoSection);
987 case ELF::SHT_SYMTAB:
988 case ELF::SHT_DYNSYM:
989 sh_link = StringTableIndex;
990 sh_info = LastLocalSymbolIndex;
993 case ELF::SHT_SYMTAB_SHNDX:
994 sh_link = SymbolTableIndex;
997 case ELF::SHT_PROGBITS:
998 case ELF::SHT_STRTAB:
999 case ELF::SHT_NOBITS:
1002 case ELF::SHT_ARM_ATTRIBUTES:
1003 case ELF::SHT_INIT_ARRAY:
1004 case ELF::SHT_FINI_ARRAY:
1005 case ELF::SHT_PREINIT_ARRAY:
1006 case ELF::SHT_X86_64_UNWIND:
1010 case ELF::SHT_GROUP:
1011 sh_link = SymbolTableIndex;
1012 sh_info = GroupSymbolIndex;
1016 assert(0 && "FIXME: sh_type value not supported!");
1020 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1021 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1022 Alignment, Section.getEntrySize());
1025 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1026 return SD.getOrdinal() == ~UINT32_C(0) &&
1027 !SD.getSection().isVirtualSection();
1030 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1032 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1034 const MCFragment &F = *i;
1035 assert(F.getKind() == MCFragment::FT_Data);
1036 Ret += cast<MCDataFragment>(F).getContents().size();
1041 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1042 const MCSectionData &SD) {
1043 if (IsELFMetaDataSection(SD))
1044 return DataSectionSize(SD);
1045 return Layout.getSectionFileSize(&SD);
1048 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1049 const MCSectionData &SD) {
1050 if (IsELFMetaDataSection(SD))
1051 return DataSectionSize(SD);
1052 return Layout.getSectionAddressSize(&SD);
1055 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1056 const MCAsmLayout &Layout,
1057 const MCSectionELF &Section) {
1058 uint64_t FileOff = OS.tell();
1059 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1061 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1062 WriteZeros(Padding);
1065 FileOff += GetSectionFileSize(Layout, SD);
1067 if (IsELFMetaDataSection(SD)) {
1068 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1070 const MCFragment &F = *i;
1071 assert(F.getKind() == MCFragment::FT_Data);
1072 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1075 Asm.writeSectionData(&SD, Layout);
1079 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1080 const GroupMapTy &GroupMap,
1081 const MCAsmLayout &Layout,
1082 const SectionIndexMapTy &SectionIndexMap,
1083 const SectionOffsetMapTy &SectionOffsetMap) {
1084 const unsigned NumSections = Asm.size() + 1;
1086 std::vector<const MCSectionELF*> Sections;
1087 Sections.resize(NumSections - 1);
1089 for (SectionIndexMapTy::const_iterator i=
1090 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1091 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1092 Sections[p.second - 1] = p.first;
1095 // Null section first.
1096 uint64_t FirstSectionSize =
1097 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1098 uint32_t FirstSectionLink =
1099 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1100 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1102 for (unsigned i = 0; i < NumSections - 1; ++i) {
1103 const MCSectionELF &Section = *Sections[i];
1104 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1105 uint32_t GroupSymbolIndex;
1106 if (Section.getType() != ELF::SHT_GROUP)
1107 GroupSymbolIndex = 0;
1109 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1110 GroupMap.lookup(&Section));
1112 uint64_t Size = GetSectionAddressSize(Layout, SD);
1114 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1115 SectionOffsetMap.lookup(&Section), Size,
1116 SD.getAlignment(), Section);
1120 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1121 std::vector<const MCSectionELF*> &Sections) {
1122 for (MCAssembler::iterator it = Asm.begin(),
1123 ie = Asm.end(); it != ie; ++it) {
1124 const MCSectionELF &Section =
1125 static_cast<const MCSectionELF &>(it->getSection());
1126 if (Section.getType() == ELF::SHT_GROUP)
1127 Sections.push_back(&Section);
1130 for (MCAssembler::iterator it = Asm.begin(),
1131 ie = Asm.end(); it != ie; ++it) {
1132 const MCSectionELF &Section =
1133 static_cast<const MCSectionELF &>(it->getSection());
1134 if (Section.getType() != ELF::SHT_GROUP &&
1135 Section.getType() != ELF::SHT_REL &&
1136 Section.getType() != ELF::SHT_RELA)
1137 Sections.push_back(&Section);
1140 for (MCAssembler::iterator it = Asm.begin(),
1141 ie = Asm.end(); it != ie; ++it) {
1142 const MCSectionELF &Section =
1143 static_cast<const MCSectionELF &>(it->getSection());
1144 if (Section.getType() == ELF::SHT_REL ||
1145 Section.getType() == ELF::SHT_RELA)
1146 Sections.push_back(&Section);
1150 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1151 const MCAsmLayout &Layout) {
1152 GroupMapTy GroupMap;
1153 RevGroupMapTy RevGroupMap;
1154 SectionIndexMapTy SectionIndexMap;
1156 unsigned NumUserSections = Asm.size();
1158 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1159 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1161 const unsigned NumUserAndRelocSections = Asm.size();
1162 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1163 RevGroupMap, SectionIndexMap, RelMap);
1164 const unsigned AllSections = Asm.size();
1165 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1167 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1169 // Compute symbol table information.
1170 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1173 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1175 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1176 const_cast<MCAsmLayout&>(Layout),
1180 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1181 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1182 sizeof(ELF::Elf32_Ehdr);
1183 uint64_t FileOff = HeaderSize;
1185 std::vector<const MCSectionELF*> Sections;
1186 ComputeSectionOrder(Asm, Sections);
1187 unsigned NumSections = Sections.size();
1188 SectionOffsetMapTy SectionOffsetMap;
1189 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1190 const MCSectionELF &Section = *Sections[i];
1191 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1193 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1195 // Remember the offset into the file for this section.
1196 SectionOffsetMap[&Section] = FileOff;
1198 // Get the size of the section in the output file (including padding).
1199 FileOff += GetSectionFileSize(Layout, SD);
1202 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1204 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1206 uint64_t SectionHeaderEntrySize = is64Bit() ?
1207 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1208 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1210 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1211 const MCSectionELF &Section = *Sections[i];
1212 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1214 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1216 // Remember the offset into the file for this section.
1217 SectionOffsetMap[&Section] = FileOff;
1219 // Get the size of the section in the output file (including padding).
1220 FileOff += GetSectionFileSize(Layout, SD);
1223 // Write out the ELF header ...
1224 WriteHeader(SectionHeaderOffset, NumSections + 1);
1226 // ... then the regular sections ...
1227 // + because of .shstrtab
1228 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1229 WriteDataSectionData(Asm, Layout, *Sections[i]);
1231 FileOff = OS.tell();
1232 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1233 WriteZeros(Padding);
1235 // ... then the section header table ...
1236 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1239 FileOff = OS.tell();
1241 // ... and then the remaining sections ...
1242 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1243 WriteDataSectionData(Asm, Layout, *Sections[i]);
1247 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1248 const MCSymbolData &DataA,
1249 const MCFragment &FB,
1251 bool IsPCRel) const {
1252 if (DataA.getFlags() & ELF_STB_Weak)
1254 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1255 Asm, DataA, FB,InSet, IsPCRel);
1258 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1260 bool IsLittleEndian) {
1261 switch (MOTW->getEMachine()) {
1263 case ELF::EM_X86_64:
1264 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1266 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1267 case ELF::EM_MBLAZE:
1268 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1271 return new PPCELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1273 return new MipsELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1274 default: llvm_unreachable("Unsupported architecture"); break;
1278 /// START OF SUBCLASSES for ELFObjectWriter
1279 //===- ARMELFObjectWriter -------------------------------------------===//
1281 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1283 bool IsLittleEndian)
1284 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1287 ARMELFObjectWriter::~ARMELFObjectWriter()
1290 // FIXME: get the real EABI Version from the Triple.
1291 void ARMELFObjectWriter::WriteEFlags() {
1292 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1295 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1296 // I.e. not as an offset to a section symbol.
1297 // This code is an approximation of what ARM/gcc does.
1299 STATISTIC(PCRelCount, "Total number of PIC Relocations");
1300 STATISTIC(NonPCRelCount, "Total number of non-PIC relocations");
1302 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1303 const MCValue &Target,
1304 const MCFragment &F,
1305 const MCFixup &Fixup,
1306 bool IsPCRel) const {
1307 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1308 bool EmitThisSym = false;
1310 const MCSectionELF &Section =
1311 static_cast<const MCSectionELF&>(Symbol.getSection());
1312 bool InNormalSection = true;
1313 unsigned RelocType = 0;
1314 RelocType = GetRelocTypeInner(Target, Fixup, IsPCRel);
1317 const MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
1318 MCSymbolRefExpr::VariantKind Kind2;
1319 Kind2 = Target.getSymB() ? Target.getSymB()->getKind() :
1320 MCSymbolRefExpr::VK_None;
1321 dbgs() << "considering symbol "
1322 << Section.getSectionName() << "/"
1323 << Symbol.getName() << "/"
1324 << " Rel:" << (unsigned)RelocType
1325 << " Kind: " << (int)Kind << "/" << (int)Kind2
1327 << Symbol.isAbsolute() << "/" << Symbol.isDefined() << "/"
1328 << Symbol.isVariable() << "/" << Symbol.isTemporary()
1329 << " Counts:" << PCRelCount << "/" << NonPCRelCount << "\n");
1331 if (IsPCRel) { ++PCRelCount;
1332 switch (RelocType) {
1334 // Most relocation types are emitted as explicit symbols
1336 StringSwitch<bool>(Section.getSectionName())
1337 .Case(".data.rel.ro.local", false)
1338 .Case(".data.rel", false)
1339 .Case(".bss", false)
1343 case ELF::R_ARM_ABS32:
1344 // But things get strange with R_ARM_ABS32
1345 // In this case, most things that go in .rodata show up
1346 // as section relative relocations
1348 StringSwitch<bool>(Section.getSectionName())
1349 .Case(".data.rel.ro.local", false)
1350 .Case(".data.rel", false)
1351 .Case(".rodata", false)
1352 .Case(".bss", false)
1354 EmitThisSym = false;
1360 StringSwitch<bool>(Section.getSectionName())
1361 .Case(".data.rel.ro.local", false)
1362 .Case(".rodata", false)
1363 .Case(".data.rel", false)
1364 .Case(".bss", false)
1367 switch (RelocType) {
1368 default: EmitThisSym = true; break;
1369 case ELF::R_ARM_ABS32: EmitThisSym = false; break;
1375 if (! Symbol.isTemporary() && InNormalSection) {
1381 // Need to examine the Fixup when determining whether to
1382 // emit the relocation as an explicit symbol or as a section relative
1384 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1385 const MCFixup &Fixup,
1387 bool IsRelocWithSymbol,
1389 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1390 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1392 unsigned Type = GetRelocTypeInner(Target, Fixup, IsPCRel);
1394 if (RelocNeedsGOT(Modifier))
1400 unsigned ARMELFObjectWriter::GetRelocTypeInner(const MCValue &Target,
1401 const MCFixup &Fixup,
1402 bool IsPCRel) const {
1403 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1404 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1408 switch ((unsigned)Fixup.getKind()) {
1409 default: assert(0 && "Unimplemented");
1412 default: llvm_unreachable("Unsupported Modifier");
1413 case MCSymbolRefExpr::VK_None:
1414 Type = ELF::R_ARM_REL32;
1416 case MCSymbolRefExpr::VK_ARM_TLSGD:
1417 assert(0 && "unimplemented");
1419 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1420 Type = ELF::R_ARM_TLS_IE32;
1424 case ARM::fixup_arm_uncondbranch:
1426 case MCSymbolRefExpr::VK_ARM_PLT:
1427 Type = ELF::R_ARM_PLT32;
1430 Type = ELF::R_ARM_CALL;
1434 case ARM::fixup_arm_condbranch:
1435 Type = ELF::R_ARM_JUMP24;
1437 case ARM::fixup_arm_movt_hi16:
1438 case ARM::fixup_arm_movt_hi16_pcrel:
1439 Type = ELF::R_ARM_MOVT_PREL;
1441 case ARM::fixup_arm_movw_lo16:
1442 case ARM::fixup_arm_movw_lo16_pcrel:
1443 Type = ELF::R_ARM_MOVW_PREL_NC;
1445 case ARM::fixup_t2_movt_hi16:
1446 case ARM::fixup_t2_movt_hi16_pcrel:
1447 Type = ELF::R_ARM_THM_MOVT_PREL;
1449 case ARM::fixup_t2_movw_lo16:
1450 case ARM::fixup_t2_movw_lo16_pcrel:
1451 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1453 case ARM::fixup_arm_thumb_bl:
1454 case ARM::fixup_arm_thumb_blx:
1456 case MCSymbolRefExpr::VK_ARM_PLT:
1457 Type = ELF::R_ARM_THM_CALL;
1460 Type = ELF::R_ARM_NONE;
1466 switch ((unsigned)Fixup.getKind()) {
1467 default: llvm_unreachable("invalid fixup kind!");
1470 default: llvm_unreachable("Unsupported Modifier"); break;
1471 case MCSymbolRefExpr::VK_ARM_GOT:
1472 Type = ELF::R_ARM_GOT_BREL;
1474 case MCSymbolRefExpr::VK_ARM_TLSGD:
1475 Type = ELF::R_ARM_TLS_GD32;
1477 case MCSymbolRefExpr::VK_ARM_TPOFF:
1478 Type = ELF::R_ARM_TLS_LE32;
1480 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1481 Type = ELF::R_ARM_TLS_IE32;
1483 case MCSymbolRefExpr::VK_None:
1484 Type = ELF::R_ARM_ABS32;
1486 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1487 Type = ELF::R_ARM_GOTOFF32;
1491 case ARM::fixup_arm_ldst_pcrel_12:
1492 case ARM::fixup_arm_pcrel_10:
1493 case ARM::fixup_arm_adr_pcrel_12:
1494 case ARM::fixup_arm_thumb_bl:
1495 case ARM::fixup_arm_thumb_cb:
1496 case ARM::fixup_arm_thumb_cp:
1497 case ARM::fixup_arm_thumb_br:
1498 assert(0 && "Unimplemented");
1500 case ARM::fixup_arm_uncondbranch:
1501 Type = ELF::R_ARM_CALL;
1503 case ARM::fixup_arm_condbranch:
1504 Type = ELF::R_ARM_JUMP24;
1506 case ARM::fixup_arm_movt_hi16:
1507 Type = ELF::R_ARM_MOVT_ABS;
1509 case ARM::fixup_arm_movw_lo16:
1510 Type = ELF::R_ARM_MOVW_ABS_NC;
1512 case ARM::fixup_t2_movt_hi16:
1513 Type = ELF::R_ARM_THM_MOVT_ABS;
1515 case ARM::fixup_t2_movw_lo16:
1516 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1524 //===- PPCELFObjectWriter -------------------------------------------===//
1526 PPCELFObjectWriter::PPCELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1528 bool IsLittleEndian)
1529 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1532 PPCELFObjectWriter::~PPCELFObjectWriter() {
1535 unsigned PPCELFObjectWriter::GetRelocType(const MCValue &Target,
1536 const MCFixup &Fixup,
1538 bool IsRelocWithSymbol,
1540 // determine the type of the relocation
1543 switch ((unsigned)Fixup.getKind()) {
1545 llvm_unreachable("Unimplemented");
1546 case PPC::fixup_ppc_br24:
1547 Type = ELF::R_PPC_REL24;
1550 Type = ELF::R_PPC_REL32;
1554 switch ((unsigned)Fixup.getKind()) {
1555 default: llvm_unreachable("invalid fixup kind!");
1556 case PPC::fixup_ppc_br24:
1557 Type = ELF::R_PPC_ADDR24;
1559 case PPC::fixup_ppc_brcond14:
1560 Type = ELF::R_PPC_ADDR14_BRTAKEN; // XXX: or BRNTAKEN?_
1562 case PPC::fixup_ppc_ha16:
1563 Type = ELF::R_PPC_ADDR16_HA;
1565 case PPC::fixup_ppc_lo16:
1566 Type = ELF::R_PPC_ADDR16_LO;
1568 case PPC::fixup_ppc_lo14:
1569 Type = ELF::R_PPC_ADDR14;
1572 Type = ELF::R_PPC_ADDR32;
1575 Type = ELF::R_PPC_ADDR16;
1582 void PPCELFObjectWriter::
1583 adjustFixupOffset(const MCFixup &Fixup, uint64_t &RelocOffset) {
1584 switch ((unsigned)Fixup.getKind()) {
1585 case PPC::fixup_ppc_ha16:
1586 case PPC::fixup_ppc_lo16:
1594 //===- MBlazeELFObjectWriter -------------------------------------------===//
1596 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1598 bool IsLittleEndian)
1599 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1602 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1605 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1606 const MCFixup &Fixup,
1608 bool IsRelocWithSymbol,
1610 // determine the type of the relocation
1613 switch ((unsigned)Fixup.getKind()) {
1615 llvm_unreachable("Unimplemented");
1617 Type = ELF::R_MICROBLAZE_64_PCREL;
1620 Type = ELF::R_MICROBLAZE_32_PCREL;
1624 switch ((unsigned)Fixup.getKind()) {
1625 default: llvm_unreachable("invalid fixup kind!");
1627 Type = ((IsRelocWithSymbol || Addend !=0)
1628 ? ELF::R_MICROBLAZE_32
1629 : ELF::R_MICROBLAZE_64);
1632 Type = ELF::R_MICROBLAZE_32;
1639 //===- X86ELFObjectWriter -------------------------------------------===//
1642 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1644 bool IsLittleEndian)
1645 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1648 X86ELFObjectWriter::~X86ELFObjectWriter()
1651 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1652 const MCFixup &Fixup,
1654 bool IsRelocWithSymbol,
1656 // determine the type of the relocation
1658 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1659 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1663 switch ((unsigned)Fixup.getKind()) {
1664 default: llvm_unreachable("invalid fixup kind!");
1666 case FK_Data_8: Type = ELF::R_X86_64_PC64; break;
1667 case FK_Data_4: Type = ELF::R_X86_64_PC32; break;
1668 case FK_Data_2: Type = ELF::R_X86_64_PC16; break;
1671 assert(Modifier == MCSymbolRefExpr::VK_None);
1672 Type = ELF::R_X86_64_PC64;
1674 case X86::reloc_signed_4byte:
1675 case X86::reloc_riprel_4byte_movq_load:
1676 case X86::reloc_riprel_4byte:
1680 llvm_unreachable("Unimplemented");
1681 case MCSymbolRefExpr::VK_None:
1682 Type = ELF::R_X86_64_PC32;
1684 case MCSymbolRefExpr::VK_PLT:
1685 Type = ELF::R_X86_64_PLT32;
1687 case MCSymbolRefExpr::VK_GOTPCREL:
1688 Type = ELF::R_X86_64_GOTPCREL;
1690 case MCSymbolRefExpr::VK_GOTTPOFF:
1691 Type = ELF::R_X86_64_GOTTPOFF;
1693 case MCSymbolRefExpr::VK_TLSGD:
1694 Type = ELF::R_X86_64_TLSGD;
1696 case MCSymbolRefExpr::VK_TLSLD:
1697 Type = ELF::R_X86_64_TLSLD;
1702 assert(Modifier == MCSymbolRefExpr::VK_None);
1703 Type = ELF::R_X86_64_PC16;
1706 assert(Modifier == MCSymbolRefExpr::VK_None);
1707 Type = ELF::R_X86_64_PC8;
1711 switch ((unsigned)Fixup.getKind()) {
1712 default: llvm_unreachable("invalid fixup kind!");
1713 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1714 case X86::reloc_signed_4byte:
1717 llvm_unreachable("Unimplemented");
1718 case MCSymbolRefExpr::VK_None:
1719 Type = ELF::R_X86_64_32S;
1721 case MCSymbolRefExpr::VK_GOT:
1722 Type = ELF::R_X86_64_GOT32;
1724 case MCSymbolRefExpr::VK_GOTPCREL:
1725 Type = ELF::R_X86_64_GOTPCREL;
1727 case MCSymbolRefExpr::VK_TPOFF:
1728 Type = ELF::R_X86_64_TPOFF32;
1730 case MCSymbolRefExpr::VK_DTPOFF:
1731 Type = ELF::R_X86_64_DTPOFF32;
1736 Type = ELF::R_X86_64_32;
1738 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1740 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1745 switch ((unsigned)Fixup.getKind()) {
1746 default: llvm_unreachable("invalid fixup kind!");
1748 case X86::reloc_global_offset_table:
1749 Type = ELF::R_386_GOTPC;
1752 case X86::reloc_signed_4byte:
1757 llvm_unreachable("Unimplemented");
1758 case MCSymbolRefExpr::VK_None:
1759 Type = ELF::R_386_PC32;
1761 case MCSymbolRefExpr::VK_PLT:
1762 Type = ELF::R_386_PLT32;
1768 switch ((unsigned)Fixup.getKind()) {
1769 default: llvm_unreachable("invalid fixup kind!");
1771 case X86::reloc_global_offset_table:
1772 Type = ELF::R_386_GOTPC;
1775 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1777 case X86::reloc_signed_4byte:
1782 llvm_unreachable("Unimplemented");
1783 case MCSymbolRefExpr::VK_None:
1784 Type = ELF::R_386_32;
1786 case MCSymbolRefExpr::VK_GOT:
1787 Type = ELF::R_386_GOT32;
1789 case MCSymbolRefExpr::VK_GOTOFF:
1790 Type = ELF::R_386_GOTOFF;
1792 case MCSymbolRefExpr::VK_TLSGD:
1793 Type = ELF::R_386_TLS_GD;
1795 case MCSymbolRefExpr::VK_TPOFF:
1796 Type = ELF::R_386_TLS_LE_32;
1798 case MCSymbolRefExpr::VK_INDNTPOFF:
1799 Type = ELF::R_386_TLS_IE;
1801 case MCSymbolRefExpr::VK_NTPOFF:
1802 Type = ELF::R_386_TLS_LE;
1804 case MCSymbolRefExpr::VK_GOTNTPOFF:
1805 Type = ELF::R_386_TLS_GOTIE;
1807 case MCSymbolRefExpr::VK_TLSLDM:
1808 Type = ELF::R_386_TLS_LDM;
1810 case MCSymbolRefExpr::VK_DTPOFF:
1811 Type = ELF::R_386_TLS_LDO_32;
1813 case MCSymbolRefExpr::VK_GOTTPOFF:
1814 Type = ELF::R_386_TLS_IE_32;
1818 case FK_Data_2: Type = ELF::R_386_16; break;
1820 case FK_Data_1: Type = ELF::R_386_8; break;
1825 if (RelocNeedsGOT(Modifier))
1831 //===- MipsELFObjectWriter -------------------------------------------===//
1833 MipsELFObjectWriter::MipsELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1835 bool IsLittleEndian)
1836 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {}
1838 MipsELFObjectWriter::~MipsELFObjectWriter() {}
1840 // FIXME: get the real EABI Version from the Triple.
1841 void MipsELFObjectWriter::WriteEFlags() {
1842 Write32(ELF::EF_MIPS_NOREORDER |
1843 ELF::EF_MIPS_ARCH_32R2);
1846 const MCSymbol *MipsELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1847 const MCValue &Target,
1848 const MCFragment &F,
1849 const MCFixup &Fixup,
1850 bool IsPCRel) const {
1851 assert(Target.getSymA() && "SymA cannot be 0.");
1852 const MCSymbol &Sym = Target.getSymA()->getSymbol();
1854 if (Sym.getSection().getKind().isMergeable1ByteCString())
1860 unsigned MipsELFObjectWriter::GetRelocType(const MCValue &Target,
1861 const MCFixup &Fixup,
1863 bool IsRelocWithSymbol,
1865 // determine the type of the relocation
1866 unsigned Type = (unsigned)ELF::R_MIPS_NONE;
1867 unsigned Kind = (unsigned)Fixup.getKind();
1871 llvm_unreachable("invalid fixup kind!");
1873 Type = ELF::R_MIPS_32;
1876 Type = ELF::R_MIPS_GPREL32;
1878 case Mips::fixup_Mips_GPREL16:
1879 Type = ELF::R_MIPS_GPREL16;
1881 case Mips::fixup_Mips_26:
1882 Type = ELF::R_MIPS_26;
1884 case Mips::fixup_Mips_CALL16:
1885 Type = ELF::R_MIPS_CALL16;
1887 case Mips::fixup_Mips_GOT_Global:
1888 case Mips::fixup_Mips_GOT_Local:
1889 Type = ELF::R_MIPS_GOT16;
1891 case Mips::fixup_Mips_HI16:
1892 Type = ELF::R_MIPS_HI16;
1894 case Mips::fixup_Mips_LO16:
1895 Type = ELF::R_MIPS_LO16;
1897 case Mips::fixup_Mips_TLSGD:
1898 Type = ELF::R_MIPS_TLS_GD;
1900 case Mips::fixup_Mips_GOTTPREL:
1901 Type = ELF::R_MIPS_TLS_GOTTPREL;
1903 case Mips::fixup_Mips_TPREL_HI:
1904 Type = ELF::R_MIPS_TLS_TPREL_HI16;
1906 case Mips::fixup_Mips_TPREL_LO:
1907 Type = ELF::R_MIPS_TLS_TPREL_LO16;
1909 case Mips::fixup_Mips_Branch_PCRel:
1910 case Mips::fixup_Mips_PC16:
1911 Type = ELF::R_MIPS_PC16;