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 "llvm/MC/ELFObjectWriter.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectWriter.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Target/TargetAsmBackend.h"
33 #include "../Target/X86/X86FixupKinds.h"
38 static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
47 static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
61 static unsigned GetVisibility(MCSymbolData &SD) {
63 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
69 static bool isFixupKindX86PCRel(unsigned Kind) {
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
76 case X86::reloc_riprel_4byte_movq_load:
81 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
85 case MCSymbolRefExpr::VK_GOT:
86 case MCSymbolRefExpr::VK_PLT:
87 case MCSymbolRefExpr::VK_GOTPCREL:
88 case MCSymbolRefExpr::VK_TPOFF:
89 case MCSymbolRefExpr::VK_TLSGD:
90 case MCSymbolRefExpr::VK_GOTTPOFF:
91 case MCSymbolRefExpr::VK_INDNTPOFF:
92 case MCSymbolRefExpr::VK_NTPOFF:
93 case MCSymbolRefExpr::VK_GOTNTPOFF:
94 case MCSymbolRefExpr::VK_TLSLDM:
95 case MCSymbolRefExpr::VK_DTPOFF:
102 class ELFObjectWriterImpl {
103 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
104 return Kind == X86::reloc_riprel_4byte ||
105 Kind == X86::reloc_riprel_4byte_movq_load;
109 /// ELFSymbolData - Helper struct for containing some precomputed information
111 struct ELFSymbolData {
112 MCSymbolData *SymbolData;
113 uint64_t StringIndex;
114 uint32_t SectionIndex;
116 // Support lexicographic sorting.
117 bool operator<(const ELFSymbolData &RHS) const {
118 if (GetType(*SymbolData) == ELF::STT_FILE)
120 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
122 return SymbolData->getSymbol().getName() <
123 RHS.SymbolData->getSymbol().getName();
127 /// @name Relocation Data
130 struct ELFRelocationEntry {
131 // Make these big enough for both 32-bit and 64-bit
135 const MCSymbol *Symbol;
138 // Support lexicographic sorting.
139 bool operator<(const ELFRelocationEntry &RE) const {
140 return RE.r_offset < r_offset;
144 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
145 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
147 llvm::DenseMap<const MCSectionData*,
148 std::vector<ELFRelocationEntry> > Relocations;
149 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
152 /// @name Symbol Table Data
155 SmallString<256> StringTable;
156 std::vector<ELFSymbolData> LocalSymbolData;
157 std::vector<ELFSymbolData> ExternalSymbolData;
158 std::vector<ELFSymbolData> UndefinedSymbolData;
162 int NumRegularSections;
166 ELFObjectWriter *Writer;
170 unsigned Is64Bit : 1;
172 bool HasRelocationAddend;
174 Triple::OSType OSType;
178 // This holds the symbol table index of the last local symbol.
179 unsigned LastLocalSymbolIndex;
180 // This holds the .strtab section index.
181 unsigned StringTableIndex;
183 unsigned ShstrtabIndex;
186 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
187 uint16_t _EMachine, bool _HasRelAddend,
188 Triple::OSType _OSType)
189 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
190 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
191 OSType(_OSType), EMachine(_EMachine) {
194 void Write8(uint8_t Value) { Writer->Write8(Value); }
195 void Write16(uint16_t Value) { Writer->Write16(Value); }
196 void Write32(uint32_t Value) { Writer->Write32(Value); }
197 //void Write64(uint64_t Value) { Writer->Write64(Value); }
198 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
199 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
200 // Writer->WriteBytes(Str, ZeroFillSize);
203 void WriteWord(uint64_t W) {
210 void String8(char *buf, uint8_t Value) {
214 void StringLE16(char *buf, uint16_t Value) {
215 buf[0] = char(Value >> 0);
216 buf[1] = char(Value >> 8);
219 void StringLE32(char *buf, uint32_t Value) {
220 StringLE16(buf, uint16_t(Value >> 0));
221 StringLE16(buf + 2, uint16_t(Value >> 16));
224 void StringLE64(char *buf, uint64_t Value) {
225 StringLE32(buf, uint32_t(Value >> 0));
226 StringLE32(buf + 4, uint32_t(Value >> 32));
229 void StringBE16(char *buf ,uint16_t Value) {
230 buf[0] = char(Value >> 8);
231 buf[1] = char(Value >> 0);
234 void StringBE32(char *buf, uint32_t Value) {
235 StringBE16(buf, uint16_t(Value >> 16));
236 StringBE16(buf + 2, uint16_t(Value >> 0));
239 void StringBE64(char *buf, uint64_t Value) {
240 StringBE32(buf, uint32_t(Value >> 32));
241 StringBE32(buf + 4, uint32_t(Value >> 0));
244 void String16(char *buf, uint16_t Value) {
245 if (Writer->isLittleEndian())
246 StringLE16(buf, Value);
248 StringBE16(buf, Value);
251 void String32(char *buf, uint32_t Value) {
252 if (Writer->isLittleEndian())
253 StringLE32(buf, Value);
255 StringBE32(buf, Value);
258 void String64(char *buf, uint64_t Value) {
259 if (Writer->isLittleEndian())
260 StringLE64(buf, Value);
262 StringBE64(buf, Value);
265 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
267 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
268 uint64_t value, uint64_t size,
269 uint8_t other, uint16_t shndx);
271 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
272 const MCAsmLayout &Layout);
274 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
275 const MCAsmLayout &Layout,
276 unsigned NumRegularSections);
278 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
279 const MCFragment *Fragment, const MCFixup &Fixup,
280 MCValue Target, uint64_t &FixedValue);
282 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
285 /// ComputeSymbolTable - Compute the symbol table data
287 /// \param StringTable [out] - The string table data.
288 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
290 void ComputeSymbolTable(MCAssembler &Asm);
292 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
293 const MCSectionData &SD);
295 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
296 for (MCAssembler::const_iterator it = Asm.begin(),
297 ie = Asm.end(); it != ie; ++it) {
298 WriteRelocation(Asm, Layout, *it);
302 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
304 void ExecutePostLayoutBinding(MCAssembler &Asm);
306 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
307 uint64_t Address, uint64_t Offset,
308 uint64_t Size, uint32_t Link, uint32_t Info,
309 uint64_t Alignment, uint64_t EntrySize);
311 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
312 const MCSectionData *SD);
314 bool IsFixupFullyResolved(const MCAssembler &Asm,
315 const MCValue Target,
317 const MCFragment *DF) const;
319 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
324 // Emit the ELF header.
325 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
326 unsigned NumberOfSections) {
332 // emitWord method behaves differently for ELF32 and ELF64, writing
333 // 4 bytes in the former and 8 in the latter.
335 Write8(0x7f); // e_ident[EI_MAG0]
336 Write8('E'); // e_ident[EI_MAG1]
337 Write8('L'); // e_ident[EI_MAG2]
338 Write8('F'); // e_ident[EI_MAG3]
340 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
343 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
345 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
348 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
349 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
350 default: Write8(ELF::ELFOSABI_NONE); break;
352 Write8(0); // e_ident[EI_ABIVERSION]
354 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
356 Write16(ELF::ET_REL); // e_type
358 Write16(EMachine); // e_machine = target
360 Write32(ELF::EV_CURRENT); // e_version
361 WriteWord(0); // e_entry, no entry point in .o file
362 WriteWord(0); // e_phoff, no program header for .o
363 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
364 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
366 // FIXME: Make this configurable.
367 Write32(0); // e_flags = whatever the target wants
369 // e_ehsize = ELF header size
370 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
372 Write16(0); // e_phentsize = prog header entry size
373 Write16(0); // e_phnum = # prog header entries = 0
375 // e_shentsize = Section header entry size
376 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
378 // e_shnum = # of section header ents
379 Write16(NumberOfSections);
381 // e_shstrndx = Section # of '.shstrtab'
382 Write16(ShstrtabIndex);
385 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
386 uint8_t info, uint64_t value,
387 uint64_t size, uint8_t other,
393 F->getContents() += StringRef(buf, 4); // st_name
396 F->getContents() += StringRef(buf, 1); // st_info
399 F->getContents() += StringRef(buf, 1); // st_other
401 String16(buf, shndx);
402 F->getContents() += StringRef(buf, 2); // st_shndx
404 String64(buf, value);
405 F->getContents() += StringRef(buf, 8); // st_value
408 F->getContents() += StringRef(buf, 8); // st_size
413 F->getContents() += StringRef(buf, 4); // st_name
415 String32(buf, value);
416 F->getContents() += StringRef(buf, 4); // st_value
419 F->getContents() += StringRef(buf, 4); // st_size
422 F->getContents() += StringRef(buf, 1); // st_info
425 F->getContents() += StringRef(buf, 1); // st_other
427 String16(buf, shndx);
428 F->getContents() += StringRef(buf, 2); // st_shndx
432 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
433 if (Data.isCommon() && Data.isExternal())
434 return Data.getCommonAlignment();
436 const MCSymbol &Symbol = Data.getSymbol();
437 if (!Symbol.isInSection())
440 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
441 if (MCFragment *FF = Data.getFragment())
442 return Layout.getSymbolAddress(&Data) -
443 Layout.getSectionAddress(FF->getParent());
448 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
449 const MCSymbol *S = &Symbol;
450 while (S->isVariable()) {
451 const MCExpr *Value = S->getVariableValue();
452 if (Value->getKind() != MCExpr::SymbolRef)
454 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
455 S = &Ref->getSymbol();
460 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
461 // The presence of symbol versions causes undefined symbols and
462 // versions declared with @@@ to be renamed.
464 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
465 ie = Asm.symbol_end(); it != ie; ++it) {
466 const MCSymbol &Alias = it->getSymbol();
467 if (!Alias.isVariable())
469 const MCSymbol &Symbol = AliasedSymbol(Alias);
470 StringRef AliasName = Alias.getName();
471 size_t Pos = AliasName.find('@');
472 if (Pos == StringRef::npos)
475 StringRef Rest = AliasName.substr(Pos);
476 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
479 // FIXME: produce a better error message.
480 if (Symbol.isUndefined() && Rest.startswith("@@") &&
481 !Rest.startswith("@@@"))
482 report_fatal_error("A @@ version cannot be undefined");
484 Renames.insert(std::make_pair(&Symbol, &Alias));
488 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
489 const MCAsmLayout &Layout) {
490 MCSymbolData &OrigData = *MSD.SymbolData;
492 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
494 uint8_t Binding = GetBinding(OrigData);
495 uint8_t Visibility = GetVisibility(OrigData);
496 uint8_t Type = GetType(Data);
498 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
499 uint8_t Other = Visibility;
501 uint64_t Value = SymbolValue(Data, Layout);
505 assert(!(Data.isCommon() && !Data.isExternal()));
507 ESize = Data.getSize();
508 if (Data.getSize()) {
510 if (ESize->getKind() == MCExpr::Binary) {
511 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
513 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
514 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
515 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
516 Size = Res.getConstant();
518 } else if (ESize->getKind() == MCExpr::Constant) {
519 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
521 assert(0 && "Unsupported size expression");
525 // Write out the symbol table entry
526 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
527 Size, Other, MSD.SectionIndex);
530 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
531 const MCAssembler &Asm,
532 const MCAsmLayout &Layout,
533 unsigned NumRegularSections) {
534 // The string table must be emitted first because we need the index
535 // into the string table for all the symbol names.
536 assert(StringTable.size() && "Missing string table");
538 // FIXME: Make sure the start of the symbol table is aligned.
540 // The first entry is the undefined symbol entry.
541 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
542 F->getContents().append(EntrySize, '\x00');
544 // Write the symbol table entries.
545 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
546 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
547 ELFSymbolData &MSD = LocalSymbolData[i];
548 WriteSymbol(F, MSD, Layout);
551 // Write out a symbol table entry for each regular section.
553 for (MCAssembler::const_iterator it = Asm.begin();
554 Index <= NumRegularSections; ++it, ++Index) {
555 const MCSectionELF &Section =
556 static_cast<const MCSectionELF&>(it->getSection());
557 // Leave out relocations so we don't have indexes within
558 // the relocations messed up
559 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
561 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
562 LastLocalSymbolIndex++;
565 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
566 ELFSymbolData &MSD = ExternalSymbolData[i];
567 MCSymbolData &Data = *MSD.SymbolData;
568 assert(((Data.getFlags() & ELF_STB_Global) ||
569 (Data.getFlags() & ELF_STB_Weak)) &&
570 "External symbol requires STB_GLOBAL or STB_WEAK flag");
571 WriteSymbol(F, MSD, Layout);
572 if (GetBinding(Data) == ELF::STB_LOCAL)
573 LastLocalSymbolIndex++;
576 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
577 ELFSymbolData &MSD = UndefinedSymbolData[i];
578 MCSymbolData &Data = *MSD.SymbolData;
579 WriteSymbol(F, MSD, Layout);
580 if (GetBinding(Data) == ELF::STB_LOCAL)
581 LastLocalSymbolIndex++;
585 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
586 const MCValue &Target,
587 const MCFragment &F) {
588 const MCSymbol &Symbol = SD.getSymbol();
589 if (Symbol.isUndefined())
592 const MCSectionELF &Section =
593 static_cast<const MCSectionELF&>(Symbol.getSection());
598 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
599 const MCSectionELF &Sec2 =
600 static_cast<const MCSectionELF&>(F.getParent()->getSection());
602 if (Section.getKind().isBSS())
605 if (&Sec2 != &Section &&
606 (Kind == MCSymbolRefExpr::VK_PLT ||
607 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
608 Kind == MCSymbolRefExpr::VK_GOTOFF))
611 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
612 return Target.getConstant() != 0;
617 // FIXME: this is currently X86/X86_64 only
618 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
619 const MCAsmLayout &Layout,
620 const MCFragment *Fragment,
621 const MCFixup &Fixup,
623 uint64_t &FixedValue) {
626 int64_t Value = Target.getConstant();
627 const MCSymbol *Symbol = 0;
629 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
630 if (!Target.isAbsolute()) {
631 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
632 const MCSymbol *Renamed = Renames.lookup(Symbol);
635 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
636 MCFragment *F = SD.getFragment();
638 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
639 const MCSymbol &SymbolB = RefB->getSymbol();
640 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
642 MCSectionData *Sec = Fragment->getParent();
644 // Offset of the symbol in the section
645 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
647 // Ofeset of the relocation in the section
648 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
652 // Check that this case has already been fully resolved before we get
654 if (Symbol->isDefined() && !SD.isExternal() &&
656 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
657 llvm_unreachable("We don't need a relocation in this case.");
661 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
662 if (!RelocOnSymbol) {
663 Index = F->getParent()->getOrdinal();
665 MCSectionData *FSD = F->getParent();
666 // Offset of the symbol in the section
667 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
669 UsedInReloc.insert(Symbol);
673 // Compensate for the addend on i386.
680 // determine the type of the relocation
682 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
688 llvm_unreachable("Unimplemented");
689 case MCSymbolRefExpr::VK_None:
690 Type = ELF::R_X86_64_PC32;
692 case MCSymbolRefExpr::VK_PLT:
693 Type = ELF::R_X86_64_PLT32;
695 case MCSymbolRefExpr::VK_GOTPCREL:
696 Type = ELF::R_X86_64_GOTPCREL;
698 case MCSymbolRefExpr::VK_GOTTPOFF:
699 Type = ELF::R_X86_64_GOTTPOFF;
701 case MCSymbolRefExpr::VK_TLSGD:
702 Type = ELF::R_X86_64_TLSGD;
706 switch ((unsigned)Fixup.getKind()) {
707 default: llvm_unreachable("invalid fixup kind!");
708 case FK_Data_8: Type = ELF::R_X86_64_64; break;
709 case X86::reloc_signed_4byte:
710 case X86::reloc_pcrel_4byte:
711 assert(isInt<32>(Target.getConstant()));
714 llvm_unreachable("Unimplemented");
715 case MCSymbolRefExpr::VK_None:
716 Type = ELF::R_X86_64_32S;
718 case MCSymbolRefExpr::VK_GOT:
719 Type = ELF::R_X86_64_GOT32;
721 case MCSymbolRefExpr::VK_GOTPCREL:
722 Type = ELF::R_X86_64_GOTPCREL;
724 case MCSymbolRefExpr::VK_TPOFF:
725 Type = ELF::R_X86_64_TPOFF32;
730 Type = ELF::R_X86_64_32;
732 case FK_Data_2: Type = ELF::R_X86_64_16; break;
733 case X86::reloc_pcrel_1byte:
734 case FK_Data_1: Type = ELF::R_X86_64_8; break;
741 llvm_unreachable("Unimplemented");
742 case MCSymbolRefExpr::VK_None:
743 Type = ELF::R_386_PC32;
745 case MCSymbolRefExpr::VK_PLT:
746 Type = ELF::R_386_PLT32;
750 switch ((unsigned)Fixup.getKind()) {
751 default: llvm_unreachable("invalid fixup kind!");
753 case X86::reloc_global_offset_table:
754 Type = ELF::R_386_GOTPC;
757 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
759 case X86::reloc_signed_4byte:
760 case X86::reloc_pcrel_4byte:
764 llvm_unreachable("Unimplemented");
765 case MCSymbolRefExpr::VK_None:
766 Type = ELF::R_386_32;
768 case MCSymbolRefExpr::VK_GOT:
769 Type = ELF::R_386_GOT32;
771 case MCSymbolRefExpr::VK_GOTOFF:
772 Type = ELF::R_386_GOTOFF;
774 case MCSymbolRefExpr::VK_TLSGD:
775 Type = ELF::R_386_TLS_GD;
777 case MCSymbolRefExpr::VK_TPOFF:
778 Type = ELF::R_386_TLS_LE_32;
780 case MCSymbolRefExpr::VK_INDNTPOFF:
781 Type = ELF::R_386_TLS_IE;
783 case MCSymbolRefExpr::VK_NTPOFF:
784 Type = ELF::R_386_TLS_LE;
786 case MCSymbolRefExpr::VK_GOTNTPOFF:
787 Type = ELF::R_386_TLS_GOTIE;
789 case MCSymbolRefExpr::VK_TLSLDM:
790 Type = ELF::R_386_TLS_LDM;
792 case MCSymbolRefExpr::VK_DTPOFF:
793 Type = ELF::R_386_TLS_LDO_32;
797 case FK_Data_2: Type = ELF::R_386_16; break;
798 case X86::reloc_pcrel_1byte:
799 case FK_Data_1: Type = ELF::R_386_8; break;
804 if (RelocNeedsGOT(Modifier))
807 ELFRelocationEntry ERE;
813 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
815 if (HasRelocationAddend)
816 ERE.r_addend = Addend;
818 ERE.r_addend = 0; // Silence compiler warning.
820 Relocations[Fragment->getParent()].push_back(ERE);
824 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
826 MCSymbolData &SD = Asm.getSymbolData(*S);
829 if (!SD.isExternal() && !S->isUndefined())
830 return SD.getIndex() + /* empty symbol */ 1;
832 // External or undefined symbol.
833 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
836 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
837 bool Used, bool Renamed) {
844 const MCSymbol &Symbol = Data.getSymbol();
846 const MCSymbol &A = AliasedSymbol(Symbol);
847 if (&A != &Symbol && A.isUndefined())
850 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
853 if (Symbol.isTemporary())
859 static bool isLocal(const MCSymbolData &Data) {
860 if (Data.isExternal())
863 const MCSymbol &Symbol = Data.getSymbol();
864 if (Symbol.isUndefined() && !Symbol.isVariable())
870 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
871 // FIXME: Is this the correct place to do this?
873 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
874 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
875 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
876 Data.setExternal(true);
879 // Build section lookup table.
880 NumRegularSections = Asm.size();
881 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
883 for (MCAssembler::iterator it = Asm.begin(),
884 ie = Asm.end(); it != ie; ++it, ++Index)
885 SectionIndexMap[&it->getSection()] = Index;
887 // Index 0 is always the empty string.
888 StringMap<uint64_t> StringIndexMap;
889 StringTable += '\x00';
891 // Add the data for the symbols.
892 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
893 ie = Asm.symbol_end(); it != ie; ++it) {
894 const MCSymbol &Symbol = it->getSymbol();
896 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol),
897 Renames.count(&Symbol)))
902 bool Local = isLocal(*it);
903 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
905 if (it->isCommon()) {
907 MSD.SectionIndex = ELF::SHN_COMMON;
908 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
909 MSD.SectionIndex = ELF::SHN_ABS;
910 } else if (RefSymbol.isUndefined()) {
911 MSD.SectionIndex = ELF::SHN_UNDEF;
912 // FIXME: Undefined symbols are global, but this is the first place we
913 // are able to set it.
914 if (GetBinding(*it) == ELF::STB_LOCAL)
915 SetBinding(*it, ELF::STB_GLOBAL);
917 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
918 assert(MSD.SectionIndex && "Invalid section index!");
921 // The @@@ in symbol version is replaced with @ in undefined symbols and
922 // @@ in defined ones.
923 StringRef Name = Symbol.getName();
924 size_t Pos = Name.find("@@@");
925 std::string FinalName;
926 if (Pos != StringRef::npos) {
927 StringRef Prefix = Name.substr(0, Pos);
928 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
929 StringRef Suffix = Name.substr(Pos + n);
930 FinalName = Prefix.str() + Suffix.str();
932 FinalName = Name.str();
935 uint64_t &Entry = StringIndexMap[FinalName];
937 Entry = StringTable.size();
938 StringTable += FinalName;
939 StringTable += '\x00';
941 MSD.StringIndex = Entry;
942 if (MSD.SectionIndex == ELF::SHN_UNDEF)
943 UndefinedSymbolData.push_back(MSD);
945 LocalSymbolData.push_back(MSD);
947 ExternalSymbolData.push_back(MSD);
950 // Symbols are required to be in lexicographic order.
951 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
952 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
953 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
955 // Set the symbol indices. Local symbols must come before all other
956 // symbols with non-local bindings.
958 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
959 LocalSymbolData[i].SymbolData->setIndex(Index++);
960 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
961 ExternalSymbolData[i].SymbolData->setIndex(Index++);
962 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
963 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
966 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
967 const MCSectionData &SD) {
968 if (!Relocations[&SD].empty()) {
969 MCContext &Ctx = Asm.getContext();
970 const MCSection *RelaSection;
971 const MCSectionELF &Section =
972 static_cast<const MCSectionELF&>(SD.getSection());
974 const StringRef SectionName = Section.getSectionName();
975 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
976 RelaSectionName += SectionName;
979 if (HasRelocationAddend)
980 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
982 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
984 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
985 ELF::SHT_RELA : ELF::SHT_REL, 0,
986 SectionKind::getReadOnly(),
989 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
990 RelaSD.setAlignment(Is64Bit ? 8 : 4);
992 MCDataFragment *F = new MCDataFragment(&RelaSD);
994 WriteRelocationsFragment(Asm, F, &SD);
996 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
1000 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1001 uint64_t Flags, uint64_t Address,
1002 uint64_t Offset, uint64_t Size,
1003 uint32_t Link, uint32_t Info,
1005 uint64_t EntrySize) {
1006 Write32(Name); // sh_name: index into string table
1007 Write32(Type); // sh_type
1008 WriteWord(Flags); // sh_flags
1009 WriteWord(Address); // sh_addr
1010 WriteWord(Offset); // sh_offset
1011 WriteWord(Size); // sh_size
1012 Write32(Link); // sh_link
1013 Write32(Info); // sh_info
1014 WriteWord(Alignment); // sh_addralign
1015 WriteWord(EntrySize); // sh_entsize
1018 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1020 const MCSectionData *SD) {
1021 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1022 // sort by the r_offset just like gnu as does
1023 array_pod_sort(Relocs.begin(), Relocs.end());
1025 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1026 ELFRelocationEntry entry = Relocs[e - i - 1];
1028 if (entry.Index < 0)
1029 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1031 entry.Index += LocalSymbolData.size() + 1;
1035 String64(buf, entry.r_offset);
1036 F->getContents() += StringRef(buf, 8);
1038 struct ELF::Elf64_Rela ERE64;
1039 ERE64.setSymbolAndType(entry.Index, entry.Type);
1040 String64(buf, ERE64.r_info);
1041 F->getContents() += StringRef(buf, 8);
1043 if (HasRelocationAddend) {
1044 String64(buf, entry.r_addend);
1045 F->getContents() += StringRef(buf, 8);
1050 String32(buf, entry.r_offset);
1051 F->getContents() += StringRef(buf, 4);
1053 struct ELF::Elf32_Rela ERE32;
1054 ERE32.setSymbolAndType(entry.Index, entry.Type);
1055 String32(buf, ERE32.r_info);
1056 F->getContents() += StringRef(buf, 4);
1058 if (HasRelocationAddend) {
1059 String32(buf, entry.r_addend);
1060 F->getContents() += StringRef(buf, 4);
1066 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1067 MCAsmLayout &Layout) {
1068 MCContext &Ctx = Asm.getContext();
1071 const MCSection *SymtabSection;
1072 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1074 unsigned NumRegularSections = Asm.size();
1076 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1077 const MCSection *ShstrtabSection;
1078 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1079 SectionKind::getReadOnly(), false);
1080 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1081 ShstrtabSD.setAlignment(1);
1082 ShstrtabIndex = Asm.size();
1084 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1085 SectionKind::getReadOnly(),
1087 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1088 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1090 const MCSection *StrtabSection;
1091 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1092 SectionKind::getReadOnly(), false);
1093 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1094 StrtabSD.setAlignment(1);
1095 StringTableIndex = Asm.size();
1097 WriteRelocations(Asm, Layout);
1100 F = new MCDataFragment(&SymtabSD);
1101 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1102 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1104 F = new MCDataFragment(&StrtabSD);
1105 F->getContents().append(StringTable.begin(), StringTable.end());
1106 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1108 F = new MCDataFragment(&ShstrtabSD);
1110 // Section header string table.
1112 // The first entry of a string table holds a null character so skip
1115 F->getContents() += '\x00';
1117 for (MCAssembler::const_iterator it = Asm.begin(),
1118 ie = Asm.end(); it != ie; ++it) {
1119 const MCSectionELF &Section =
1120 static_cast<const MCSectionELF&>(it->getSection());
1121 // FIXME: We could merge suffixes like in .text and .rela.text.
1123 // Remember the index into the string table so we can write it
1124 // into the sh_name field of the section header table.
1125 SectionStringTableIndex[&it->getSection()] = Index;
1127 Index += Section.getSectionName().size() + 1;
1128 F->getContents() += Section.getSectionName();
1129 F->getContents() += '\x00';
1132 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1135 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1136 const MCValue Target,
1138 const MCFragment *DF) const {
1139 // If this is a PCrel relocation, find the section this fixup value is
1141 const MCSection *BaseSection = 0;
1143 BaseSection = &DF->getParent()->getSection();
1144 assert(BaseSection);
1147 const MCSection *SectionA = 0;
1148 const MCSymbol *SymbolA = 0;
1149 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1150 SymbolA = &A->getSymbol();
1151 SectionA = &SymbolA->getSection();
1154 const MCSection *SectionB = 0;
1155 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1156 SectionB = &B->getSymbol().getSection();
1160 return SectionA == SectionB;
1162 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1163 if (DataA.isExternal())
1166 return !SectionB && BaseSection == SectionA;
1169 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1170 const MCAsmLayout &Layout) {
1171 // Compute symbol table information.
1172 ComputeSymbolTable(Asm);
1174 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1175 const_cast<MCAsmLayout&>(Layout));
1177 // Add 1 for the null section.
1178 unsigned NumSections = Asm.size() + 1;
1179 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1180 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1181 uint64_t FileOff = HeaderSize;
1183 for (MCAssembler::const_iterator it = Asm.begin(),
1184 ie = Asm.end(); it != ie; ++it) {
1185 const MCSectionData &SD = *it;
1187 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1189 // Get the size of the section in the output file (including padding).
1190 uint64_t Size = Layout.getSectionFileSize(&SD);
1195 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1197 // Write out the ELF header ...
1198 WriteHeader(FileOff - HeaderSize, NumSections);
1200 FileOff = HeaderSize;
1202 // ... then all of the sections ...
1203 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1205 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1208 for (MCAssembler::const_iterator it = Asm.begin(),
1209 ie = Asm.end(); it != ie; ++it) {
1210 const MCSectionData &SD = *it;
1212 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1213 WriteZeros(Padding);
1216 // Remember the offset into the file for this section.
1217 SectionOffsetMap[&it->getSection()] = FileOff;
1218 SectionIndexMap[&it->getSection()] = Index++;
1220 FileOff += Layout.getSectionFileSize(&SD);
1222 Asm.WriteSectionData(it, Layout, Writer);
1225 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1226 WriteZeros(Padding);
1229 // ... and then the section header table.
1230 // Should we align the section header table?
1232 // Null section first.
1233 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1235 for (MCAssembler::const_iterator it = Asm.begin(),
1236 ie = Asm.end(); it != ie; ++it) {
1237 const MCSectionData &SD = *it;
1238 const MCSectionELF &Section =
1239 static_cast<const MCSectionELF&>(SD.getSection());
1241 uint64_t sh_link = 0;
1242 uint64_t sh_info = 0;
1244 switch(Section.getType()) {
1245 case ELF::SHT_DYNAMIC:
1246 sh_link = SectionStringTableIndex[&it->getSection()];
1251 case ELF::SHT_RELA: {
1252 const MCSection *SymtabSection;
1253 const MCSection *InfoSection;
1255 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1256 SectionKind::getReadOnly(),
1258 sh_link = SectionIndexMap[SymtabSection];
1260 // Remove ".rel" and ".rela" prefixes.
1261 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1262 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1264 InfoSection = Asm.getContext().getELFSection(SectionName,
1265 ELF::SHT_PROGBITS, 0,
1266 SectionKind::getReadOnly(),
1268 sh_info = SectionIndexMap[InfoSection];
1272 case ELF::SHT_SYMTAB:
1273 case ELF::SHT_DYNSYM:
1274 sh_link = StringTableIndex;
1275 sh_info = LastLocalSymbolIndex;
1278 case ELF::SHT_PROGBITS:
1279 case ELF::SHT_STRTAB:
1280 case ELF::SHT_NOBITS:
1282 case ELF::SHT_ARM_ATTRIBUTES:
1287 assert(0 && "FIXME: sh_type value not supported!");
1291 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1292 Section.getType(), Section.getFlags(),
1294 SectionOffsetMap.lookup(&SD.getSection()),
1295 Layout.getSectionSize(&SD), sh_link,
1296 sh_info, SD.getAlignment(),
1297 Section.getEntrySize());
1301 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1303 Triple::OSType OSType,
1305 bool IsLittleEndian,
1306 bool HasRelocationAddend)
1307 : MCObjectWriter(OS, IsLittleEndian)
1309 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1310 HasRelocationAddend, OSType);
1313 ELFObjectWriter::~ELFObjectWriter() {
1314 delete (ELFObjectWriterImpl*) Impl;
1317 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1318 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1321 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1322 const MCAsmLayout &Layout,
1323 const MCFragment *Fragment,
1324 const MCFixup &Fixup, MCValue Target,
1325 uint64_t &FixedValue) {
1326 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1327 Target, FixedValue);
1330 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1331 const MCValue Target,
1333 const MCFragment *DF) const {
1334 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1338 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1339 const MCAsmLayout &Layout) {
1340 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);