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/ARM/MCTargetDesc/ARMFixupKinds.h"
33 #include "../Target/PowerPC/MCTargetDesc/PPCFixupKinds.h"
39 #define DEBUG_TYPE "reloc-info"
41 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
42 const MCFixupKindInfo &FKI =
43 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
45 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
48 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
52 case MCSymbolRefExpr::VK_GOT:
53 case MCSymbolRefExpr::VK_PLT:
54 case MCSymbolRefExpr::VK_GOTPCREL:
55 case MCSymbolRefExpr::VK_GOTOFF:
56 case MCSymbolRefExpr::VK_TPOFF:
57 case MCSymbolRefExpr::VK_TLSGD:
58 case MCSymbolRefExpr::VK_GOTTPOFF:
59 case MCSymbolRefExpr::VK_INDNTPOFF:
60 case MCSymbolRefExpr::VK_NTPOFF:
61 case MCSymbolRefExpr::VK_GOTNTPOFF:
62 case MCSymbolRefExpr::VK_TLSLDM:
63 case MCSymbolRefExpr::VK_DTPOFF:
64 case MCSymbolRefExpr::VK_TLSLD:
69 ELFObjectWriter::~ELFObjectWriter()
72 // Emit the ELF header.
73 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
74 unsigned NumberOfSections) {
80 // emitWord method behaves differently for ELF32 and ELF64, writing
81 // 4 bytes in the former and 8 in the latter.
83 Write8(0x7f); // e_ident[EI_MAG0]
84 Write8('E'); // e_ident[EI_MAG1]
85 Write8('L'); // e_ident[EI_MAG2]
86 Write8('F'); // e_ident[EI_MAG3]
88 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
91 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
93 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
95 Write8(TargetObjectWriter->getOSABI());
96 Write8(0); // e_ident[EI_ABIVERSION]
98 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
100 Write16(ELF::ET_REL); // e_type
102 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
104 Write32(ELF::EV_CURRENT); // e_version
105 WriteWord(0); // e_entry, no entry point in .o file
106 WriteWord(0); // e_phoff, no program header for .o
107 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
108 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
110 // e_flags = whatever the target wants
111 Write32(getEFlags());
113 // e_ehsize = ELF header size
114 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
116 Write16(0); // e_phentsize = prog header entry size
117 Write16(0); // e_phnum = # prog header entries = 0
119 // e_shentsize = Section header entry size
120 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
122 // e_shnum = # of section header ents
123 if (NumberOfSections >= ELF::SHN_LORESERVE)
124 Write16(ELF::SHN_UNDEF);
126 Write16(NumberOfSections);
128 // e_shstrndx = Section # of '.shstrtab'
129 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
130 Write16(ELF::SHN_XINDEX);
132 Write16(ShstrtabIndex);
135 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
136 MCDataFragment *ShndxF,
138 uint8_t info, uint64_t value,
139 uint64_t size, uint8_t other,
143 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
144 String32(*ShndxF, shndx);
146 String32(*ShndxF, 0);
149 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
150 uint16_t(ELF::SHN_XINDEX) : shndx;
153 String32(*SymtabF, name); // st_name
154 String8(*SymtabF, info); // st_info
155 String8(*SymtabF, other); // st_other
156 String16(*SymtabF, Index); // st_shndx
157 String64(*SymtabF, value); // st_value
158 String64(*SymtabF, size); // st_size
160 String32(*SymtabF, name); // st_name
161 String32(*SymtabF, value); // st_value
162 String32(*SymtabF, size); // st_size
163 String8(*SymtabF, info); // st_info
164 String8(*SymtabF, other); // st_other
165 String16(*SymtabF, Index); // st_shndx
169 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
170 const MCAsmLayout &Layout) {
171 if (Data.isCommon() && Data.isExternal())
172 return Data.getCommonAlignment();
174 const MCSymbol &Symbol = Data.getSymbol();
176 if (Symbol.isAbsolute() && Symbol.isVariable()) {
177 if (const MCExpr *Value = Symbol.getVariableValue()) {
179 if (Value->EvaluateAsAbsolute(IntValue, Layout))
180 return (uint64_t)IntValue;
184 if (!Symbol.isInSection())
188 if (Data.getFragment()) {
189 if (Data.getFlags() & ELF_Other_ThumbFunc)
190 return Layout.getSymbolOffset(&Data)+1;
192 return Layout.getSymbolOffset(&Data);
198 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
199 const MCAsmLayout &Layout) {
200 // The presence of symbol versions causes undefined symbols and
201 // versions declared with @@@ to be renamed.
203 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
204 ie = Asm.symbol_end(); it != ie; ++it) {
205 const MCSymbol &Alias = it->getSymbol();
206 const MCSymbol &Symbol = Alias.AliasedSymbol();
207 MCSymbolData &SD = Asm.getSymbolData(Symbol);
210 if (&Symbol == &Alias)
213 StringRef AliasName = Alias.getName();
214 size_t Pos = AliasName.find('@');
215 if (Pos == StringRef::npos)
218 // Aliases defined with .symvar copy the binding from the symbol they alias.
219 // This is the first place we are able to copy this information.
220 it->setExternal(SD.isExternal());
221 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
223 StringRef Rest = AliasName.substr(Pos);
224 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
227 // FIXME: produce a better error message.
228 if (Symbol.isUndefined() && Rest.startswith("@@") &&
229 !Rest.startswith("@@@"))
230 report_fatal_error("A @@ version cannot be undefined");
232 Renames.insert(std::make_pair(&Symbol, &Alias));
236 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
237 MCDataFragment *ShndxF,
239 const MCAsmLayout &Layout) {
240 MCSymbolData &OrigData = *MSD.SymbolData;
242 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
244 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
245 Data.getSymbol().isVariable();
247 uint8_t Binding = MCELF::GetBinding(OrigData);
248 uint8_t Visibility = MCELF::GetVisibility(OrigData);
249 uint8_t Type = MCELF::GetType(Data);
251 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
252 uint8_t Other = Visibility;
254 uint64_t Value = SymbolValue(Data, Layout);
257 assert(!(Data.isCommon() && !Data.isExternal()));
259 const MCExpr *ESize = Data.getSize();
262 if (!ESize->EvaluateAsAbsolute(Res, Layout))
263 report_fatal_error("Size expression must be absolute.");
267 // Write out the symbol table entry
268 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
269 Size, Other, MSD.SectionIndex, IsReserved);
272 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
273 MCDataFragment *ShndxF,
274 const MCAssembler &Asm,
275 const MCAsmLayout &Layout,
276 const SectionIndexMapTy &SectionIndexMap) {
277 // The string table must be emitted first because we need the index
278 // into the string table for all the symbol names.
279 assert(StringTable.size() && "Missing string table");
281 // FIXME: Make sure the start of the symbol table is aligned.
283 // The first entry is the undefined symbol entry.
284 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
286 // Write the symbol table entries.
287 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
288 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
289 ELFSymbolData &MSD = LocalSymbolData[i];
290 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
293 // Write out a symbol table entry for each regular section.
294 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
296 const MCSectionELF &Section =
297 static_cast<const MCSectionELF&>(i->getSection());
298 if (Section.getType() == ELF::SHT_RELA ||
299 Section.getType() == ELF::SHT_REL ||
300 Section.getType() == ELF::SHT_STRTAB ||
301 Section.getType() == ELF::SHT_SYMTAB ||
302 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
304 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
305 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
307 LastLocalSymbolIndex++;
310 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
311 ELFSymbolData &MSD = ExternalSymbolData[i];
312 MCSymbolData &Data = *MSD.SymbolData;
313 assert(((Data.getFlags() & ELF_STB_Global) ||
314 (Data.getFlags() & ELF_STB_Weak)) &&
315 "External symbol requires STB_GLOBAL or STB_WEAK flag");
316 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
317 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
318 LastLocalSymbolIndex++;
321 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
322 ELFSymbolData &MSD = UndefinedSymbolData[i];
323 MCSymbolData &Data = *MSD.SymbolData;
324 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
325 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
326 LastLocalSymbolIndex++;
330 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
331 const MCValue &Target,
333 const MCFixup &Fixup,
334 bool IsPCRel) const {
335 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
336 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
337 const MCSymbol *Renamed = Renames.lookup(&Symbol);
338 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
340 if (ASymbol.isUndefined()) {
346 if (SD.isExternal()) {
352 const MCSectionELF &Section =
353 static_cast<const MCSectionELF&>(ASymbol.getSection());
354 const SectionKind secKind = Section.getKind();
357 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
359 if (secKind.isThreadLocal()) {
365 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
366 const MCSectionELF &Sec2 =
367 static_cast<const MCSectionELF&>(F.getParent()->getSection());
369 if (&Sec2 != &Section &&
370 (Kind == MCSymbolRefExpr::VK_PLT ||
371 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
372 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
378 if (Section.getFlags() & ELF::SHF_MERGE) {
379 if (Target.getConstant() == 0)
380 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
386 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
391 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
392 const MCAsmLayout &Layout,
393 const MCFragment *Fragment,
394 const MCFixup &Fixup,
396 uint64_t &FixedValue) {
399 int64_t Value = Target.getConstant();
400 const MCSymbol *RelocSymbol = NULL;
402 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
403 if (!Target.isAbsolute()) {
404 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
405 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
406 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
408 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
409 const MCSymbol &SymbolB = RefB->getSymbol();
410 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
413 // Offset of the symbol in the section
414 int64_t a = Layout.getSymbolOffset(&SDB);
416 // Offset of the relocation in the section
417 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
422 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
423 MCFragment *F = SD.getFragment();
425 Index = F->getParent()->getOrdinal() + 1;
427 // Offset of the symbol in the section
428 Value += Layout.getSymbolOffset(&SD);
430 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
431 WeakrefUsedInReloc.insert(RelocSymbol);
433 UsedInReloc.insert(RelocSymbol);
437 // Compensate for the addend on i386.
443 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
444 (RelocSymbol != 0), Addend);
445 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
446 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
447 if (RelocNeedsGOT(Modifier))
450 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
453 adjustFixupOffset(Fixup, RelocOffset);
455 if (!hasRelocationAddend())
459 assert(isInt<64>(Addend));
461 assert(isInt<32>(Addend));
463 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
464 Relocations[Fragment->getParent()].push_back(ERE);
469 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
471 MCSymbolData &SD = Asm.getSymbolData(*S);
472 return SD.getIndex();
475 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
476 const MCSymbolData &Data,
477 bool Used, bool Renamed) {
478 if (Data.getFlags() & ELF_Other_Weakref)
487 const MCSymbol &Symbol = Data.getSymbol();
489 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
492 const MCSymbol &A = Symbol.AliasedSymbol();
493 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
496 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
497 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
500 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
503 if (Symbol.isTemporary())
509 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
510 bool isUsedInReloc) {
511 if (Data.isExternal())
514 const MCSymbol &Symbol = Data.getSymbol();
515 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
517 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
518 if (isSignature && !isUsedInReloc)
527 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
528 SectionIndexMapTy &SectionIndexMap,
529 const RelMapTy &RelMap) {
531 for (MCAssembler::iterator it = Asm.begin(),
532 ie = Asm.end(); it != ie; ++it) {
533 const MCSectionELF &Section =
534 static_cast<const MCSectionELF &>(it->getSection());
535 if (Section.getType() != ELF::SHT_GROUP)
537 SectionIndexMap[&Section] = Index++;
540 for (MCAssembler::iterator it = Asm.begin(),
541 ie = Asm.end(); it != ie; ++it) {
542 const MCSectionELF &Section =
543 static_cast<const MCSectionELF &>(it->getSection());
544 if (Section.getType() == ELF::SHT_GROUP ||
545 Section.getType() == ELF::SHT_REL ||
546 Section.getType() == ELF::SHT_RELA)
548 SectionIndexMap[&Section] = Index++;
549 const MCSectionELF *RelSection = RelMap.lookup(&Section);
551 SectionIndexMap[RelSection] = Index++;
555 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
556 const SectionIndexMapTy &SectionIndexMap,
557 RevGroupMapTy RevGroupMap,
558 unsigned NumRegularSections) {
559 // FIXME: Is this the correct place to do this?
560 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
562 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
563 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
564 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
565 Data.setExternal(true);
566 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
569 // Index 0 is always the empty string.
570 StringMap<uint64_t> StringIndexMap;
571 StringTable += '\x00';
573 // FIXME: We could optimize suffixes in strtab in the same way we
574 // optimize them in shstrtab.
576 // Add the data for the symbols.
577 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
578 ie = Asm.symbol_end(); it != ie; ++it) {
579 const MCSymbol &Symbol = it->getSymbol();
581 bool Used = UsedInReloc.count(&Symbol);
582 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
583 bool isSignature = RevGroupMap.count(&Symbol);
585 if (!isInSymtab(Asm, *it,
586 Used || WeakrefUsed || isSignature,
587 Renames.count(&Symbol)))
592 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
594 // Undefined symbols are global, but this is the first place we
595 // are able to set it.
596 bool Local = isLocal(*it, isSignature, Used);
597 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
598 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
599 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
600 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
603 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
604 MCELF::SetBinding(*it, ELF::STB_WEAK);
606 if (it->isCommon()) {
608 MSD.SectionIndex = ELF::SHN_COMMON;
609 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
610 MSD.SectionIndex = ELF::SHN_ABS;
611 } else if (RefSymbol.isUndefined()) {
612 if (isSignature && !Used)
613 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
615 MSD.SectionIndex = ELF::SHN_UNDEF;
617 const MCSectionELF &Section =
618 static_cast<const MCSectionELF&>(RefSymbol.getSection());
619 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
620 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
621 NeedsSymtabShndx = true;
622 assert(MSD.SectionIndex && "Invalid section index!");
625 // The @@@ in symbol version is replaced with @ in undefined symbols and
626 // @@ in defined ones.
627 StringRef Name = Symbol.getName();
630 size_t Pos = Name.find("@@@");
631 if (Pos != StringRef::npos) {
632 Buf += Name.substr(0, Pos);
633 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
634 Buf += Name.substr(Pos + Skip);
638 uint64_t &Entry = StringIndexMap[Name];
640 Entry = StringTable.size();
642 StringTable += '\x00';
644 MSD.StringIndex = Entry;
645 if (MSD.SectionIndex == ELF::SHN_UNDEF)
646 UndefinedSymbolData.push_back(MSD);
648 LocalSymbolData.push_back(MSD);
650 ExternalSymbolData.push_back(MSD);
653 // Symbols are required to be in lexicographic order.
654 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
655 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
656 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
658 // Set the symbol indices. Local symbols must come before all other
659 // symbols with non-local bindings.
661 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
662 LocalSymbolData[i].SymbolData->setIndex(Index++);
664 Index += NumRegularSections;
666 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
667 ExternalSymbolData[i].SymbolData->setIndex(Index++);
668 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
669 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
671 if (NumRegularSections > ELF::SHN_LORESERVE)
672 NeedsSymtabShndx = true;
675 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
678 for (MCAssembler::const_iterator it = Asm.begin(),
679 ie = Asm.end(); it != ie; ++it) {
680 const MCSectionData &SD = *it;
681 if (Relocations[&SD].empty())
684 MCContext &Ctx = Asm.getContext();
685 const MCSectionELF &Section =
686 static_cast<const MCSectionELF&>(SD.getSection());
688 const StringRef SectionName = Section.getSectionName();
689 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
690 RelaSectionName += SectionName;
693 if (hasRelocationAddend())
694 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
696 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
698 const MCSectionELF *RelaSection =
699 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
700 ELF::SHT_RELA : ELF::SHT_REL, 0,
701 SectionKind::getReadOnly(),
703 RelMap[&Section] = RelaSection;
704 Asm.getOrCreateSectionData(*RelaSection);
708 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
709 const RelMapTy &RelMap) {
710 for (MCAssembler::const_iterator it = Asm.begin(),
711 ie = Asm.end(); it != ie; ++it) {
712 const MCSectionData &SD = *it;
713 const MCSectionELF &Section =
714 static_cast<const MCSectionELF&>(SD.getSection());
716 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
719 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
720 RelaSD.setAlignment(is64Bit() ? 8 : 4);
722 MCDataFragment *F = new MCDataFragment(&RelaSD);
723 WriteRelocationsFragment(Asm, F, &*it);
727 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
728 uint64_t Flags, uint64_t Address,
729 uint64_t Offset, uint64_t Size,
730 uint32_t Link, uint32_t Info,
732 uint64_t EntrySize) {
733 Write32(Name); // sh_name: index into string table
734 Write32(Type); // sh_type
735 WriteWord(Flags); // sh_flags
736 WriteWord(Address); // sh_addr
737 WriteWord(Offset); // sh_offset
738 WriteWord(Size); // sh_size
739 Write32(Link); // sh_link
740 Write32(Info); // sh_info
741 WriteWord(Alignment); // sh_addralign
742 WriteWord(EntrySize); // sh_entsize
745 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
747 const MCSectionData *SD) {
748 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
749 // sort by the r_offset just like gnu as does
750 array_pod_sort(Relocs.begin(), Relocs.end());
752 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
753 ELFRelocationEntry entry = Relocs[e - i - 1];
757 else if (entry.Index < 0)
758 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
760 entry.Index += LocalSymbolData.size();
762 String64(*F, entry.r_offset);
764 struct ELF::Elf64_Rela ERE64;
765 ERE64.setSymbolAndType(entry.Index, entry.Type);
766 String64(*F, ERE64.r_info);
768 if (hasRelocationAddend())
769 String64(*F, entry.r_addend);
771 String32(*F, entry.r_offset);
773 struct ELF::Elf32_Rela ERE32;
774 ERE32.setSymbolAndType(entry.Index, entry.Type);
775 String32(*F, ERE32.r_info);
777 if (hasRelocationAddend())
778 String32(*F, entry.r_addend);
783 static int compareBySuffix(const void *a, const void *b) {
784 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
785 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
786 const StringRef &NameA = secA->getSectionName();
787 const StringRef &NameB = secB->getSectionName();
788 const unsigned sizeA = NameA.size();
789 const unsigned sizeB = NameB.size();
790 const unsigned len = std::min(sizeA, sizeB);
791 for (unsigned int i = 0; i < len; ++i) {
792 char ca = NameA[sizeA - i - 1];
793 char cb = NameB[sizeB - i - 1];
798 return sizeB - sizeA;
801 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
803 SectionIndexMapTy &SectionIndexMap,
804 const RelMapTy &RelMap) {
805 MCContext &Ctx = Asm.getContext();
808 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
810 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
811 const MCSectionELF *ShstrtabSection =
812 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
813 SectionKind::getReadOnly());
814 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
815 ShstrtabSD.setAlignment(1);
817 const MCSectionELF *SymtabSection =
818 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
819 SectionKind::getReadOnly(),
821 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
822 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
824 MCSectionData *SymtabShndxSD = NULL;
826 if (NeedsSymtabShndx) {
827 const MCSectionELF *SymtabShndxSection =
828 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
829 SectionKind::getReadOnly(), 4, "");
830 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
831 SymtabShndxSD->setAlignment(4);
834 const MCSectionELF *StrtabSection;
835 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
836 SectionKind::getReadOnly());
837 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
838 StrtabSD.setAlignment(1);
840 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
842 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
843 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
844 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
847 F = new MCDataFragment(&SymtabSD);
848 MCDataFragment *ShndxF = NULL;
849 if (NeedsSymtabShndx) {
850 ShndxF = new MCDataFragment(SymtabShndxSD);
852 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
854 F = new MCDataFragment(&StrtabSD);
855 F->getContents().append(StringTable.begin(), StringTable.end());
857 F = new MCDataFragment(&ShstrtabSD);
859 std::vector<const MCSectionELF*> Sections;
860 for (MCAssembler::const_iterator it = Asm.begin(),
861 ie = Asm.end(); it != ie; ++it) {
862 const MCSectionELF &Section =
863 static_cast<const MCSectionELF&>(it->getSection());
864 Sections.push_back(&Section);
866 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
868 // Section header string table.
870 // The first entry of a string table holds a null character so skip
873 F->getContents() += '\x00';
875 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
876 const MCSectionELF &Section = *Sections[I];
878 StringRef Name = Section.getSectionName();
880 StringRef PreviousName = Sections[I - 1]->getSectionName();
881 if (PreviousName.endswith(Name)) {
882 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
886 // Remember the index into the string table so we can write it
887 // into the sh_name field of the section header table.
888 SectionStringTableIndex[&Section] = Index;
890 Index += Name.size() + 1;
891 F->getContents() += Name;
892 F->getContents() += '\x00';
896 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
898 GroupMapTy &GroupMap,
899 RevGroupMapTy &RevGroupMap,
900 SectionIndexMapTy &SectionIndexMap,
901 const RelMapTy &RelMap) {
902 // Create the .note.GNU-stack section if needed.
903 MCContext &Ctx = Asm.getContext();
904 if (Asm.getNoExecStack()) {
905 const MCSectionELF *GnuStackSection =
906 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
907 SectionKind::getReadOnly());
908 Asm.getOrCreateSectionData(*GnuStackSection);
912 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
914 const MCSectionELF &Section =
915 static_cast<const MCSectionELF&>(it->getSection());
916 if (!(Section.getFlags() & ELF::SHF_GROUP))
919 const MCSymbol *SignatureSymbol = Section.getGroup();
920 Asm.getOrCreateSymbolData(*SignatureSymbol);
921 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
923 Group = Ctx.CreateELFGroupSection();
924 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
925 Data.setAlignment(4);
926 MCDataFragment *F = new MCDataFragment(&Data);
927 String32(*F, ELF::GRP_COMDAT);
929 GroupMap[Group] = SignatureSymbol;
932 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
934 // Add sections to the groups
935 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
937 const MCSectionELF &Section =
938 static_cast<const MCSectionELF&>(it->getSection());
939 if (!(Section.getFlags() & ELF::SHF_GROUP))
941 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
942 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
943 // FIXME: we could use the previous fragment
944 MCDataFragment *F = new MCDataFragment(&Data);
945 unsigned Index = SectionIndexMap.lookup(&Section);
950 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
951 const SectionIndexMapTy &SectionIndexMap,
952 uint32_t GroupSymbolIndex,
953 uint64_t Offset, uint64_t Size,
955 const MCSectionELF &Section) {
956 uint64_t sh_link = 0;
957 uint64_t sh_info = 0;
959 switch(Section.getType()) {
960 case ELF::SHT_DYNAMIC:
961 sh_link = SectionStringTableIndex[&Section];
966 case ELF::SHT_RELA: {
967 const MCSectionELF *SymtabSection;
968 const MCSectionELF *InfoSection;
969 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
971 SectionKind::getReadOnly());
972 sh_link = SectionIndexMap.lookup(SymtabSection);
973 assert(sh_link && ".symtab not found");
975 // Remove ".rel" and ".rela" prefixes.
976 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
977 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
979 InfoSection = Asm.getContext().getELFSection(SectionName,
980 ELF::SHT_PROGBITS, 0,
981 SectionKind::getReadOnly());
982 sh_info = SectionIndexMap.lookup(InfoSection);
986 case ELF::SHT_SYMTAB:
987 case ELF::SHT_DYNSYM:
988 sh_link = StringTableIndex;
989 sh_info = LastLocalSymbolIndex;
992 case ELF::SHT_SYMTAB_SHNDX:
993 sh_link = SymbolTableIndex;
996 case ELF::SHT_PROGBITS:
997 case ELF::SHT_STRTAB:
998 case ELF::SHT_NOBITS:
1001 case ELF::SHT_ARM_ATTRIBUTES:
1002 case ELF::SHT_INIT_ARRAY:
1003 case ELF::SHT_FINI_ARRAY:
1004 case ELF::SHT_PREINIT_ARRAY:
1005 case ELF::SHT_X86_64_UNWIND:
1009 case ELF::SHT_GROUP:
1010 sh_link = SymbolTableIndex;
1011 sh_info = GroupSymbolIndex;
1015 assert(0 && "FIXME: sh_type value not supported!");
1019 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1020 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1021 Alignment, Section.getEntrySize());
1024 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1025 return SD.getOrdinal() == ~UINT32_C(0) &&
1026 !SD.getSection().isVirtualSection();
1029 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1031 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1033 const MCFragment &F = *i;
1034 assert(F.getKind() == MCFragment::FT_Data);
1035 Ret += cast<MCDataFragment>(F).getContents().size();
1040 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1041 const MCSectionData &SD) {
1042 if (IsELFMetaDataSection(SD))
1043 return DataSectionSize(SD);
1044 return Layout.getSectionFileSize(&SD);
1047 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1048 const MCSectionData &SD) {
1049 if (IsELFMetaDataSection(SD))
1050 return DataSectionSize(SD);
1051 return Layout.getSectionAddressSize(&SD);
1054 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1055 const MCAsmLayout &Layout,
1056 const MCSectionELF &Section) {
1057 uint64_t FileOff = OS.tell();
1058 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1060 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1061 WriteZeros(Padding);
1064 FileOff += GetSectionFileSize(Layout, SD);
1066 if (IsELFMetaDataSection(SD)) {
1067 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1069 const MCFragment &F = *i;
1070 assert(F.getKind() == MCFragment::FT_Data);
1071 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1074 Asm.writeSectionData(&SD, Layout);
1078 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1079 const GroupMapTy &GroupMap,
1080 const MCAsmLayout &Layout,
1081 const SectionIndexMapTy &SectionIndexMap,
1082 const SectionOffsetMapTy &SectionOffsetMap) {
1083 const unsigned NumSections = Asm.size() + 1;
1085 std::vector<const MCSectionELF*> Sections;
1086 Sections.resize(NumSections - 1);
1088 for (SectionIndexMapTy::const_iterator i=
1089 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1090 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1091 Sections[p.second - 1] = p.first;
1094 // Null section first.
1095 uint64_t FirstSectionSize =
1096 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1097 uint32_t FirstSectionLink =
1098 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1099 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1101 for (unsigned i = 0; i < NumSections - 1; ++i) {
1102 const MCSectionELF &Section = *Sections[i];
1103 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1104 uint32_t GroupSymbolIndex;
1105 if (Section.getType() != ELF::SHT_GROUP)
1106 GroupSymbolIndex = 0;
1108 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1109 GroupMap.lookup(&Section));
1111 uint64_t Size = GetSectionAddressSize(Layout, SD);
1113 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1114 SectionOffsetMap.lookup(&Section), Size,
1115 SD.getAlignment(), Section);
1119 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1120 std::vector<const MCSectionELF*> &Sections) {
1121 for (MCAssembler::iterator it = Asm.begin(),
1122 ie = Asm.end(); it != ie; ++it) {
1123 const MCSectionELF &Section =
1124 static_cast<const MCSectionELF &>(it->getSection());
1125 if (Section.getType() == ELF::SHT_GROUP)
1126 Sections.push_back(&Section);
1129 for (MCAssembler::iterator it = Asm.begin(),
1130 ie = Asm.end(); it != ie; ++it) {
1131 const MCSectionELF &Section =
1132 static_cast<const MCSectionELF &>(it->getSection());
1133 if (Section.getType() != ELF::SHT_GROUP &&
1134 Section.getType() != ELF::SHT_REL &&
1135 Section.getType() != ELF::SHT_RELA)
1136 Sections.push_back(&Section);
1139 for (MCAssembler::iterator it = Asm.begin(),
1140 ie = Asm.end(); it != ie; ++it) {
1141 const MCSectionELF &Section =
1142 static_cast<const MCSectionELF &>(it->getSection());
1143 if (Section.getType() == ELF::SHT_REL ||
1144 Section.getType() == ELF::SHT_RELA)
1145 Sections.push_back(&Section);
1149 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1150 const MCAsmLayout &Layout) {
1151 GroupMapTy GroupMap;
1152 RevGroupMapTy RevGroupMap;
1153 SectionIndexMapTy SectionIndexMap;
1155 unsigned NumUserSections = Asm.size();
1157 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1158 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1160 const unsigned NumUserAndRelocSections = Asm.size();
1161 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1162 RevGroupMap, SectionIndexMap, RelMap);
1163 const unsigned AllSections = Asm.size();
1164 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1166 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1168 // Compute symbol table information.
1169 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1172 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1174 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1175 const_cast<MCAsmLayout&>(Layout),
1179 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1180 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1181 sizeof(ELF::Elf32_Ehdr);
1182 uint64_t FileOff = HeaderSize;
1184 std::vector<const MCSectionELF*> Sections;
1185 ComputeSectionOrder(Asm, Sections);
1186 unsigned NumSections = Sections.size();
1187 SectionOffsetMapTy SectionOffsetMap;
1188 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1189 const MCSectionELF &Section = *Sections[i];
1190 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1192 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1194 // Remember the offset into the file for this section.
1195 SectionOffsetMap[&Section] = FileOff;
1197 // Get the size of the section in the output file (including padding).
1198 FileOff += GetSectionFileSize(Layout, SD);
1201 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1203 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1205 uint64_t SectionHeaderEntrySize = is64Bit() ?
1206 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1207 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1209 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1210 const MCSectionELF &Section = *Sections[i];
1211 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1213 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1215 // Remember the offset into the file for this section.
1216 SectionOffsetMap[&Section] = FileOff;
1218 // Get the size of the section in the output file (including padding).
1219 FileOff += GetSectionFileSize(Layout, SD);
1222 // Write out the ELF header ...
1223 WriteHeader(SectionHeaderOffset, NumSections + 1);
1225 // ... then the regular sections ...
1226 // + because of .shstrtab
1227 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1228 WriteDataSectionData(Asm, Layout, *Sections[i]);
1230 FileOff = OS.tell();
1231 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1232 WriteZeros(Padding);
1234 // ... then the section header table ...
1235 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1238 FileOff = OS.tell();
1240 // ... and then the remaining sections ...
1241 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1242 WriteDataSectionData(Asm, Layout, *Sections[i]);
1246 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1247 const MCSymbolData &DataA,
1248 const MCFragment &FB,
1250 bool IsPCRel) const {
1251 if (DataA.getFlags() & ELF_STB_Weak)
1253 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1254 Asm, DataA, FB,InSet, IsPCRel);
1257 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1259 bool IsLittleEndian) {
1260 switch (MOTW->getEMachine()) {
1262 case ELF::EM_X86_64:
1263 return new ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1265 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1266 case ELF::EM_MBLAZE:
1267 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1270 return new PPCELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1272 return new MipsELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1273 default: llvm_unreachable("Unsupported architecture"); break;
1277 unsigned ELFObjectWriter::GetRelocType(const MCValue &Target,
1278 const MCFixup &Fixup,
1280 bool IsRelocWithSymbol,
1281 int64_t Addend) const {
1282 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
1283 IsRelocWithSymbol, Addend);
1286 /// START OF SUBCLASSES for ELFObjectWriter
1287 //===- ARMELFObjectWriter -------------------------------------------===//
1289 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1291 bool IsLittleEndian)
1292 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1295 ARMELFObjectWriter::~ARMELFObjectWriter()
1298 // FIXME: get the real EABI Version from the Triple.
1299 unsigned ARMELFObjectWriter::getEFlags() {
1300 return ELF::EF_ARM_EABIMASK & DefaultEABIVersion;
1303 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1304 // I.e. not as an offset to a section symbol.
1305 // This code is an approximation of what ARM/gcc does.
1307 STATISTIC(PCRelCount, "Total number of PIC Relocations");
1308 STATISTIC(NonPCRelCount, "Total number of non-PIC relocations");
1310 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1311 const MCValue &Target,
1312 const MCFragment &F,
1313 const MCFixup &Fixup,
1314 bool IsPCRel) const {
1315 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1316 bool EmitThisSym = false;
1318 const MCSectionELF &Section =
1319 static_cast<const MCSectionELF&>(Symbol.getSection());
1320 bool InNormalSection = true;
1321 unsigned RelocType = 0;
1322 RelocType = GetRelocTypeInner(Target, Fixup, IsPCRel);
1325 const MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
1326 MCSymbolRefExpr::VariantKind Kind2;
1327 Kind2 = Target.getSymB() ? Target.getSymB()->getKind() :
1328 MCSymbolRefExpr::VK_None;
1329 dbgs() << "considering symbol "
1330 << Section.getSectionName() << "/"
1331 << Symbol.getName() << "/"
1332 << " Rel:" << (unsigned)RelocType
1333 << " Kind: " << (int)Kind << "/" << (int)Kind2
1335 << Symbol.isAbsolute() << "/" << Symbol.isDefined() << "/"
1336 << Symbol.isVariable() << "/" << Symbol.isTemporary()
1337 << " Counts:" << PCRelCount << "/" << NonPCRelCount << "\n");
1339 if (IsPCRel) { ++PCRelCount;
1340 switch (RelocType) {
1342 // Most relocation types are emitted as explicit symbols
1344 StringSwitch<bool>(Section.getSectionName())
1345 .Case(".data.rel.ro.local", false)
1346 .Case(".data.rel", false)
1347 .Case(".bss", false)
1351 case ELF::R_ARM_ABS32:
1352 // But things get strange with R_ARM_ABS32
1353 // In this case, most things that go in .rodata show up
1354 // as section relative relocations
1356 StringSwitch<bool>(Section.getSectionName())
1357 .Case(".data.rel.ro.local", false)
1358 .Case(".data.rel", false)
1359 .Case(".rodata", false)
1360 .Case(".bss", false)
1362 EmitThisSym = false;
1368 StringSwitch<bool>(Section.getSectionName())
1369 .Case(".data.rel.ro.local", false)
1370 .Case(".rodata", false)
1371 .Case(".data.rel", false)
1372 .Case(".bss", false)
1375 switch (RelocType) {
1376 default: EmitThisSym = true; break;
1377 case ELF::R_ARM_ABS32: EmitThisSym = false; break;
1383 if (! Symbol.isTemporary() && InNormalSection) {
1389 // Need to examine the Fixup when determining whether to
1390 // emit the relocation as an explicit symbol or as a section relative
1392 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1393 const MCFixup &Fixup,
1395 bool IsRelocWithSymbol,
1396 int64_t Addend) const {
1397 return GetRelocTypeInner(Target, Fixup, IsPCRel);
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,
1539 int64_t Addend) const {
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,
1609 int64_t Addend) const {
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 //===- MipsELFObjectWriter -------------------------------------------===//
1641 MipsELFObjectWriter::MipsELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1643 bool IsLittleEndian)
1644 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {}
1646 MipsELFObjectWriter::~MipsELFObjectWriter() {}
1648 // FIXME: get the real EABI Version from the Triple.
1649 unsigned MipsELFObjectWriter::getEFlags() {
1650 return ELF::EF_MIPS_NOREORDER | ELF::EF_MIPS_ARCH_32R2;
1653 const MCSymbol *MipsELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1654 const MCValue &Target,
1655 const MCFragment &F,
1656 const MCFixup &Fixup,
1657 bool IsPCRel) const {
1658 assert(Target.getSymA() && "SymA cannot be 0.");
1659 const MCSymbol &Sym = Target.getSymA()->getSymbol();
1661 if (Sym.getSection().getKind().isMergeableCString() ||
1662 Sym.getSection().getKind().isMergeableConst())
1668 unsigned MipsELFObjectWriter::GetRelocType(const MCValue &Target,
1669 const MCFixup &Fixup,
1671 bool IsRelocWithSymbol,
1672 int64_t Addend) const {
1673 // determine the type of the relocation
1674 unsigned Type = (unsigned)ELF::R_MIPS_NONE;
1675 unsigned Kind = (unsigned)Fixup.getKind();
1679 llvm_unreachable("invalid fixup kind!");
1681 Type = ELF::R_MIPS_32;
1684 Type = ELF::R_MIPS_GPREL32;
1686 case Mips::fixup_Mips_GPREL16:
1687 Type = ELF::R_MIPS_GPREL16;
1689 case Mips::fixup_Mips_26:
1690 Type = ELF::R_MIPS_26;
1692 case Mips::fixup_Mips_CALL16:
1693 Type = ELF::R_MIPS_CALL16;
1695 case Mips::fixup_Mips_GOT_Global:
1696 case Mips::fixup_Mips_GOT_Local:
1697 Type = ELF::R_MIPS_GOT16;
1699 case Mips::fixup_Mips_HI16:
1700 Type = ELF::R_MIPS_HI16;
1702 case Mips::fixup_Mips_LO16:
1703 Type = ELF::R_MIPS_LO16;
1705 case Mips::fixup_Mips_TLSGD:
1706 Type = ELF::R_MIPS_TLS_GD;
1708 case Mips::fixup_Mips_GOTTPREL:
1709 Type = ELF::R_MIPS_TLS_GOTTPREL;
1711 case Mips::fixup_Mips_TPREL_HI:
1712 Type = ELF::R_MIPS_TLS_TPREL_HI16;
1714 case Mips::fixup_Mips_TPREL_LO:
1715 Type = ELF::R_MIPS_TLS_TPREL_LO16;
1717 case Mips::fixup_Mips_Branch_PCRel:
1718 case Mips::fixup_Mips_PC16:
1719 Type = ELF::R_MIPS_PC16;