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:
100 class ELFObjectWriterImpl {
101 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
102 return Kind == X86::reloc_riprel_4byte ||
103 Kind == X86::reloc_riprel_4byte_movq_load;
107 /// ELFSymbolData - Helper struct for containing some precomputed information
109 struct ELFSymbolData {
110 MCSymbolData *SymbolData;
111 uint64_t StringIndex;
112 uint32_t SectionIndex;
114 // Support lexicographic sorting.
115 bool operator<(const ELFSymbolData &RHS) const {
116 if (GetType(*SymbolData) == ELF::STT_FILE)
118 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
120 return SymbolData->getSymbol().getName() <
121 RHS.SymbolData->getSymbol().getName();
125 /// @name Relocation Data
128 struct ELFRelocationEntry {
129 // Make these big enough for both 32-bit and 64-bit
133 const MCSymbol *Symbol;
136 // Support lexicographic sorting.
137 bool operator<(const ELFRelocationEntry &RE) const {
138 return RE.r_offset < r_offset;
142 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
143 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
145 llvm::DenseMap<const MCSectionData*,
146 std::vector<ELFRelocationEntry> > Relocations;
147 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
150 /// @name Symbol Table Data
153 SmallString<256> StringTable;
154 std::vector<ELFSymbolData> LocalSymbolData;
155 std::vector<ELFSymbolData> ExternalSymbolData;
156 std::vector<ELFSymbolData> UndefinedSymbolData;
160 int NumRegularSections;
164 ELFObjectWriter *Writer;
168 unsigned Is64Bit : 1;
170 bool HasRelocationAddend;
172 Triple::OSType OSType;
176 // This holds the symbol table index of the last local symbol.
177 unsigned LastLocalSymbolIndex;
178 // This holds the .strtab section index.
179 unsigned StringTableIndex;
181 unsigned ShstrtabIndex;
184 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
185 uint16_t _EMachine, bool _HasRelAddend,
186 Triple::OSType _OSType)
187 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
188 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
189 OSType(_OSType), EMachine(_EMachine) {
192 void Write8(uint8_t Value) { Writer->Write8(Value); }
193 void Write16(uint16_t Value) { Writer->Write16(Value); }
194 void Write32(uint32_t Value) { Writer->Write32(Value); }
195 //void Write64(uint64_t Value) { Writer->Write64(Value); }
196 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
197 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
198 // Writer->WriteBytes(Str, ZeroFillSize);
201 void WriteWord(uint64_t W) {
208 void String8(char *buf, uint8_t Value) {
212 void StringLE16(char *buf, uint16_t Value) {
213 buf[0] = char(Value >> 0);
214 buf[1] = char(Value >> 8);
217 void StringLE32(char *buf, uint32_t Value) {
218 StringLE16(buf, uint16_t(Value >> 0));
219 StringLE16(buf + 2, uint16_t(Value >> 16));
222 void StringLE64(char *buf, uint64_t Value) {
223 StringLE32(buf, uint32_t(Value >> 0));
224 StringLE32(buf + 4, uint32_t(Value >> 32));
227 void StringBE16(char *buf ,uint16_t Value) {
228 buf[0] = char(Value >> 8);
229 buf[1] = char(Value >> 0);
232 void StringBE32(char *buf, uint32_t Value) {
233 StringBE16(buf, uint16_t(Value >> 16));
234 StringBE16(buf + 2, uint16_t(Value >> 0));
237 void StringBE64(char *buf, uint64_t Value) {
238 StringBE32(buf, uint32_t(Value >> 32));
239 StringBE32(buf + 4, uint32_t(Value >> 0));
242 void String16(char *buf, uint16_t Value) {
243 if (Writer->isLittleEndian())
244 StringLE16(buf, Value);
246 StringBE16(buf, Value);
249 void String32(char *buf, uint32_t Value) {
250 if (Writer->isLittleEndian())
251 StringLE32(buf, Value);
253 StringBE32(buf, Value);
256 void String64(char *buf, uint64_t Value) {
257 if (Writer->isLittleEndian())
258 StringLE64(buf, Value);
260 StringBE64(buf, Value);
263 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
265 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
266 uint64_t value, uint64_t size,
267 uint8_t other, uint16_t shndx);
269 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
270 const MCAsmLayout &Layout);
272 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
273 const MCAsmLayout &Layout,
274 unsigned NumRegularSections);
276 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
277 const MCFragment *Fragment, const MCFixup &Fixup,
278 MCValue Target, uint64_t &FixedValue);
280 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
283 /// ComputeSymbolTable - Compute the symbol table data
285 /// \param StringTable [out] - The string table data.
286 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
288 void ComputeSymbolTable(MCAssembler &Asm);
290 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
291 const MCSectionData &SD);
293 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
294 for (MCAssembler::const_iterator it = Asm.begin(),
295 ie = Asm.end(); it != ie; ++it) {
296 WriteRelocation(Asm, Layout, *it);
300 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
302 void ExecutePostLayoutBinding(MCAssembler &Asm);
304 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
305 uint64_t Address, uint64_t Offset,
306 uint64_t Size, uint32_t Link, uint32_t Info,
307 uint64_t Alignment, uint64_t EntrySize);
309 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
310 const MCSectionData *SD);
312 bool IsFixupFullyResolved(const MCAssembler &Asm,
313 const MCValue Target,
315 const MCFragment *DF) const;
317 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
322 // Emit the ELF header.
323 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
324 unsigned NumberOfSections) {
330 // emitWord method behaves differently for ELF32 and ELF64, writing
331 // 4 bytes in the former and 8 in the latter.
333 Write8(0x7f); // e_ident[EI_MAG0]
334 Write8('E'); // e_ident[EI_MAG1]
335 Write8('L'); // e_ident[EI_MAG2]
336 Write8('F'); // e_ident[EI_MAG3]
338 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
341 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
343 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
346 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
347 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
348 default: Write8(ELF::ELFOSABI_NONE); break;
350 Write8(0); // e_ident[EI_ABIVERSION]
352 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
354 Write16(ELF::ET_REL); // e_type
356 Write16(EMachine); // e_machine = target
358 Write32(ELF::EV_CURRENT); // e_version
359 WriteWord(0); // e_entry, no entry point in .o file
360 WriteWord(0); // e_phoff, no program header for .o
361 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
362 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
364 // FIXME: Make this configurable.
365 Write32(0); // e_flags = whatever the target wants
367 // e_ehsize = ELF header size
368 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
370 Write16(0); // e_phentsize = prog header entry size
371 Write16(0); // e_phnum = # prog header entries = 0
373 // e_shentsize = Section header entry size
374 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
376 // e_shnum = # of section header ents
377 Write16(NumberOfSections);
379 // e_shstrndx = Section # of '.shstrtab'
380 Write16(ShstrtabIndex);
383 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
384 uint8_t info, uint64_t value,
385 uint64_t size, uint8_t other,
391 F->getContents() += StringRef(buf, 4); // st_name
394 F->getContents() += StringRef(buf, 1); // st_info
397 F->getContents() += StringRef(buf, 1); // st_other
399 String16(buf, shndx);
400 F->getContents() += StringRef(buf, 2); // st_shndx
402 String64(buf, value);
403 F->getContents() += StringRef(buf, 8); // st_value
406 F->getContents() += StringRef(buf, 8); // st_size
411 F->getContents() += StringRef(buf, 4); // st_name
413 String32(buf, value);
414 F->getContents() += StringRef(buf, 4); // st_value
417 F->getContents() += StringRef(buf, 4); // st_size
420 F->getContents() += StringRef(buf, 1); // st_info
423 F->getContents() += StringRef(buf, 1); // st_other
425 String16(buf, shndx);
426 F->getContents() += StringRef(buf, 2); // st_shndx
430 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
431 if (Data.isCommon() && Data.isExternal())
432 return Data.getCommonAlignment();
434 const MCSymbol &Symbol = Data.getSymbol();
435 if (!Symbol.isInSection())
438 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
439 if (MCFragment *FF = Data.getFragment())
440 return Layout.getSymbolAddress(&Data) -
441 Layout.getSectionAddress(FF->getParent());
446 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
447 const MCSymbol *S = &Symbol;
448 while (S->isVariable()) {
449 const MCExpr *Value = S->getVariableValue();
450 if (Value->getKind() != MCExpr::SymbolRef)
452 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
453 S = &Ref->getSymbol();
458 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
459 // The presence of symbol versions causes undefined symbols and
460 // versions declared with @@@ to be renamed.
462 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
463 ie = Asm.symbol_end(); it != ie; ++it) {
464 const MCSymbol &Alias = it->getSymbol();
465 if (!Alias.isVariable())
467 const MCSymbol &Symbol = AliasedSymbol(Alias);
468 StringRef AliasName = Alias.getName();
469 size_t Pos = AliasName.find('@');
470 if (Pos == StringRef::npos)
473 StringRef Rest = AliasName.substr(Pos);
474 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
477 // FIXME: produce a better error message.
478 if (Symbol.isUndefined() && Rest.startswith("@@") &&
479 !Rest.startswith("@@@"))
480 report_fatal_error("A @@ version cannot be undefined");
482 Renames.insert(std::make_pair(&Symbol, &Alias));
486 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
487 const MCAsmLayout &Layout) {
488 MCSymbolData &OrigData = *MSD.SymbolData;
490 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
492 uint8_t Binding = GetBinding(OrigData);
493 uint8_t Visibility = GetVisibility(OrigData);
494 uint8_t Type = GetType(Data);
496 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
497 uint8_t Other = Visibility;
499 uint64_t Value = SymbolValue(Data, Layout);
503 assert(!(Data.isCommon() && !Data.isExternal()));
505 ESize = Data.getSize();
506 if (Data.getSize()) {
508 if (ESize->getKind() == MCExpr::Binary) {
509 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
511 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
512 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
513 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
514 Size = Res.getConstant();
516 } else if (ESize->getKind() == MCExpr::Constant) {
517 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
519 assert(0 && "Unsupported size expression");
523 // Write out the symbol table entry
524 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
525 Size, Other, MSD.SectionIndex);
528 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
529 const MCAssembler &Asm,
530 const MCAsmLayout &Layout,
531 unsigned NumRegularSections) {
532 // The string table must be emitted first because we need the index
533 // into the string table for all the symbol names.
534 assert(StringTable.size() && "Missing string table");
536 // FIXME: Make sure the start of the symbol table is aligned.
538 // The first entry is the undefined symbol entry.
539 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
540 F->getContents().append(EntrySize, '\x00');
542 // Write the symbol table entries.
543 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
544 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
545 ELFSymbolData &MSD = LocalSymbolData[i];
546 WriteSymbol(F, MSD, Layout);
549 // Write out a symbol table entry for each regular section.
551 for (MCAssembler::const_iterator it = Asm.begin();
552 Index <= NumRegularSections; ++it, ++Index) {
553 const MCSectionELF &Section =
554 static_cast<const MCSectionELF&>(it->getSection());
555 // Leave out relocations so we don't have indexes within
556 // the relocations messed up
557 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
559 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
560 LastLocalSymbolIndex++;
563 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
564 ELFSymbolData &MSD = ExternalSymbolData[i];
565 MCSymbolData &Data = *MSD.SymbolData;
566 assert(((Data.getFlags() & ELF_STB_Global) ||
567 (Data.getFlags() & ELF_STB_Weak)) &&
568 "External symbol requires STB_GLOBAL or STB_WEAK flag");
569 WriteSymbol(F, MSD, Layout);
570 if (GetBinding(Data) == ELF::STB_LOCAL)
571 LastLocalSymbolIndex++;
574 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
575 ELFSymbolData &MSD = UndefinedSymbolData[i];
576 MCSymbolData &Data = *MSD.SymbolData;
577 WriteSymbol(F, MSD, Layout);
578 if (GetBinding(Data) == ELF::STB_LOCAL)
579 LastLocalSymbolIndex++;
583 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
584 const MCValue &Target,
585 const MCFragment &F) {
586 const MCSymbol &Symbol = SD.getSymbol();
587 if (Symbol.isUndefined())
590 const MCSectionELF &Section =
591 static_cast<const MCSectionELF&>(Symbol.getSection());
596 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
597 const MCSectionELF &Sec2 =
598 static_cast<const MCSectionELF&>(F.getParent()->getSection());
600 if (Section.getKind().isBSS())
603 if (&Sec2 != &Section &&
604 (Kind == MCSymbolRefExpr::VK_PLT ||
605 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
606 Kind == MCSymbolRefExpr::VK_GOTOFF))
609 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
610 return Target.getConstant() != 0;
615 // FIXME: this is currently X86/X86_64 only
616 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
617 const MCAsmLayout &Layout,
618 const MCFragment *Fragment,
619 const MCFixup &Fixup,
621 uint64_t &FixedValue) {
624 int64_t Value = Target.getConstant();
625 const MCSymbol *Symbol = 0;
627 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
628 if (!Target.isAbsolute()) {
629 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
630 const MCSymbol *Renamed = Renames.lookup(Symbol);
633 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
634 MCFragment *F = SD.getFragment();
636 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
637 const MCSymbol &SymbolB = RefB->getSymbol();
638 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
640 MCSectionData *Sec = Fragment->getParent();
642 // Offset of the symbol in the section
643 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
645 // Ofeset of the relocation in the section
646 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
650 // Check that this case has already been fully resolved before we get
652 if (Symbol->isDefined() && !SD.isExternal() &&
654 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
655 llvm_unreachable("We don't need a relocation in this case.");
659 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
660 if (!RelocOnSymbol) {
661 Index = F->getParent()->getOrdinal();
663 MCSectionData *FSD = F->getParent();
664 // Offset of the symbol in the section
665 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
667 UsedInReloc.insert(Symbol);
671 // Compensate for the addend on i386.
678 // determine the type of the relocation
680 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
686 llvm_unreachable("Unimplemented");
687 case MCSymbolRefExpr::VK_None:
688 Type = ELF::R_X86_64_PC32;
690 case MCSymbolRefExpr::VK_PLT:
691 Type = ELF::R_X86_64_PLT32;
693 case MCSymbolRefExpr::VK_GOTPCREL:
694 Type = ELF::R_X86_64_GOTPCREL;
696 case MCSymbolRefExpr::VK_GOTTPOFF:
697 Type = ELF::R_X86_64_GOTTPOFF;
699 case MCSymbolRefExpr::VK_TLSGD:
700 Type = ELF::R_X86_64_TLSGD;
704 switch ((unsigned)Fixup.getKind()) {
705 default: llvm_unreachable("invalid fixup kind!");
706 case FK_Data_8: Type = ELF::R_X86_64_64; break;
707 case X86::reloc_signed_4byte:
708 case X86::reloc_pcrel_4byte:
709 assert(isInt<32>(Target.getConstant()));
712 llvm_unreachable("Unimplemented");
713 case MCSymbolRefExpr::VK_None:
714 Type = ELF::R_X86_64_32S;
716 case MCSymbolRefExpr::VK_GOT:
717 Type = ELF::R_X86_64_GOT32;
719 case MCSymbolRefExpr::VK_GOTPCREL:
720 Type = ELF::R_X86_64_GOTPCREL;
722 case MCSymbolRefExpr::VK_TPOFF:
723 Type = ELF::R_X86_64_TPOFF32;
728 Type = ELF::R_X86_64_32;
730 case FK_Data_2: Type = ELF::R_X86_64_16; break;
731 case X86::reloc_pcrel_1byte:
732 case FK_Data_1: Type = ELF::R_X86_64_8; break;
739 llvm_unreachable("Unimplemented");
740 case MCSymbolRefExpr::VK_None:
741 Type = ELF::R_386_PC32;
743 case MCSymbolRefExpr::VK_PLT:
744 Type = ELF::R_386_PLT32;
748 switch ((unsigned)Fixup.getKind()) {
749 default: llvm_unreachable("invalid fixup kind!");
751 case X86::reloc_global_offset_table:
752 Type = ELF::R_386_GOTPC;
755 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
757 case X86::reloc_signed_4byte:
758 case X86::reloc_pcrel_4byte:
762 llvm_unreachable("Unimplemented");
763 case MCSymbolRefExpr::VK_None:
764 Type = ELF::R_386_32;
766 case MCSymbolRefExpr::VK_GOT:
767 Type = ELF::R_386_GOT32;
769 case MCSymbolRefExpr::VK_GOTOFF:
770 Type = ELF::R_386_GOTOFF;
772 case MCSymbolRefExpr::VK_TLSGD:
773 Type = ELF::R_386_TLS_GD;
775 case MCSymbolRefExpr::VK_TPOFF:
776 Type = ELF::R_386_TLS_LE_32;
778 case MCSymbolRefExpr::VK_INDNTPOFF:
779 Type = ELF::R_386_TLS_IE;
781 case MCSymbolRefExpr::VK_NTPOFF:
782 Type = ELF::R_386_TLS_LE;
784 case MCSymbolRefExpr::VK_GOTNTPOFF:
785 Type = ELF::R_386_TLS_GOTIE;
789 case FK_Data_2: Type = ELF::R_386_16; break;
790 case X86::reloc_pcrel_1byte:
791 case FK_Data_1: Type = ELF::R_386_8; break;
796 if (RelocNeedsGOT(Modifier))
799 ELFRelocationEntry ERE;
805 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
807 if (HasRelocationAddend)
808 ERE.r_addend = Addend;
810 ERE.r_addend = 0; // Silence compiler warning.
812 Relocations[Fragment->getParent()].push_back(ERE);
816 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
818 MCSymbolData &SD = Asm.getSymbolData(*S);
821 if (!SD.isExternal() && !S->isUndefined())
822 return SD.getIndex() + /* empty symbol */ 1;
824 // External or undefined symbol.
825 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
828 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
829 bool Used, bool Renamed) {
836 const MCSymbol &Symbol = Data.getSymbol();
838 const MCSymbol &A = AliasedSymbol(Symbol);
839 if (&A != &Symbol && A.isUndefined())
842 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
845 if (Symbol.isTemporary())
851 static bool isLocal(const MCSymbolData &Data) {
852 if (Data.isExternal())
855 const MCSymbol &Symbol = Data.getSymbol();
856 if (Symbol.isUndefined() && !Symbol.isVariable())
862 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
863 // FIXME: Is this the correct place to do this?
865 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
866 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
867 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
868 Data.setExternal(true);
871 // Build section lookup table.
872 NumRegularSections = Asm.size();
873 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
875 for (MCAssembler::iterator it = Asm.begin(),
876 ie = Asm.end(); it != ie; ++it, ++Index)
877 SectionIndexMap[&it->getSection()] = Index;
879 // Index 0 is always the empty string.
880 StringMap<uint64_t> StringIndexMap;
881 StringTable += '\x00';
883 // Add the data for the symbols.
884 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
885 ie = Asm.symbol_end(); it != ie; ++it) {
886 const MCSymbol &Symbol = it->getSymbol();
888 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol),
889 Renames.count(&Symbol)))
894 bool Local = isLocal(*it);
895 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
897 if (it->isCommon()) {
899 MSD.SectionIndex = ELF::SHN_COMMON;
900 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
901 MSD.SectionIndex = ELF::SHN_ABS;
902 } else if (RefSymbol.isUndefined()) {
903 MSD.SectionIndex = ELF::SHN_UNDEF;
904 // FIXME: Undefined symbols are global, but this is the first place we
905 // are able to set it.
906 if (GetBinding(*it) == ELF::STB_LOCAL)
907 SetBinding(*it, ELF::STB_GLOBAL);
909 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
910 assert(MSD.SectionIndex && "Invalid section index!");
913 // The @@@ in symbol version is replaced with @ in undefined symbols and
914 // @@ in defined ones.
915 StringRef Name = Symbol.getName();
916 size_t Pos = Name.find("@@@");
917 std::string FinalName;
918 if (Pos != StringRef::npos) {
919 StringRef Prefix = Name.substr(0, Pos);
920 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
921 StringRef Suffix = Name.substr(Pos + n);
922 FinalName = Prefix.str() + Suffix.str();
924 FinalName = Name.str();
927 uint64_t &Entry = StringIndexMap[FinalName];
929 Entry = StringTable.size();
930 StringTable += FinalName;
931 StringTable += '\x00';
933 MSD.StringIndex = Entry;
934 if (MSD.SectionIndex == ELF::SHN_UNDEF)
935 UndefinedSymbolData.push_back(MSD);
937 LocalSymbolData.push_back(MSD);
939 ExternalSymbolData.push_back(MSD);
942 // Symbols are required to be in lexicographic order.
943 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
944 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
945 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
947 // Set the symbol indices. Local symbols must come before all other
948 // symbols with non-local bindings.
950 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
951 LocalSymbolData[i].SymbolData->setIndex(Index++);
952 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
953 ExternalSymbolData[i].SymbolData->setIndex(Index++);
954 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
955 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
958 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
959 const MCSectionData &SD) {
960 if (!Relocations[&SD].empty()) {
961 MCContext &Ctx = Asm.getContext();
962 const MCSection *RelaSection;
963 const MCSectionELF &Section =
964 static_cast<const MCSectionELF&>(SD.getSection());
966 const StringRef SectionName = Section.getSectionName();
967 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
968 RelaSectionName += SectionName;
971 if (HasRelocationAddend)
972 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
974 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
976 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
977 ELF::SHT_RELA : ELF::SHT_REL, 0,
978 SectionKind::getReadOnly(),
981 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
982 RelaSD.setAlignment(Is64Bit ? 8 : 4);
984 MCDataFragment *F = new MCDataFragment(&RelaSD);
986 WriteRelocationsFragment(Asm, F, &SD);
988 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
992 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
993 uint64_t Flags, uint64_t Address,
994 uint64_t Offset, uint64_t Size,
995 uint32_t Link, uint32_t Info,
997 uint64_t EntrySize) {
998 Write32(Name); // sh_name: index into string table
999 Write32(Type); // sh_type
1000 WriteWord(Flags); // sh_flags
1001 WriteWord(Address); // sh_addr
1002 WriteWord(Offset); // sh_offset
1003 WriteWord(Size); // sh_size
1004 Write32(Link); // sh_link
1005 Write32(Info); // sh_info
1006 WriteWord(Alignment); // sh_addralign
1007 WriteWord(EntrySize); // sh_entsize
1010 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1012 const MCSectionData *SD) {
1013 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1014 // sort by the r_offset just like gnu as does
1015 array_pod_sort(Relocs.begin(), Relocs.end());
1017 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1018 ELFRelocationEntry entry = Relocs[e - i - 1];
1020 if (entry.Index < 0)
1021 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1023 entry.Index += LocalSymbolData.size() + 1;
1027 String64(buf, entry.r_offset);
1028 F->getContents() += StringRef(buf, 8);
1030 struct ELF::Elf64_Rela ERE64;
1031 ERE64.setSymbolAndType(entry.Index, entry.Type);
1032 String64(buf, ERE64.r_info);
1033 F->getContents() += StringRef(buf, 8);
1035 if (HasRelocationAddend) {
1036 String64(buf, entry.r_addend);
1037 F->getContents() += StringRef(buf, 8);
1042 String32(buf, entry.r_offset);
1043 F->getContents() += StringRef(buf, 4);
1045 struct ELF::Elf32_Rela ERE32;
1046 ERE32.setSymbolAndType(entry.Index, entry.Type);
1047 String32(buf, ERE32.r_info);
1048 F->getContents() += StringRef(buf, 4);
1050 if (HasRelocationAddend) {
1051 String32(buf, entry.r_addend);
1052 F->getContents() += StringRef(buf, 4);
1058 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1059 MCAsmLayout &Layout) {
1060 MCContext &Ctx = Asm.getContext();
1063 const MCSection *SymtabSection;
1064 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1066 unsigned NumRegularSections = Asm.size();
1068 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1069 const MCSection *ShstrtabSection;
1070 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1071 SectionKind::getReadOnly(), false);
1072 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1073 ShstrtabSD.setAlignment(1);
1074 ShstrtabIndex = Asm.size();
1076 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1077 SectionKind::getReadOnly(),
1079 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1080 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1082 const MCSection *StrtabSection;
1083 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1084 SectionKind::getReadOnly(), false);
1085 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1086 StrtabSD.setAlignment(1);
1087 StringTableIndex = Asm.size();
1089 WriteRelocations(Asm, Layout);
1092 F = new MCDataFragment(&SymtabSD);
1093 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1094 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1096 F = new MCDataFragment(&StrtabSD);
1097 F->getContents().append(StringTable.begin(), StringTable.end());
1098 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1100 F = new MCDataFragment(&ShstrtabSD);
1102 // Section header string table.
1104 // The first entry of a string table holds a null character so skip
1107 F->getContents() += '\x00';
1109 for (MCAssembler::const_iterator it = Asm.begin(),
1110 ie = Asm.end(); it != ie; ++it) {
1111 const MCSectionELF &Section =
1112 static_cast<const MCSectionELF&>(it->getSection());
1113 // FIXME: We could merge suffixes like in .text and .rela.text.
1115 // Remember the index into the string table so we can write it
1116 // into the sh_name field of the section header table.
1117 SectionStringTableIndex[&it->getSection()] = Index;
1119 Index += Section.getSectionName().size() + 1;
1120 F->getContents() += Section.getSectionName();
1121 F->getContents() += '\x00';
1124 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1127 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1128 const MCValue Target,
1130 const MCFragment *DF) const {
1131 // If this is a PCrel relocation, find the section this fixup value is
1133 const MCSection *BaseSection = 0;
1135 BaseSection = &DF->getParent()->getSection();
1136 assert(BaseSection);
1139 const MCSection *SectionA = 0;
1140 const MCSymbol *SymbolA = 0;
1141 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1142 SymbolA = &A->getSymbol();
1143 SectionA = &SymbolA->getSection();
1146 const MCSection *SectionB = 0;
1147 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1148 SectionB = &B->getSymbol().getSection();
1152 return SectionA == SectionB;
1154 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1155 if (DataA.isExternal())
1158 return !SectionB && BaseSection == SectionA;
1161 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1162 const MCAsmLayout &Layout) {
1163 // Compute symbol table information.
1164 ComputeSymbolTable(Asm);
1166 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1167 const_cast<MCAsmLayout&>(Layout));
1169 // Add 1 for the null section.
1170 unsigned NumSections = Asm.size() + 1;
1171 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1172 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1173 uint64_t FileOff = HeaderSize;
1175 for (MCAssembler::const_iterator it = Asm.begin(),
1176 ie = Asm.end(); it != ie; ++it) {
1177 const MCSectionData &SD = *it;
1179 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1181 // Get the size of the section in the output file (including padding).
1182 uint64_t Size = Layout.getSectionFileSize(&SD);
1187 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1189 // Write out the ELF header ...
1190 WriteHeader(FileOff - HeaderSize, NumSections);
1192 FileOff = HeaderSize;
1194 // ... then all of the sections ...
1195 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1197 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1200 for (MCAssembler::const_iterator it = Asm.begin(),
1201 ie = Asm.end(); it != ie; ++it) {
1202 const MCSectionData &SD = *it;
1204 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1205 WriteZeros(Padding);
1208 // Remember the offset into the file for this section.
1209 SectionOffsetMap[&it->getSection()] = FileOff;
1210 SectionIndexMap[&it->getSection()] = Index++;
1212 FileOff += Layout.getSectionFileSize(&SD);
1214 Asm.WriteSectionData(it, Layout, Writer);
1217 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1218 WriteZeros(Padding);
1221 // ... and then the section header table.
1222 // Should we align the section header table?
1224 // Null section first.
1225 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1227 for (MCAssembler::const_iterator it = Asm.begin(),
1228 ie = Asm.end(); it != ie; ++it) {
1229 const MCSectionData &SD = *it;
1230 const MCSectionELF &Section =
1231 static_cast<const MCSectionELF&>(SD.getSection());
1233 uint64_t sh_link = 0;
1234 uint64_t sh_info = 0;
1236 switch(Section.getType()) {
1237 case ELF::SHT_DYNAMIC:
1238 sh_link = SectionStringTableIndex[&it->getSection()];
1243 case ELF::SHT_RELA: {
1244 const MCSection *SymtabSection;
1245 const MCSection *InfoSection;
1247 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1248 SectionKind::getReadOnly(),
1250 sh_link = SectionIndexMap[SymtabSection];
1252 // Remove ".rel" and ".rela" prefixes.
1253 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1254 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1256 InfoSection = Asm.getContext().getELFSection(SectionName,
1257 ELF::SHT_PROGBITS, 0,
1258 SectionKind::getReadOnly(),
1260 sh_info = SectionIndexMap[InfoSection];
1264 case ELF::SHT_SYMTAB:
1265 case ELF::SHT_DYNSYM:
1266 sh_link = StringTableIndex;
1267 sh_info = LastLocalSymbolIndex;
1270 case ELF::SHT_PROGBITS:
1271 case ELF::SHT_STRTAB:
1272 case ELF::SHT_NOBITS:
1274 case ELF::SHT_ARM_ATTRIBUTES:
1279 assert(0 && "FIXME: sh_type value not supported!");
1283 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1284 Section.getType(), Section.getFlags(),
1286 SectionOffsetMap.lookup(&SD.getSection()),
1287 Layout.getSectionSize(&SD), sh_link,
1288 sh_info, SD.getAlignment(),
1289 Section.getEntrySize());
1293 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1295 Triple::OSType OSType,
1297 bool IsLittleEndian,
1298 bool HasRelocationAddend)
1299 : MCObjectWriter(OS, IsLittleEndian)
1301 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1302 HasRelocationAddend, OSType);
1305 ELFObjectWriter::~ELFObjectWriter() {
1306 delete (ELFObjectWriterImpl*) Impl;
1309 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1310 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1313 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1314 const MCAsmLayout &Layout,
1315 const MCFragment *Fragment,
1316 const MCFixup &Fixup, MCValue Target,
1317 uint64_t &FixedValue) {
1318 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1319 Target, FixedValue);
1322 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1323 const MCValue Target,
1325 const MCFragment *DF) const {
1326 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1330 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1331 const MCAsmLayout &Layout) {
1332 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);