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;
138 llvm::DenseMap<const MCSectionData*,
139 std::vector<ELFRelocationEntry> > Relocations;
140 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
143 /// @name Symbol Table Data
146 SmallString<256> StringTable;
147 std::vector<ELFSymbolData> LocalSymbolData;
148 std::vector<ELFSymbolData> ExternalSymbolData;
149 std::vector<ELFSymbolData> UndefinedSymbolData;
153 int NumRegularSections;
157 ELFObjectWriter *Writer;
161 unsigned Is64Bit : 1;
163 bool HasRelocationAddend;
165 Triple::OSType OSType;
167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
172 unsigned ShstrtabIndex;
175 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
176 bool _HasRelAddend, Triple::OSType _OSType)
177 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
178 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
182 void Write8(uint8_t Value) { Writer->Write8(Value); }
183 void Write16(uint16_t Value) { Writer->Write16(Value); }
184 void Write32(uint32_t Value) { Writer->Write32(Value); }
185 //void Write64(uint64_t Value) { Writer->Write64(Value); }
186 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
187 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
188 // Writer->WriteBytes(Str, ZeroFillSize);
191 void WriteWord(uint64_t W) {
198 void String8(char *buf, uint8_t Value) {
202 void StringLE16(char *buf, uint16_t Value) {
203 buf[0] = char(Value >> 0);
204 buf[1] = char(Value >> 8);
207 void StringLE32(char *buf, uint32_t Value) {
208 StringLE16(buf, uint16_t(Value >> 0));
209 StringLE16(buf + 2, uint16_t(Value >> 16));
212 void StringLE64(char *buf, uint64_t Value) {
213 StringLE32(buf, uint32_t(Value >> 0));
214 StringLE32(buf + 4, uint32_t(Value >> 32));
217 void StringBE16(char *buf ,uint16_t Value) {
218 buf[0] = char(Value >> 8);
219 buf[1] = char(Value >> 0);
222 void StringBE32(char *buf, uint32_t Value) {
223 StringBE16(buf, uint16_t(Value >> 16));
224 StringBE16(buf + 2, uint16_t(Value >> 0));
227 void StringBE64(char *buf, uint64_t Value) {
228 StringBE32(buf, uint32_t(Value >> 32));
229 StringBE32(buf + 4, uint32_t(Value >> 0));
232 void String16(char *buf, uint16_t Value) {
233 if (Writer->isLittleEndian())
234 StringLE16(buf, Value);
236 StringBE16(buf, Value);
239 void String32(char *buf, uint32_t Value) {
240 if (Writer->isLittleEndian())
241 StringLE32(buf, Value);
243 StringBE32(buf, Value);
246 void String64(char *buf, uint64_t Value) {
247 if (Writer->isLittleEndian())
248 StringLE64(buf, Value);
250 StringBE64(buf, Value);
253 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
255 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
256 uint64_t value, uint64_t size,
257 uint8_t other, uint16_t shndx);
259 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
260 const MCAsmLayout &Layout);
262 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
263 const MCAsmLayout &Layout,
264 unsigned NumRegularSections);
266 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
267 const MCFragment *Fragment, const MCFixup &Fixup,
268 MCValue Target, uint64_t &FixedValue);
270 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
273 /// ComputeSymbolTable - Compute the symbol table data
275 /// \param StringTable [out] - The string table data.
276 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
278 void ComputeSymbolTable(MCAssembler &Asm);
280 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
281 const MCSectionData &SD);
283 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
284 for (MCAssembler::const_iterator it = Asm.begin(),
285 ie = Asm.end(); it != ie; ++it) {
286 WriteRelocation(Asm, Layout, *it);
290 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
292 void ExecutePostLayoutBinding(MCAssembler &Asm) {
295 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
296 uint64_t Address, uint64_t Offset,
297 uint64_t Size, uint32_t Link, uint32_t Info,
298 uint64_t Alignment, uint64_t EntrySize);
300 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
301 const MCSectionData *SD);
303 bool IsFixupFullyResolved(const MCAssembler &Asm,
304 const MCValue Target,
306 const MCFragment *DF) const;
308 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
313 // Emit the ELF header.
314 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
315 unsigned NumberOfSections) {
321 // emitWord method behaves differently for ELF32 and ELF64, writing
322 // 4 bytes in the former and 8 in the latter.
324 Write8(0x7f); // e_ident[EI_MAG0]
325 Write8('E'); // e_ident[EI_MAG1]
326 Write8('L'); // e_ident[EI_MAG2]
327 Write8('F'); // e_ident[EI_MAG3]
329 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
332 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
334 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
337 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
338 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
339 default: Write8(ELF::ELFOSABI_NONE); break;
341 Write8(0); // e_ident[EI_ABIVERSION]
343 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
345 Write16(ELF::ET_REL); // e_type
347 // FIXME: Make this configurable
348 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
350 Write32(ELF::EV_CURRENT); // e_version
351 WriteWord(0); // e_entry, no entry point in .o file
352 WriteWord(0); // e_phoff, no program header for .o
353 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
354 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
356 // FIXME: Make this configurable.
357 Write32(0); // e_flags = whatever the target wants
359 // e_ehsize = ELF header size
360 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
362 Write16(0); // e_phentsize = prog header entry size
363 Write16(0); // e_phnum = # prog header entries = 0
365 // e_shentsize = Section header entry size
366 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
368 // e_shnum = # of section header ents
369 Write16(NumberOfSections);
371 // e_shstrndx = Section # of '.shstrtab'
372 Write16(ShstrtabIndex);
375 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
376 uint8_t info, uint64_t value,
377 uint64_t size, uint8_t other,
383 F->getContents() += StringRef(buf, 4); // st_name
386 F->getContents() += StringRef(buf, 1); // st_info
389 F->getContents() += StringRef(buf, 1); // st_other
391 String16(buf, shndx);
392 F->getContents() += StringRef(buf, 2); // st_shndx
394 String64(buf, value);
395 F->getContents() += StringRef(buf, 8); // st_value
398 F->getContents() += StringRef(buf, 8); // st_size
403 F->getContents() += StringRef(buf, 4); // st_name
405 String32(buf, value);
406 F->getContents() += StringRef(buf, 4); // st_value
409 F->getContents() += StringRef(buf, 4); // st_size
412 F->getContents() += StringRef(buf, 1); // st_info
415 F->getContents() += StringRef(buf, 1); // st_other
417 String16(buf, shndx);
418 F->getContents() += StringRef(buf, 2); // st_shndx
422 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
423 if (Data.isCommon() && Data.isExternal())
424 return Data.getCommonAlignment();
426 const MCSymbol &Symbol = Data.getSymbol();
427 if (!Symbol.isInSection())
430 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
431 if (MCFragment *FF = Data.getFragment())
432 return Layout.getSymbolAddress(&Data) -
433 Layout.getSectionAddress(FF->getParent());
438 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
439 const MCSymbol *S = &Symbol;
440 while (S->isVariable()) {
441 const MCExpr *Value = S->getVariableValue();
442 assert (Value->getKind() == MCExpr::SymbolRef && "Unimplemented");
443 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
444 S = &Ref->getSymbol();
449 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
450 const MCAsmLayout &Layout) {
451 MCSymbolData &OrigData = *MSD.SymbolData;
453 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
455 uint8_t Binding = GetBinding(OrigData);
456 uint8_t Visibility = GetVisibility(OrigData);
457 uint8_t Type = GetType(Data);
459 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
460 uint8_t Other = Visibility;
462 uint64_t Value = SymbolValue(Data, Layout);
466 assert(!(Data.isCommon() && !Data.isExternal()));
468 ESize = Data.getSize();
469 if (Data.getSize()) {
471 if (ESize->getKind() == MCExpr::Binary) {
472 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
474 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
475 uint64_t AddressA = 0;
476 uint64_t AddressB = 0;
477 const MCSymbol &SymA = Res.getSymA()->getSymbol();
478 const MCSymbol &SymB = Res.getSymB()->getSymbol();
480 if (SymA.isDefined()) {
481 MCSymbolData &A = Layout.getAssembler().getSymbolData(SymA);
482 AddressA = Layout.getSymbolAddress(&A);
485 if (SymB.isDefined()) {
486 MCSymbolData &B = Layout.getAssembler().getSymbolData(SymB);
487 AddressB = Layout.getSymbolAddress(&B);
490 Size = AddressA - AddressB;
492 } else if (ESize->getKind() == MCExpr::Constant) {
493 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
495 assert(0 && "Unsupported size expression");
499 // Write out the symbol table entry
500 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
501 Size, Other, MSD.SectionIndex);
504 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
505 const MCAssembler &Asm,
506 const MCAsmLayout &Layout,
507 unsigned NumRegularSections) {
508 // The string table must be emitted first because we need the index
509 // into the string table for all the symbol names.
510 assert(StringTable.size() && "Missing string table");
512 // FIXME: Make sure the start of the symbol table is aligned.
514 // The first entry is the undefined symbol entry.
515 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
516 F->getContents().append(EntrySize, '\x00');
518 // Write the symbol table entries.
519 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
520 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
521 ELFSymbolData &MSD = LocalSymbolData[i];
522 WriteSymbol(F, MSD, Layout);
525 // Write out a symbol table entry for each regular section.
527 for (MCAssembler::const_iterator it = Asm.begin();
528 Index <= NumRegularSections; ++it, ++Index) {
529 const MCSectionELF &Section =
530 static_cast<const MCSectionELF&>(it->getSection());
531 // Leave out relocations so we don't have indexes within
532 // the relocations messed up
533 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
535 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
536 LastLocalSymbolIndex++;
539 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
540 ELFSymbolData &MSD = ExternalSymbolData[i];
541 MCSymbolData &Data = *MSD.SymbolData;
542 assert(((Data.getFlags() & ELF_STB_Global) ||
543 (Data.getFlags() & ELF_STB_Weak)) &&
544 "External symbol requires STB_GLOBAL or STB_WEAK flag");
545 WriteSymbol(F, MSD, Layout);
546 if (GetBinding(Data) == ELF::STB_LOCAL)
547 LastLocalSymbolIndex++;
550 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
551 ELFSymbolData &MSD = UndefinedSymbolData[i];
552 MCSymbolData &Data = *MSD.SymbolData;
553 WriteSymbol(F, MSD, Layout);
554 if (GetBinding(Data) == ELF::STB_LOCAL)
555 LastLocalSymbolIndex++;
559 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
560 const MCValue &Target,
561 const MCFragment &F) {
562 const MCSymbol &Symbol = SD.getSymbol();
563 if (Symbol.isUndefined())
566 const MCSectionELF &Section =
567 static_cast<const MCSectionELF&>(Symbol.getSection());
572 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
573 return Target.getConstant() != 0;
575 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
576 const MCSectionELF &Sec2 =
577 static_cast<const MCSectionELF&>(F.getParent()->getSection());
579 if (&Sec2 != &Section &&
580 (Kind == MCSymbolRefExpr::VK_PLT || Kind == MCSymbolRefExpr::VK_GOTPCREL))
586 // FIXME: this is currently X86/X86_64 only
587 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
588 const MCAsmLayout &Layout,
589 const MCFragment *Fragment,
590 const MCFixup &Fixup,
592 uint64_t &FixedValue) {
595 int64_t Value = Target.getConstant();
596 const MCSymbol *Symbol = 0;
598 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
599 if (!Target.isAbsolute()) {
600 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
601 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
602 MCFragment *F = SD.getFragment();
604 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
605 const MCSymbol &SymbolB = RefB->getSymbol();
606 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
608 MCSectionData *Sec = Fragment->getParent();
610 // Offset of the symbol in the section
611 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
613 // Ofeset of the relocation in the section
614 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
618 // Check that this case has already been fully resolved before we get
620 if (Symbol->isDefined() && !SD.isExternal() &&
622 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
623 llvm_unreachable("We don't need a relocation in this case.");
627 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
628 if (!RelocOnSymbol) {
629 Index = F->getParent()->getOrdinal();
631 MCSectionData *FSD = F->getParent();
632 // Offset of the symbol in the section
633 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
635 UsedInReloc.insert(Symbol);
639 // Compensate for the addend on i386.
646 // determine the type of the relocation
648 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
653 case MCSymbolRefExpr::VK_None:
654 Type = ELF::R_X86_64_PC32;
656 case MCSymbolRefExpr::VK_PLT:
657 Type = ELF::R_X86_64_PLT32;
659 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
660 Type = ELF::R_X86_64_GOTPCREL;
663 llvm_unreachable("Unimplemented");
666 switch ((unsigned)Fixup.getKind()) {
667 default: llvm_unreachable("invalid fixup kind!");
668 case FK_Data_8: Type = ELF::R_X86_64_64; break;
669 case X86::reloc_signed_4byte:
670 case X86::reloc_pcrel_4byte:
671 assert(isInt<32>(Target.getConstant()));
673 case MCSymbolRefExpr::VK_None:
674 Type = ELF::R_X86_64_32S;
676 case MCSymbolRefExpr::VK_GOT:
677 Type = ELF::R_X86_64_GOT32;
679 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
680 Type = ELF::R_X86_64_GOTPCREL;
683 llvm_unreachable("Unimplemented");
687 Type = ELF::R_X86_64_32;
689 case FK_Data_2: Type = ELF::R_X86_64_16; break;
690 case X86::reloc_pcrel_1byte:
691 case FK_Data_1: Type = ELF::R_X86_64_8; break;
696 Type = ELF::R_386_PC32;
698 switch ((unsigned)Fixup.getKind()) {
699 default: llvm_unreachable("invalid fixup kind!");
701 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
703 case X86::reloc_signed_4byte:
704 case X86::reloc_pcrel_4byte:
705 case FK_Data_4: Type = ELF::R_386_32; break;
706 case FK_Data_2: Type = ELF::R_386_16; break;
707 case X86::reloc_pcrel_1byte:
708 case FK_Data_1: Type = ELF::R_386_8; break;
713 if (RelocNeedsGOT(Type))
716 ELFRelocationEntry ERE;
722 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
724 if (HasRelocationAddend)
725 ERE.r_addend = Addend;
727 ERE.r_addend = 0; // Silence compiler warning.
729 Relocations[Fragment->getParent()].push_back(ERE);
733 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
735 MCSymbolData &SD = Asm.getSymbolData(*S);
738 if (!SD.isExternal() && !S->isUndefined())
739 return SD.getIndex() + /* empty symbol */ 1;
741 // External or undefined symbol.
742 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
745 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
747 const MCSymbol &Symbol = Data.getSymbol();
748 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
751 if (!Used && Symbol.isTemporary())
757 static bool isLocal(const MCSymbolData &Data) {
758 if (Data.isExternal())
761 const MCSymbol &Symbol = Data.getSymbol();
762 if (Symbol.isUndefined() && !Symbol.isVariable())
768 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
769 // FIXME: Is this the correct place to do this?
771 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
772 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
773 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
774 Data.setExternal(true);
777 // Build section lookup table.
778 NumRegularSections = Asm.size();
779 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
781 for (MCAssembler::iterator it = Asm.begin(),
782 ie = Asm.end(); it != ie; ++it, ++Index)
783 SectionIndexMap[&it->getSection()] = Index;
785 // Index 0 is always the empty string.
786 StringMap<uint64_t> StringIndexMap;
787 StringTable += '\x00';
789 // Add the data for the symbols.
790 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
791 ie = Asm.symbol_end(); it != ie; ++it) {
792 const MCSymbol &Symbol = it->getSymbol();
794 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol)))
799 bool Local = isLocal(*it);
802 if (it->isCommon()) {
804 MSD.SectionIndex = ELF::SHN_COMMON;
806 } else if (Symbol.isAbsolute()) {
807 MSD.SectionIndex = ELF::SHN_ABS;
809 } else if (Symbol.isVariable()) {
810 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
811 if (RefSymbol.isDefined()) {
812 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
813 assert(MSD.SectionIndex && "Invalid section index!");
816 } else if (Symbol.isUndefined()) {
818 MSD.SectionIndex = ELF::SHN_UNDEF;
819 // FIXME: Undefined symbols are global, but this is the first place we
820 // are able to set it.
821 if (GetBinding(*it) == ELF::STB_LOCAL)
822 SetBinding(*it, ELF::STB_GLOBAL);
825 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
826 assert(MSD.SectionIndex && "Invalid section index!");
831 uint64_t &Entry = StringIndexMap[Symbol.getName()];
833 Entry = StringTable.size();
834 StringTable += Symbol.getName();
835 StringTable += '\x00';
837 MSD.StringIndex = Entry;
838 if (MSD.SectionIndex == ELF::SHN_UNDEF)
839 UndefinedSymbolData.push_back(MSD);
841 LocalSymbolData.push_back(MSD);
843 ExternalSymbolData.push_back(MSD);
847 // Symbols are required to be in lexicographic order.
848 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
849 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
850 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
852 // Set the symbol indices. Local symbols must come before all other
853 // symbols with non-local bindings.
855 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
856 LocalSymbolData[i].SymbolData->setIndex(Index++);
857 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
858 ExternalSymbolData[i].SymbolData->setIndex(Index++);
859 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
860 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
863 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
864 const MCSectionData &SD) {
865 if (!Relocations[&SD].empty()) {
866 MCContext &Ctx = Asm.getContext();
867 const MCSection *RelaSection;
868 const MCSectionELF &Section =
869 static_cast<const MCSectionELF&>(SD.getSection());
871 const StringRef SectionName = Section.getSectionName();
872 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
873 RelaSectionName += SectionName;
876 if (HasRelocationAddend)
877 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
879 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
881 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
882 ELF::SHT_RELA : ELF::SHT_REL, 0,
883 SectionKind::getReadOnly(),
886 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
887 RelaSD.setAlignment(Is64Bit ? 8 : 4);
889 MCDataFragment *F = new MCDataFragment(&RelaSD);
891 WriteRelocationsFragment(Asm, F, &SD);
893 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
897 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
898 uint64_t Flags, uint64_t Address,
899 uint64_t Offset, uint64_t Size,
900 uint32_t Link, uint32_t Info,
902 uint64_t EntrySize) {
903 Write32(Name); // sh_name: index into string table
904 Write32(Type); // sh_type
905 WriteWord(Flags); // sh_flags
906 WriteWord(Address); // sh_addr
907 WriteWord(Offset); // sh_offset
908 WriteWord(Size); // sh_size
909 Write32(Link); // sh_link
910 Write32(Info); // sh_info
911 WriteWord(Alignment); // sh_addralign
912 WriteWord(EntrySize); // sh_entsize
915 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
917 const MCSectionData *SD) {
918 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
919 // sort by the r_offset just like gnu as does
920 array_pod_sort(Relocs.begin(), Relocs.end());
922 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
923 ELFRelocationEntry entry = Relocs[e - i - 1];
926 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
928 entry.Index += LocalSymbolData.size() + 1;
932 String64(buf, entry.r_offset);
933 F->getContents() += StringRef(buf, 8);
935 struct ELF::Elf64_Rela ERE64;
936 ERE64.setSymbolAndType(entry.Index, entry.Type);
937 String64(buf, ERE64.r_info);
938 F->getContents() += StringRef(buf, 8);
940 if (HasRelocationAddend) {
941 String64(buf, entry.r_addend);
942 F->getContents() += StringRef(buf, 8);
947 String32(buf, entry.r_offset);
948 F->getContents() += StringRef(buf, 4);
950 struct ELF::Elf32_Rela ERE32;
951 ERE32.setSymbolAndType(entry.Index, entry.Type);
952 String32(buf, ERE32.r_info);
953 F->getContents() += StringRef(buf, 4);
955 if (HasRelocationAddend) {
956 String32(buf, entry.r_addend);
957 F->getContents() += StringRef(buf, 4);
963 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
964 MCAsmLayout &Layout) {
965 MCContext &Ctx = Asm.getContext();
968 const MCSection *SymtabSection;
969 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
971 unsigned NumRegularSections = Asm.size();
973 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
974 const MCSection *ShstrtabSection;
975 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
976 SectionKind::getReadOnly(), false);
977 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
978 ShstrtabSD.setAlignment(1);
979 ShstrtabIndex = Asm.size();
981 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
982 SectionKind::getReadOnly(),
984 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
985 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
987 const MCSection *StrtabSection;
988 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
989 SectionKind::getReadOnly(), false);
990 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
991 StrtabSD.setAlignment(1);
992 StringTableIndex = Asm.size();
994 WriteRelocations(Asm, Layout);
997 F = new MCDataFragment(&SymtabSD);
998 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
999 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1001 F = new MCDataFragment(&StrtabSD);
1002 F->getContents().append(StringTable.begin(), StringTable.end());
1003 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1005 F = new MCDataFragment(&ShstrtabSD);
1007 // Section header string table.
1009 // The first entry of a string table holds a null character so skip
1012 F->getContents() += '\x00';
1014 for (MCAssembler::const_iterator it = Asm.begin(),
1015 ie = Asm.end(); it != ie; ++it) {
1016 const MCSectionELF &Section =
1017 static_cast<const MCSectionELF&>(it->getSection());
1018 // FIXME: We could merge suffixes like in .text and .rela.text.
1020 // Remember the index into the string table so we can write it
1021 // into the sh_name field of the section header table.
1022 SectionStringTableIndex[&it->getSection()] = Index;
1024 Index += Section.getSectionName().size() + 1;
1025 F->getContents() += Section.getSectionName();
1026 F->getContents() += '\x00';
1029 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1032 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1033 const MCValue Target,
1035 const MCFragment *DF) const {
1036 // If this is a PCrel relocation, find the section this fixup value is
1038 const MCSection *BaseSection = 0;
1040 BaseSection = &DF->getParent()->getSection();
1041 assert(BaseSection);
1044 const MCSection *SectionA = 0;
1045 const MCSymbol *SymbolA = 0;
1046 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1047 SymbolA = &A->getSymbol();
1048 SectionA = &SymbolA->getSection();
1051 const MCSection *SectionB = 0;
1052 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1053 SectionB = &B->getSymbol().getSection();
1057 return SectionA == SectionB;
1059 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1060 if (DataA.isExternal())
1063 return !SectionB && BaseSection == SectionA;
1066 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1067 const MCAsmLayout &Layout) {
1068 // Compute symbol table information.
1069 ComputeSymbolTable(Asm);
1071 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1072 const_cast<MCAsmLayout&>(Layout));
1074 // Add 1 for the null section.
1075 unsigned NumSections = Asm.size() + 1;
1076 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1077 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1078 uint64_t FileOff = HeaderSize;
1080 for (MCAssembler::const_iterator it = Asm.begin(),
1081 ie = Asm.end(); it != ie; ++it) {
1082 const MCSectionData &SD = *it;
1084 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1086 // Get the size of the section in the output file (including padding).
1087 uint64_t Size = Layout.getSectionFileSize(&SD);
1092 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1094 // Write out the ELF header ...
1095 WriteHeader(FileOff - HeaderSize, NumSections);
1097 FileOff = HeaderSize;
1099 // ... then all of the sections ...
1100 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1102 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1105 for (MCAssembler::const_iterator it = Asm.begin(),
1106 ie = Asm.end(); it != ie; ++it) {
1107 const MCSectionData &SD = *it;
1109 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1110 WriteZeros(Padding);
1113 // Remember the offset into the file for this section.
1114 SectionOffsetMap[&it->getSection()] = FileOff;
1115 SectionIndexMap[&it->getSection()] = Index++;
1117 FileOff += Layout.getSectionFileSize(&SD);
1119 Asm.WriteSectionData(it, Layout, Writer);
1122 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1123 WriteZeros(Padding);
1126 // ... and then the section header table.
1127 // Should we align the section header table?
1129 // Null section first.
1130 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1132 for (MCAssembler::const_iterator it = Asm.begin(),
1133 ie = Asm.end(); it != ie; ++it) {
1134 const MCSectionData &SD = *it;
1135 const MCSectionELF &Section =
1136 static_cast<const MCSectionELF&>(SD.getSection());
1138 uint64_t sh_link = 0;
1139 uint64_t sh_info = 0;
1141 switch(Section.getType()) {
1142 case ELF::SHT_DYNAMIC:
1143 sh_link = SectionStringTableIndex[&it->getSection()];
1148 case ELF::SHT_RELA: {
1149 const MCSection *SymtabSection;
1150 const MCSection *InfoSection;
1152 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1153 SectionKind::getReadOnly(),
1155 sh_link = SectionIndexMap[SymtabSection];
1157 // Remove ".rel" and ".rela" prefixes.
1158 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1159 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1161 InfoSection = Asm.getContext().getELFSection(SectionName,
1162 ELF::SHT_PROGBITS, 0,
1163 SectionKind::getReadOnly(),
1165 sh_info = SectionIndexMap[InfoSection];
1169 case ELF::SHT_SYMTAB:
1170 case ELF::SHT_DYNSYM:
1171 sh_link = StringTableIndex;
1172 sh_info = LastLocalSymbolIndex;
1175 case ELF::SHT_PROGBITS:
1176 case ELF::SHT_STRTAB:
1177 case ELF::SHT_NOBITS:
1183 case ELF::SHT_GROUP:
1184 case ELF::SHT_SYMTAB_SHNDX:
1186 assert(0 && "FIXME: sh_type value not supported!");
1190 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1191 Section.getType(), Section.getFlags(),
1193 SectionOffsetMap.lookup(&SD.getSection()),
1194 Layout.getSectionSize(&SD), sh_link,
1195 sh_info, SD.getAlignment(),
1196 Section.getEntrySize());
1200 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1202 Triple::OSType OSType,
1203 bool IsLittleEndian,
1204 bool HasRelocationAddend)
1205 : MCObjectWriter(OS, IsLittleEndian)
1207 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1210 ELFObjectWriter::~ELFObjectWriter() {
1211 delete (ELFObjectWriterImpl*) Impl;
1214 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1215 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1218 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1219 const MCAsmLayout &Layout,
1220 const MCFragment *Fragment,
1221 const MCFixup &Fixup, MCValue Target,
1222 uint64_t &FixedValue) {
1223 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1224 Target, FixedValue);
1227 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1228 const MCValue Target,
1230 const MCFragment *DF) const {
1231 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1235 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1236 const MCAsmLayout &Layout) {
1237 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);