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);
450 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
451 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
452 if (RelocNeedsGOT(Modifier))
455 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
458 adjustFixupOffset(Fixup, RelocOffset);
460 if (!hasRelocationAddend())
464 assert(isInt<64>(Addend));
466 assert(isInt<32>(Addend));
468 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
469 Relocations[Fragment->getParent()].push_back(ERE);
474 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
476 MCSymbolData &SD = Asm.getSymbolData(*S);
477 return SD.getIndex();
480 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
481 const MCSymbolData &Data,
482 bool Used, bool Renamed) {
483 if (Data.getFlags() & ELF_Other_Weakref)
492 const MCSymbol &Symbol = Data.getSymbol();
494 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
497 const MCSymbol &A = Symbol.AliasedSymbol();
498 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
501 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
502 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
505 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
508 if (Symbol.isTemporary())
514 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
515 bool isUsedInReloc) {
516 if (Data.isExternal())
519 const MCSymbol &Symbol = Data.getSymbol();
520 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
522 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
523 if (isSignature && !isUsedInReloc)
532 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
533 SectionIndexMapTy &SectionIndexMap,
534 const RelMapTy &RelMap) {
536 for (MCAssembler::iterator it = Asm.begin(),
537 ie = Asm.end(); it != ie; ++it) {
538 const MCSectionELF &Section =
539 static_cast<const MCSectionELF &>(it->getSection());
540 if (Section.getType() != ELF::SHT_GROUP)
542 SectionIndexMap[&Section] = Index++;
545 for (MCAssembler::iterator it = Asm.begin(),
546 ie = Asm.end(); it != ie; ++it) {
547 const MCSectionELF &Section =
548 static_cast<const MCSectionELF &>(it->getSection());
549 if (Section.getType() == ELF::SHT_GROUP ||
550 Section.getType() == ELF::SHT_REL ||
551 Section.getType() == ELF::SHT_RELA)
553 SectionIndexMap[&Section] = Index++;
554 const MCSectionELF *RelSection = RelMap.lookup(&Section);
556 SectionIndexMap[RelSection] = Index++;
560 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
561 const SectionIndexMapTy &SectionIndexMap,
562 RevGroupMapTy RevGroupMap,
563 unsigned NumRegularSections) {
564 // FIXME: Is this the correct place to do this?
565 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
567 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
568 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
569 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
570 Data.setExternal(true);
571 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
574 // Index 0 is always the empty string.
575 StringMap<uint64_t> StringIndexMap;
576 StringTable += '\x00';
578 // FIXME: We could optimize suffixes in strtab in the same way we
579 // optimize them in shstrtab.
581 // Add the data for the symbols.
582 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
583 ie = Asm.symbol_end(); it != ie; ++it) {
584 const MCSymbol &Symbol = it->getSymbol();
586 bool Used = UsedInReloc.count(&Symbol);
587 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
588 bool isSignature = RevGroupMap.count(&Symbol);
590 if (!isInSymtab(Asm, *it,
591 Used || WeakrefUsed || isSignature,
592 Renames.count(&Symbol)))
597 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
599 // Undefined symbols are global, but this is the first place we
600 // are able to set it.
601 bool Local = isLocal(*it, isSignature, Used);
602 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
603 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
604 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
605 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
608 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
609 MCELF::SetBinding(*it, ELF::STB_WEAK);
611 if (it->isCommon()) {
613 MSD.SectionIndex = ELF::SHN_COMMON;
614 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
615 MSD.SectionIndex = ELF::SHN_ABS;
616 } else if (RefSymbol.isUndefined()) {
617 if (isSignature && !Used)
618 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
620 MSD.SectionIndex = ELF::SHN_UNDEF;
622 const MCSectionELF &Section =
623 static_cast<const MCSectionELF&>(RefSymbol.getSection());
624 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
625 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
626 NeedsSymtabShndx = true;
627 assert(MSD.SectionIndex && "Invalid section index!");
630 // The @@@ in symbol version is replaced with @ in undefined symbols and
631 // @@ in defined ones.
632 StringRef Name = Symbol.getName();
635 size_t Pos = Name.find("@@@");
636 if (Pos != StringRef::npos) {
637 Buf += Name.substr(0, Pos);
638 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
639 Buf += Name.substr(Pos + Skip);
643 uint64_t &Entry = StringIndexMap[Name];
645 Entry = StringTable.size();
647 StringTable += '\x00';
649 MSD.StringIndex = Entry;
650 if (MSD.SectionIndex == ELF::SHN_UNDEF)
651 UndefinedSymbolData.push_back(MSD);
653 LocalSymbolData.push_back(MSD);
655 ExternalSymbolData.push_back(MSD);
658 // Symbols are required to be in lexicographic order.
659 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
660 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
661 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
663 // Set the symbol indices. Local symbols must come before all other
664 // symbols with non-local bindings.
666 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
667 LocalSymbolData[i].SymbolData->setIndex(Index++);
669 Index += NumRegularSections;
671 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
672 ExternalSymbolData[i].SymbolData->setIndex(Index++);
673 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
674 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
676 if (NumRegularSections > ELF::SHN_LORESERVE)
677 NeedsSymtabShndx = true;
680 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
683 for (MCAssembler::const_iterator it = Asm.begin(),
684 ie = Asm.end(); it != ie; ++it) {
685 const MCSectionData &SD = *it;
686 if (Relocations[&SD].empty())
689 MCContext &Ctx = Asm.getContext();
690 const MCSectionELF &Section =
691 static_cast<const MCSectionELF&>(SD.getSection());
693 const StringRef SectionName = Section.getSectionName();
694 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
695 RelaSectionName += SectionName;
698 if (hasRelocationAddend())
699 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
701 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
703 const MCSectionELF *RelaSection =
704 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
705 ELF::SHT_RELA : ELF::SHT_REL, 0,
706 SectionKind::getReadOnly(),
708 RelMap[&Section] = RelaSection;
709 Asm.getOrCreateSectionData(*RelaSection);
713 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
714 const RelMapTy &RelMap) {
715 for (MCAssembler::const_iterator it = Asm.begin(),
716 ie = Asm.end(); it != ie; ++it) {
717 const MCSectionData &SD = *it;
718 const MCSectionELF &Section =
719 static_cast<const MCSectionELF&>(SD.getSection());
721 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
724 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
725 RelaSD.setAlignment(is64Bit() ? 8 : 4);
727 MCDataFragment *F = new MCDataFragment(&RelaSD);
728 WriteRelocationsFragment(Asm, F, &*it);
732 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
733 uint64_t Flags, uint64_t Address,
734 uint64_t Offset, uint64_t Size,
735 uint32_t Link, uint32_t Info,
737 uint64_t EntrySize) {
738 Write32(Name); // sh_name: index into string table
739 Write32(Type); // sh_type
740 WriteWord(Flags); // sh_flags
741 WriteWord(Address); // sh_addr
742 WriteWord(Offset); // sh_offset
743 WriteWord(Size); // sh_size
744 Write32(Link); // sh_link
745 Write32(Info); // sh_info
746 WriteWord(Alignment); // sh_addralign
747 WriteWord(EntrySize); // sh_entsize
750 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
752 const MCSectionData *SD) {
753 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
754 // sort by the r_offset just like gnu as does
755 array_pod_sort(Relocs.begin(), Relocs.end());
757 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
758 ELFRelocationEntry entry = Relocs[e - i - 1];
762 else if (entry.Index < 0)
763 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
765 entry.Index += LocalSymbolData.size();
767 String64(*F, entry.r_offset);
769 struct ELF::Elf64_Rela ERE64;
770 ERE64.setSymbolAndType(entry.Index, entry.Type);
771 String64(*F, ERE64.r_info);
773 if (hasRelocationAddend())
774 String64(*F, entry.r_addend);
776 String32(*F, entry.r_offset);
778 struct ELF::Elf32_Rela ERE32;
779 ERE32.setSymbolAndType(entry.Index, entry.Type);
780 String32(*F, ERE32.r_info);
782 if (hasRelocationAddend())
783 String32(*F, entry.r_addend);
788 static int compareBySuffix(const void *a, const void *b) {
789 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
790 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
791 const StringRef &NameA = secA->getSectionName();
792 const StringRef &NameB = secB->getSectionName();
793 const unsigned sizeA = NameA.size();
794 const unsigned sizeB = NameB.size();
795 const unsigned len = std::min(sizeA, sizeB);
796 for (unsigned int i = 0; i < len; ++i) {
797 char ca = NameA[sizeA - i - 1];
798 char cb = NameB[sizeB - i - 1];
803 return sizeB - sizeA;
806 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
808 SectionIndexMapTy &SectionIndexMap,
809 const RelMapTy &RelMap) {
810 MCContext &Ctx = Asm.getContext();
813 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
815 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
816 const MCSectionELF *ShstrtabSection =
817 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
818 SectionKind::getReadOnly());
819 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
820 ShstrtabSD.setAlignment(1);
822 const MCSectionELF *SymtabSection =
823 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
824 SectionKind::getReadOnly(),
826 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
827 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
829 MCSectionData *SymtabShndxSD = NULL;
831 if (NeedsSymtabShndx) {
832 const MCSectionELF *SymtabShndxSection =
833 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
834 SectionKind::getReadOnly(), 4, "");
835 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
836 SymtabShndxSD->setAlignment(4);
839 const MCSectionELF *StrtabSection;
840 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
841 SectionKind::getReadOnly());
842 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
843 StrtabSD.setAlignment(1);
845 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
847 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
848 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
849 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
852 F = new MCDataFragment(&SymtabSD);
853 MCDataFragment *ShndxF = NULL;
854 if (NeedsSymtabShndx) {
855 ShndxF = new MCDataFragment(SymtabShndxSD);
857 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
859 F = new MCDataFragment(&StrtabSD);
860 F->getContents().append(StringTable.begin(), StringTable.end());
862 F = new MCDataFragment(&ShstrtabSD);
864 std::vector<const MCSectionELF*> Sections;
865 for (MCAssembler::const_iterator it = Asm.begin(),
866 ie = Asm.end(); it != ie; ++it) {
867 const MCSectionELF &Section =
868 static_cast<const MCSectionELF&>(it->getSection());
869 Sections.push_back(&Section);
871 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
873 // Section header string table.
875 // The first entry of a string table holds a null character so skip
878 F->getContents() += '\x00';
880 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
881 const MCSectionELF &Section = *Sections[I];
883 StringRef Name = Section.getSectionName();
885 StringRef PreviousName = Sections[I - 1]->getSectionName();
886 if (PreviousName.endswith(Name)) {
887 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
891 // Remember the index into the string table so we can write it
892 // into the sh_name field of the section header table.
893 SectionStringTableIndex[&Section] = Index;
895 Index += Name.size() + 1;
896 F->getContents() += Name;
897 F->getContents() += '\x00';
901 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
903 GroupMapTy &GroupMap,
904 RevGroupMapTy &RevGroupMap,
905 SectionIndexMapTy &SectionIndexMap,
906 const RelMapTy &RelMap) {
907 // Create the .note.GNU-stack section if needed.
908 MCContext &Ctx = Asm.getContext();
909 if (Asm.getNoExecStack()) {
910 const MCSectionELF *GnuStackSection =
911 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
912 SectionKind::getReadOnly());
913 Asm.getOrCreateSectionData(*GnuStackSection);
917 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
919 const MCSectionELF &Section =
920 static_cast<const MCSectionELF&>(it->getSection());
921 if (!(Section.getFlags() & ELF::SHF_GROUP))
924 const MCSymbol *SignatureSymbol = Section.getGroup();
925 Asm.getOrCreateSymbolData(*SignatureSymbol);
926 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
928 Group = Ctx.CreateELFGroupSection();
929 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
930 Data.setAlignment(4);
931 MCDataFragment *F = new MCDataFragment(&Data);
932 String32(*F, ELF::GRP_COMDAT);
934 GroupMap[Group] = SignatureSymbol;
937 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
939 // Add sections to the groups
940 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
942 const MCSectionELF &Section =
943 static_cast<const MCSectionELF&>(it->getSection());
944 if (!(Section.getFlags() & ELF::SHF_GROUP))
946 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
947 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
948 // FIXME: we could use the previous fragment
949 MCDataFragment *F = new MCDataFragment(&Data);
950 unsigned Index = SectionIndexMap.lookup(&Section);
955 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
956 const SectionIndexMapTy &SectionIndexMap,
957 uint32_t GroupSymbolIndex,
958 uint64_t Offset, uint64_t Size,
960 const MCSectionELF &Section) {
961 uint64_t sh_link = 0;
962 uint64_t sh_info = 0;
964 switch(Section.getType()) {
965 case ELF::SHT_DYNAMIC:
966 sh_link = SectionStringTableIndex[&Section];
971 case ELF::SHT_RELA: {
972 const MCSectionELF *SymtabSection;
973 const MCSectionELF *InfoSection;
974 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
976 SectionKind::getReadOnly());
977 sh_link = SectionIndexMap.lookup(SymtabSection);
978 assert(sh_link && ".symtab not found");
980 // Remove ".rel" and ".rela" prefixes.
981 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
982 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
984 InfoSection = Asm.getContext().getELFSection(SectionName,
985 ELF::SHT_PROGBITS, 0,
986 SectionKind::getReadOnly());
987 sh_info = SectionIndexMap.lookup(InfoSection);
991 case ELF::SHT_SYMTAB:
992 case ELF::SHT_DYNSYM:
993 sh_link = StringTableIndex;
994 sh_info = LastLocalSymbolIndex;
997 case ELF::SHT_SYMTAB_SHNDX:
998 sh_link = SymbolTableIndex;
1001 case ELF::SHT_PROGBITS:
1002 case ELF::SHT_STRTAB:
1003 case ELF::SHT_NOBITS:
1006 case ELF::SHT_ARM_ATTRIBUTES:
1007 case ELF::SHT_INIT_ARRAY:
1008 case ELF::SHT_FINI_ARRAY:
1009 case ELF::SHT_PREINIT_ARRAY:
1010 case ELF::SHT_X86_64_UNWIND:
1014 case ELF::SHT_GROUP:
1015 sh_link = SymbolTableIndex;
1016 sh_info = GroupSymbolIndex;
1020 assert(0 && "FIXME: sh_type value not supported!");
1024 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1025 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1026 Alignment, Section.getEntrySize());
1029 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1030 return SD.getOrdinal() == ~UINT32_C(0) &&
1031 !SD.getSection().isVirtualSection();
1034 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1036 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1038 const MCFragment &F = *i;
1039 assert(F.getKind() == MCFragment::FT_Data);
1040 Ret += cast<MCDataFragment>(F).getContents().size();
1045 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1046 const MCSectionData &SD) {
1047 if (IsELFMetaDataSection(SD))
1048 return DataSectionSize(SD);
1049 return Layout.getSectionFileSize(&SD);
1052 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1053 const MCSectionData &SD) {
1054 if (IsELFMetaDataSection(SD))
1055 return DataSectionSize(SD);
1056 return Layout.getSectionAddressSize(&SD);
1059 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1060 const MCAsmLayout &Layout,
1061 const MCSectionELF &Section) {
1062 uint64_t FileOff = OS.tell();
1063 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1065 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1066 WriteZeros(Padding);
1069 FileOff += GetSectionFileSize(Layout, SD);
1071 if (IsELFMetaDataSection(SD)) {
1072 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1074 const MCFragment &F = *i;
1075 assert(F.getKind() == MCFragment::FT_Data);
1076 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1079 Asm.writeSectionData(&SD, Layout);
1083 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1084 const GroupMapTy &GroupMap,
1085 const MCAsmLayout &Layout,
1086 const SectionIndexMapTy &SectionIndexMap,
1087 const SectionOffsetMapTy &SectionOffsetMap) {
1088 const unsigned NumSections = Asm.size() + 1;
1090 std::vector<const MCSectionELF*> Sections;
1091 Sections.resize(NumSections - 1);
1093 for (SectionIndexMapTy::const_iterator i=
1094 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1095 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1096 Sections[p.second - 1] = p.first;
1099 // Null section first.
1100 uint64_t FirstSectionSize =
1101 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1102 uint32_t FirstSectionLink =
1103 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1104 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1106 for (unsigned i = 0; i < NumSections - 1; ++i) {
1107 const MCSectionELF &Section = *Sections[i];
1108 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1109 uint32_t GroupSymbolIndex;
1110 if (Section.getType() != ELF::SHT_GROUP)
1111 GroupSymbolIndex = 0;
1113 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1114 GroupMap.lookup(&Section));
1116 uint64_t Size = GetSectionAddressSize(Layout, SD);
1118 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1119 SectionOffsetMap.lookup(&Section), Size,
1120 SD.getAlignment(), Section);
1124 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1125 std::vector<const MCSectionELF*> &Sections) {
1126 for (MCAssembler::iterator it = Asm.begin(),
1127 ie = Asm.end(); it != ie; ++it) {
1128 const MCSectionELF &Section =
1129 static_cast<const MCSectionELF &>(it->getSection());
1130 if (Section.getType() == ELF::SHT_GROUP)
1131 Sections.push_back(&Section);
1134 for (MCAssembler::iterator it = Asm.begin(),
1135 ie = Asm.end(); it != ie; ++it) {
1136 const MCSectionELF &Section =
1137 static_cast<const MCSectionELF &>(it->getSection());
1138 if (Section.getType() != ELF::SHT_GROUP &&
1139 Section.getType() != ELF::SHT_REL &&
1140 Section.getType() != ELF::SHT_RELA)
1141 Sections.push_back(&Section);
1144 for (MCAssembler::iterator it = Asm.begin(),
1145 ie = Asm.end(); it != ie; ++it) {
1146 const MCSectionELF &Section =
1147 static_cast<const MCSectionELF &>(it->getSection());
1148 if (Section.getType() == ELF::SHT_REL ||
1149 Section.getType() == ELF::SHT_RELA)
1150 Sections.push_back(&Section);
1154 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1155 const MCAsmLayout &Layout) {
1156 GroupMapTy GroupMap;
1157 RevGroupMapTy RevGroupMap;
1158 SectionIndexMapTy SectionIndexMap;
1160 unsigned NumUserSections = Asm.size();
1162 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1163 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1165 const unsigned NumUserAndRelocSections = Asm.size();
1166 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1167 RevGroupMap, SectionIndexMap, RelMap);
1168 const unsigned AllSections = Asm.size();
1169 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1171 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1173 // Compute symbol table information.
1174 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1177 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1179 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1180 const_cast<MCAsmLayout&>(Layout),
1184 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1185 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1186 sizeof(ELF::Elf32_Ehdr);
1187 uint64_t FileOff = HeaderSize;
1189 std::vector<const MCSectionELF*> Sections;
1190 ComputeSectionOrder(Asm, Sections);
1191 unsigned NumSections = Sections.size();
1192 SectionOffsetMapTy SectionOffsetMap;
1193 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1194 const MCSectionELF &Section = *Sections[i];
1195 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1197 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1199 // Remember the offset into the file for this section.
1200 SectionOffsetMap[&Section] = FileOff;
1202 // Get the size of the section in the output file (including padding).
1203 FileOff += GetSectionFileSize(Layout, SD);
1206 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1208 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1210 uint64_t SectionHeaderEntrySize = is64Bit() ?
1211 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1212 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1214 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1215 const MCSectionELF &Section = *Sections[i];
1216 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1218 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1220 // Remember the offset into the file for this section.
1221 SectionOffsetMap[&Section] = FileOff;
1223 // Get the size of the section in the output file (including padding).
1224 FileOff += GetSectionFileSize(Layout, SD);
1227 // Write out the ELF header ...
1228 WriteHeader(SectionHeaderOffset, NumSections + 1);
1230 // ... then the regular sections ...
1231 // + because of .shstrtab
1232 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1233 WriteDataSectionData(Asm, Layout, *Sections[i]);
1235 FileOff = OS.tell();
1236 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1237 WriteZeros(Padding);
1239 // ... then the section header table ...
1240 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1243 FileOff = OS.tell();
1245 // ... and then the remaining sections ...
1246 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1247 WriteDataSectionData(Asm, Layout, *Sections[i]);
1251 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1252 const MCSymbolData &DataA,
1253 const MCFragment &FB,
1255 bool IsPCRel) const {
1256 if (DataA.getFlags() & ELF_STB_Weak)
1258 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1259 Asm, DataA, FB,InSet, IsPCRel);
1262 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1264 bool IsLittleEndian) {
1265 switch (MOTW->getEMachine()) {
1267 case ELF::EM_X86_64:
1268 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1270 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1271 case ELF::EM_MBLAZE:
1272 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1275 return new PPCELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1277 return new MipsELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1278 default: llvm_unreachable("Unsupported architecture"); break;
1282 /// START OF SUBCLASSES for ELFObjectWriter
1283 //===- ARMELFObjectWriter -------------------------------------------===//
1285 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1287 bool IsLittleEndian)
1288 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1291 ARMELFObjectWriter::~ARMELFObjectWriter()
1294 // FIXME: get the real EABI Version from the Triple.
1295 void ARMELFObjectWriter::WriteEFlags() {
1296 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1299 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1300 // I.e. not as an offset to a section symbol.
1301 // This code is an approximation of what ARM/gcc does.
1303 STATISTIC(PCRelCount, "Total number of PIC Relocations");
1304 STATISTIC(NonPCRelCount, "Total number of non-PIC relocations");
1306 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1307 const MCValue &Target,
1308 const MCFragment &F,
1309 const MCFixup &Fixup,
1310 bool IsPCRel) const {
1311 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1312 bool EmitThisSym = false;
1314 const MCSectionELF &Section =
1315 static_cast<const MCSectionELF&>(Symbol.getSection());
1316 bool InNormalSection = true;
1317 unsigned RelocType = 0;
1318 RelocType = GetRelocTypeInner(Target, Fixup, IsPCRel);
1321 const MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
1322 MCSymbolRefExpr::VariantKind Kind2;
1323 Kind2 = Target.getSymB() ? Target.getSymB()->getKind() :
1324 MCSymbolRefExpr::VK_None;
1325 dbgs() << "considering symbol "
1326 << Section.getSectionName() << "/"
1327 << Symbol.getName() << "/"
1328 << " Rel:" << (unsigned)RelocType
1329 << " Kind: " << (int)Kind << "/" << (int)Kind2
1331 << Symbol.isAbsolute() << "/" << Symbol.isDefined() << "/"
1332 << Symbol.isVariable() << "/" << Symbol.isTemporary()
1333 << " Counts:" << PCRelCount << "/" << NonPCRelCount << "\n");
1335 if (IsPCRel) { ++PCRelCount;
1336 switch (RelocType) {
1338 // Most relocation types are emitted as explicit symbols
1340 StringSwitch<bool>(Section.getSectionName())
1341 .Case(".data.rel.ro.local", false)
1342 .Case(".data.rel", false)
1343 .Case(".bss", false)
1347 case ELF::R_ARM_ABS32:
1348 // But things get strange with R_ARM_ABS32
1349 // In this case, most things that go in .rodata show up
1350 // as section relative relocations
1352 StringSwitch<bool>(Section.getSectionName())
1353 .Case(".data.rel.ro.local", false)
1354 .Case(".data.rel", false)
1355 .Case(".rodata", false)
1356 .Case(".bss", false)
1358 EmitThisSym = false;
1364 StringSwitch<bool>(Section.getSectionName())
1365 .Case(".data.rel.ro.local", false)
1366 .Case(".rodata", false)
1367 .Case(".data.rel", false)
1368 .Case(".bss", false)
1371 switch (RelocType) {
1372 default: EmitThisSym = true; break;
1373 case ELF::R_ARM_ABS32: EmitThisSym = false; break;
1379 if (! Symbol.isTemporary() && InNormalSection) {
1385 // Need to examine the Fixup when determining whether to
1386 // emit the relocation as an explicit symbol or as a section relative
1388 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1389 const MCFixup &Fixup,
1391 bool IsRelocWithSymbol,
1392 int64_t Addend) const {
1393 return GetRelocTypeInner(Target, Fixup, IsPCRel);
1396 unsigned ARMELFObjectWriter::GetRelocTypeInner(const MCValue &Target,
1397 const MCFixup &Fixup,
1398 bool IsPCRel) const {
1399 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1400 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1404 switch ((unsigned)Fixup.getKind()) {
1405 default: assert(0 && "Unimplemented");
1408 default: llvm_unreachable("Unsupported Modifier");
1409 case MCSymbolRefExpr::VK_None:
1410 Type = ELF::R_ARM_REL32;
1412 case MCSymbolRefExpr::VK_ARM_TLSGD:
1413 assert(0 && "unimplemented");
1415 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1416 Type = ELF::R_ARM_TLS_IE32;
1420 case ARM::fixup_arm_uncondbranch:
1422 case MCSymbolRefExpr::VK_ARM_PLT:
1423 Type = ELF::R_ARM_PLT32;
1426 Type = ELF::R_ARM_CALL;
1430 case ARM::fixup_arm_condbranch:
1431 Type = ELF::R_ARM_JUMP24;
1433 case ARM::fixup_arm_movt_hi16:
1434 case ARM::fixup_arm_movt_hi16_pcrel:
1435 Type = ELF::R_ARM_MOVT_PREL;
1437 case ARM::fixup_arm_movw_lo16:
1438 case ARM::fixup_arm_movw_lo16_pcrel:
1439 Type = ELF::R_ARM_MOVW_PREL_NC;
1441 case ARM::fixup_t2_movt_hi16:
1442 case ARM::fixup_t2_movt_hi16_pcrel:
1443 Type = ELF::R_ARM_THM_MOVT_PREL;
1445 case ARM::fixup_t2_movw_lo16:
1446 case ARM::fixup_t2_movw_lo16_pcrel:
1447 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1449 case ARM::fixup_arm_thumb_bl:
1450 case ARM::fixup_arm_thumb_blx:
1452 case MCSymbolRefExpr::VK_ARM_PLT:
1453 Type = ELF::R_ARM_THM_CALL;
1456 Type = ELF::R_ARM_NONE;
1462 switch ((unsigned)Fixup.getKind()) {
1463 default: llvm_unreachable("invalid fixup kind!");
1466 default: llvm_unreachable("Unsupported Modifier"); break;
1467 case MCSymbolRefExpr::VK_ARM_GOT:
1468 Type = ELF::R_ARM_GOT_BREL;
1470 case MCSymbolRefExpr::VK_ARM_TLSGD:
1471 Type = ELF::R_ARM_TLS_GD32;
1473 case MCSymbolRefExpr::VK_ARM_TPOFF:
1474 Type = ELF::R_ARM_TLS_LE32;
1476 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1477 Type = ELF::R_ARM_TLS_IE32;
1479 case MCSymbolRefExpr::VK_None:
1480 Type = ELF::R_ARM_ABS32;
1482 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1483 Type = ELF::R_ARM_GOTOFF32;
1487 case ARM::fixup_arm_ldst_pcrel_12:
1488 case ARM::fixup_arm_pcrel_10:
1489 case ARM::fixup_arm_adr_pcrel_12:
1490 case ARM::fixup_arm_thumb_bl:
1491 case ARM::fixup_arm_thumb_cb:
1492 case ARM::fixup_arm_thumb_cp:
1493 case ARM::fixup_arm_thumb_br:
1494 assert(0 && "Unimplemented");
1496 case ARM::fixup_arm_uncondbranch:
1497 Type = ELF::R_ARM_CALL;
1499 case ARM::fixup_arm_condbranch:
1500 Type = ELF::R_ARM_JUMP24;
1502 case ARM::fixup_arm_movt_hi16:
1503 Type = ELF::R_ARM_MOVT_ABS;
1505 case ARM::fixup_arm_movw_lo16:
1506 Type = ELF::R_ARM_MOVW_ABS_NC;
1508 case ARM::fixup_t2_movt_hi16:
1509 Type = ELF::R_ARM_THM_MOVT_ABS;
1511 case ARM::fixup_t2_movw_lo16:
1512 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1520 //===- PPCELFObjectWriter -------------------------------------------===//
1522 PPCELFObjectWriter::PPCELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1524 bool IsLittleEndian)
1525 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1528 PPCELFObjectWriter::~PPCELFObjectWriter() {
1531 unsigned PPCELFObjectWriter::GetRelocType(const MCValue &Target,
1532 const MCFixup &Fixup,
1534 bool IsRelocWithSymbol,
1535 int64_t Addend) const {
1536 // determine the type of the relocation
1539 switch ((unsigned)Fixup.getKind()) {
1541 llvm_unreachable("Unimplemented");
1542 case PPC::fixup_ppc_br24:
1543 Type = ELF::R_PPC_REL24;
1546 Type = ELF::R_PPC_REL32;
1550 switch ((unsigned)Fixup.getKind()) {
1551 default: llvm_unreachable("invalid fixup kind!");
1552 case PPC::fixup_ppc_br24:
1553 Type = ELF::R_PPC_ADDR24;
1555 case PPC::fixup_ppc_brcond14:
1556 Type = ELF::R_PPC_ADDR14_BRTAKEN; // XXX: or BRNTAKEN?_
1558 case PPC::fixup_ppc_ha16:
1559 Type = ELF::R_PPC_ADDR16_HA;
1561 case PPC::fixup_ppc_lo16:
1562 Type = ELF::R_PPC_ADDR16_LO;
1564 case PPC::fixup_ppc_lo14:
1565 Type = ELF::R_PPC_ADDR14;
1568 Type = ELF::R_PPC_ADDR32;
1571 Type = ELF::R_PPC_ADDR16;
1578 void PPCELFObjectWriter::
1579 adjustFixupOffset(const MCFixup &Fixup, uint64_t &RelocOffset) {
1580 switch ((unsigned)Fixup.getKind()) {
1581 case PPC::fixup_ppc_ha16:
1582 case PPC::fixup_ppc_lo16:
1590 //===- MBlazeELFObjectWriter -------------------------------------------===//
1592 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1594 bool IsLittleEndian)
1595 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1598 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1601 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1602 const MCFixup &Fixup,
1604 bool IsRelocWithSymbol,
1605 int64_t Addend) const {
1606 // determine the type of the relocation
1609 switch ((unsigned)Fixup.getKind()) {
1611 llvm_unreachable("Unimplemented");
1613 Type = ELF::R_MICROBLAZE_64_PCREL;
1616 Type = ELF::R_MICROBLAZE_32_PCREL;
1620 switch ((unsigned)Fixup.getKind()) {
1621 default: llvm_unreachable("invalid fixup kind!");
1623 Type = ((IsRelocWithSymbol || Addend !=0)
1624 ? ELF::R_MICROBLAZE_32
1625 : ELF::R_MICROBLAZE_64);
1628 Type = ELF::R_MICROBLAZE_32;
1635 //===- X86ELFObjectWriter -------------------------------------------===//
1638 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1640 bool IsLittleEndian)
1641 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1644 X86ELFObjectWriter::~X86ELFObjectWriter()
1647 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1648 const MCFixup &Fixup,
1650 bool IsRelocWithSymbol,
1651 int64_t Addend) const {
1652 // determine the type of the relocation
1654 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1655 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1659 switch ((unsigned)Fixup.getKind()) {
1660 default: llvm_unreachable("invalid fixup kind!");
1662 case FK_Data_8: Type = ELF::R_X86_64_PC64; break;
1663 case FK_Data_4: Type = ELF::R_X86_64_PC32; break;
1664 case FK_Data_2: Type = ELF::R_X86_64_PC16; break;
1667 assert(Modifier == MCSymbolRefExpr::VK_None);
1668 Type = ELF::R_X86_64_PC64;
1670 case X86::reloc_signed_4byte:
1671 case X86::reloc_riprel_4byte_movq_load:
1672 case X86::reloc_riprel_4byte:
1676 llvm_unreachable("Unimplemented");
1677 case MCSymbolRefExpr::VK_None:
1678 Type = ELF::R_X86_64_PC32;
1680 case MCSymbolRefExpr::VK_PLT:
1681 Type = ELF::R_X86_64_PLT32;
1683 case MCSymbolRefExpr::VK_GOTPCREL:
1684 Type = ELF::R_X86_64_GOTPCREL;
1686 case MCSymbolRefExpr::VK_GOTTPOFF:
1687 Type = ELF::R_X86_64_GOTTPOFF;
1689 case MCSymbolRefExpr::VK_TLSGD:
1690 Type = ELF::R_X86_64_TLSGD;
1692 case MCSymbolRefExpr::VK_TLSLD:
1693 Type = ELF::R_X86_64_TLSLD;
1698 assert(Modifier == MCSymbolRefExpr::VK_None);
1699 Type = ELF::R_X86_64_PC16;
1702 assert(Modifier == MCSymbolRefExpr::VK_None);
1703 Type = ELF::R_X86_64_PC8;
1707 switch ((unsigned)Fixup.getKind()) {
1708 default: llvm_unreachable("invalid fixup kind!");
1709 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1710 case X86::reloc_signed_4byte:
1713 llvm_unreachable("Unimplemented");
1714 case MCSymbolRefExpr::VK_None:
1715 Type = ELF::R_X86_64_32S;
1717 case MCSymbolRefExpr::VK_GOT:
1718 Type = ELF::R_X86_64_GOT32;
1720 case MCSymbolRefExpr::VK_GOTPCREL:
1721 Type = ELF::R_X86_64_GOTPCREL;
1723 case MCSymbolRefExpr::VK_TPOFF:
1724 Type = ELF::R_X86_64_TPOFF32;
1726 case MCSymbolRefExpr::VK_DTPOFF:
1727 Type = ELF::R_X86_64_DTPOFF32;
1732 Type = ELF::R_X86_64_32;
1734 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1736 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1741 switch ((unsigned)Fixup.getKind()) {
1742 default: llvm_unreachable("invalid fixup kind!");
1744 case X86::reloc_global_offset_table:
1745 Type = ELF::R_386_GOTPC;
1748 case X86::reloc_signed_4byte:
1753 llvm_unreachable("Unimplemented");
1754 case MCSymbolRefExpr::VK_None:
1755 Type = ELF::R_386_PC32;
1757 case MCSymbolRefExpr::VK_PLT:
1758 Type = ELF::R_386_PLT32;
1764 switch ((unsigned)Fixup.getKind()) {
1765 default: llvm_unreachable("invalid fixup kind!");
1767 case X86::reloc_global_offset_table:
1768 Type = ELF::R_386_GOTPC;
1771 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1773 case X86::reloc_signed_4byte:
1778 llvm_unreachable("Unimplemented");
1779 case MCSymbolRefExpr::VK_None:
1780 Type = ELF::R_386_32;
1782 case MCSymbolRefExpr::VK_GOT:
1783 Type = ELF::R_386_GOT32;
1785 case MCSymbolRefExpr::VK_GOTOFF:
1786 Type = ELF::R_386_GOTOFF;
1788 case MCSymbolRefExpr::VK_TLSGD:
1789 Type = ELF::R_386_TLS_GD;
1791 case MCSymbolRefExpr::VK_TPOFF:
1792 Type = ELF::R_386_TLS_LE_32;
1794 case MCSymbolRefExpr::VK_INDNTPOFF:
1795 Type = ELF::R_386_TLS_IE;
1797 case MCSymbolRefExpr::VK_NTPOFF:
1798 Type = ELF::R_386_TLS_LE;
1800 case MCSymbolRefExpr::VK_GOTNTPOFF:
1801 Type = ELF::R_386_TLS_GOTIE;
1803 case MCSymbolRefExpr::VK_TLSLDM:
1804 Type = ELF::R_386_TLS_LDM;
1806 case MCSymbolRefExpr::VK_DTPOFF:
1807 Type = ELF::R_386_TLS_LDO_32;
1809 case MCSymbolRefExpr::VK_GOTTPOFF:
1810 Type = ELF::R_386_TLS_IE_32;
1814 case FK_Data_2: Type = ELF::R_386_16; break;
1816 case FK_Data_1: Type = ELF::R_386_8; break;
1824 //===- MipsELFObjectWriter -------------------------------------------===//
1826 MipsELFObjectWriter::MipsELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1828 bool IsLittleEndian)
1829 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {}
1831 MipsELFObjectWriter::~MipsELFObjectWriter() {}
1833 // FIXME: get the real EABI Version from the Triple.
1834 void MipsELFObjectWriter::WriteEFlags() {
1835 Write32(ELF::EF_MIPS_NOREORDER |
1836 ELF::EF_MIPS_ARCH_32R2);
1839 const MCSymbol *MipsELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1840 const MCValue &Target,
1841 const MCFragment &F,
1842 const MCFixup &Fixup,
1843 bool IsPCRel) const {
1844 assert(Target.getSymA() && "SymA cannot be 0.");
1845 const MCSymbol &Sym = Target.getSymA()->getSymbol();
1847 if (Sym.getSection().getKind().isMergeableCString() ||
1848 Sym.getSection().getKind().isMergeableConst())
1854 unsigned MipsELFObjectWriter::GetRelocType(const MCValue &Target,
1855 const MCFixup &Fixup,
1857 bool IsRelocWithSymbol,
1858 int64_t Addend) const {
1859 // determine the type of the relocation
1860 unsigned Type = (unsigned)ELF::R_MIPS_NONE;
1861 unsigned Kind = (unsigned)Fixup.getKind();
1865 llvm_unreachable("invalid fixup kind!");
1867 Type = ELF::R_MIPS_32;
1870 Type = ELF::R_MIPS_GPREL32;
1872 case Mips::fixup_Mips_GPREL16:
1873 Type = ELF::R_MIPS_GPREL16;
1875 case Mips::fixup_Mips_26:
1876 Type = ELF::R_MIPS_26;
1878 case Mips::fixup_Mips_CALL16:
1879 Type = ELF::R_MIPS_CALL16;
1881 case Mips::fixup_Mips_GOT_Global:
1882 case Mips::fixup_Mips_GOT_Local:
1883 Type = ELF::R_MIPS_GOT16;
1885 case Mips::fixup_Mips_HI16:
1886 Type = ELF::R_MIPS_HI16;
1888 case Mips::fixup_Mips_LO16:
1889 Type = ELF::R_MIPS_LO16;
1891 case Mips::fixup_Mips_TLSGD:
1892 Type = ELF::R_MIPS_TLS_GD;
1894 case Mips::fixup_Mips_GOTTPREL:
1895 Type = ELF::R_MIPS_TLS_GOTTPREL;
1897 case Mips::fixup_Mips_TPREL_HI:
1898 Type = ELF::R_MIPS_TLS_TPREL_HI16;
1900 case Mips::fixup_Mips_TPREL_LO:
1901 Type = ELF::R_MIPS_TLS_TPREL_LO16;
1903 case Mips::fixup_Mips_Branch_PCRel:
1904 case Mips::fixup_Mips_PC16:
1905 Type = ELF::R_MIPS_PC16;