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 bool isFixupKindX86PCRel(unsigned Kind) {
65 case X86::reloc_pcrel_1byte:
66 case X86::reloc_pcrel_4byte:
67 case X86::reloc_riprel_4byte:
68 case X86::reloc_riprel_4byte_movq_load:
75 class ELFObjectWriterImpl {
76 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
77 return Kind == X86::reloc_riprel_4byte ||
78 Kind == X86::reloc_riprel_4byte_movq_load;
82 /// ELFSymbolData - Helper struct for containing some precomputed information
84 struct ELFSymbolData {
85 MCSymbolData *SymbolData;
87 uint32_t SectionIndex;
89 // Support lexicographic sorting.
90 bool operator<(const ELFSymbolData &RHS) const {
91 if (GetType(*SymbolData) == ELF::STT_FILE)
93 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
95 return SymbolData->getSymbol().getName() <
96 RHS.SymbolData->getSymbol().getName();
100 /// @name Relocation Data
103 struct ELFRelocationEntry {
104 // Make these big enough for both 32-bit and 64-bit
108 const MCSymbol *Symbol;
111 // Support lexicographic sorting.
112 bool operator<(const ELFRelocationEntry &RE) const {
113 return RE.r_offset < r_offset;
117 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
119 llvm::DenseMap<const MCSectionData*,
120 std::vector<ELFRelocationEntry> > Relocations;
121 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
124 /// @name Symbol Table Data
127 SmallString<256> StringTable;
128 std::vector<ELFSymbolData> LocalSymbolData;
129 std::vector<ELFSymbolData> ExternalSymbolData;
130 std::vector<ELFSymbolData> UndefinedSymbolData;
134 int NumRegularSections;
136 ELFObjectWriter *Writer;
140 unsigned Is64Bit : 1;
142 bool HasRelocationAddend;
144 Triple::OSType OSType;
146 // This holds the symbol table index of the last local symbol.
147 unsigned LastLocalSymbolIndex;
148 // This holds the .strtab section index.
149 unsigned StringTableIndex;
151 unsigned ShstrtabIndex;
154 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
155 bool _HasRelAddend, Triple::OSType _OSType)
156 : Writer(_Writer), OS(Writer->getStream()),
157 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
161 void Write8(uint8_t Value) { Writer->Write8(Value); }
162 void Write16(uint16_t Value) { Writer->Write16(Value); }
163 void Write32(uint32_t Value) { Writer->Write32(Value); }
164 //void Write64(uint64_t Value) { Writer->Write64(Value); }
165 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
166 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
167 // Writer->WriteBytes(Str, ZeroFillSize);
170 void WriteWord(uint64_t W) {
177 void String8(char *buf, uint8_t Value) {
181 void StringLE16(char *buf, uint16_t Value) {
182 buf[0] = char(Value >> 0);
183 buf[1] = char(Value >> 8);
186 void StringLE32(char *buf, uint32_t Value) {
187 StringLE16(buf, uint16_t(Value >> 0));
188 StringLE16(buf + 2, uint16_t(Value >> 16));
191 void StringLE64(char *buf, uint64_t Value) {
192 StringLE32(buf, uint32_t(Value >> 0));
193 StringLE32(buf + 4, uint32_t(Value >> 32));
196 void StringBE16(char *buf ,uint16_t Value) {
197 buf[0] = char(Value >> 8);
198 buf[1] = char(Value >> 0);
201 void StringBE32(char *buf, uint32_t Value) {
202 StringBE16(buf, uint16_t(Value >> 16));
203 StringBE16(buf + 2, uint16_t(Value >> 0));
206 void StringBE64(char *buf, uint64_t Value) {
207 StringBE32(buf, uint32_t(Value >> 32));
208 StringBE32(buf + 4, uint32_t(Value >> 0));
211 void String16(char *buf, uint16_t Value) {
212 if (Writer->isLittleEndian())
213 StringLE16(buf, Value);
215 StringBE16(buf, Value);
218 void String32(char *buf, uint32_t Value) {
219 if (Writer->isLittleEndian())
220 StringLE32(buf, Value);
222 StringBE32(buf, Value);
225 void String64(char *buf, uint64_t Value) {
226 if (Writer->isLittleEndian())
227 StringLE64(buf, Value);
229 StringBE64(buf, Value);
232 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
234 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
235 uint64_t value, uint64_t size,
236 uint8_t other, uint16_t shndx);
238 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
239 const MCAsmLayout &Layout);
241 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
242 const MCAsmLayout &Layout,
243 unsigned NumRegularSections);
245 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
246 const MCFragment *Fragment, const MCFixup &Fixup,
247 MCValue Target, uint64_t &FixedValue);
249 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
252 /// ComputeSymbolTable - Compute the symbol table data
254 /// \param StringTable [out] - The string table data.
255 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
257 void ComputeSymbolTable(MCAssembler &Asm);
259 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
260 const MCSectionData &SD);
262 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
263 for (MCAssembler::const_iterator it = Asm.begin(),
264 ie = Asm.end(); it != ie; ++it) {
265 WriteRelocation(Asm, Layout, *it);
269 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
271 void ExecutePostLayoutBinding(MCAssembler &Asm) {
274 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
275 uint64_t Address, uint64_t Offset,
276 uint64_t Size, uint32_t Link, uint32_t Info,
277 uint64_t Alignment, uint64_t EntrySize);
279 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
280 const MCSectionData *SD);
282 bool IsFixupFullyResolved(const MCAssembler &Asm,
283 const MCValue Target,
285 const MCFragment *DF) const;
287 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
292 // Emit the ELF header.
293 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
294 unsigned NumberOfSections) {
300 // emitWord method behaves differently for ELF32 and ELF64, writing
301 // 4 bytes in the former and 8 in the latter.
303 Write8(0x7f); // e_ident[EI_MAG0]
304 Write8('E'); // e_ident[EI_MAG1]
305 Write8('L'); // e_ident[EI_MAG2]
306 Write8('F'); // e_ident[EI_MAG3]
308 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
311 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
313 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
316 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
317 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
318 default: Write8(ELF::ELFOSABI_NONE); break;
320 Write8(0); // e_ident[EI_ABIVERSION]
322 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
324 Write16(ELF::ET_REL); // e_type
326 // FIXME: Make this configurable
327 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
329 Write32(ELF::EV_CURRENT); // e_version
330 WriteWord(0); // e_entry, no entry point in .o file
331 WriteWord(0); // e_phoff, no program header for .o
332 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
333 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
335 // FIXME: Make this configurable.
336 Write32(0); // e_flags = whatever the target wants
338 // e_ehsize = ELF header size
339 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
341 Write16(0); // e_phentsize = prog header entry size
342 Write16(0); // e_phnum = # prog header entries = 0
344 // e_shentsize = Section header entry size
345 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
347 // e_shnum = # of section header ents
348 Write16(NumberOfSections);
350 // e_shstrndx = Section # of '.shstrtab'
351 Write16(ShstrtabIndex);
354 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
355 uint8_t info, uint64_t value,
356 uint64_t size, uint8_t other,
362 F->getContents() += StringRef(buf, 4); // st_name
365 F->getContents() += StringRef(buf, 1); // st_info
368 F->getContents() += StringRef(buf, 1); // st_other
370 String16(buf, shndx);
371 F->getContents() += StringRef(buf, 2); // st_shndx
373 String64(buf, value);
374 F->getContents() += StringRef(buf, 8); // st_value
377 F->getContents() += StringRef(buf, 8); // st_size
382 F->getContents() += StringRef(buf, 4); // st_name
384 String32(buf, value);
385 F->getContents() += StringRef(buf, 4); // st_value
388 F->getContents() += StringRef(buf, 4); // st_size
391 F->getContents() += StringRef(buf, 1); // st_info
394 F->getContents() += StringRef(buf, 1); // st_other
396 String16(buf, shndx);
397 F->getContents() += StringRef(buf, 2); // st_shndx
401 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
402 if (Data.isCommon() && Data.isExternal())
403 return Data.getCommonAlignment();
405 const MCSymbol &Symbol = Data.getSymbol();
406 if (!Symbol.isInSection())
409 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
410 if (MCFragment *FF = Data.getFragment())
411 return Layout.getSymbolAddress(&Data) -
412 Layout.getSectionAddress(FF->getParent());
417 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
418 const MCAsmLayout &Layout) {
419 MCSymbolData &Data = *MSD.SymbolData;
420 uint8_t Info = (Data.getFlags() & 0xff);
421 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
422 uint64_t Value = SymbolValue(Data, Layout);
426 assert(!(Data.isCommon() && !Data.isExternal()));
428 ESize = Data.getSize();
429 if (Data.getSize()) {
431 if (ESize->getKind() == MCExpr::Binary) {
432 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
434 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
436 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
438 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
440 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
442 } else if (ESize->getKind() == MCExpr::Constant) {
443 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
445 assert(0 && "Unsupported size expression");
449 // Write out the symbol table entry
450 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
451 Size, Other, MSD.SectionIndex);
454 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
455 const MCAssembler &Asm,
456 const MCAsmLayout &Layout,
457 unsigned NumRegularSections) {
458 // The string table must be emitted first because we need the index
459 // into the string table for all the symbol names.
460 assert(StringTable.size() && "Missing string table");
462 // FIXME: Make sure the start of the symbol table is aligned.
464 // The first entry is the undefined symbol entry.
465 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
466 F->getContents().append(EntrySize, '\x00');
468 // Write the symbol table entries.
469 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
470 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
471 ELFSymbolData &MSD = LocalSymbolData[i];
472 WriteSymbol(F, MSD, Layout);
475 // Write out a symbol table entry for each regular section.
477 for (MCAssembler::const_iterator it = Asm.begin();
478 Index <= NumRegularSections; ++it, ++Index) {
479 const MCSectionELF &Section =
480 static_cast<const MCSectionELF&>(it->getSection());
481 // Leave out relocations so we don't have indexes within
482 // the relocations messed up
483 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
485 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
486 LastLocalSymbolIndex++;
489 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
490 ELFSymbolData &MSD = ExternalSymbolData[i];
491 MCSymbolData &Data = *MSD.SymbolData;
492 assert((Data.getFlags() & ELF_STB_Global) &&
493 "External symbol requires STB_GLOBAL flag");
494 WriteSymbol(F, MSD, Layout);
495 if (GetBinding(Data) == ELF::STB_LOCAL)
496 LastLocalSymbolIndex++;
499 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
500 ELFSymbolData &MSD = UndefinedSymbolData[i];
501 MCSymbolData &Data = *MSD.SymbolData;
502 WriteSymbol(F, MSD, Layout);
503 if (GetBinding(Data) == ELF::STB_LOCAL)
504 LastLocalSymbolIndex++;
508 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
509 const MCValue &Target) {
510 const MCSymbol &Symbol = SD.getSymbol();
511 if (Symbol.isUndefined())
514 const MCSectionELF &Section =
515 static_cast<const MCSectionELF&>(Symbol.getSection());
517 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
518 return Target.getConstant() != 0;
526 // FIXME: this is currently X86/X86_64 only
527 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
528 const MCAsmLayout &Layout,
529 const MCFragment *Fragment,
530 const MCFixup &Fixup,
532 uint64_t &FixedValue) {
535 int64_t Value = Target.getConstant();
536 const MCSymbol *Symbol = 0;
538 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
539 if (!Target.isAbsolute()) {
540 Symbol = &Target.getSymA()->getSymbol();
541 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
542 MCFragment *F = SD.getFragment();
544 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
545 const MCSymbol &SymbolB = RefB->getSymbol();
546 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
548 MCSectionData *Sec = Fragment->getParent();
550 // Offset of the symbol in the section
551 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
553 // Ofeset of the relocation in the section
554 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
558 // Check that this case has already been fully resolved before we get
560 if (Symbol->isDefined() && !SD.isExternal() &&
562 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
563 llvm_unreachable("We don't need a relocation in this case.");
567 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target);
568 if (!RelocOnSymbol) {
569 Index = F->getParent()->getOrdinal();
571 MCSectionData *FSD = F->getParent();
572 // Offset of the symbol in the section
573 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
575 UsedInReloc.insert(Symbol);
579 // Compensate for the addend on i386.
586 // determine the type of the relocation
588 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
593 case MCSymbolRefExpr::VK_None:
594 Type = ELF::R_X86_64_PC32;
596 case MCSymbolRefExpr::VK_PLT:
597 Type = ELF::R_X86_64_PLT32;
599 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
600 Type = ELF::R_X86_64_GOTPCREL;
603 llvm_unreachable("Unimplemented");
606 switch ((unsigned)Fixup.getKind()) {
607 default: llvm_unreachable("invalid fixup kind!");
608 case FK_Data_8: Type = ELF::R_X86_64_64; break;
609 case X86::reloc_signed_4byte:
610 case X86::reloc_pcrel_4byte:
611 assert(isInt<32>(Target.getConstant()));
613 case MCSymbolRefExpr::VK_None:
614 Type = ELF::R_X86_64_32S;
616 case MCSymbolRefExpr::VK_GOT:
617 Type = ELF::R_X86_64_GOT32;
620 llvm_unreachable("Unimplemented");
624 Type = ELF::R_X86_64_32;
626 case FK_Data_2: Type = ELF::R_X86_64_16; break;
627 case X86::reloc_pcrel_1byte:
628 case FK_Data_1: Type = ELF::R_X86_64_8; break;
633 Type = ELF::R_386_PC32;
635 switch ((unsigned)Fixup.getKind()) {
636 default: llvm_unreachable("invalid fixup kind!");
638 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
640 case X86::reloc_signed_4byte:
641 case X86::reloc_pcrel_4byte:
642 case FK_Data_4: Type = ELF::R_386_32; break;
643 case FK_Data_2: Type = ELF::R_386_16; break;
644 case X86::reloc_pcrel_1byte:
645 case FK_Data_1: Type = ELF::R_386_8; break;
650 ELFRelocationEntry ERE;
656 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
658 if (HasRelocationAddend)
659 ERE.r_addend = Addend;
661 ERE.r_addend = 0; // Silence compiler warning.
663 Relocations[Fragment->getParent()].push_back(ERE);
667 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
669 MCSymbolData &SD = Asm.getSymbolData(*S);
672 if (!SD.isExternal() && !S->isUndefined())
673 return SD.getIndex() + /* empty symbol */ 1;
675 // External or undefined symbol.
676 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
679 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
680 // Build section lookup table.
681 NumRegularSections = Asm.size();
682 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
684 for (MCAssembler::iterator it = Asm.begin(),
685 ie = Asm.end(); it != ie; ++it, ++Index)
686 SectionIndexMap[&it->getSection()] = Index;
688 // Index 0 is always the empty string.
689 StringMap<uint64_t> StringIndexMap;
690 StringTable += '\x00';
692 // Add the data for local symbols.
693 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
694 ie = Asm.symbol_end(); it != ie; ++it) {
695 const MCSymbol &Symbol = it->getSymbol();
697 // Ignore non-linker visible symbols.
698 if (!Asm.isSymbolLinkerVisible(Symbol))
701 if (it->isExternal() || Symbol.isUndefined())
704 if (Symbol.isTemporary() && !UsedInReloc.count(&Symbol))
707 uint64_t &Entry = StringIndexMap[Symbol.getName()];
709 Entry = StringTable.size();
710 StringTable += Symbol.getName();
711 StringTable += '\x00';
716 MSD.StringIndex = Entry;
718 if (Symbol.isAbsolute()) {
719 MSD.SectionIndex = ELF::SHN_ABS;
720 LocalSymbolData.push_back(MSD);
722 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
723 assert(MSD.SectionIndex && "Invalid section index!");
724 LocalSymbolData.push_back(MSD);
728 // Now add non-local symbols.
729 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
730 ie = Asm.symbol_end(); it != ie; ++it) {
731 const MCSymbol &Symbol = it->getSymbol();
733 // Ignore non-linker visible symbols.
734 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
737 if (!it->isExternal() && !Symbol.isUndefined())
740 if (Symbol.isVariable())
743 if (Symbol.isUndefined() && !UsedInReloc.count(&Symbol)
744 && Symbol.isTemporary())
747 uint64_t &Entry = StringIndexMap[Symbol.getName()];
749 Entry = StringTable.size();
750 StringTable += Symbol.getName();
751 StringTable += '\x00';
756 MSD.StringIndex = Entry;
758 if (it->isCommon()) {
759 MSD.SectionIndex = ELF::SHN_COMMON;
760 ExternalSymbolData.push_back(MSD);
761 } else if (Symbol.isUndefined()) {
762 MSD.SectionIndex = ELF::SHN_UNDEF;
763 // FIXME: Undefined symbols are global, but this is the first place we
764 // are able to set it.
765 if (GetBinding(*it) == ELF::STB_LOCAL)
766 SetBinding(*it, ELF::STB_GLOBAL);
767 UndefinedSymbolData.push_back(MSD);
768 } else if (Symbol.isAbsolute()) {
769 MSD.SectionIndex = ELF::SHN_ABS;
770 ExternalSymbolData.push_back(MSD);
772 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
773 assert(MSD.SectionIndex && "Invalid section index!");
774 ExternalSymbolData.push_back(MSD);
778 // Symbols are required to be in lexicographic order.
779 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
780 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
781 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
783 // Set the symbol indices. Local symbols must come before all other
784 // symbols with non-local bindings.
786 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
787 LocalSymbolData[i].SymbolData->setIndex(Index++);
788 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
789 ExternalSymbolData[i].SymbolData->setIndex(Index++);
790 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
791 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
794 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
795 const MCSectionData &SD) {
796 if (!Relocations[&SD].empty()) {
797 MCContext &Ctx = Asm.getContext();
798 const MCSection *RelaSection;
799 const MCSectionELF &Section =
800 static_cast<const MCSectionELF&>(SD.getSection());
802 const StringRef SectionName = Section.getSectionName();
803 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
804 RelaSectionName += SectionName;
807 if (HasRelocationAddend)
808 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
810 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
812 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
813 ELF::SHT_RELA : ELF::SHT_REL, 0,
814 SectionKind::getReadOnly(),
817 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
818 RelaSD.setAlignment(Is64Bit ? 8 : 4);
820 MCDataFragment *F = new MCDataFragment(&RelaSD);
822 WriteRelocationsFragment(Asm, F, &SD);
824 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
828 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
829 uint64_t Flags, uint64_t Address,
830 uint64_t Offset, uint64_t Size,
831 uint32_t Link, uint32_t Info,
833 uint64_t EntrySize) {
834 Write32(Name); // sh_name: index into string table
835 Write32(Type); // sh_type
836 WriteWord(Flags); // sh_flags
837 WriteWord(Address); // sh_addr
838 WriteWord(Offset); // sh_offset
839 WriteWord(Size); // sh_size
840 Write32(Link); // sh_link
841 Write32(Info); // sh_info
842 WriteWord(Alignment); // sh_addralign
843 WriteWord(EntrySize); // sh_entsize
846 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
848 const MCSectionData *SD) {
849 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
850 // sort by the r_offset just like gnu as does
851 array_pod_sort(Relocs.begin(), Relocs.end());
853 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
854 ELFRelocationEntry entry = Relocs[e - i - 1];
857 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
859 entry.Index += LocalSymbolData.size() + 1;
863 String64(buf, entry.r_offset);
864 F->getContents() += StringRef(buf, 8);
866 struct ELF::Elf64_Rela ERE64;
867 ERE64.setSymbolAndType(entry.Index, entry.Type);
868 String64(buf, ERE64.r_info);
869 F->getContents() += StringRef(buf, 8);
871 if (HasRelocationAddend) {
872 String64(buf, entry.r_addend);
873 F->getContents() += StringRef(buf, 8);
878 String32(buf, entry.r_offset);
879 F->getContents() += StringRef(buf, 4);
881 struct ELF::Elf32_Rela ERE32;
882 ERE32.setSymbolAndType(entry.Index, entry.Type);
883 String32(buf, ERE32.r_info);
884 F->getContents() += StringRef(buf, 4);
886 if (HasRelocationAddend) {
887 String32(buf, entry.r_addend);
888 F->getContents() += StringRef(buf, 4);
894 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
895 MCAsmLayout &Layout) {
896 MCContext &Ctx = Asm.getContext();
899 const MCSection *SymtabSection;
900 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
902 unsigned NumRegularSections = Asm.size();
904 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
905 const MCSection *ShstrtabSection;
906 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
907 SectionKind::getReadOnly(), false);
908 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
909 ShstrtabSD.setAlignment(1);
910 ShstrtabIndex = Asm.size();
912 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
913 SectionKind::getReadOnly(),
915 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
916 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
918 const MCSection *StrtabSection;
919 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
920 SectionKind::getReadOnly(), false);
921 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
922 StrtabSD.setAlignment(1);
923 StringTableIndex = Asm.size();
925 WriteRelocations(Asm, Layout);
928 F = new MCDataFragment(&SymtabSD);
929 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
930 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
932 F = new MCDataFragment(&StrtabSD);
933 F->getContents().append(StringTable.begin(), StringTable.end());
934 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
936 F = new MCDataFragment(&ShstrtabSD);
938 // Section header string table.
940 // The first entry of a string table holds a null character so skip
943 F->getContents() += '\x00';
945 for (MCAssembler::const_iterator it = Asm.begin(),
946 ie = Asm.end(); it != ie; ++it) {
947 const MCSectionELF &Section =
948 static_cast<const MCSectionELF&>(it->getSection());
949 // FIXME: We could merge suffixes like in .text and .rela.text.
951 // Remember the index into the string table so we can write it
952 // into the sh_name field of the section header table.
953 SectionStringTableIndex[&it->getSection()] = Index;
955 Index += Section.getSectionName().size() + 1;
956 F->getContents() += Section.getSectionName();
957 F->getContents() += '\x00';
960 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
963 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
964 const MCValue Target,
966 const MCFragment *DF) const {
967 // If this is a PCrel relocation, find the section this fixup value is
969 const MCSection *BaseSection = 0;
971 BaseSection = &DF->getParent()->getSection();
975 const MCSection *SectionA = 0;
976 const MCSymbol *SymbolA = 0;
977 if (const MCSymbolRefExpr *A = Target.getSymA()) {
978 SymbolA = &A->getSymbol();
979 SectionA = &SymbolA->getSection();
982 const MCSection *SectionB = 0;
983 if (const MCSymbolRefExpr *B = Target.getSymB()) {
984 SectionB = &B->getSymbol().getSection();
988 return SectionA == SectionB;
990 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
991 if (DataA.isExternal())
994 return !SectionB && BaseSection == SectionA;
997 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
998 const MCAsmLayout &Layout) {
999 // Compute symbol table information.
1000 ComputeSymbolTable(Asm);
1002 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1003 const_cast<MCAsmLayout&>(Layout));
1005 // Add 1 for the null section.
1006 unsigned NumSections = Asm.size() + 1;
1007 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1008 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1009 uint64_t FileOff = HeaderSize;
1011 for (MCAssembler::const_iterator it = Asm.begin(),
1012 ie = Asm.end(); it != ie; ++it) {
1013 const MCSectionData &SD = *it;
1015 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1017 // Get the size of the section in the output file (including padding).
1018 uint64_t Size = Layout.getSectionFileSize(&SD);
1023 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1025 // Write out the ELF header ...
1026 WriteHeader(FileOff - HeaderSize, NumSections);
1028 FileOff = HeaderSize;
1030 // ... then all of the sections ...
1031 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1033 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1036 for (MCAssembler::const_iterator it = Asm.begin(),
1037 ie = Asm.end(); it != ie; ++it) {
1038 const MCSectionData &SD = *it;
1040 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1041 WriteZeros(Padding);
1044 // Remember the offset into the file for this section.
1045 SectionOffsetMap[&it->getSection()] = FileOff;
1046 SectionIndexMap[&it->getSection()] = Index++;
1048 FileOff += Layout.getSectionFileSize(&SD);
1050 Asm.WriteSectionData(it, Layout, Writer);
1053 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1054 WriteZeros(Padding);
1057 // ... and then the section header table.
1058 // Should we align the section header table?
1060 // Null section first.
1061 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1063 for (MCAssembler::const_iterator it = Asm.begin(),
1064 ie = Asm.end(); it != ie; ++it) {
1065 const MCSectionData &SD = *it;
1066 const MCSectionELF &Section =
1067 static_cast<const MCSectionELF&>(SD.getSection());
1069 uint64_t sh_link = 0;
1070 uint64_t sh_info = 0;
1072 switch(Section.getType()) {
1073 case ELF::SHT_DYNAMIC:
1074 sh_link = SectionStringTableIndex[&it->getSection()];
1079 case ELF::SHT_RELA: {
1080 const MCSection *SymtabSection;
1081 const MCSection *InfoSection;
1083 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1084 SectionKind::getReadOnly(),
1086 sh_link = SectionIndexMap[SymtabSection];
1088 // Remove ".rel" and ".rela" prefixes.
1089 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1090 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1092 InfoSection = Asm.getContext().getELFSection(SectionName,
1093 ELF::SHT_PROGBITS, 0,
1094 SectionKind::getReadOnly(),
1096 sh_info = SectionIndexMap[InfoSection];
1100 case ELF::SHT_SYMTAB:
1101 case ELF::SHT_DYNSYM:
1102 sh_link = StringTableIndex;
1103 sh_info = LastLocalSymbolIndex;
1106 case ELF::SHT_PROGBITS:
1107 case ELF::SHT_STRTAB:
1108 case ELF::SHT_NOBITS:
1114 case ELF::SHT_GROUP:
1115 case ELF::SHT_SYMTAB_SHNDX:
1117 assert(0 && "FIXME: sh_type value not supported!");
1121 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1122 Section.getType(), Section.getFlags(),
1124 SectionOffsetMap.lookup(&SD.getSection()),
1125 Layout.getSectionSize(&SD), sh_link,
1126 sh_info, SD.getAlignment(),
1127 Section.getEntrySize());
1131 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1133 Triple::OSType OSType,
1134 bool IsLittleEndian,
1135 bool HasRelocationAddend)
1136 : MCObjectWriter(OS, IsLittleEndian)
1138 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1141 ELFObjectWriter::~ELFObjectWriter() {
1142 delete (ELFObjectWriterImpl*) Impl;
1145 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1146 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1149 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1150 const MCAsmLayout &Layout,
1151 const MCFragment *Fragment,
1152 const MCFixup &Fixup, MCValue Target,
1153 uint64_t &FixedValue) {
1154 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1155 Target, FixedValue);
1158 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1159 const MCValue Target,
1161 const MCFragment *DF) const {
1162 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1166 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1167 const MCAsmLayout &Layout) {
1168 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);