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/MCAsmLayout.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCSectionELF.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/ELF.h"
26 #include "llvm/Target/TargetAsmBackend.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/ADT/Statistic.h"
31 #include "../Target/X86/X86FixupKinds.h"
32 #include "../Target/ARM/ARMFixupKinds.h"
38 #define DEBUG_TYPE "reloc-info"
40 // Emulate the wierd behavior of GNU-as for relocation types
43 ForceARMElfPIC("arm-elf-force-pic", cl::Hidden, cl::init(false),
44 cl::desc("Force ELF emitter to emit PIC style relocations"));
47 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
48 const MCFixupKindInfo &FKI =
49 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
51 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
54 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
58 case MCSymbolRefExpr::VK_GOT:
59 case MCSymbolRefExpr::VK_PLT:
60 case MCSymbolRefExpr::VK_GOTPCREL:
61 case MCSymbolRefExpr::VK_TPOFF:
62 case MCSymbolRefExpr::VK_TLSGD:
63 case MCSymbolRefExpr::VK_GOTTPOFF:
64 case MCSymbolRefExpr::VK_INDNTPOFF:
65 case MCSymbolRefExpr::VK_NTPOFF:
66 case MCSymbolRefExpr::VK_GOTNTPOFF:
67 case MCSymbolRefExpr::VK_TLSLDM:
68 case MCSymbolRefExpr::VK_DTPOFF:
69 case MCSymbolRefExpr::VK_TLSLD:
74 ELFObjectWriter::~ELFObjectWriter()
77 // Emit the ELF header.
78 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
79 unsigned NumberOfSections) {
85 // emitWord method behaves differently for ELF32 and ELF64, writing
86 // 4 bytes in the former and 8 in the latter.
88 Write8(0x7f); // e_ident[EI_MAG0]
89 Write8('E'); // e_ident[EI_MAG1]
90 Write8('L'); // e_ident[EI_MAG2]
91 Write8('F'); // e_ident[EI_MAG3]
93 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
96 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
98 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
100 switch (TargetObjectWriter->getOSType()) {
101 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
102 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
103 default: Write8(ELF::ELFOSABI_NONE); break;
105 Write8(0); // e_ident[EI_ABIVERSION]
107 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
109 Write16(ELF::ET_REL); // e_type
111 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
113 Write32(ELF::EV_CURRENT); // e_version
114 WriteWord(0); // e_entry, no entry point in .o file
115 WriteWord(0); // e_phoff, no program header for .o
116 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
117 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
119 // e_flags = whatever the target wants
122 // e_ehsize = ELF header size
123 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
125 Write16(0); // e_phentsize = prog header entry size
126 Write16(0); // e_phnum = # prog header entries = 0
128 // e_shentsize = Section header entry size
129 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
131 // e_shnum = # of section header ents
132 if (NumberOfSections >= ELF::SHN_LORESERVE)
135 Write16(NumberOfSections);
137 // e_shstrndx = Section # of '.shstrtab'
138 if (NumberOfSections >= ELF::SHN_LORESERVE)
139 Write16(ELF::SHN_XINDEX);
141 Write16(ShstrtabIndex);
144 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
145 MCDataFragment *ShndxF,
147 uint8_t info, uint64_t value,
148 uint64_t size, uint8_t other,
152 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
153 String32(*ShndxF, shndx);
155 String32(*ShndxF, 0);
158 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
159 uint16_t(ELF::SHN_XINDEX) : shndx;
162 String32(*SymtabF, name); // st_name
163 String8(*SymtabF, info); // st_info
164 String8(*SymtabF, other); // st_other
165 String16(*SymtabF, Index); // st_shndx
166 String64(*SymtabF, value); // st_value
167 String64(*SymtabF, size); // st_size
169 String32(*SymtabF, name); // st_name
170 String32(*SymtabF, value); // st_value
171 String32(*SymtabF, size); // st_size
172 String8(*SymtabF, info); // st_info
173 String8(*SymtabF, other); // st_other
174 String16(*SymtabF, Index); // st_shndx
178 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
179 const MCAsmLayout &Layout) {
180 if (Data.isCommon() && Data.isExternal())
181 return Data.getCommonAlignment();
183 const MCSymbol &Symbol = Data.getSymbol();
185 if (Symbol.isAbsolute() && Symbol.isVariable()) {
186 if (const MCExpr *Value = Symbol.getVariableValue()) {
188 if (Value->EvaluateAsAbsolute(IntValue, Layout))
189 return (uint64_t)IntValue;
193 if (!Symbol.isInSection())
197 if (Data.getFragment()) {
198 if (Data.getFlags() & ELF_Other_ThumbFunc)
199 return Layout.getSymbolOffset(&Data)+1;
201 return Layout.getSymbolOffset(&Data);
207 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
208 const MCAsmLayout &Layout) {
209 // The presence of symbol versions causes undefined symbols and
210 // versions declared with @@@ to be renamed.
212 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
213 ie = Asm.symbol_end(); it != ie; ++it) {
214 const MCSymbol &Alias = it->getSymbol();
215 const MCSymbol &Symbol = Alias.AliasedSymbol();
216 MCSymbolData &SD = Asm.getSymbolData(Symbol);
219 if (&Symbol == &Alias)
222 StringRef AliasName = Alias.getName();
223 size_t Pos = AliasName.find('@');
224 if (Pos == StringRef::npos)
227 // Aliases defined with .symvar copy the binding from the symbol they alias.
228 // This is the first place we are able to copy this information.
229 it->setExternal(SD.isExternal());
230 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
232 StringRef Rest = AliasName.substr(Pos);
233 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
236 // FIXME: produce a better error message.
237 if (Symbol.isUndefined() && Rest.startswith("@@") &&
238 !Rest.startswith("@@@"))
239 report_fatal_error("A @@ version cannot be undefined");
241 Renames.insert(std::make_pair(&Symbol, &Alias));
245 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
246 MCDataFragment *ShndxF,
248 const MCAsmLayout &Layout) {
249 MCSymbolData &OrigData = *MSD.SymbolData;
251 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
253 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
254 Data.getSymbol().isVariable();
256 uint8_t Binding = MCELF::GetBinding(OrigData);
257 uint8_t Visibility = MCELF::GetVisibility(OrigData);
258 uint8_t Type = MCELF::GetType(Data);
260 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
261 uint8_t Other = Visibility;
263 uint64_t Value = SymbolValue(Data, Layout);
266 assert(!(Data.isCommon() && !Data.isExternal()));
268 const MCExpr *ESize = Data.getSize();
271 if (!ESize->EvaluateAsAbsolute(Res, Layout))
272 report_fatal_error("Size expression must be absolute.");
276 // Write out the symbol table entry
277 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
278 Size, Other, MSD.SectionIndex, IsReserved);
281 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
282 MCDataFragment *ShndxF,
283 const MCAssembler &Asm,
284 const MCAsmLayout &Layout,
285 const SectionIndexMapTy &SectionIndexMap) {
286 // The string table must be emitted first because we need the index
287 // into the string table for all the symbol names.
288 assert(StringTable.size() && "Missing string table");
290 // FIXME: Make sure the start of the symbol table is aligned.
292 // The first entry is the undefined symbol entry.
293 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
295 // Write the symbol table entries.
296 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
297 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
298 ELFSymbolData &MSD = LocalSymbolData[i];
299 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
302 // Write out a symbol table entry for each regular section.
303 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
305 const MCSectionELF &Section =
306 static_cast<const MCSectionELF&>(i->getSection());
307 if (Section.getType() == ELF::SHT_RELA ||
308 Section.getType() == ELF::SHT_REL ||
309 Section.getType() == ELF::SHT_STRTAB ||
310 Section.getType() == ELF::SHT_SYMTAB)
312 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
313 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
314 LastLocalSymbolIndex++;
317 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
318 ELFSymbolData &MSD = ExternalSymbolData[i];
319 MCSymbolData &Data = *MSD.SymbolData;
320 assert(((Data.getFlags() & ELF_STB_Global) ||
321 (Data.getFlags() & ELF_STB_Weak)) &&
322 "External symbol requires STB_GLOBAL or STB_WEAK flag");
323 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
324 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
325 LastLocalSymbolIndex++;
328 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
329 ELFSymbolData &MSD = UndefinedSymbolData[i];
330 MCSymbolData &Data = *MSD.SymbolData;
331 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
332 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
333 LastLocalSymbolIndex++;
337 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
338 const MCValue &Target,
340 const MCFixup &Fixup,
341 bool IsPCRel) const {
342 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
343 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
344 const MCSymbol *Renamed = Renames.lookup(&Symbol);
345 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
347 if (ASymbol.isUndefined()) {
353 if (SD.isExternal()) {
359 const MCSectionELF &Section =
360 static_cast<const MCSectionELF&>(ASymbol.getSection());
361 const SectionKind secKind = Section.getKind();
364 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
366 if (secKind.isThreadLocal()) {
372 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
373 const MCSectionELF &Sec2 =
374 static_cast<const MCSectionELF&>(F.getParent()->getSection());
376 if (&Sec2 != &Section &&
377 (Kind == MCSymbolRefExpr::VK_PLT ||
378 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
379 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
385 if (Section.getFlags() & ELF::SHF_MERGE) {
386 if (Target.getConstant() == 0)
387 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
393 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
398 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
399 const MCAsmLayout &Layout,
400 const MCFragment *Fragment,
401 const MCFixup &Fixup,
403 uint64_t &FixedValue) {
406 int64_t Value = Target.getConstant();
407 const MCSymbol *RelocSymbol = NULL;
409 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
410 if (!Target.isAbsolute()) {
411 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
412 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
413 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
415 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
416 const MCSymbol &SymbolB = RefB->getSymbol();
417 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
420 // Offset of the symbol in the section
421 int64_t a = Layout.getSymbolOffset(&SDB);
423 // Ofeset of the relocation in the section
424 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
429 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
430 MCFragment *F = SD.getFragment();
432 Index = F->getParent()->getOrdinal() + 1;
434 // Offset of the symbol in the section
435 Value += Layout.getSymbolOffset(&SD);
437 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
438 WeakrefUsedInReloc.insert(RelocSymbol);
440 UsedInReloc.insert(RelocSymbol);
444 // Compensate for the addend on i386.
450 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
451 (RelocSymbol != 0), Addend);
453 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
456 if (!hasRelocationAddend())
458 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
459 Relocations[Fragment->getParent()].push_back(ERE);
464 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
466 MCSymbolData &SD = Asm.getSymbolData(*S);
467 return SD.getIndex();
470 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
471 const MCSymbolData &Data,
472 bool Used, bool Renamed) {
473 if (Data.getFlags() & ELF_Other_Weakref)
482 const MCSymbol &Symbol = Data.getSymbol();
484 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
487 const MCSymbol &A = Symbol.AliasedSymbol();
488 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
491 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
492 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
495 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
498 if (Symbol.isTemporary())
504 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
505 bool isUsedInReloc) {
506 if (Data.isExternal())
509 const MCSymbol &Symbol = Data.getSymbol();
510 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
512 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
513 if (isSignature && !isUsedInReloc)
522 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
523 SectionIndexMapTy &SectionIndexMap,
524 const RelMapTy &RelMap) {
526 for (MCAssembler::iterator it = Asm.begin(),
527 ie = Asm.end(); it != ie; ++it) {
528 const MCSectionELF &Section =
529 static_cast<const MCSectionELF &>(it->getSection());
530 if (Section.getType() != ELF::SHT_GROUP)
532 SectionIndexMap[&Section] = Index++;
535 for (MCAssembler::iterator it = Asm.begin(),
536 ie = Asm.end(); it != ie; ++it) {
537 const MCSectionELF &Section =
538 static_cast<const MCSectionELF &>(it->getSection());
539 if (Section.getType() == ELF::SHT_GROUP ||
540 Section.getType() == ELF::SHT_REL ||
541 Section.getType() == ELF::SHT_RELA)
543 SectionIndexMap[&Section] = Index++;
544 const MCSectionELF *RelSection = RelMap.lookup(&Section);
546 SectionIndexMap[RelSection] = Index++;
550 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
551 const SectionIndexMapTy &SectionIndexMap,
552 RevGroupMapTy RevGroupMap,
553 unsigned NumRegularSections) {
554 // FIXME: Is this the correct place to do this?
556 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
557 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
558 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
559 Data.setExternal(true);
560 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
563 // Index 0 is always the empty string.
564 StringMap<uint64_t> StringIndexMap;
565 StringTable += '\x00';
567 // FIXME: We could optimize suffixes in strtab in the same way we
568 // optimize them in shstrtab.
570 // Add the data for the symbols.
571 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
572 ie = Asm.symbol_end(); it != ie; ++it) {
573 const MCSymbol &Symbol = it->getSymbol();
575 bool Used = UsedInReloc.count(&Symbol);
576 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
577 bool isSignature = RevGroupMap.count(&Symbol);
579 if (!isInSymtab(Asm, *it,
580 Used || WeakrefUsed || isSignature,
581 Renames.count(&Symbol)))
586 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
588 // Undefined symbols are global, but this is the first place we
589 // are able to set it.
590 bool Local = isLocal(*it, isSignature, Used);
591 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
592 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
593 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
594 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
597 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
598 MCELF::SetBinding(*it, ELF::STB_WEAK);
600 if (it->isCommon()) {
602 MSD.SectionIndex = ELF::SHN_COMMON;
603 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
604 MSD.SectionIndex = ELF::SHN_ABS;
605 } else if (RefSymbol.isUndefined()) {
606 if (isSignature && !Used)
607 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
609 MSD.SectionIndex = ELF::SHN_UNDEF;
611 const MCSectionELF &Section =
612 static_cast<const MCSectionELF&>(RefSymbol.getSection());
613 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
614 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
615 NeedsSymtabShndx = true;
616 assert(MSD.SectionIndex && "Invalid section index!");
619 // The @@@ in symbol version is replaced with @ in undefined symbols and
620 // @@ in defined ones.
621 StringRef Name = Symbol.getName();
624 size_t Pos = Name.find("@@@");
625 if (Pos != StringRef::npos) {
626 Buf += Name.substr(0, Pos);
627 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
628 Buf += Name.substr(Pos + Skip);
632 uint64_t &Entry = StringIndexMap[Name];
634 Entry = StringTable.size();
636 StringTable += '\x00';
638 MSD.StringIndex = Entry;
639 if (MSD.SectionIndex == ELF::SHN_UNDEF)
640 UndefinedSymbolData.push_back(MSD);
642 LocalSymbolData.push_back(MSD);
644 ExternalSymbolData.push_back(MSD);
647 // Symbols are required to be in lexicographic order.
648 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
649 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
650 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
652 // Set the symbol indices. Local symbols must come before all other
653 // symbols with non-local bindings.
655 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
656 LocalSymbolData[i].SymbolData->setIndex(Index++);
658 Index += NumRegularSections;
660 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
661 ExternalSymbolData[i].SymbolData->setIndex(Index++);
662 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
663 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
666 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
669 for (MCAssembler::const_iterator it = Asm.begin(),
670 ie = Asm.end(); it != ie; ++it) {
671 const MCSectionData &SD = *it;
672 if (Relocations[&SD].empty())
675 MCContext &Ctx = Asm.getContext();
676 const MCSectionELF &Section =
677 static_cast<const MCSectionELF&>(SD.getSection());
679 const StringRef SectionName = Section.getSectionName();
680 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
681 RelaSectionName += SectionName;
684 if (hasRelocationAddend())
685 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
687 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
689 const MCSectionELF *RelaSection =
690 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
691 ELF::SHT_RELA : ELF::SHT_REL, 0,
692 SectionKind::getReadOnly(),
694 RelMap[&Section] = RelaSection;
695 Asm.getOrCreateSectionData(*RelaSection);
699 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
700 const RelMapTy &RelMap) {
701 for (MCAssembler::const_iterator it = Asm.begin(),
702 ie = Asm.end(); it != ie; ++it) {
703 const MCSectionData &SD = *it;
704 const MCSectionELF &Section =
705 static_cast<const MCSectionELF&>(SD.getSection());
707 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
710 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
711 RelaSD.setAlignment(is64Bit() ? 8 : 4);
713 MCDataFragment *F = new MCDataFragment(&RelaSD);
714 WriteRelocationsFragment(Asm, F, &*it);
718 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
719 uint64_t Flags, uint64_t Address,
720 uint64_t Offset, uint64_t Size,
721 uint32_t Link, uint32_t Info,
723 uint64_t EntrySize) {
724 Write32(Name); // sh_name: index into string table
725 Write32(Type); // sh_type
726 WriteWord(Flags); // sh_flags
727 WriteWord(Address); // sh_addr
728 WriteWord(Offset); // sh_offset
729 WriteWord(Size); // sh_size
730 Write32(Link); // sh_link
731 Write32(Info); // sh_info
732 WriteWord(Alignment); // sh_addralign
733 WriteWord(EntrySize); // sh_entsize
736 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
738 const MCSectionData *SD) {
739 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
740 // sort by the r_offset just like gnu as does
741 array_pod_sort(Relocs.begin(), Relocs.end());
743 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
744 ELFRelocationEntry entry = Relocs[e - i - 1];
748 else if (entry.Index < 0)
749 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
751 entry.Index += LocalSymbolData.size();
753 String64(*F, entry.r_offset);
755 struct ELF::Elf64_Rela ERE64;
756 ERE64.setSymbolAndType(entry.Index, entry.Type);
757 String64(*F, ERE64.r_info);
759 if (hasRelocationAddend())
760 String64(*F, entry.r_addend);
762 String32(*F, entry.r_offset);
764 struct ELF::Elf32_Rela ERE32;
765 ERE32.setSymbolAndType(entry.Index, entry.Type);
766 String32(*F, ERE32.r_info);
768 if (hasRelocationAddend())
769 String32(*F, entry.r_addend);
774 static int compareBySuffix(const void *a, const void *b) {
775 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
776 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
777 const StringRef &NameA = secA->getSectionName();
778 const StringRef &NameB = secB->getSectionName();
779 const unsigned sizeA = NameA.size();
780 const unsigned sizeB = NameB.size();
781 const unsigned len = std::min(sizeA, sizeB);
782 for (unsigned int i = 0; i < len; ++i) {
783 char ca = NameA[sizeA - i - 1];
784 char cb = NameB[sizeB - i - 1];
789 return sizeB - sizeA;
792 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
794 SectionIndexMapTy &SectionIndexMap,
795 const RelMapTy &RelMap) {
796 MCContext &Ctx = Asm.getContext();
799 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
801 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
802 const MCSectionELF *ShstrtabSection =
803 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
804 SectionKind::getReadOnly());
805 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
806 ShstrtabSD.setAlignment(1);
808 const MCSectionELF *SymtabSection =
809 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
810 SectionKind::getReadOnly(),
812 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
813 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
815 MCSectionData *SymtabShndxSD = NULL;
817 if (NeedsSymtabShndx) {
818 const MCSectionELF *SymtabShndxSection =
819 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
820 SectionKind::getReadOnly(), 4, "");
821 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
822 SymtabShndxSD->setAlignment(4);
825 const MCSectionELF *StrtabSection;
826 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
827 SectionKind::getReadOnly());
828 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
829 StrtabSD.setAlignment(1);
831 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
833 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
834 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
835 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
838 F = new MCDataFragment(&SymtabSD);
839 MCDataFragment *ShndxF = NULL;
840 if (NeedsSymtabShndx) {
841 ShndxF = new MCDataFragment(SymtabShndxSD);
843 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
845 F = new MCDataFragment(&StrtabSD);
846 F->getContents().append(StringTable.begin(), StringTable.end());
848 F = new MCDataFragment(&ShstrtabSD);
850 std::vector<const MCSectionELF*> Sections;
851 for (MCAssembler::const_iterator it = Asm.begin(),
852 ie = Asm.end(); it != ie; ++it) {
853 const MCSectionELF &Section =
854 static_cast<const MCSectionELF&>(it->getSection());
855 Sections.push_back(&Section);
857 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
859 // Section header string table.
861 // The first entry of a string table holds a null character so skip
864 F->getContents() += '\x00';
866 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
867 const MCSectionELF &Section = *Sections[I];
869 StringRef Name = Section.getSectionName();
871 StringRef PreviousName = Sections[I - 1]->getSectionName();
872 if (PreviousName.endswith(Name)) {
873 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
877 // Remember the index into the string table so we can write it
878 // into the sh_name field of the section header table.
879 SectionStringTableIndex[&Section] = Index;
881 Index += Name.size() + 1;
882 F->getContents() += Name;
883 F->getContents() += '\x00';
887 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
889 GroupMapTy &GroupMap,
890 RevGroupMapTy &RevGroupMap,
891 SectionIndexMapTy &SectionIndexMap,
892 const RelMapTy &RelMap) {
893 // Create the .note.GNU-stack section if needed.
894 MCContext &Ctx = Asm.getContext();
895 if (Asm.getNoExecStack()) {
896 const MCSectionELF *GnuStackSection =
897 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
898 SectionKind::getReadOnly());
899 Asm.getOrCreateSectionData(*GnuStackSection);
903 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
905 const MCSectionELF &Section =
906 static_cast<const MCSectionELF&>(it->getSection());
907 if (!(Section.getFlags() & ELF::SHF_GROUP))
910 const MCSymbol *SignatureSymbol = Section.getGroup();
911 Asm.getOrCreateSymbolData(*SignatureSymbol);
912 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
914 Group = Ctx.CreateELFGroupSection();
915 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
916 Data.setAlignment(4);
917 MCDataFragment *F = new MCDataFragment(&Data);
918 String32(*F, ELF::GRP_COMDAT);
920 GroupMap[Group] = SignatureSymbol;
923 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
925 // Add sections to the groups
926 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
928 const MCSectionELF &Section =
929 static_cast<const MCSectionELF&>(it->getSection());
930 if (!(Section.getFlags() & ELF::SHF_GROUP))
932 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
933 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
934 // FIXME: we could use the previous fragment
935 MCDataFragment *F = new MCDataFragment(&Data);
936 unsigned Index = SectionIndexMap.lookup(&Section);
941 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
942 const SectionIndexMapTy &SectionIndexMap,
943 uint32_t GroupSymbolIndex,
944 uint64_t Offset, uint64_t Size,
946 const MCSectionELF &Section) {
947 uint64_t sh_link = 0;
948 uint64_t sh_info = 0;
950 switch(Section.getType()) {
951 case ELF::SHT_DYNAMIC:
952 sh_link = SectionStringTableIndex[&Section];
957 case ELF::SHT_RELA: {
958 const MCSectionELF *SymtabSection;
959 const MCSectionELF *InfoSection;
960 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
962 SectionKind::getReadOnly());
963 sh_link = SectionIndexMap.lookup(SymtabSection);
964 assert(sh_link && ".symtab not found");
966 // Remove ".rel" and ".rela" prefixes.
967 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
968 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
970 InfoSection = Asm.getContext().getELFSection(SectionName,
971 ELF::SHT_PROGBITS, 0,
972 SectionKind::getReadOnly());
973 sh_info = SectionIndexMap.lookup(InfoSection);
977 case ELF::SHT_SYMTAB:
978 case ELF::SHT_DYNSYM:
979 sh_link = StringTableIndex;
980 sh_info = LastLocalSymbolIndex;
983 case ELF::SHT_SYMTAB_SHNDX:
984 sh_link = SymbolTableIndex;
987 case ELF::SHT_PROGBITS:
988 case ELF::SHT_STRTAB:
989 case ELF::SHT_NOBITS:
992 case ELF::SHT_ARM_ATTRIBUTES:
993 case ELF::SHT_INIT_ARRAY:
994 case ELF::SHT_FINI_ARRAY:
995 case ELF::SHT_PREINIT_ARRAY:
996 case ELF::SHT_X86_64_UNWIND:
1000 case ELF::SHT_GROUP: {
1001 sh_link = SymbolTableIndex;
1002 sh_info = GroupSymbolIndex;
1007 assert(0 && "FIXME: sh_type value not supported!");
1011 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1012 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1013 Alignment, Section.getEntrySize());
1016 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1017 return SD.getOrdinal() == ~UINT32_C(0) &&
1018 !SD.getSection().isVirtualSection();
1021 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1023 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1025 const MCFragment &F = *i;
1026 assert(F.getKind() == MCFragment::FT_Data);
1027 Ret += cast<MCDataFragment>(F).getContents().size();
1032 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1033 const MCSectionData &SD) {
1034 if (IsELFMetaDataSection(SD))
1035 return DataSectionSize(SD);
1036 return Layout.getSectionFileSize(&SD);
1039 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1040 const MCSectionData &SD) {
1041 if (IsELFMetaDataSection(SD))
1042 return DataSectionSize(SD);
1043 return Layout.getSectionAddressSize(&SD);
1046 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1047 const MCAsmLayout &Layout,
1048 const MCSectionELF &Section) {
1049 uint64_t FileOff = OS.tell();
1050 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1052 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1053 WriteZeros(Padding);
1056 FileOff += GetSectionFileSize(Layout, SD);
1058 if (IsELFMetaDataSection(SD)) {
1059 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1061 const MCFragment &F = *i;
1062 assert(F.getKind() == MCFragment::FT_Data);
1063 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1066 Asm.WriteSectionData(&SD, Layout);
1070 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1071 const GroupMapTy &GroupMap,
1072 const MCAsmLayout &Layout,
1073 const SectionIndexMapTy &SectionIndexMap,
1074 const SectionOffsetMapTy &SectionOffsetMap) {
1075 const unsigned NumSections = Asm.size() + 1;
1077 std::vector<const MCSectionELF*> Sections;
1078 Sections.resize(NumSections - 1);
1080 for (SectionIndexMapTy::const_iterator i=
1081 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1082 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1083 Sections[p.second - 1] = p.first;
1086 // Null section first.
1087 uint64_t FirstSectionSize =
1088 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1089 uint32_t FirstSectionLink =
1090 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1091 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1093 for (unsigned i = 0; i < NumSections - 1; ++i) {
1094 const MCSectionELF &Section = *Sections[i];
1095 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1096 uint32_t GroupSymbolIndex;
1097 if (Section.getType() != ELF::SHT_GROUP)
1098 GroupSymbolIndex = 0;
1100 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1101 GroupMap.lookup(&Section));
1103 uint64_t Size = GetSectionAddressSize(Layout, SD);
1105 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1106 SectionOffsetMap.lookup(&Section), Size,
1107 SD.getAlignment(), Section);
1111 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1112 std::vector<const MCSectionELF*> &Sections) {
1113 for (MCAssembler::iterator it = Asm.begin(),
1114 ie = Asm.end(); it != ie; ++it) {
1115 const MCSectionELF &Section =
1116 static_cast<const MCSectionELF &>(it->getSection());
1117 if (Section.getType() == ELF::SHT_GROUP)
1118 Sections.push_back(&Section);
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 Section.getType() != ELF::SHT_REL &&
1127 Section.getType() != ELF::SHT_RELA)
1128 Sections.push_back(&Section);
1131 for (MCAssembler::iterator it = Asm.begin(),
1132 ie = Asm.end(); it != ie; ++it) {
1133 const MCSectionELF &Section =
1134 static_cast<const MCSectionELF &>(it->getSection());
1135 if (Section.getType() == ELF::SHT_REL ||
1136 Section.getType() == ELF::SHT_RELA)
1137 Sections.push_back(&Section);
1141 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1142 const MCAsmLayout &Layout) {
1143 GroupMapTy GroupMap;
1144 RevGroupMapTy RevGroupMap;
1145 SectionIndexMapTy SectionIndexMap;
1147 unsigned NumUserSections = Asm.size();
1149 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1150 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1152 const unsigned NumUserAndRelocSections = Asm.size();
1153 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1154 RevGroupMap, SectionIndexMap, RelMap);
1155 const unsigned AllSections = Asm.size();
1156 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1158 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1160 // Compute symbol table information.
1161 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1164 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1166 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1167 const_cast<MCAsmLayout&>(Layout),
1171 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1172 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1173 sizeof(ELF::Elf32_Ehdr);
1174 uint64_t FileOff = HeaderSize;
1176 std::vector<const MCSectionELF*> Sections;
1177 ComputeSectionOrder(Asm, Sections);
1178 unsigned NumSections = Sections.size();
1179 SectionOffsetMapTy SectionOffsetMap;
1180 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1181 const MCSectionELF &Section = *Sections[i];
1182 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1184 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1186 // Remember the offset into the file for this section.
1187 SectionOffsetMap[&Section] = FileOff;
1189 // Get the size of the section in the output file (including padding).
1190 FileOff += GetSectionFileSize(Layout, SD);
1193 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1195 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1197 uint64_t SectionHeaderEntrySize = is64Bit() ?
1198 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1199 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1201 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1202 const MCSectionELF &Section = *Sections[i];
1203 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1205 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1207 // Remember the offset into the file for this section.
1208 SectionOffsetMap[&Section] = FileOff;
1210 // Get the size of the section in the output file (including padding).
1211 FileOff += GetSectionFileSize(Layout, SD);
1214 // Write out the ELF header ...
1215 WriteHeader(SectionHeaderOffset, NumSections + 1);
1217 // ... then the regular sections ...
1218 // + because of .shstrtab
1219 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1220 WriteDataSectionData(Asm, Layout, *Sections[i]);
1222 FileOff = OS.tell();
1223 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1224 WriteZeros(Padding);
1226 // ... then the section header table ...
1227 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1230 FileOff = OS.tell();
1232 // ... and then the remainting sections ...
1233 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1234 WriteDataSectionData(Asm, Layout, *Sections[i]);
1238 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1239 const MCSymbolData &DataA,
1240 const MCFragment &FB,
1242 bool IsPCRel) const {
1243 if (DataA.getFlags() & ELF_STB_Weak)
1245 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1246 Asm, DataA, FB,InSet, IsPCRel);
1249 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1251 bool IsLittleEndian) {
1252 switch (MOTW->getEMachine()) {
1254 case ELF::EM_X86_64:
1255 return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1257 return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1258 case ELF::EM_MBLAZE:
1259 return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1260 default: llvm_unreachable("Unsupported architecture"); break;
1265 /// START OF SUBCLASSES for ELFObjectWriter
1266 //===- ARMELFObjectWriter -------------------------------------------===//
1268 ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1270 bool IsLittleEndian)
1271 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1274 ARMELFObjectWriter::~ARMELFObjectWriter()
1277 // FIXME: get the real EABI Version from the Triple.
1278 void ARMELFObjectWriter::WriteEFlags() {
1279 Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
1282 // In ARM, _MergedGlobals and other most symbols get emitted directly.
1283 // I.e. not as an offset to a section symbol.
1284 // This code is an approximation of what ARM/gcc does.
1286 STATISTIC(PCRelCount, "Total number of PIC Relocations");
1287 STATISTIC(NonPCRelCount, "Total number of non-PIC relocations");
1289 const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
1290 const MCValue &Target,
1291 const MCFragment &F,
1292 const MCFixup &Fixup,
1293 bool IsPCRel) const {
1294 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
1295 bool EmitThisSym = false;
1297 const MCSectionELF &Section =
1298 static_cast<const MCSectionELF&>(Symbol.getSection());
1299 bool InNormalSection = true;
1300 unsigned RelocType = 0;
1301 RelocType = GetRelocTypeInner(Target, Fixup, IsPCRel);
1304 const MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
1305 MCSymbolRefExpr::VariantKind Kind2;
1306 Kind2 = Target.getSymB() ? Target.getSymB()->getKind() :
1307 MCSymbolRefExpr::VK_None;
1308 dbgs() << "considering symbol "
1309 << Section.getSectionName() << "/"
1310 << Symbol.getName() << "/"
1311 << " Rel:" << (unsigned)RelocType
1312 << " Kind: " << (int)Kind << "/" << (int)Kind2
1314 << Symbol.isAbsolute() << "/" << Symbol.isDefined() << "/"
1315 << Symbol.isVariable() << "/" << Symbol.isTemporary()
1316 << " Counts:" << PCRelCount << "/" << NonPCRelCount << "\n");
1318 if (IsPCRel || ForceARMElfPIC) { ++PCRelCount;
1319 switch (RelocType) {
1321 // Most relocation types are emitted as explicit symbols
1323 StringSwitch<bool>(Section.getSectionName())
1324 .Case(".data.rel.ro.local", false)
1325 .Case(".data.rel", false)
1326 .Case(".bss", false)
1330 case ELF::R_ARM_ABS32:
1331 // But things get strange with R_ARM_ABS32
1332 // In this case, most things that go in .rodata show up
1333 // as section relative relocations
1335 StringSwitch<bool>(Section.getSectionName())
1336 .Case(".data.rel.ro.local", false)
1337 .Case(".data.rel", false)
1338 .Case(".rodata", false)
1339 .Case(".bss", false)
1341 EmitThisSym = false;
1347 StringSwitch<bool>(Section.getSectionName())
1348 .Case(".data.rel.ro.local", false)
1349 .Case(".rodata", false)
1350 .Case(".data.rel", false)
1351 .Case(".bss", false)
1354 switch (RelocType) {
1355 default: EmitThisSym = true; break;
1356 case ELF::R_ARM_ABS32: EmitThisSym = false; break;
1362 if (! Symbol.isTemporary() && InNormalSection) {
1368 // Need to examine the Fixup when determining whether to
1369 // emit the relocation as an explicit symbol or as a section relative
1371 unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
1372 const MCFixup &Fixup,
1374 bool IsRelocWithSymbol,
1376 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1377 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1379 unsigned Type = GetRelocTypeInner(Target, Fixup, IsPCRel);
1381 if (RelocNeedsGOT(Modifier))
1387 unsigned ARMELFObjectWriter::GetRelocTypeInner(const MCValue &Target,
1388 const MCFixup &Fixup,
1389 bool IsPCRel) const {
1390 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1391 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1395 switch ((unsigned)Fixup.getKind()) {
1396 default: assert(0 && "Unimplemented");
1399 default: llvm_unreachable("Unsupported Modifier");
1400 case MCSymbolRefExpr::VK_None:
1401 Type = ELF::R_ARM_REL32;
1403 case MCSymbolRefExpr::VK_ARM_TLSGD:
1404 assert(0 && "unimplemented");
1406 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1407 Type = ELF::R_ARM_TLS_IE32;
1411 case ARM::fixup_arm_uncondbranch:
1413 case MCSymbolRefExpr::VK_ARM_PLT:
1414 Type = ELF::R_ARM_PLT32;
1417 Type = ELF::R_ARM_CALL;
1421 case ARM::fixup_arm_condbranch:
1422 Type = ELF::R_ARM_JUMP24;
1424 case ARM::fixup_arm_movt_hi16:
1425 case ARM::fixup_arm_movt_hi16_pcrel:
1426 Type = ELF::R_ARM_MOVT_PREL;
1428 case ARM::fixup_arm_movw_lo16:
1429 case ARM::fixup_arm_movw_lo16_pcrel:
1430 Type = ELF::R_ARM_MOVW_PREL_NC;
1432 case ARM::fixup_t2_movt_hi16:
1433 case ARM::fixup_t2_movt_hi16_pcrel:
1434 Type = ELF::R_ARM_THM_MOVT_PREL;
1436 case ARM::fixup_t2_movw_lo16:
1437 case ARM::fixup_t2_movw_lo16_pcrel:
1438 Type = ELF::R_ARM_THM_MOVW_PREL_NC;
1442 switch ((unsigned)Fixup.getKind()) {
1443 default: llvm_unreachable("invalid fixup kind!");
1446 default: llvm_unreachable("Unsupported Modifier"); break;
1447 case MCSymbolRefExpr::VK_ARM_GOT:
1448 Type = ELF::R_ARM_GOT_BREL;
1450 case MCSymbolRefExpr::VK_ARM_TLSGD:
1451 Type = ELF::R_ARM_TLS_GD32;
1453 case MCSymbolRefExpr::VK_ARM_TPOFF:
1454 Type = ELF::R_ARM_TLS_LE32;
1456 case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
1457 Type = ELF::R_ARM_TLS_IE32;
1459 case MCSymbolRefExpr::VK_None:
1460 Type = ELF::R_ARM_ABS32;
1462 case MCSymbolRefExpr::VK_ARM_GOTOFF:
1463 Type = ELF::R_ARM_GOTOFF32;
1467 case ARM::fixup_arm_ldst_pcrel_12:
1468 case ARM::fixup_arm_pcrel_10:
1469 case ARM::fixup_arm_adr_pcrel_12:
1470 case ARM::fixup_arm_thumb_bl:
1471 case ARM::fixup_arm_thumb_cb:
1472 case ARM::fixup_arm_thumb_cp:
1473 case ARM::fixup_arm_thumb_br:
1474 assert(0 && "Unimplemented");
1476 case ARM::fixup_arm_uncondbranch:
1477 Type = ELF::R_ARM_CALL;
1479 case ARM::fixup_arm_condbranch:
1480 Type = ELF::R_ARM_JUMP24;
1482 case ARM::fixup_arm_movt_hi16:
1483 Type = ELF::R_ARM_MOVT_ABS;
1485 case ARM::fixup_arm_movw_lo16:
1486 Type = ELF::R_ARM_MOVW_ABS_NC;
1488 case ARM::fixup_t2_movt_hi16:
1489 Type = ELF::R_ARM_THM_MOVT_ABS;
1491 case ARM::fixup_t2_movw_lo16:
1492 Type = ELF::R_ARM_THM_MOVW_ABS_NC;
1500 //===- MBlazeELFObjectWriter -------------------------------------------===//
1502 MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1504 bool IsLittleEndian)
1505 : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
1508 MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
1511 unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
1512 const MCFixup &Fixup,
1514 bool IsRelocWithSymbol,
1516 // determine the type of the relocation
1519 switch ((unsigned)Fixup.getKind()) {
1521 llvm_unreachable("Unimplemented");
1523 Type = ELF::R_MICROBLAZE_64_PCREL;
1526 Type = ELF::R_MICROBLAZE_32_PCREL;
1530 switch ((unsigned)Fixup.getKind()) {
1531 default: llvm_unreachable("invalid fixup kind!");
1533 Type = ((IsRelocWithSymbol || Addend !=0)
1534 ? ELF::R_MICROBLAZE_32
1535 : ELF::R_MICROBLAZE_64);
1538 Type = ELF::R_MICROBLAZE_32;
1545 //===- X86ELFObjectWriter -------------------------------------------===//
1548 X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1550 bool IsLittleEndian)
1551 : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
1554 X86ELFObjectWriter::~X86ELFObjectWriter()
1557 unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
1558 const MCFixup &Fixup,
1560 bool IsRelocWithSymbol,
1562 // determine the type of the relocation
1564 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
1565 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
1569 switch ((unsigned)Fixup.getKind()) {
1570 default: llvm_unreachable("invalid fixup kind!");
1572 case FK_Data_8: Type = ELF::R_X86_64_PC64; break;
1573 case FK_Data_4: Type = ELF::R_X86_64_PC32; break;
1574 case FK_Data_2: Type = ELF::R_X86_64_PC16; break;
1577 assert(Modifier == MCSymbolRefExpr::VK_None);
1578 Type = ELF::R_X86_64_PC64;
1580 case X86::reloc_signed_4byte:
1581 case X86::reloc_riprel_4byte_movq_load:
1582 case X86::reloc_riprel_4byte:
1586 llvm_unreachable("Unimplemented");
1587 case MCSymbolRefExpr::VK_None:
1588 Type = ELF::R_X86_64_PC32;
1590 case MCSymbolRefExpr::VK_PLT:
1591 Type = ELF::R_X86_64_PLT32;
1593 case MCSymbolRefExpr::VK_GOTPCREL:
1594 Type = ELF::R_X86_64_GOTPCREL;
1596 case MCSymbolRefExpr::VK_GOTTPOFF:
1597 Type = ELF::R_X86_64_GOTTPOFF;
1599 case MCSymbolRefExpr::VK_TLSGD:
1600 Type = ELF::R_X86_64_TLSGD;
1602 case MCSymbolRefExpr::VK_TLSLD:
1603 Type = ELF::R_X86_64_TLSLD;
1608 assert(Modifier == MCSymbolRefExpr::VK_None);
1609 Type = ELF::R_X86_64_PC16;
1612 assert(Modifier == MCSymbolRefExpr::VK_None);
1613 Type = ELF::R_X86_64_PC8;
1617 switch ((unsigned)Fixup.getKind()) {
1618 default: llvm_unreachable("invalid fixup kind!");
1619 case FK_Data_8: Type = ELF::R_X86_64_64; break;
1620 case X86::reloc_signed_4byte:
1621 assert(isInt<32>(Target.getConstant()));
1624 llvm_unreachable("Unimplemented");
1625 case MCSymbolRefExpr::VK_None:
1626 Type = ELF::R_X86_64_32S;
1628 case MCSymbolRefExpr::VK_GOT:
1629 Type = ELF::R_X86_64_GOT32;
1631 case MCSymbolRefExpr::VK_GOTPCREL:
1632 Type = ELF::R_X86_64_GOTPCREL;
1634 case MCSymbolRefExpr::VK_TPOFF:
1635 Type = ELF::R_X86_64_TPOFF32;
1637 case MCSymbolRefExpr::VK_DTPOFF:
1638 Type = ELF::R_X86_64_DTPOFF32;
1643 Type = ELF::R_X86_64_32;
1645 case FK_Data_2: Type = ELF::R_X86_64_16; break;
1647 case FK_Data_1: Type = ELF::R_X86_64_8; break;
1654 llvm_unreachable("Unimplemented");
1655 case MCSymbolRefExpr::VK_None:
1656 Type = ELF::R_386_PC32;
1658 case MCSymbolRefExpr::VK_PLT:
1659 Type = ELF::R_386_PLT32;
1663 switch ((unsigned)Fixup.getKind()) {
1664 default: llvm_unreachable("invalid fixup kind!");
1666 case X86::reloc_global_offset_table:
1667 Type = ELF::R_386_GOTPC;
1670 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
1672 case X86::reloc_signed_4byte:
1677 llvm_unreachable("Unimplemented");
1678 case MCSymbolRefExpr::VK_None:
1679 Type = ELF::R_386_32;
1681 case MCSymbolRefExpr::VK_GOT:
1682 Type = ELF::R_386_GOT32;
1684 case MCSymbolRefExpr::VK_GOTOFF:
1685 Type = ELF::R_386_GOTOFF;
1687 case MCSymbolRefExpr::VK_TLSGD:
1688 Type = ELF::R_386_TLS_GD;
1690 case MCSymbolRefExpr::VK_TPOFF:
1691 Type = ELF::R_386_TLS_LE_32;
1693 case MCSymbolRefExpr::VK_INDNTPOFF:
1694 Type = ELF::R_386_TLS_IE;
1696 case MCSymbolRefExpr::VK_NTPOFF:
1697 Type = ELF::R_386_TLS_LE;
1699 case MCSymbolRefExpr::VK_GOTNTPOFF:
1700 Type = ELF::R_386_TLS_GOTIE;
1702 case MCSymbolRefExpr::VK_TLSLDM:
1703 Type = ELF::R_386_TLS_LDM;
1705 case MCSymbolRefExpr::VK_DTPOFF:
1706 Type = ELF::R_386_TLS_LDO_32;
1710 case FK_Data_2: Type = ELF::R_386_16; break;
1712 case FK_Data_1: Type = ELF::R_386_8; break;
1717 if (RelocNeedsGOT(Modifier))