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(unsigned Type) {
85 case ELF::R_X86_64_GOT32:
86 case ELF::R_X86_64_PLT32:
87 case ELF::R_X86_64_GOTPCREL:
94 class ELFObjectWriterImpl {
95 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
96 return Kind == X86::reloc_riprel_4byte ||
97 Kind == X86::reloc_riprel_4byte_movq_load;
101 /// ELFSymbolData - Helper struct for containing some precomputed information
103 struct ELFSymbolData {
104 MCSymbolData *SymbolData;
105 uint64_t StringIndex;
106 uint32_t SectionIndex;
108 // Support lexicographic sorting.
109 bool operator<(const ELFSymbolData &RHS) const {
110 if (GetType(*SymbolData) == ELF::STT_FILE)
112 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
114 return SymbolData->getSymbol().getName() <
115 RHS.SymbolData->getSymbol().getName();
119 /// @name Relocation Data
122 struct ELFRelocationEntry {
123 // Make these big enough for both 32-bit and 64-bit
127 const MCSymbol *Symbol;
130 // Support lexicographic sorting.
131 bool operator<(const ELFRelocationEntry &RE) const {
132 return RE.r_offset < r_offset;
136 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
137 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
139 llvm::DenseMap<const MCSectionData*,
140 std::vector<ELFRelocationEntry> > Relocations;
141 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
144 /// @name Symbol Table Data
147 SmallString<256> StringTable;
148 std::vector<ELFSymbolData> LocalSymbolData;
149 std::vector<ELFSymbolData> ExternalSymbolData;
150 std::vector<ELFSymbolData> UndefinedSymbolData;
154 int NumRegularSections;
158 ELFObjectWriter *Writer;
162 unsigned Is64Bit : 1;
164 bool HasRelocationAddend;
166 Triple::OSType OSType;
170 // This holds the symbol table index of the last local symbol.
171 unsigned LastLocalSymbolIndex;
172 // This holds the .strtab section index.
173 unsigned StringTableIndex;
175 unsigned ShstrtabIndex;
178 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
179 uint16_t _EMachine, bool _HasRelAddend,
180 Triple::OSType _OSType)
181 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
182 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
183 OSType(_OSType), EMachine(_EMachine) {
186 void Write8(uint8_t Value) { Writer->Write8(Value); }
187 void Write16(uint16_t Value) { Writer->Write16(Value); }
188 void Write32(uint32_t Value) { Writer->Write32(Value); }
189 //void Write64(uint64_t Value) { Writer->Write64(Value); }
190 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
191 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
192 // Writer->WriteBytes(Str, ZeroFillSize);
195 void WriteWord(uint64_t W) {
202 void String8(char *buf, uint8_t Value) {
206 void StringLE16(char *buf, uint16_t Value) {
207 buf[0] = char(Value >> 0);
208 buf[1] = char(Value >> 8);
211 void StringLE32(char *buf, uint32_t Value) {
212 StringLE16(buf, uint16_t(Value >> 0));
213 StringLE16(buf + 2, uint16_t(Value >> 16));
216 void StringLE64(char *buf, uint64_t Value) {
217 StringLE32(buf, uint32_t(Value >> 0));
218 StringLE32(buf + 4, uint32_t(Value >> 32));
221 void StringBE16(char *buf ,uint16_t Value) {
222 buf[0] = char(Value >> 8);
223 buf[1] = char(Value >> 0);
226 void StringBE32(char *buf, uint32_t Value) {
227 StringBE16(buf, uint16_t(Value >> 16));
228 StringBE16(buf + 2, uint16_t(Value >> 0));
231 void StringBE64(char *buf, uint64_t Value) {
232 StringBE32(buf, uint32_t(Value >> 32));
233 StringBE32(buf + 4, uint32_t(Value >> 0));
236 void String16(char *buf, uint16_t Value) {
237 if (Writer->isLittleEndian())
238 StringLE16(buf, Value);
240 StringBE16(buf, Value);
243 void String32(char *buf, uint32_t Value) {
244 if (Writer->isLittleEndian())
245 StringLE32(buf, Value);
247 StringBE32(buf, Value);
250 void String64(char *buf, uint64_t Value) {
251 if (Writer->isLittleEndian())
252 StringLE64(buf, Value);
254 StringBE64(buf, Value);
257 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
259 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
260 uint64_t value, uint64_t size,
261 uint8_t other, uint16_t shndx);
263 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
264 const MCAsmLayout &Layout);
266 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
267 const MCAsmLayout &Layout,
268 unsigned NumRegularSections);
270 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
271 const MCFragment *Fragment, const MCFixup &Fixup,
272 MCValue Target, uint64_t &FixedValue);
274 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
277 /// ComputeSymbolTable - Compute the symbol table data
279 /// \param StringTable [out] - The string table data.
280 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
282 void ComputeSymbolTable(MCAssembler &Asm);
284 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
285 const MCSectionData &SD);
287 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
288 for (MCAssembler::const_iterator it = Asm.begin(),
289 ie = Asm.end(); it != ie; ++it) {
290 WriteRelocation(Asm, Layout, *it);
294 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
296 void ExecutePostLayoutBinding(MCAssembler &Asm);
298 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
299 uint64_t Address, uint64_t Offset,
300 uint64_t Size, uint32_t Link, uint32_t Info,
301 uint64_t Alignment, uint64_t EntrySize);
303 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
304 const MCSectionData *SD);
306 bool IsFixupFullyResolved(const MCAssembler &Asm,
307 const MCValue Target,
309 const MCFragment *DF) const;
311 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
316 // Emit the ELF header.
317 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
318 unsigned NumberOfSections) {
324 // emitWord method behaves differently for ELF32 and ELF64, writing
325 // 4 bytes in the former and 8 in the latter.
327 Write8(0x7f); // e_ident[EI_MAG0]
328 Write8('E'); // e_ident[EI_MAG1]
329 Write8('L'); // e_ident[EI_MAG2]
330 Write8('F'); // e_ident[EI_MAG3]
332 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
335 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
337 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
340 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
341 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
342 default: Write8(ELF::ELFOSABI_NONE); break;
344 Write8(0); // e_ident[EI_ABIVERSION]
346 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
348 Write16(ELF::ET_REL); // e_type
350 Write16(EMachine); // e_machine = target
352 Write32(ELF::EV_CURRENT); // e_version
353 WriteWord(0); // e_entry, no entry point in .o file
354 WriteWord(0); // e_phoff, no program header for .o
355 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
356 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
358 // FIXME: Make this configurable.
359 Write32(0); // e_flags = whatever the target wants
361 // e_ehsize = ELF header size
362 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
364 Write16(0); // e_phentsize = prog header entry size
365 Write16(0); // e_phnum = # prog header entries = 0
367 // e_shentsize = Section header entry size
368 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
370 // e_shnum = # of section header ents
371 Write16(NumberOfSections);
373 // e_shstrndx = Section # of '.shstrtab'
374 Write16(ShstrtabIndex);
377 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
378 uint8_t info, uint64_t value,
379 uint64_t size, uint8_t other,
385 F->getContents() += StringRef(buf, 4); // st_name
388 F->getContents() += StringRef(buf, 1); // st_info
391 F->getContents() += StringRef(buf, 1); // st_other
393 String16(buf, shndx);
394 F->getContents() += StringRef(buf, 2); // st_shndx
396 String64(buf, value);
397 F->getContents() += StringRef(buf, 8); // st_value
400 F->getContents() += StringRef(buf, 8); // st_size
405 F->getContents() += StringRef(buf, 4); // st_name
407 String32(buf, value);
408 F->getContents() += StringRef(buf, 4); // st_value
411 F->getContents() += StringRef(buf, 4); // st_size
414 F->getContents() += StringRef(buf, 1); // st_info
417 F->getContents() += StringRef(buf, 1); // st_other
419 String16(buf, shndx);
420 F->getContents() += StringRef(buf, 2); // st_shndx
424 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
425 if (Data.isCommon() && Data.isExternal())
426 return Data.getCommonAlignment();
428 const MCSymbol &Symbol = Data.getSymbol();
429 if (!Symbol.isInSection())
432 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
433 if (MCFragment *FF = Data.getFragment())
434 return Layout.getSymbolAddress(&Data) -
435 Layout.getSectionAddress(FF->getParent());
440 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
441 const MCSymbol *S = &Symbol;
442 while (S->isVariable()) {
443 const MCExpr *Value = S->getVariableValue();
444 if (Value->getKind() != MCExpr::SymbolRef)
446 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
447 S = &Ref->getSymbol();
452 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
453 // The presence of symbol versions causes undefined symbols and
454 // versions declared with @@@ to be renamed.
456 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
457 ie = Asm.symbol_end(); it != ie; ++it) {
458 const MCSymbol &Alias = it->getSymbol();
459 if (!Alias.isVariable())
461 const MCSymbol &Symbol = AliasedSymbol(Alias);
462 StringRef AliasName = Alias.getName();
463 size_t Pos = AliasName.find('@');
464 if (Pos == StringRef::npos)
467 StringRef Rest = AliasName.substr(Pos);
468 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
471 // FIXME: produce a better error message.
472 if (Symbol.isUndefined() && Rest.startswith("@@") &&
473 !Rest.startswith("@@@"))
474 report_fatal_error("A @@ version cannot be undefined");
476 Renames.insert(std::make_pair(&Symbol, &Alias));
480 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
481 const MCAsmLayout &Layout) {
482 MCSymbolData &OrigData = *MSD.SymbolData;
484 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
486 uint8_t Binding = GetBinding(OrigData);
487 uint8_t Visibility = GetVisibility(OrigData);
488 uint8_t Type = GetType(Data);
490 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
491 uint8_t Other = Visibility;
493 uint64_t Value = SymbolValue(Data, Layout);
497 assert(!(Data.isCommon() && !Data.isExternal()));
499 ESize = Data.getSize();
500 if (Data.getSize()) {
502 if (ESize->getKind() == MCExpr::Binary) {
503 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
505 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
506 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
507 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
508 Size = Res.getConstant();
510 } else if (ESize->getKind() == MCExpr::Constant) {
511 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
513 assert(0 && "Unsupported size expression");
517 // Write out the symbol table entry
518 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
519 Size, Other, MSD.SectionIndex);
522 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
523 const MCAssembler &Asm,
524 const MCAsmLayout &Layout,
525 unsigned NumRegularSections) {
526 // The string table must be emitted first because we need the index
527 // into the string table for all the symbol names.
528 assert(StringTable.size() && "Missing string table");
530 // FIXME: Make sure the start of the symbol table is aligned.
532 // The first entry is the undefined symbol entry.
533 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
534 F->getContents().append(EntrySize, '\x00');
536 // Write the symbol table entries.
537 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
538 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
539 ELFSymbolData &MSD = LocalSymbolData[i];
540 WriteSymbol(F, MSD, Layout);
543 // Write out a symbol table entry for each regular section.
545 for (MCAssembler::const_iterator it = Asm.begin();
546 Index <= NumRegularSections; ++it, ++Index) {
547 const MCSectionELF &Section =
548 static_cast<const MCSectionELF&>(it->getSection());
549 // Leave out relocations so we don't have indexes within
550 // the relocations messed up
551 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
553 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
554 LastLocalSymbolIndex++;
557 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
558 ELFSymbolData &MSD = ExternalSymbolData[i];
559 MCSymbolData &Data = *MSD.SymbolData;
560 assert(((Data.getFlags() & ELF_STB_Global) ||
561 (Data.getFlags() & ELF_STB_Weak)) &&
562 "External symbol requires STB_GLOBAL or STB_WEAK flag");
563 WriteSymbol(F, MSD, Layout);
564 if (GetBinding(Data) == ELF::STB_LOCAL)
565 LastLocalSymbolIndex++;
568 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
569 ELFSymbolData &MSD = UndefinedSymbolData[i];
570 MCSymbolData &Data = *MSD.SymbolData;
571 WriteSymbol(F, MSD, Layout);
572 if (GetBinding(Data) == ELF::STB_LOCAL)
573 LastLocalSymbolIndex++;
577 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
578 const MCValue &Target,
579 const MCFragment &F) {
580 const MCSymbol &Symbol = SD.getSymbol();
581 if (Symbol.isUndefined())
584 const MCSectionELF &Section =
585 static_cast<const MCSectionELF&>(Symbol.getSection());
590 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
591 const MCSectionELF &Sec2 =
592 static_cast<const MCSectionELF&>(F.getParent()->getSection());
594 if (Section.getKind().isBSS())
597 if (&Sec2 != &Section &&
598 (Kind == MCSymbolRefExpr::VK_PLT ||
599 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
600 Kind == MCSymbolRefExpr::VK_GOTOFF))
603 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
604 return Target.getConstant() != 0;
609 // FIXME: this is currently X86/X86_64 only
610 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
611 const MCAsmLayout &Layout,
612 const MCFragment *Fragment,
613 const MCFixup &Fixup,
615 uint64_t &FixedValue) {
618 int64_t Value = Target.getConstant();
619 const MCSymbol *Symbol = 0;
621 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
622 if (!Target.isAbsolute()) {
623 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
624 const MCSymbol *Renamed = Renames.lookup(Symbol);
627 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
628 MCFragment *F = SD.getFragment();
630 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
631 const MCSymbol &SymbolB = RefB->getSymbol();
632 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
634 MCSectionData *Sec = Fragment->getParent();
636 // Offset of the symbol in the section
637 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
639 // Ofeset of the relocation in the section
640 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
644 // Check that this case has already been fully resolved before we get
646 if (Symbol->isDefined() && !SD.isExternal() &&
648 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
649 llvm_unreachable("We don't need a relocation in this case.");
653 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
654 if (!RelocOnSymbol) {
655 Index = F->getParent()->getOrdinal();
657 MCSectionData *FSD = F->getParent();
658 // Offset of the symbol in the section
659 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
661 UsedInReloc.insert(Symbol);
665 // Compensate for the addend on i386.
672 // determine the type of the relocation
674 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
680 llvm_unreachable("Unimplemented");
681 case MCSymbolRefExpr::VK_None:
682 Type = ELF::R_X86_64_PC32;
684 case MCSymbolRefExpr::VK_PLT:
685 Type = ELF::R_X86_64_PLT32;
687 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
688 Type = ELF::R_X86_64_GOTPCREL;
692 switch ((unsigned)Fixup.getKind()) {
693 default: llvm_unreachable("invalid fixup kind!");
694 case FK_Data_8: Type = ELF::R_X86_64_64; break;
695 case X86::reloc_signed_4byte:
696 case X86::reloc_pcrel_4byte:
697 assert(isInt<32>(Target.getConstant()));
700 llvm_unreachable("Unimplemented");
701 case MCSymbolRefExpr::VK_None:
702 Type = ELF::R_X86_64_32S;
704 case MCSymbolRefExpr::VK_GOT:
705 Type = ELF::R_X86_64_GOT32;
707 case MCSymbolRefExpr::VK_GOTPCREL:
708 Type = ELF::R_X86_64_GOTPCREL;
713 Type = ELF::R_X86_64_32;
715 case FK_Data_2: Type = ELF::R_X86_64_16; break;
716 case X86::reloc_pcrel_1byte:
717 case FK_Data_1: Type = ELF::R_X86_64_8; break;
724 llvm_unreachable("Unimplemented");
725 case MCSymbolRefExpr::VK_None:
726 Type = ELF::R_386_PC32;
728 case MCSymbolRefExpr::VK_PLT:
729 Type = ELF::R_386_PLT32;
733 switch ((unsigned)Fixup.getKind()) {
734 default: llvm_unreachable("invalid fixup kind!");
736 case X86::reloc_global_offset_table:
737 Type = ELF::R_386_GOTPC;
740 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
742 case X86::reloc_signed_4byte:
743 case X86::reloc_pcrel_4byte:
747 llvm_unreachable("Unimplemented");
748 case MCSymbolRefExpr::VK_None:
749 Type = ELF::R_386_32;
751 case MCSymbolRefExpr::VK_GOT:
752 Type = ELF::R_386_GOT32;
754 case MCSymbolRefExpr::VK_GOTOFF:
755 Type = ELF::R_386_GOTOFF;
759 case FK_Data_2: Type = ELF::R_386_16; break;
760 case X86::reloc_pcrel_1byte:
761 case FK_Data_1: Type = ELF::R_386_8; break;
766 if (RelocNeedsGOT(Type))
769 ELFRelocationEntry ERE;
775 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
777 if (HasRelocationAddend)
778 ERE.r_addend = Addend;
780 ERE.r_addend = 0; // Silence compiler warning.
782 Relocations[Fragment->getParent()].push_back(ERE);
786 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
788 MCSymbolData &SD = Asm.getSymbolData(*S);
791 if (!SD.isExternal() && !S->isUndefined())
792 return SD.getIndex() + /* empty symbol */ 1;
794 // External or undefined symbol.
795 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
798 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
799 bool Used, bool Renamed) {
806 const MCSymbol &Symbol = Data.getSymbol();
808 const MCSymbol &A = AliasedSymbol(Symbol);
809 if (&A != &Symbol && A.isUndefined())
812 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
815 if (Symbol.isTemporary())
821 static bool isLocal(const MCSymbolData &Data) {
822 if (Data.isExternal())
825 const MCSymbol &Symbol = Data.getSymbol();
826 if (Symbol.isUndefined() && !Symbol.isVariable())
832 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
833 // FIXME: Is this the correct place to do this?
835 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
836 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
837 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
838 Data.setExternal(true);
841 // Build section lookup table.
842 NumRegularSections = Asm.size();
843 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
845 for (MCAssembler::iterator it = Asm.begin(),
846 ie = Asm.end(); it != ie; ++it, ++Index)
847 SectionIndexMap[&it->getSection()] = Index;
849 // Index 0 is always the empty string.
850 StringMap<uint64_t> StringIndexMap;
851 StringTable += '\x00';
853 // Add the data for the symbols.
854 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
855 ie = Asm.symbol_end(); it != ie; ++it) {
856 const MCSymbol &Symbol = it->getSymbol();
858 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol),
859 Renames.count(&Symbol)))
864 bool Local = isLocal(*it);
865 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
867 if (it->isCommon()) {
869 MSD.SectionIndex = ELF::SHN_COMMON;
870 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
871 MSD.SectionIndex = ELF::SHN_ABS;
872 } else if (RefSymbol.isUndefined()) {
873 MSD.SectionIndex = ELF::SHN_UNDEF;
874 // FIXME: Undefined symbols are global, but this is the first place we
875 // are able to set it.
876 if (GetBinding(*it) == ELF::STB_LOCAL)
877 SetBinding(*it, ELF::STB_GLOBAL);
879 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
880 assert(MSD.SectionIndex && "Invalid section index!");
883 // The @@@ in symbol version is replaced with @ in undefined symbols and
884 // @@ in defined ones.
885 StringRef Name = Symbol.getName();
886 size_t Pos = Name.find("@@@");
887 std::string FinalName;
888 if (Pos != StringRef::npos) {
889 StringRef Prefix = Name.substr(0, Pos);
890 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
891 StringRef Suffix = Name.substr(Pos + n);
892 FinalName = Prefix.str() + Suffix.str();
894 FinalName = Name.str();
897 uint64_t &Entry = StringIndexMap[FinalName];
899 Entry = StringTable.size();
900 StringTable += FinalName;
901 StringTable += '\x00';
903 MSD.StringIndex = Entry;
904 if (MSD.SectionIndex == ELF::SHN_UNDEF)
905 UndefinedSymbolData.push_back(MSD);
907 LocalSymbolData.push_back(MSD);
909 ExternalSymbolData.push_back(MSD);
912 // Symbols are required to be in lexicographic order.
913 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
914 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
915 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
917 // Set the symbol indices. Local symbols must come before all other
918 // symbols with non-local bindings.
920 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
921 LocalSymbolData[i].SymbolData->setIndex(Index++);
922 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
923 ExternalSymbolData[i].SymbolData->setIndex(Index++);
924 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
925 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
928 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
929 const MCSectionData &SD) {
930 if (!Relocations[&SD].empty()) {
931 MCContext &Ctx = Asm.getContext();
932 const MCSection *RelaSection;
933 const MCSectionELF &Section =
934 static_cast<const MCSectionELF&>(SD.getSection());
936 const StringRef SectionName = Section.getSectionName();
937 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
938 RelaSectionName += SectionName;
941 if (HasRelocationAddend)
942 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
944 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
946 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
947 ELF::SHT_RELA : ELF::SHT_REL, 0,
948 SectionKind::getReadOnly(),
951 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
952 RelaSD.setAlignment(Is64Bit ? 8 : 4);
954 MCDataFragment *F = new MCDataFragment(&RelaSD);
956 WriteRelocationsFragment(Asm, F, &SD);
958 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
962 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
963 uint64_t Flags, uint64_t Address,
964 uint64_t Offset, uint64_t Size,
965 uint32_t Link, uint32_t Info,
967 uint64_t EntrySize) {
968 Write32(Name); // sh_name: index into string table
969 Write32(Type); // sh_type
970 WriteWord(Flags); // sh_flags
971 WriteWord(Address); // sh_addr
972 WriteWord(Offset); // sh_offset
973 WriteWord(Size); // sh_size
974 Write32(Link); // sh_link
975 Write32(Info); // sh_info
976 WriteWord(Alignment); // sh_addralign
977 WriteWord(EntrySize); // sh_entsize
980 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
982 const MCSectionData *SD) {
983 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
984 // sort by the r_offset just like gnu as does
985 array_pod_sort(Relocs.begin(), Relocs.end());
987 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
988 ELFRelocationEntry entry = Relocs[e - i - 1];
991 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
993 entry.Index += LocalSymbolData.size() + 1;
997 String64(buf, entry.r_offset);
998 F->getContents() += StringRef(buf, 8);
1000 struct ELF::Elf64_Rela ERE64;
1001 ERE64.setSymbolAndType(entry.Index, entry.Type);
1002 String64(buf, ERE64.r_info);
1003 F->getContents() += StringRef(buf, 8);
1005 if (HasRelocationAddend) {
1006 String64(buf, entry.r_addend);
1007 F->getContents() += StringRef(buf, 8);
1012 String32(buf, entry.r_offset);
1013 F->getContents() += StringRef(buf, 4);
1015 struct ELF::Elf32_Rela ERE32;
1016 ERE32.setSymbolAndType(entry.Index, entry.Type);
1017 String32(buf, ERE32.r_info);
1018 F->getContents() += StringRef(buf, 4);
1020 if (HasRelocationAddend) {
1021 String32(buf, entry.r_addend);
1022 F->getContents() += StringRef(buf, 4);
1028 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1029 MCAsmLayout &Layout) {
1030 MCContext &Ctx = Asm.getContext();
1033 const MCSection *SymtabSection;
1034 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1036 unsigned NumRegularSections = Asm.size();
1038 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1039 const MCSection *ShstrtabSection;
1040 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1041 SectionKind::getReadOnly(), false);
1042 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1043 ShstrtabSD.setAlignment(1);
1044 ShstrtabIndex = Asm.size();
1046 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1047 SectionKind::getReadOnly(),
1049 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1050 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1052 const MCSection *StrtabSection;
1053 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1054 SectionKind::getReadOnly(), false);
1055 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1056 StrtabSD.setAlignment(1);
1057 StringTableIndex = Asm.size();
1059 WriteRelocations(Asm, Layout);
1062 F = new MCDataFragment(&SymtabSD);
1063 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1064 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1066 F = new MCDataFragment(&StrtabSD);
1067 F->getContents().append(StringTable.begin(), StringTable.end());
1068 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1070 F = new MCDataFragment(&ShstrtabSD);
1072 // Section header string table.
1074 // The first entry of a string table holds a null character so skip
1077 F->getContents() += '\x00';
1079 for (MCAssembler::const_iterator it = Asm.begin(),
1080 ie = Asm.end(); it != ie; ++it) {
1081 const MCSectionELF &Section =
1082 static_cast<const MCSectionELF&>(it->getSection());
1083 // FIXME: We could merge suffixes like in .text and .rela.text.
1085 // Remember the index into the string table so we can write it
1086 // into the sh_name field of the section header table.
1087 SectionStringTableIndex[&it->getSection()] = Index;
1089 Index += Section.getSectionName().size() + 1;
1090 F->getContents() += Section.getSectionName();
1091 F->getContents() += '\x00';
1094 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1097 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1098 const MCValue Target,
1100 const MCFragment *DF) const {
1101 // If this is a PCrel relocation, find the section this fixup value is
1103 const MCSection *BaseSection = 0;
1105 BaseSection = &DF->getParent()->getSection();
1106 assert(BaseSection);
1109 const MCSection *SectionA = 0;
1110 const MCSymbol *SymbolA = 0;
1111 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1112 SymbolA = &A->getSymbol();
1113 SectionA = &SymbolA->getSection();
1116 const MCSection *SectionB = 0;
1117 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1118 SectionB = &B->getSymbol().getSection();
1122 return SectionA == SectionB;
1124 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1125 if (DataA.isExternal())
1128 return !SectionB && BaseSection == SectionA;
1131 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1132 const MCAsmLayout &Layout) {
1133 // Compute symbol table information.
1134 ComputeSymbolTable(Asm);
1136 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1137 const_cast<MCAsmLayout&>(Layout));
1139 // Add 1 for the null section.
1140 unsigned NumSections = Asm.size() + 1;
1141 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1142 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1143 uint64_t FileOff = HeaderSize;
1145 for (MCAssembler::const_iterator it = Asm.begin(),
1146 ie = Asm.end(); it != ie; ++it) {
1147 const MCSectionData &SD = *it;
1149 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1151 // Get the size of the section in the output file (including padding).
1152 uint64_t Size = Layout.getSectionFileSize(&SD);
1157 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1159 // Write out the ELF header ...
1160 WriteHeader(FileOff - HeaderSize, NumSections);
1162 FileOff = HeaderSize;
1164 // ... then all of the sections ...
1165 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1167 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1170 for (MCAssembler::const_iterator it = Asm.begin(),
1171 ie = Asm.end(); it != ie; ++it) {
1172 const MCSectionData &SD = *it;
1174 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1175 WriteZeros(Padding);
1178 // Remember the offset into the file for this section.
1179 SectionOffsetMap[&it->getSection()] = FileOff;
1180 SectionIndexMap[&it->getSection()] = Index++;
1182 FileOff += Layout.getSectionFileSize(&SD);
1184 Asm.WriteSectionData(it, Layout, Writer);
1187 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1188 WriteZeros(Padding);
1191 // ... and then the section header table.
1192 // Should we align the section header table?
1194 // Null section first.
1195 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1197 for (MCAssembler::const_iterator it = Asm.begin(),
1198 ie = Asm.end(); it != ie; ++it) {
1199 const MCSectionData &SD = *it;
1200 const MCSectionELF &Section =
1201 static_cast<const MCSectionELF&>(SD.getSection());
1203 uint64_t sh_link = 0;
1204 uint64_t sh_info = 0;
1206 switch(Section.getType()) {
1207 case ELF::SHT_DYNAMIC:
1208 sh_link = SectionStringTableIndex[&it->getSection()];
1213 case ELF::SHT_RELA: {
1214 const MCSection *SymtabSection;
1215 const MCSection *InfoSection;
1217 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1218 SectionKind::getReadOnly(),
1220 sh_link = SectionIndexMap[SymtabSection];
1222 // Remove ".rel" and ".rela" prefixes.
1223 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1224 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1226 InfoSection = Asm.getContext().getELFSection(SectionName,
1227 ELF::SHT_PROGBITS, 0,
1228 SectionKind::getReadOnly(),
1230 sh_info = SectionIndexMap[InfoSection];
1234 case ELF::SHT_SYMTAB:
1235 case ELF::SHT_DYNSYM:
1236 sh_link = StringTableIndex;
1237 sh_info = LastLocalSymbolIndex;
1240 case ELF::SHT_PROGBITS:
1241 case ELF::SHT_STRTAB:
1242 case ELF::SHT_NOBITS:
1244 case ELF::SHT_ARM_ATTRIBUTES:
1249 assert(0 && "FIXME: sh_type value not supported!");
1253 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1254 Section.getType(), Section.getFlags(),
1256 SectionOffsetMap.lookup(&SD.getSection()),
1257 Layout.getSectionSize(&SD), sh_link,
1258 sh_info, SD.getAlignment(),
1259 Section.getEntrySize());
1263 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1265 Triple::OSType OSType,
1267 bool IsLittleEndian,
1268 bool HasRelocationAddend)
1269 : MCObjectWriter(OS, IsLittleEndian)
1271 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1272 HasRelocationAddend, OSType);
1275 ELFObjectWriter::~ELFObjectWriter() {
1276 delete (ELFObjectWriterImpl*) Impl;
1279 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1280 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1283 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1284 const MCAsmLayout &Layout,
1285 const MCFragment *Fragment,
1286 const MCFixup &Fixup, MCValue Target,
1287 uint64_t &FixedValue) {
1288 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1289 Target, FixedValue);
1292 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1293 const MCValue Target,
1295 const MCFragment *DF) const {
1296 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1300 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1301 const MCAsmLayout &Layout) {
1302 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);