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/StringSwitch.h"
34 #define DEBUG_TYPE "reloc-info"
36 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
37 const MCFixupKindInfo &FKI =
38 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
40 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
43 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
47 case MCSymbolRefExpr::VK_GOT:
48 case MCSymbolRefExpr::VK_PLT:
49 case MCSymbolRefExpr::VK_GOTPCREL:
50 case MCSymbolRefExpr::VK_GOTOFF:
51 case MCSymbolRefExpr::VK_TPOFF:
52 case MCSymbolRefExpr::VK_TLSGD:
53 case MCSymbolRefExpr::VK_GOTTPOFF:
54 case MCSymbolRefExpr::VK_INDNTPOFF:
55 case MCSymbolRefExpr::VK_NTPOFF:
56 case MCSymbolRefExpr::VK_GOTNTPOFF:
57 case MCSymbolRefExpr::VK_TLSLDM:
58 case MCSymbolRefExpr::VK_DTPOFF:
59 case MCSymbolRefExpr::VK_TLSLD:
64 ELFObjectWriter::~ELFObjectWriter()
67 // Emit the ELF header.
68 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
69 unsigned NumberOfSections) {
75 // emitWord method behaves differently for ELF32 and ELF64, writing
76 // 4 bytes in the former and 8 in the latter.
78 Write8(0x7f); // e_ident[EI_MAG0]
79 Write8('E'); // e_ident[EI_MAG1]
80 Write8('L'); // e_ident[EI_MAG2]
81 Write8('F'); // e_ident[EI_MAG3]
83 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
86 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
88 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
90 Write8(TargetObjectWriter->getOSABI());
91 Write8(0); // e_ident[EI_ABIVERSION]
93 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
95 Write16(ELF::ET_REL); // e_type
97 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
99 Write32(ELF::EV_CURRENT); // e_version
100 WriteWord(0); // e_entry, no entry point in .o file
101 WriteWord(0); // e_phoff, no program header for .o
102 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
103 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
105 // e_flags = whatever the target wants
106 Write32(getEFlags());
108 // e_ehsize = ELF header size
109 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
111 Write16(0); // e_phentsize = prog header entry size
112 Write16(0); // e_phnum = # prog header entries = 0
114 // e_shentsize = Section header entry size
115 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
117 // e_shnum = # of section header ents
118 if (NumberOfSections >= ELF::SHN_LORESERVE)
119 Write16(ELF::SHN_UNDEF);
121 Write16(NumberOfSections);
123 // e_shstrndx = Section # of '.shstrtab'
124 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
125 Write16(ELF::SHN_XINDEX);
127 Write16(ShstrtabIndex);
130 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
131 MCDataFragment *ShndxF,
133 uint8_t info, uint64_t value,
134 uint64_t size, uint8_t other,
138 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
139 String32(*ShndxF, shndx);
141 String32(*ShndxF, 0);
144 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
145 uint16_t(ELF::SHN_XINDEX) : shndx;
148 String32(*SymtabF, name); // st_name
149 String8(*SymtabF, info); // st_info
150 String8(*SymtabF, other); // st_other
151 String16(*SymtabF, Index); // st_shndx
152 String64(*SymtabF, value); // st_value
153 String64(*SymtabF, size); // st_size
155 String32(*SymtabF, name); // st_name
156 String32(*SymtabF, value); // st_value
157 String32(*SymtabF, size); // st_size
158 String8(*SymtabF, info); // st_info
159 String8(*SymtabF, other); // st_other
160 String16(*SymtabF, Index); // st_shndx
164 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
165 const MCAsmLayout &Layout) {
166 if (Data.isCommon() && Data.isExternal())
167 return Data.getCommonAlignment();
169 const MCSymbol &Symbol = Data.getSymbol();
171 if (Symbol.isAbsolute() && Symbol.isVariable()) {
172 if (const MCExpr *Value = Symbol.getVariableValue()) {
174 if (Value->EvaluateAsAbsolute(IntValue, Layout))
175 return (uint64_t)IntValue;
179 if (!Symbol.isInSection())
183 if (Data.getFragment()) {
184 if (Data.getFlags() & ELF_Other_ThumbFunc)
185 return Layout.getSymbolOffset(&Data)+1;
187 return Layout.getSymbolOffset(&Data);
193 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
194 const MCAsmLayout &Layout) {
195 // The presence of symbol versions causes undefined symbols and
196 // versions declared with @@@ to be renamed.
198 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
199 ie = Asm.symbol_end(); it != ie; ++it) {
200 const MCSymbol &Alias = it->getSymbol();
201 const MCSymbol &Symbol = Alias.AliasedSymbol();
202 MCSymbolData &SD = Asm.getSymbolData(Symbol);
205 if (&Symbol == &Alias)
208 StringRef AliasName = Alias.getName();
209 size_t Pos = AliasName.find('@');
210 if (Pos == StringRef::npos)
213 // Aliases defined with .symvar copy the binding from the symbol they alias.
214 // This is the first place we are able to copy this information.
215 it->setExternal(SD.isExternal());
216 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
218 StringRef Rest = AliasName.substr(Pos);
219 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
222 // FIXME: produce a better error message.
223 if (Symbol.isUndefined() && Rest.startswith("@@") &&
224 !Rest.startswith("@@@"))
225 report_fatal_error("A @@ version cannot be undefined");
227 Renames.insert(std::make_pair(&Symbol, &Alias));
231 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
232 MCDataFragment *ShndxF,
234 const MCAsmLayout &Layout) {
235 MCSymbolData &OrigData = *MSD.SymbolData;
237 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
239 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
240 Data.getSymbol().isVariable();
242 uint8_t Binding = MCELF::GetBinding(OrigData);
243 uint8_t Visibility = MCELF::GetVisibility(OrigData);
244 uint8_t Type = MCELF::GetType(Data);
246 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
247 uint8_t Other = Visibility;
249 uint64_t Value = SymbolValue(Data, Layout);
252 assert(!(Data.isCommon() && !Data.isExternal()));
254 const MCExpr *ESize = Data.getSize();
257 if (!ESize->EvaluateAsAbsolute(Res, Layout))
258 report_fatal_error("Size expression must be absolute.");
262 // Write out the symbol table entry
263 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
264 Size, Other, MSD.SectionIndex, IsReserved);
267 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
268 MCDataFragment *ShndxF,
269 const MCAssembler &Asm,
270 const MCAsmLayout &Layout,
271 const SectionIndexMapTy &SectionIndexMap) {
272 // The string table must be emitted first because we need the index
273 // into the string table for all the symbol names.
274 assert(StringTable.size() && "Missing string table");
276 // FIXME: Make sure the start of the symbol table is aligned.
278 // The first entry is the undefined symbol entry.
279 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
281 // Write the symbol table entries.
282 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
283 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
284 ELFSymbolData &MSD = LocalSymbolData[i];
285 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
288 // Write out a symbol table entry for each regular section.
289 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
291 const MCSectionELF &Section =
292 static_cast<const MCSectionELF&>(i->getSection());
293 if (Section.getType() == ELF::SHT_RELA ||
294 Section.getType() == ELF::SHT_REL ||
295 Section.getType() == ELF::SHT_STRTAB ||
296 Section.getType() == ELF::SHT_SYMTAB ||
297 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
299 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
300 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
302 LastLocalSymbolIndex++;
305 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
306 ELFSymbolData &MSD = ExternalSymbolData[i];
307 MCSymbolData &Data = *MSD.SymbolData;
308 assert(((Data.getFlags() & ELF_STB_Global) ||
309 (Data.getFlags() & ELF_STB_Weak)) &&
310 "External symbol requires STB_GLOBAL or STB_WEAK flag");
311 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
312 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
313 LastLocalSymbolIndex++;
316 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
317 ELFSymbolData &MSD = UndefinedSymbolData[i];
318 MCSymbolData &Data = *MSD.SymbolData;
319 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
320 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
321 LastLocalSymbolIndex++;
325 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
326 const MCValue &Target,
328 const MCFixup &Fixup,
329 bool IsPCRel) const {
330 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
331 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
332 const MCSymbol *Renamed = Renames.lookup(&Symbol);
333 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
335 if (ASymbol.isUndefined()) {
341 if (SD.isExternal()) {
347 const MCSectionELF &Section =
348 static_cast<const MCSectionELF&>(ASymbol.getSection());
349 const SectionKind secKind = Section.getKind();
352 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
354 if (secKind.isThreadLocal()) {
360 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
361 const MCSectionELF &Sec2 =
362 static_cast<const MCSectionELF&>(F.getParent()->getSection());
364 if (&Sec2 != &Section &&
365 (Kind == MCSymbolRefExpr::VK_PLT ||
366 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
367 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
373 if (Section.getFlags() & ELF::SHF_MERGE) {
374 if (Target.getConstant() == 0)
375 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
381 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
386 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
387 const MCAsmLayout &Layout,
388 const MCFragment *Fragment,
389 const MCFixup &Fixup,
391 uint64_t &FixedValue) {
394 int64_t Value = Target.getConstant();
395 const MCSymbol *RelocSymbol = NULL;
397 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
398 if (!Target.isAbsolute()) {
399 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
400 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
401 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
403 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
404 const MCSymbol &SymbolB = RefB->getSymbol();
405 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
408 // Offset of the symbol in the section
409 int64_t a = Layout.getSymbolOffset(&SDB);
411 // Offset of the relocation in the section
412 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
417 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
418 MCFragment *F = SD.getFragment();
420 Index = F->getParent()->getOrdinal() + 1;
422 // Offset of the symbol in the section
423 Value += Layout.getSymbolOffset(&SD);
425 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
426 WeakrefUsedInReloc.insert(RelocSymbol);
428 UsedInReloc.insert(RelocSymbol);
432 // Compensate for the addend on i386.
438 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
439 (RelocSymbol != 0), Addend);
440 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
441 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
442 if (RelocNeedsGOT(Modifier))
445 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
448 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
449 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
451 if (!hasRelocationAddend())
455 assert(isInt<64>(Addend));
457 assert(isInt<32>(Addend));
459 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
460 Relocations[Fragment->getParent()].push_back(ERE);
465 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
467 MCSymbolData &SD = Asm.getSymbolData(*S);
468 return SD.getIndex();
471 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
472 const MCSymbolData &Data,
473 bool Used, bool Renamed) {
474 if (Data.getFlags() & ELF_Other_Weakref)
483 const MCSymbol &Symbol = Data.getSymbol();
485 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
488 const MCSymbol &A = Symbol.AliasedSymbol();
489 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
492 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
493 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
496 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
499 if (Symbol.isTemporary())
505 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
506 bool isUsedInReloc) {
507 if (Data.isExternal())
510 const MCSymbol &Symbol = Data.getSymbol();
511 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
513 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
514 if (isSignature && !isUsedInReloc)
523 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
524 SectionIndexMapTy &SectionIndexMap,
525 const RelMapTy &RelMap) {
527 for (MCAssembler::iterator it = Asm.begin(),
528 ie = Asm.end(); it != ie; ++it) {
529 const MCSectionELF &Section =
530 static_cast<const MCSectionELF &>(it->getSection());
531 if (Section.getType() != ELF::SHT_GROUP)
533 SectionIndexMap[&Section] = Index++;
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 ||
541 Section.getType() == ELF::SHT_REL ||
542 Section.getType() == ELF::SHT_RELA)
544 SectionIndexMap[&Section] = Index++;
545 const MCSectionELF *RelSection = RelMap.lookup(&Section);
547 SectionIndexMap[RelSection] = Index++;
551 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
552 const SectionIndexMapTy &SectionIndexMap,
553 RevGroupMapTy RevGroupMap,
554 unsigned NumRegularSections) {
555 // FIXME: Is this the correct place to do this?
556 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
558 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
559 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
560 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
561 Data.setExternal(true);
562 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
565 // Index 0 is always the empty string.
566 StringMap<uint64_t> StringIndexMap;
567 StringTable += '\x00';
569 // FIXME: We could optimize suffixes in strtab in the same way we
570 // optimize them in shstrtab.
572 // Add the data for the symbols.
573 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
574 ie = Asm.symbol_end(); it != ie; ++it) {
575 const MCSymbol &Symbol = it->getSymbol();
577 bool Used = UsedInReloc.count(&Symbol);
578 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
579 bool isSignature = RevGroupMap.count(&Symbol);
581 if (!isInSymtab(Asm, *it,
582 Used || WeakrefUsed || isSignature,
583 Renames.count(&Symbol)))
588 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
590 // Undefined symbols are global, but this is the first place we
591 // are able to set it.
592 bool Local = isLocal(*it, isSignature, Used);
593 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
594 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
595 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
596 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
599 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
600 MCELF::SetBinding(*it, ELF::STB_WEAK);
602 if (it->isCommon()) {
604 MSD.SectionIndex = ELF::SHN_COMMON;
605 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
606 MSD.SectionIndex = ELF::SHN_ABS;
607 } else if (RefSymbol.isUndefined()) {
608 if (isSignature && !Used)
609 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
611 MSD.SectionIndex = ELF::SHN_UNDEF;
613 const MCSectionELF &Section =
614 static_cast<const MCSectionELF&>(RefSymbol.getSection());
615 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
616 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
617 NeedsSymtabShndx = true;
618 assert(MSD.SectionIndex && "Invalid section index!");
621 // The @@@ in symbol version is replaced with @ in undefined symbols and
622 // @@ in defined ones.
623 StringRef Name = Symbol.getName();
626 size_t Pos = Name.find("@@@");
627 if (Pos != StringRef::npos) {
628 Buf += Name.substr(0, Pos);
629 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
630 Buf += Name.substr(Pos + Skip);
634 uint64_t &Entry = StringIndexMap[Name];
636 Entry = StringTable.size();
638 StringTable += '\x00';
640 MSD.StringIndex = Entry;
641 if (MSD.SectionIndex == ELF::SHN_UNDEF)
642 UndefinedSymbolData.push_back(MSD);
644 LocalSymbolData.push_back(MSD);
646 ExternalSymbolData.push_back(MSD);
649 // Symbols are required to be in lexicographic order.
650 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
651 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
652 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
654 // Set the symbol indices. Local symbols must come before all other
655 // symbols with non-local bindings.
657 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
658 LocalSymbolData[i].SymbolData->setIndex(Index++);
660 Index += NumRegularSections;
662 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
663 ExternalSymbolData[i].SymbolData->setIndex(Index++);
664 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
665 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
667 if (NumRegularSections > ELF::SHN_LORESERVE)
668 NeedsSymtabShndx = true;
671 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
674 for (MCAssembler::const_iterator it = Asm.begin(),
675 ie = Asm.end(); it != ie; ++it) {
676 const MCSectionData &SD = *it;
677 if (Relocations[&SD].empty())
680 MCContext &Ctx = Asm.getContext();
681 const MCSectionELF &Section =
682 static_cast<const MCSectionELF&>(SD.getSection());
684 const StringRef SectionName = Section.getSectionName();
685 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
686 RelaSectionName += SectionName;
689 if (hasRelocationAddend())
690 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
692 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
694 const MCSectionELF *RelaSection =
695 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
696 ELF::SHT_RELA : ELF::SHT_REL, 0,
697 SectionKind::getReadOnly(),
699 RelMap[&Section] = RelaSection;
700 Asm.getOrCreateSectionData(*RelaSection);
704 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
705 const RelMapTy &RelMap) {
706 for (MCAssembler::const_iterator it = Asm.begin(),
707 ie = Asm.end(); it != ie; ++it) {
708 const MCSectionData &SD = *it;
709 const MCSectionELF &Section =
710 static_cast<const MCSectionELF&>(SD.getSection());
712 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
715 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
716 RelaSD.setAlignment(is64Bit() ? 8 : 4);
718 MCDataFragment *F = new MCDataFragment(&RelaSD);
719 WriteRelocationsFragment(Asm, F, &*it);
723 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
724 uint64_t Flags, uint64_t Address,
725 uint64_t Offset, uint64_t Size,
726 uint32_t Link, uint32_t Info,
728 uint64_t EntrySize) {
729 Write32(Name); // sh_name: index into string table
730 Write32(Type); // sh_type
731 WriteWord(Flags); // sh_flags
732 WriteWord(Address); // sh_addr
733 WriteWord(Offset); // sh_offset
734 WriteWord(Size); // sh_size
735 Write32(Link); // sh_link
736 Write32(Info); // sh_info
737 WriteWord(Alignment); // sh_addralign
738 WriteWord(EntrySize); // sh_entsize
741 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
743 const MCSectionData *SD) {
744 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
745 // sort by the r_offset just like gnu as does
746 array_pod_sort(Relocs.begin(), Relocs.end());
748 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
749 ELFRelocationEntry entry = Relocs[e - i - 1];
753 else if (entry.Index < 0)
754 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
756 entry.Index += LocalSymbolData.size();
758 String64(*F, entry.r_offset);
760 struct ELF::Elf64_Rela ERE64;
761 ERE64.setSymbolAndType(entry.Index, entry.Type);
762 String64(*F, ERE64.r_info);
764 if (hasRelocationAddend())
765 String64(*F, entry.r_addend);
767 String32(*F, entry.r_offset);
769 struct ELF::Elf32_Rela ERE32;
770 ERE32.setSymbolAndType(entry.Index, entry.Type);
771 String32(*F, ERE32.r_info);
773 if (hasRelocationAddend())
774 String32(*F, entry.r_addend);
779 static int compareBySuffix(const void *a, const void *b) {
780 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
781 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
782 const StringRef &NameA = secA->getSectionName();
783 const StringRef &NameB = secB->getSectionName();
784 const unsigned sizeA = NameA.size();
785 const unsigned sizeB = NameB.size();
786 const unsigned len = std::min(sizeA, sizeB);
787 for (unsigned int i = 0; i < len; ++i) {
788 char ca = NameA[sizeA - i - 1];
789 char cb = NameB[sizeB - i - 1];
794 return sizeB - sizeA;
797 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
799 SectionIndexMapTy &SectionIndexMap,
800 const RelMapTy &RelMap) {
801 MCContext &Ctx = Asm.getContext();
804 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
806 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
807 const MCSectionELF *ShstrtabSection =
808 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
809 SectionKind::getReadOnly());
810 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
811 ShstrtabSD.setAlignment(1);
813 const MCSectionELF *SymtabSection =
814 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
815 SectionKind::getReadOnly(),
817 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
818 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
820 MCSectionData *SymtabShndxSD = NULL;
822 if (NeedsSymtabShndx) {
823 const MCSectionELF *SymtabShndxSection =
824 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
825 SectionKind::getReadOnly(), 4, "");
826 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
827 SymtabShndxSD->setAlignment(4);
830 const MCSectionELF *StrtabSection;
831 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
832 SectionKind::getReadOnly());
833 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
834 StrtabSD.setAlignment(1);
836 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
838 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
839 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
840 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
843 F = new MCDataFragment(&SymtabSD);
844 MCDataFragment *ShndxF = NULL;
845 if (NeedsSymtabShndx) {
846 ShndxF = new MCDataFragment(SymtabShndxSD);
848 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
850 F = new MCDataFragment(&StrtabSD);
851 F->getContents().append(StringTable.begin(), StringTable.end());
853 F = new MCDataFragment(&ShstrtabSD);
855 std::vector<const MCSectionELF*> Sections;
856 for (MCAssembler::const_iterator it = Asm.begin(),
857 ie = Asm.end(); it != ie; ++it) {
858 const MCSectionELF &Section =
859 static_cast<const MCSectionELF&>(it->getSection());
860 Sections.push_back(&Section);
862 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
864 // Section header string table.
866 // The first entry of a string table holds a null character so skip
869 F->getContents() += '\x00';
871 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
872 const MCSectionELF &Section = *Sections[I];
874 StringRef Name = Section.getSectionName();
876 StringRef PreviousName = Sections[I - 1]->getSectionName();
877 if (PreviousName.endswith(Name)) {
878 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
882 // Remember the index into the string table so we can write it
883 // into the sh_name field of the section header table.
884 SectionStringTableIndex[&Section] = Index;
886 Index += Name.size() + 1;
887 F->getContents() += Name;
888 F->getContents() += '\x00';
892 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
894 GroupMapTy &GroupMap,
895 RevGroupMapTy &RevGroupMap,
896 SectionIndexMapTy &SectionIndexMap,
897 const RelMapTy &RelMap) {
898 // Create the .note.GNU-stack section if needed.
899 MCContext &Ctx = Asm.getContext();
900 if (Asm.getNoExecStack()) {
901 const MCSectionELF *GnuStackSection =
902 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
903 SectionKind::getReadOnly());
904 Asm.getOrCreateSectionData(*GnuStackSection);
908 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
910 const MCSectionELF &Section =
911 static_cast<const MCSectionELF&>(it->getSection());
912 if (!(Section.getFlags() & ELF::SHF_GROUP))
915 const MCSymbol *SignatureSymbol = Section.getGroup();
916 Asm.getOrCreateSymbolData(*SignatureSymbol);
917 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
919 Group = Ctx.CreateELFGroupSection();
920 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
921 Data.setAlignment(4);
922 MCDataFragment *F = new MCDataFragment(&Data);
923 String32(*F, ELF::GRP_COMDAT);
925 GroupMap[Group] = SignatureSymbol;
928 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
930 // Add sections to the groups
931 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
933 const MCSectionELF &Section =
934 static_cast<const MCSectionELF&>(it->getSection());
935 if (!(Section.getFlags() & ELF::SHF_GROUP))
937 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
938 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
939 // FIXME: we could use the previous fragment
940 MCDataFragment *F = new MCDataFragment(&Data);
941 unsigned Index = SectionIndexMap.lookup(&Section);
946 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
947 const SectionIndexMapTy &SectionIndexMap,
948 uint32_t GroupSymbolIndex,
949 uint64_t Offset, uint64_t Size,
951 const MCSectionELF &Section) {
952 uint64_t sh_link = 0;
953 uint64_t sh_info = 0;
955 switch(Section.getType()) {
956 case ELF::SHT_DYNAMIC:
957 sh_link = SectionStringTableIndex[&Section];
962 case ELF::SHT_RELA: {
963 const MCSectionELF *SymtabSection;
964 const MCSectionELF *InfoSection;
965 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
967 SectionKind::getReadOnly());
968 sh_link = SectionIndexMap.lookup(SymtabSection);
969 assert(sh_link && ".symtab not found");
971 // Remove ".rel" and ".rela" prefixes.
972 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
973 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
975 InfoSection = Asm.getContext().getELFSection(SectionName,
976 ELF::SHT_PROGBITS, 0,
977 SectionKind::getReadOnly());
978 sh_info = SectionIndexMap.lookup(InfoSection);
982 case ELF::SHT_SYMTAB:
983 case ELF::SHT_DYNSYM:
984 sh_link = StringTableIndex;
985 sh_info = LastLocalSymbolIndex;
988 case ELF::SHT_SYMTAB_SHNDX:
989 sh_link = SymbolTableIndex;
992 case ELF::SHT_PROGBITS:
993 case ELF::SHT_STRTAB:
994 case ELF::SHT_NOBITS:
997 case ELF::SHT_ARM_ATTRIBUTES:
998 case ELF::SHT_INIT_ARRAY:
999 case ELF::SHT_FINI_ARRAY:
1000 case ELF::SHT_PREINIT_ARRAY:
1001 case ELF::SHT_X86_64_UNWIND:
1005 case ELF::SHT_GROUP:
1006 sh_link = SymbolTableIndex;
1007 sh_info = GroupSymbolIndex;
1011 assert(0 && "FIXME: sh_type value not supported!");
1015 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1016 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1017 Alignment, Section.getEntrySize());
1020 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1021 return SD.getOrdinal() == ~UINT32_C(0) &&
1022 !SD.getSection().isVirtualSection();
1025 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1027 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1029 const MCFragment &F = *i;
1030 assert(F.getKind() == MCFragment::FT_Data);
1031 Ret += cast<MCDataFragment>(F).getContents().size();
1036 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1037 const MCSectionData &SD) {
1038 if (IsELFMetaDataSection(SD))
1039 return DataSectionSize(SD);
1040 return Layout.getSectionFileSize(&SD);
1043 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1044 const MCSectionData &SD) {
1045 if (IsELFMetaDataSection(SD))
1046 return DataSectionSize(SD);
1047 return Layout.getSectionAddressSize(&SD);
1050 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1051 const MCAsmLayout &Layout,
1052 const MCSectionELF &Section) {
1053 uint64_t FileOff = OS.tell();
1054 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1056 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1057 WriteZeros(Padding);
1060 FileOff += GetSectionFileSize(Layout, SD);
1062 if (IsELFMetaDataSection(SD)) {
1063 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1065 const MCFragment &F = *i;
1066 assert(F.getKind() == MCFragment::FT_Data);
1067 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1070 Asm.writeSectionData(&SD, Layout);
1074 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1075 const GroupMapTy &GroupMap,
1076 const MCAsmLayout &Layout,
1077 const SectionIndexMapTy &SectionIndexMap,
1078 const SectionOffsetMapTy &SectionOffsetMap) {
1079 const unsigned NumSections = Asm.size() + 1;
1081 std::vector<const MCSectionELF*> Sections;
1082 Sections.resize(NumSections - 1);
1084 for (SectionIndexMapTy::const_iterator i=
1085 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1086 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1087 Sections[p.second - 1] = p.first;
1090 // Null section first.
1091 uint64_t FirstSectionSize =
1092 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1093 uint32_t FirstSectionLink =
1094 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1095 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1097 for (unsigned i = 0; i < NumSections - 1; ++i) {
1098 const MCSectionELF &Section = *Sections[i];
1099 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1100 uint32_t GroupSymbolIndex;
1101 if (Section.getType() != ELF::SHT_GROUP)
1102 GroupSymbolIndex = 0;
1104 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1105 GroupMap.lookup(&Section));
1107 uint64_t Size = GetSectionAddressSize(Layout, SD);
1109 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1110 SectionOffsetMap.lookup(&Section), Size,
1111 SD.getAlignment(), Section);
1115 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1116 std::vector<const MCSectionELF*> &Sections) {
1117 for (MCAssembler::iterator it = Asm.begin(),
1118 ie = Asm.end(); it != ie; ++it) {
1119 const MCSectionELF &Section =
1120 static_cast<const MCSectionELF &>(it->getSection());
1121 if (Section.getType() == ELF::SHT_GROUP)
1122 Sections.push_back(&Section);
1125 for (MCAssembler::iterator it = Asm.begin(),
1126 ie = Asm.end(); it != ie; ++it) {
1127 const MCSectionELF &Section =
1128 static_cast<const MCSectionELF &>(it->getSection());
1129 if (Section.getType() != ELF::SHT_GROUP &&
1130 Section.getType() != ELF::SHT_REL &&
1131 Section.getType() != ELF::SHT_RELA)
1132 Sections.push_back(&Section);
1135 for (MCAssembler::iterator it = Asm.begin(),
1136 ie = Asm.end(); it != ie; ++it) {
1137 const MCSectionELF &Section =
1138 static_cast<const MCSectionELF &>(it->getSection());
1139 if (Section.getType() == ELF::SHT_REL ||
1140 Section.getType() == ELF::SHT_RELA)
1141 Sections.push_back(&Section);
1145 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1146 const MCAsmLayout &Layout) {
1147 GroupMapTy GroupMap;
1148 RevGroupMapTy RevGroupMap;
1149 SectionIndexMapTy SectionIndexMap;
1151 unsigned NumUserSections = Asm.size();
1153 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1154 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1156 const unsigned NumUserAndRelocSections = Asm.size();
1157 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1158 RevGroupMap, SectionIndexMap, RelMap);
1159 const unsigned AllSections = Asm.size();
1160 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1162 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1164 // Compute symbol table information.
1165 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1168 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1170 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1171 const_cast<MCAsmLayout&>(Layout),
1175 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1176 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1177 sizeof(ELF::Elf32_Ehdr);
1178 uint64_t FileOff = HeaderSize;
1180 std::vector<const MCSectionELF*> Sections;
1181 ComputeSectionOrder(Asm, Sections);
1182 unsigned NumSections = Sections.size();
1183 SectionOffsetMapTy SectionOffsetMap;
1184 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1185 const MCSectionELF &Section = *Sections[i];
1186 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1188 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1190 // Remember the offset into the file for this section.
1191 SectionOffsetMap[&Section] = FileOff;
1193 // Get the size of the section in the output file (including padding).
1194 FileOff += GetSectionFileSize(Layout, SD);
1197 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1199 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1201 uint64_t SectionHeaderEntrySize = is64Bit() ?
1202 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1203 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1205 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1206 const MCSectionELF &Section = *Sections[i];
1207 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1209 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1211 // Remember the offset into the file for this section.
1212 SectionOffsetMap[&Section] = FileOff;
1214 // Get the size of the section in the output file (including padding).
1215 FileOff += GetSectionFileSize(Layout, SD);
1218 // Write out the ELF header ...
1219 WriteHeader(SectionHeaderOffset, NumSections + 1);
1221 // ... then the regular sections ...
1222 // + because of .shstrtab
1223 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1224 WriteDataSectionData(Asm, Layout, *Sections[i]);
1226 FileOff = OS.tell();
1227 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1228 WriteZeros(Padding);
1230 // ... then the section header table ...
1231 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1234 FileOff = OS.tell();
1236 // ... and then the remaining sections ...
1237 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1238 WriteDataSectionData(Asm, Layout, *Sections[i]);
1242 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1243 const MCSymbolData &DataA,
1244 const MCFragment &FB,
1246 bool IsPCRel) const {
1247 if (DataA.getFlags() & ELF_STB_Weak)
1249 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1250 Asm, DataA, FB,InSet, IsPCRel);
1253 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1255 bool IsLittleEndian) {
1256 switch (MOTW->getEMachine()) {
1258 case ELF::EM_X86_64:
1262 case ELF::EM_MBLAZE:
1264 return new ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
1265 default: llvm_unreachable("Unsupported architecture"); break;
1269 unsigned ELFObjectWriter::GetRelocType(const MCValue &Target,
1270 const MCFixup &Fixup,
1272 bool IsRelocWithSymbol,
1273 int64_t Addend) const {
1274 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
1275 IsRelocWithSymbol, Addend);