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:
96 case MCSymbolRefExpr::VK_TLSLD:
103 class ELFObjectWriterImpl {
104 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
105 return Kind == X86::reloc_riprel_4byte ||
106 Kind == X86::reloc_riprel_4byte_movq_load;
110 /// ELFSymbolData - Helper struct for containing some precomputed information
112 struct ELFSymbolData {
113 MCSymbolData *SymbolData;
114 uint64_t StringIndex;
115 uint32_t SectionIndex;
117 // Support lexicographic sorting.
118 bool operator<(const ELFSymbolData &RHS) const {
119 if (GetType(*SymbolData) == ELF::STT_FILE)
121 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
123 return SymbolData->getSymbol().getName() <
124 RHS.SymbolData->getSymbol().getName();
128 /// @name Relocation Data
131 struct ELFRelocationEntry {
132 // Make these big enough for both 32-bit and 64-bit
136 const MCSymbol *Symbol;
139 // Support lexicographic sorting.
140 bool operator<(const ELFRelocationEntry &RE) const {
141 return RE.r_offset < r_offset;
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
148 llvm::DenseMap<const MCSectionData*,
149 std::vector<ELFRelocationEntry> > Relocations;
150 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
153 /// @name Symbol Table Data
156 SmallString<256> StringTable;
157 std::vector<ELFSymbolData> LocalSymbolData;
158 std::vector<ELFSymbolData> ExternalSymbolData;
159 std::vector<ELFSymbolData> UndefinedSymbolData;
163 int NumRegularSections;
167 ELFObjectWriter *Writer;
171 unsigned Is64Bit : 1;
173 bool HasRelocationAddend;
175 Triple::OSType OSType;
179 // This holds the symbol table index of the last local symbol.
180 unsigned LastLocalSymbolIndex;
181 // This holds the .strtab section index.
182 unsigned StringTableIndex;
184 unsigned ShstrtabIndex;
187 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
188 uint16_t _EMachine, bool _HasRelAddend,
189 Triple::OSType _OSType)
190 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
191 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
192 OSType(_OSType), EMachine(_EMachine) {
195 void Write8(uint8_t Value) { Writer->Write8(Value); }
196 void Write16(uint16_t Value) { Writer->Write16(Value); }
197 void Write32(uint32_t Value) { Writer->Write32(Value); }
198 //void Write64(uint64_t Value) { Writer->Write64(Value); }
199 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
200 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
201 // Writer->WriteBytes(Str, ZeroFillSize);
204 void WriteWord(uint64_t W) {
211 void String8(char *buf, uint8_t Value) {
215 void StringLE16(char *buf, uint16_t Value) {
216 buf[0] = char(Value >> 0);
217 buf[1] = char(Value >> 8);
220 void StringLE32(char *buf, uint32_t Value) {
221 StringLE16(buf, uint16_t(Value >> 0));
222 StringLE16(buf + 2, uint16_t(Value >> 16));
225 void StringLE64(char *buf, uint64_t Value) {
226 StringLE32(buf, uint32_t(Value >> 0));
227 StringLE32(buf + 4, uint32_t(Value >> 32));
230 void StringBE16(char *buf ,uint16_t Value) {
231 buf[0] = char(Value >> 8);
232 buf[1] = char(Value >> 0);
235 void StringBE32(char *buf, uint32_t Value) {
236 StringBE16(buf, uint16_t(Value >> 16));
237 StringBE16(buf + 2, uint16_t(Value >> 0));
240 void StringBE64(char *buf, uint64_t Value) {
241 StringBE32(buf, uint32_t(Value >> 32));
242 StringBE32(buf + 4, uint32_t(Value >> 0));
245 void String16(char *buf, uint16_t Value) {
246 if (Writer->isLittleEndian())
247 StringLE16(buf, Value);
249 StringBE16(buf, Value);
252 void String32(char *buf, uint32_t Value) {
253 if (Writer->isLittleEndian())
254 StringLE32(buf, Value);
256 StringBE32(buf, Value);
259 void String64(char *buf, uint64_t Value) {
260 if (Writer->isLittleEndian())
261 StringLE64(buf, Value);
263 StringBE64(buf, Value);
266 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
268 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
269 uint64_t value, uint64_t size,
270 uint8_t other, uint16_t shndx);
272 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
273 const MCAsmLayout &Layout);
275 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
276 const MCAsmLayout &Layout,
277 unsigned NumRegularSections);
279 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
280 const MCFragment *Fragment, const MCFixup &Fixup,
281 MCValue Target, uint64_t &FixedValue);
283 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
286 /// ComputeSymbolTable - Compute the symbol table data
288 /// \param StringTable [out] - The string table data.
289 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
291 void ComputeSymbolTable(MCAssembler &Asm);
293 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
294 const MCSectionData &SD);
296 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
297 for (MCAssembler::const_iterator it = Asm.begin(),
298 ie = Asm.end(); it != ie; ++it) {
299 WriteRelocation(Asm, Layout, *it);
303 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
305 void ExecutePostLayoutBinding(MCAssembler &Asm);
307 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
308 uint64_t Address, uint64_t Offset,
309 uint64_t Size, uint32_t Link, uint32_t Info,
310 uint64_t Alignment, uint64_t EntrySize);
312 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
313 const MCSectionData *SD);
315 bool IsFixupFullyResolved(const MCAssembler &Asm,
316 const MCValue Target,
318 const MCFragment *DF) const;
320 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
325 // Emit the ELF header.
326 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
327 unsigned NumberOfSections) {
333 // emitWord method behaves differently for ELF32 and ELF64, writing
334 // 4 bytes in the former and 8 in the latter.
336 Write8(0x7f); // e_ident[EI_MAG0]
337 Write8('E'); // e_ident[EI_MAG1]
338 Write8('L'); // e_ident[EI_MAG2]
339 Write8('F'); // e_ident[EI_MAG3]
341 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
344 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
346 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
349 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
350 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
351 default: Write8(ELF::ELFOSABI_NONE); break;
353 Write8(0); // e_ident[EI_ABIVERSION]
355 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
357 Write16(ELF::ET_REL); // e_type
359 Write16(EMachine); // e_machine = target
361 Write32(ELF::EV_CURRENT); // e_version
362 WriteWord(0); // e_entry, no entry point in .o file
363 WriteWord(0); // e_phoff, no program header for .o
364 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
365 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
367 // FIXME: Make this configurable.
368 Write32(0); // e_flags = whatever the target wants
370 // e_ehsize = ELF header size
371 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
373 Write16(0); // e_phentsize = prog header entry size
374 Write16(0); // e_phnum = # prog header entries = 0
376 // e_shentsize = Section header entry size
377 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
379 // e_shnum = # of section header ents
380 Write16(NumberOfSections);
382 // e_shstrndx = Section # of '.shstrtab'
383 Write16(ShstrtabIndex);
386 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
387 uint8_t info, uint64_t value,
388 uint64_t size, uint8_t other,
394 F->getContents() += StringRef(buf, 4); // st_name
397 F->getContents() += StringRef(buf, 1); // st_info
400 F->getContents() += StringRef(buf, 1); // st_other
402 String16(buf, shndx);
403 F->getContents() += StringRef(buf, 2); // st_shndx
405 String64(buf, value);
406 F->getContents() += StringRef(buf, 8); // st_value
409 F->getContents() += StringRef(buf, 8); // st_size
414 F->getContents() += StringRef(buf, 4); // st_name
416 String32(buf, value);
417 F->getContents() += StringRef(buf, 4); // st_value
420 F->getContents() += StringRef(buf, 4); // st_size
423 F->getContents() += StringRef(buf, 1); // st_info
426 F->getContents() += StringRef(buf, 1); // st_other
428 String16(buf, shndx);
429 F->getContents() += StringRef(buf, 2); // st_shndx
433 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
434 if (Data.isCommon() && Data.isExternal())
435 return Data.getCommonAlignment();
437 const MCSymbol &Symbol = Data.getSymbol();
438 if (!Symbol.isInSection())
441 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
442 if (MCFragment *FF = Data.getFragment())
443 return Layout.getSymbolAddress(&Data) -
444 Layout.getSectionAddress(FF->getParent());
449 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
450 const MCSymbol *S = &Symbol;
451 while (S->isVariable()) {
452 const MCExpr *Value = S->getVariableValue();
453 if (Value->getKind() != MCExpr::SymbolRef)
455 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
456 S = &Ref->getSymbol();
461 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
462 // The presence of symbol versions causes undefined symbols and
463 // versions declared with @@@ to be renamed.
465 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
466 ie = Asm.symbol_end(); it != ie; ++it) {
467 const MCSymbol &Alias = it->getSymbol();
468 const MCSymbol &Symbol = AliasedSymbol(Alias);
469 MCSymbolData &SD = Asm.getSymbolData(Symbol);
471 // Undefined symbols are global, but this is the first place we
472 // are able to set it.
473 if (Symbol.isUndefined() && !Symbol.isVariable()) {
474 if (GetBinding(SD) == ELF::STB_LOCAL) {
475 SetBinding(SD, ELF::STB_GLOBAL);
476 SetBinding(*it, ELF::STB_GLOBAL);
481 if (&Symbol == &Alias)
484 StringRef AliasName = Alias.getName();
485 size_t Pos = AliasName.find('@');
486 if (Pos == StringRef::npos)
489 // Aliases defined with .symvar copy the binding from the symbol they alias.
490 // This is the first place we are able to copy this information.
491 it->setExternal(SD.isExternal());
492 SetBinding(*it, GetBinding(SD));
494 StringRef Rest = AliasName.substr(Pos);
495 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
498 // FIXME: produce a better error message.
499 if (Symbol.isUndefined() && Rest.startswith("@@") &&
500 !Rest.startswith("@@@"))
501 report_fatal_error("A @@ version cannot be undefined");
503 Renames.insert(std::make_pair(&Symbol, &Alias));
507 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
508 const MCAsmLayout &Layout) {
509 MCSymbolData &OrigData = *MSD.SymbolData;
511 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
513 uint8_t Binding = GetBinding(OrigData);
514 uint8_t Visibility = GetVisibility(OrigData);
515 uint8_t Type = GetType(Data);
517 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
518 uint8_t Other = Visibility;
520 uint64_t Value = SymbolValue(Data, Layout);
524 assert(!(Data.isCommon() && !Data.isExternal()));
526 ESize = Data.getSize();
527 if (Data.getSize()) {
529 if (ESize->getKind() == MCExpr::Binary) {
530 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
532 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
533 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
534 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
535 Size = Res.getConstant();
537 } else if (ESize->getKind() == MCExpr::Constant) {
538 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
540 assert(0 && "Unsupported size expression");
544 // Write out the symbol table entry
545 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
546 Size, Other, MSD.SectionIndex);
549 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
550 const MCAssembler &Asm,
551 const MCAsmLayout &Layout,
552 unsigned NumRegularSections) {
553 // The string table must be emitted first because we need the index
554 // into the string table for all the symbol names.
555 assert(StringTable.size() && "Missing string table");
557 // FIXME: Make sure the start of the symbol table is aligned.
559 // The first entry is the undefined symbol entry.
560 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
561 F->getContents().append(EntrySize, '\x00');
563 // Write the symbol table entries.
564 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
565 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
566 ELFSymbolData &MSD = LocalSymbolData[i];
567 WriteSymbol(F, MSD, Layout);
570 // Write out a symbol table entry for each regular section.
572 for (MCAssembler::const_iterator it = Asm.begin();
573 Index <= NumRegularSections; ++it, ++Index) {
574 const MCSectionELF &Section =
575 static_cast<const MCSectionELF&>(it->getSection());
576 // Leave out relocations so we don't have indexes within
577 // the relocations messed up
578 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
580 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
581 LastLocalSymbolIndex++;
584 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
585 ELFSymbolData &MSD = ExternalSymbolData[i];
586 MCSymbolData &Data = *MSD.SymbolData;
587 assert(((Data.getFlags() & ELF_STB_Global) ||
588 (Data.getFlags() & ELF_STB_Weak)) &&
589 "External symbol requires STB_GLOBAL or STB_WEAK flag");
590 WriteSymbol(F, MSD, Layout);
591 if (GetBinding(Data) == ELF::STB_LOCAL)
592 LastLocalSymbolIndex++;
595 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
596 ELFSymbolData &MSD = UndefinedSymbolData[i];
597 MCSymbolData &Data = *MSD.SymbolData;
598 WriteSymbol(F, MSD, Layout);
599 if (GetBinding(Data) == ELF::STB_LOCAL)
600 LastLocalSymbolIndex++;
604 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
605 const MCValue &Target,
606 const MCFragment &F) {
607 const MCSymbol &Symbol = SD.getSymbol();
608 if (Symbol.isUndefined())
611 const MCSectionELF &Section =
612 static_cast<const MCSectionELF&>(Symbol.getSection());
617 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
618 const MCSectionELF &Sec2 =
619 static_cast<const MCSectionELF&>(F.getParent()->getSection());
621 if (Section.getKind().isBSS())
624 if (&Sec2 != &Section &&
625 (Kind == MCSymbolRefExpr::VK_PLT ||
626 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
627 Kind == MCSymbolRefExpr::VK_GOTOFF))
630 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
631 return Target.getConstant() != 0;
636 // FIXME: this is currently X86/X86_64 only
637 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
638 const MCAsmLayout &Layout,
639 const MCFragment *Fragment,
640 const MCFixup &Fixup,
642 uint64_t &FixedValue) {
645 int64_t Value = Target.getConstant();
646 const MCSymbol *Symbol = 0;
647 const MCSymbol *Renamed = 0;
649 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
650 if (!Target.isAbsolute()) {
651 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
652 Renamed = Renames.lookup(Symbol);
655 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
656 MCFragment *F = SD.getFragment();
658 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
659 const MCSymbol &SymbolB = RefB->getSymbol();
660 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
662 MCSectionData *Sec = Fragment->getParent();
664 // Offset of the symbol in the section
665 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
667 // Ofeset of the relocation in the section
668 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
672 // Check that this case has already been fully resolved before we get
674 if (Symbol->isDefined() && !SD.isExternal() &&
676 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
677 llvm_unreachable("We don't need a relocation in this case.");
681 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
682 if (!RelocOnSymbol) {
683 Index = F->getParent()->getOrdinal();
685 MCSectionData *FSD = F->getParent();
686 // Offset of the symbol in the section
687 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
689 UsedInReloc.insert(Renamed);
693 // Compensate for the addend on i386.
700 // determine the type of the relocation
702 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
708 llvm_unreachable("Unimplemented");
709 case MCSymbolRefExpr::VK_None:
710 Type = ELF::R_X86_64_PC32;
712 case MCSymbolRefExpr::VK_PLT:
713 Type = ELF::R_X86_64_PLT32;
715 case MCSymbolRefExpr::VK_GOTPCREL:
716 Type = ELF::R_X86_64_GOTPCREL;
718 case MCSymbolRefExpr::VK_GOTTPOFF:
719 Type = ELF::R_X86_64_GOTTPOFF;
721 case MCSymbolRefExpr::VK_TLSGD:
722 Type = ELF::R_X86_64_TLSGD;
724 case MCSymbolRefExpr::VK_TLSLD:
725 Type = ELF::R_X86_64_TLSLD;
729 switch ((unsigned)Fixup.getKind()) {
730 default: llvm_unreachable("invalid fixup kind!");
731 case FK_Data_8: Type = ELF::R_X86_64_64; break;
732 case X86::reloc_signed_4byte:
733 case X86::reloc_pcrel_4byte:
734 assert(isInt<32>(Target.getConstant()));
737 llvm_unreachable("Unimplemented");
738 case MCSymbolRefExpr::VK_None:
739 Type = ELF::R_X86_64_32S;
741 case MCSymbolRefExpr::VK_GOT:
742 Type = ELF::R_X86_64_GOT32;
744 case MCSymbolRefExpr::VK_GOTPCREL:
745 Type = ELF::R_X86_64_GOTPCREL;
747 case MCSymbolRefExpr::VK_TPOFF:
748 Type = ELF::R_X86_64_TPOFF32;
750 case MCSymbolRefExpr::VK_DTPOFF:
751 Type = ELF::R_X86_64_DTPOFF32;
756 Type = ELF::R_X86_64_32;
758 case FK_Data_2: Type = ELF::R_X86_64_16; break;
759 case X86::reloc_pcrel_1byte:
760 case FK_Data_1: Type = ELF::R_X86_64_8; break;
767 llvm_unreachable("Unimplemented");
768 case MCSymbolRefExpr::VK_None:
769 Type = ELF::R_386_PC32;
771 case MCSymbolRefExpr::VK_PLT:
772 Type = ELF::R_386_PLT32;
776 switch ((unsigned)Fixup.getKind()) {
777 default: llvm_unreachable("invalid fixup kind!");
779 case X86::reloc_global_offset_table:
780 Type = ELF::R_386_GOTPC;
783 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
785 case X86::reloc_signed_4byte:
786 case X86::reloc_pcrel_4byte:
790 llvm_unreachable("Unimplemented");
791 case MCSymbolRefExpr::VK_None:
792 Type = ELF::R_386_32;
794 case MCSymbolRefExpr::VK_GOT:
795 Type = ELF::R_386_GOT32;
797 case MCSymbolRefExpr::VK_GOTOFF:
798 Type = ELF::R_386_GOTOFF;
800 case MCSymbolRefExpr::VK_TLSGD:
801 Type = ELF::R_386_TLS_GD;
803 case MCSymbolRefExpr::VK_TPOFF:
804 Type = ELF::R_386_TLS_LE_32;
806 case MCSymbolRefExpr::VK_INDNTPOFF:
807 Type = ELF::R_386_TLS_IE;
809 case MCSymbolRefExpr::VK_NTPOFF:
810 Type = ELF::R_386_TLS_LE;
812 case MCSymbolRefExpr::VK_GOTNTPOFF:
813 Type = ELF::R_386_TLS_GOTIE;
815 case MCSymbolRefExpr::VK_TLSLDM:
816 Type = ELF::R_386_TLS_LDM;
818 case MCSymbolRefExpr::VK_DTPOFF:
819 Type = ELF::R_386_TLS_LDO_32;
823 case FK_Data_2: Type = ELF::R_386_16; break;
824 case X86::reloc_pcrel_1byte:
825 case FK_Data_1: Type = ELF::R_386_8; break;
830 if (RelocNeedsGOT(Modifier))
833 ELFRelocationEntry ERE;
837 ERE.Symbol = Renamed;
839 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
841 if (HasRelocationAddend)
842 ERE.r_addend = Addend;
844 ERE.r_addend = 0; // Silence compiler warning.
846 Relocations[Fragment->getParent()].push_back(ERE);
850 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
852 MCSymbolData &SD = Asm.getSymbolData(*S);
855 if (!SD.isExternal() && !S->isUndefined())
856 return SD.getIndex() + /* empty symbol */ 1;
858 // External or undefined symbol.
859 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
862 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
863 bool Used, bool Renamed) {
870 const MCSymbol &Symbol = Data.getSymbol();
872 const MCSymbol &A = AliasedSymbol(Symbol);
873 if (&A != &Symbol && A.isUndefined())
876 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
879 if (Symbol.isTemporary())
885 static bool isLocal(const MCSymbolData &Data) {
886 if (Data.isExternal())
889 const MCSymbol &Symbol = Data.getSymbol();
890 if (Symbol.isUndefined() && !Symbol.isVariable())
896 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
897 // FIXME: Is this the correct place to do this?
899 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
900 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
901 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
902 Data.setExternal(true);
903 SetBinding(Data, ELF::STB_GLOBAL);
906 // Build section lookup table.
907 NumRegularSections = Asm.size();
908 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
910 for (MCAssembler::iterator it = Asm.begin(),
911 ie = Asm.end(); it != ie; ++it, ++Index)
912 SectionIndexMap[&it->getSection()] = Index;
914 // Index 0 is always the empty string.
915 StringMap<uint64_t> StringIndexMap;
916 StringTable += '\x00';
918 // Add the data for the symbols.
919 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
920 ie = Asm.symbol_end(); it != ie; ++it) {
921 const MCSymbol &Symbol = it->getSymbol();
923 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol),
924 Renames.count(&Symbol)))
929 bool Local = isLocal(*it);
930 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
932 if (it->isCommon()) {
934 MSD.SectionIndex = ELF::SHN_COMMON;
935 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
936 MSD.SectionIndex = ELF::SHN_ABS;
937 } else if (RefSymbol.isUndefined()) {
938 MSD.SectionIndex = ELF::SHN_UNDEF;
940 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
941 assert(MSD.SectionIndex && "Invalid section index!");
944 // The @@@ in symbol version is replaced with @ in undefined symbols and
945 // @@ in defined ones.
946 StringRef Name = Symbol.getName();
947 size_t Pos = Name.find("@@@");
948 std::string FinalName;
949 if (Pos != StringRef::npos) {
950 StringRef Prefix = Name.substr(0, Pos);
951 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
952 StringRef Suffix = Name.substr(Pos + n);
953 FinalName = Prefix.str() + Suffix.str();
955 FinalName = Name.str();
958 uint64_t &Entry = StringIndexMap[FinalName];
960 Entry = StringTable.size();
961 StringTable += FinalName;
962 StringTable += '\x00';
964 MSD.StringIndex = Entry;
965 if (MSD.SectionIndex == ELF::SHN_UNDEF)
966 UndefinedSymbolData.push_back(MSD);
968 LocalSymbolData.push_back(MSD);
970 ExternalSymbolData.push_back(MSD);
973 // Symbols are required to be in lexicographic order.
974 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
975 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
976 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
978 // Set the symbol indices. Local symbols must come before all other
979 // symbols with non-local bindings.
981 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
982 LocalSymbolData[i].SymbolData->setIndex(Index++);
983 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
984 ExternalSymbolData[i].SymbolData->setIndex(Index++);
985 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
986 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
989 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
990 const MCSectionData &SD) {
991 if (!Relocations[&SD].empty()) {
992 MCContext &Ctx = Asm.getContext();
993 const MCSection *RelaSection;
994 const MCSectionELF &Section =
995 static_cast<const MCSectionELF&>(SD.getSection());
997 const StringRef SectionName = Section.getSectionName();
998 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
999 RelaSectionName += SectionName;
1002 if (HasRelocationAddend)
1003 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1005 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1007 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1008 ELF::SHT_RELA : ELF::SHT_REL, 0,
1009 SectionKind::getReadOnly(),
1012 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1013 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1015 MCDataFragment *F = new MCDataFragment(&RelaSD);
1017 WriteRelocationsFragment(Asm, F, &SD);
1019 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
1023 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1024 uint64_t Flags, uint64_t Address,
1025 uint64_t Offset, uint64_t Size,
1026 uint32_t Link, uint32_t Info,
1028 uint64_t EntrySize) {
1029 Write32(Name); // sh_name: index into string table
1030 Write32(Type); // sh_type
1031 WriteWord(Flags); // sh_flags
1032 WriteWord(Address); // sh_addr
1033 WriteWord(Offset); // sh_offset
1034 WriteWord(Size); // sh_size
1035 Write32(Link); // sh_link
1036 Write32(Info); // sh_info
1037 WriteWord(Alignment); // sh_addralign
1038 WriteWord(EntrySize); // sh_entsize
1041 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1043 const MCSectionData *SD) {
1044 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1045 // sort by the r_offset just like gnu as does
1046 array_pod_sort(Relocs.begin(), Relocs.end());
1048 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1049 ELFRelocationEntry entry = Relocs[e - i - 1];
1051 if (entry.Index < 0)
1052 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1054 entry.Index += LocalSymbolData.size() + 1;
1058 String64(buf, entry.r_offset);
1059 F->getContents() += StringRef(buf, 8);
1061 struct ELF::Elf64_Rela ERE64;
1062 ERE64.setSymbolAndType(entry.Index, entry.Type);
1063 String64(buf, ERE64.r_info);
1064 F->getContents() += StringRef(buf, 8);
1066 if (HasRelocationAddend) {
1067 String64(buf, entry.r_addend);
1068 F->getContents() += StringRef(buf, 8);
1073 String32(buf, entry.r_offset);
1074 F->getContents() += StringRef(buf, 4);
1076 struct ELF::Elf32_Rela ERE32;
1077 ERE32.setSymbolAndType(entry.Index, entry.Type);
1078 String32(buf, ERE32.r_info);
1079 F->getContents() += StringRef(buf, 4);
1081 if (HasRelocationAddend) {
1082 String32(buf, entry.r_addend);
1083 F->getContents() += StringRef(buf, 4);
1089 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1090 MCAsmLayout &Layout) {
1091 MCContext &Ctx = Asm.getContext();
1094 const MCSection *SymtabSection;
1095 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1097 unsigned NumRegularSections = Asm.size();
1099 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1100 const MCSection *ShstrtabSection;
1101 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1102 SectionKind::getReadOnly(), false);
1103 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1104 ShstrtabSD.setAlignment(1);
1105 ShstrtabIndex = Asm.size();
1107 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1108 SectionKind::getReadOnly(),
1110 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1111 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1113 const MCSection *StrtabSection;
1114 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1115 SectionKind::getReadOnly(), false);
1116 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1117 StrtabSD.setAlignment(1);
1118 StringTableIndex = Asm.size();
1120 WriteRelocations(Asm, Layout);
1123 F = new MCDataFragment(&SymtabSD);
1124 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1125 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1127 F = new MCDataFragment(&StrtabSD);
1128 F->getContents().append(StringTable.begin(), StringTable.end());
1129 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1131 F = new MCDataFragment(&ShstrtabSD);
1133 // Section header string table.
1135 // The first entry of a string table holds a null character so skip
1138 F->getContents() += '\x00';
1140 for (MCAssembler::const_iterator it = Asm.begin(),
1141 ie = Asm.end(); it != ie; ++it) {
1142 const MCSectionELF &Section =
1143 static_cast<const MCSectionELF&>(it->getSection());
1144 // FIXME: We could merge suffixes like in .text and .rela.text.
1146 // Remember the index into the string table so we can write it
1147 // into the sh_name field of the section header table.
1148 SectionStringTableIndex[&it->getSection()] = Index;
1150 Index += Section.getSectionName().size() + 1;
1151 F->getContents() += Section.getSectionName();
1152 F->getContents() += '\x00';
1155 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1158 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1159 const MCValue Target,
1161 const MCFragment *DF) const {
1162 // If this is a PCrel relocation, find the section this fixup value is
1164 const MCSection *BaseSection = 0;
1166 BaseSection = &DF->getParent()->getSection();
1167 assert(BaseSection);
1170 const MCSection *SectionA = 0;
1171 const MCSymbol *SymbolA = 0;
1172 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1173 SymbolA = &A->getSymbol();
1174 SectionA = &SymbolA->getSection();
1177 const MCSection *SectionB = 0;
1178 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1179 SectionB = &B->getSymbol().getSection();
1183 return SectionA == SectionB;
1185 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1186 if (DataA.isExternal())
1189 return !SectionB && BaseSection == SectionA;
1192 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1193 const MCAsmLayout &Layout) {
1194 // Compute symbol table information.
1195 ComputeSymbolTable(Asm);
1197 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1198 const_cast<MCAsmLayout&>(Layout));
1200 // Add 1 for the null section.
1201 unsigned NumSections = Asm.size() + 1;
1202 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1203 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1204 uint64_t FileOff = HeaderSize;
1206 for (MCAssembler::const_iterator it = Asm.begin(),
1207 ie = Asm.end(); it != ie; ++it) {
1208 const MCSectionData &SD = *it;
1210 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1212 // Get the size of the section in the output file (including padding).
1213 uint64_t Size = Layout.getSectionFileSize(&SD);
1218 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1220 // Write out the ELF header ...
1221 WriteHeader(FileOff - HeaderSize, NumSections);
1223 FileOff = HeaderSize;
1225 // ... then all of the sections ...
1226 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1228 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1231 for (MCAssembler::const_iterator it = Asm.begin(),
1232 ie = Asm.end(); it != ie; ++it) {
1233 const MCSectionData &SD = *it;
1235 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1236 WriteZeros(Padding);
1239 // Remember the offset into the file for this section.
1240 SectionOffsetMap[&it->getSection()] = FileOff;
1241 SectionIndexMap[&it->getSection()] = Index++;
1243 FileOff += Layout.getSectionFileSize(&SD);
1245 Asm.WriteSectionData(it, Layout, Writer);
1248 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1249 WriteZeros(Padding);
1252 // ... and then the section header table.
1253 // Should we align the section header table?
1255 // Null section first.
1256 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1258 for (MCAssembler::const_iterator it = Asm.begin(),
1259 ie = Asm.end(); it != ie; ++it) {
1260 const MCSectionData &SD = *it;
1261 const MCSectionELF &Section =
1262 static_cast<const MCSectionELF&>(SD.getSection());
1264 uint64_t sh_link = 0;
1265 uint64_t sh_info = 0;
1267 switch(Section.getType()) {
1268 case ELF::SHT_DYNAMIC:
1269 sh_link = SectionStringTableIndex[&it->getSection()];
1274 case ELF::SHT_RELA: {
1275 const MCSection *SymtabSection;
1276 const MCSection *InfoSection;
1278 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1279 SectionKind::getReadOnly(),
1281 sh_link = SectionIndexMap[SymtabSection];
1283 // Remove ".rel" and ".rela" prefixes.
1284 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1285 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1287 InfoSection = Asm.getContext().getELFSection(SectionName,
1288 ELF::SHT_PROGBITS, 0,
1289 SectionKind::getReadOnly(),
1291 sh_info = SectionIndexMap[InfoSection];
1295 case ELF::SHT_SYMTAB:
1296 case ELF::SHT_DYNSYM:
1297 sh_link = StringTableIndex;
1298 sh_info = LastLocalSymbolIndex;
1301 case ELF::SHT_PROGBITS:
1302 case ELF::SHT_STRTAB:
1303 case ELF::SHT_NOBITS:
1305 case ELF::SHT_ARM_ATTRIBUTES:
1310 assert(0 && "FIXME: sh_type value not supported!");
1314 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1315 Section.getType(), Section.getFlags(),
1317 SectionOffsetMap.lookup(&SD.getSection()),
1318 Layout.getSectionSize(&SD), sh_link,
1319 sh_info, SD.getAlignment(),
1320 Section.getEntrySize());
1324 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1326 Triple::OSType OSType,
1328 bool IsLittleEndian,
1329 bool HasRelocationAddend)
1330 : MCObjectWriter(OS, IsLittleEndian)
1332 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1333 HasRelocationAddend, OSType);
1336 ELFObjectWriter::~ELFObjectWriter() {
1337 delete (ELFObjectWriterImpl*) Impl;
1340 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1341 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1344 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1345 const MCAsmLayout &Layout,
1346 const MCFragment *Fragment,
1347 const MCFixup &Fixup, MCValue Target,
1348 uint64_t &FixedValue) {
1349 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1350 Target, FixedValue);
1353 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1354 const MCValue Target,
1356 const MCFragment *DF) const {
1357 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1361 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1362 const MCAsmLayout &Layout) {
1363 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);