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/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Target/TargetAsmBackend.h"
32 #include "../Target/X86/X86FixupKinds.h"
39 class ELFObjectWriterImpl {
40 static bool isFixupKindX86PCRel(unsigned Kind) {
44 case X86::reloc_pcrel_1byte:
45 case X86::reloc_pcrel_4byte:
46 case X86::reloc_riprel_4byte:
47 case X86::reloc_riprel_4byte_movq_load:
52 static bool isFixupKindX86RIPRel(unsigned Kind) {
53 return Kind == X86::reloc_riprel_4byte ||
54 Kind == X86::reloc_riprel_4byte_movq_load;
58 /// ELFSymbolData - Helper struct for containing some precomputed information
60 struct ELFSymbolData {
61 MCSymbolData *SymbolData;
63 uint32_t SectionIndex;
65 // Support lexicographic sorting.
66 bool operator<(const ELFSymbolData &RHS) const {
67 return SymbolData->getSymbol().getName() <
68 RHS.SymbolData->getSymbol().getName();
72 /// @name Relocation Data
75 struct ELFRelocationEntry {
76 // Make these big enough for both 32-bit and 64-bit
81 // Support lexicographic sorting.
82 bool operator<(const ELFRelocationEntry &RE) const {
83 return RE.r_offset < r_offset;
87 llvm::DenseMap<const MCSectionData*,
88 std::vector<ELFRelocationEntry> > Relocations;
89 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
92 /// @name Symbol Table Data
95 SmallString<256> StringTable;
96 std::vector<ELFSymbolData> LocalSymbolData;
97 std::vector<ELFSymbolData> ExternalSymbolData;
98 std::vector<ELFSymbolData> UndefinedSymbolData;
102 ELFObjectWriter *Writer;
106 // This holds the current offset into the object file.
109 unsigned Is64Bit : 1;
111 bool HasRelocationAddend;
113 // This holds the symbol table index of the last local symbol.
114 unsigned LastLocalSymbolIndex;
115 // This holds the .strtab section index.
116 unsigned StringTableIndex;
118 unsigned ShstrtabIndex;
121 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
123 : Writer(_Writer), OS(Writer->getStream()), FileOff(0),
124 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend) {
127 void Write8(uint8_t Value) { Writer->Write8(Value); }
128 void Write16(uint16_t Value) { Writer->Write16(Value); }
129 void Write32(uint32_t Value) { Writer->Write32(Value); }
130 void Write64(uint64_t Value) { Writer->Write64(Value); }
131 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
132 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
133 Writer->WriteBytes(Str, ZeroFillSize);
136 void WriteWord(uint64_t W) {
144 void String8(char *buf, uint8_t Value) {
148 void StringLE16(char *buf, uint16_t Value) {
149 buf[0] = char(Value >> 0);
150 buf[1] = char(Value >> 8);
153 void StringLE32(char *buf, uint32_t Value) {
154 StringLE16(buf, uint16_t(Value >> 0));
155 StringLE16(buf, uint16_t(Value >> 16));
158 void StringLE64(char *buf, uint64_t Value) {
159 StringLE32(buf, uint32_t(Value >> 0));
160 StringLE32(buf, uint32_t(Value >> 32));
163 void StringBE16(char *buf ,uint16_t Value) {
164 buf[0] = char(Value >> 8);
165 buf[1] = char(Value >> 0);
168 void StringBE32(char *buf, uint32_t Value) {
169 StringBE16(buf, uint16_t(Value >> 16));
170 StringBE16(buf, uint16_t(Value >> 0));
173 void StringBE64(char *buf, uint64_t Value) {
174 StringBE32(buf, uint32_t(Value >> 32));
175 StringBE32(buf, uint32_t(Value >> 0));
178 void String16(char *buf, uint16_t Value) {
179 if (Writer->isLittleEndian())
180 StringLE16(buf, Value);
182 StringBE16(buf, Value);
185 void String32(char *buf, uint32_t Value) {
186 if (Writer->isLittleEndian())
187 StringLE32(buf, Value);
189 StringBE32(buf, Value);
192 void String64(char *buf, uint64_t Value) {
193 if (Writer->isLittleEndian())
194 StringLE64(buf, Value);
196 StringBE64(buf, Value);
199 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
201 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
202 uint64_t value, uint64_t size,
203 uint8_t other, uint16_t shndx);
205 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
206 const MCAsmLayout &Layout);
208 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
209 const MCAsmLayout &Layout);
211 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
212 const MCFragment *Fragment, const MCFixup &Fixup,
213 MCValue Target, uint64_t &FixedValue);
215 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
218 /// ComputeSymbolTable - Compute the symbol table data
220 /// \param StringTable [out] - The string table data.
221 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
223 void ComputeSymbolTable(MCAssembler &Asm);
225 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
226 const MCSectionData &SD);
228 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
229 for (MCAssembler::const_iterator it = Asm.begin(),
230 ie = Asm.end(); it != ie; ++it) {
231 WriteRelocation(Asm, Layout, *it);
235 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
237 void ExecutePostLayoutBinding(MCAssembler &Asm) {
238 // Compute symbol table information.
239 ComputeSymbolTable(Asm);
242 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
243 uint64_t Address, uint64_t Offset,
244 uint64_t Size, uint32_t Link, uint32_t Info,
245 uint64_t Alignment, uint64_t EntrySize);
247 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
248 const MCSectionData *SD);
250 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
255 // Emit the ELF header.
256 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
257 unsigned NumberOfSections) {
263 // emitWord method behaves differently for ELF32 and ELF64, writing
264 // 4 bytes in the former and 8 in the latter.
266 Write8(0x7f); // e_ident[EI_MAG0]
267 Write8('E'); // e_ident[EI_MAG1]
268 Write8('L'); // e_ident[EI_MAG2]
269 Write8('F'); // e_ident[EI_MAG3]
271 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
274 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
276 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
277 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
278 Write8(0); // e_ident[EI_ABIVERSION]
280 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
282 Write16(ELF::ET_REL); // e_type
284 // FIXME: Make this configurable
285 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
287 Write32(ELF::EV_CURRENT); // e_version
288 WriteWord(0); // e_entry, no entry point in .o file
289 WriteWord(0); // e_phoff, no program header for .o
290 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
291 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
293 // FIXME: Make this configurable.
294 Write32(0); // e_flags = whatever the target wants
296 // e_ehsize = ELF header size
297 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
299 Write16(0); // e_phentsize = prog header entry size
300 Write16(0); // e_phnum = # prog header entries = 0
302 // e_shentsize = Section header entry size
303 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
305 // e_shnum = # of section header ents
306 Write16(NumberOfSections);
308 // e_shstrndx = Section # of '.shstrtab'
309 Write16(ShstrtabIndex);
312 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
313 uint8_t info, uint64_t value,
314 uint64_t size, uint8_t other,
320 F->getContents() += StringRef(buf, 4); // st_name
323 F->getContents() += StringRef(buf, 1); // st_info
326 F->getContents() += StringRef(buf, 1); // st_other
328 String16(buf, shndx);
329 F->getContents() += StringRef(buf, 2); // st_shndx
331 String64(buf, value);
332 F->getContents() += StringRef(buf, 8); // st_value
335 F->getContents() += StringRef(buf, 8); // st_size
340 F->getContents() += StringRef(buf, 4); // st_name
342 String32(buf, value);
343 F->getContents() += StringRef(buf, 4); // st_value
346 F->getContents() += StringRef(buf, 4); // st_size
349 F->getContents() += StringRef(buf, 1); // st_info
352 F->getContents() += StringRef(buf, 1); // st_other
354 String16(buf, shndx);
355 F->getContents() += StringRef(buf, 2); // st_shndx
359 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
360 const MCAsmLayout &Layout) {
361 MCSymbolData &Data = *MSD.SymbolData;
362 uint8_t Info = (Data.getFlags() & 0xff);
363 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
368 if (Data.isCommon() && Data.isExternal())
369 Value = Data.getCommonAlignment();
371 ESize = Data.getSize();
372 if (Data.getSize()) {
374 if (ESize->getKind() == MCExpr::Binary) {
375 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
377 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
379 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
381 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
383 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
384 Value = Layout.getSymbolAddress(&Data);
386 } else if (ESize->getKind() == MCExpr::Constant) {
387 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
389 assert(0 && "Unsupported size expression");
393 // Write out the symbol table entry
394 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
395 Size, Other, MSD.SectionIndex);
398 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
399 const MCAssembler &Asm,
400 const MCAsmLayout &Layout) {
401 // The string table must be emitted first because we need the index
402 // into the string table for all the symbol names.
403 assert(StringTable.size() && "Missing string table");
405 // FIXME: Make sure the start of the symbol table is aligned.
407 // The first entry is the undefined symbol entry.
408 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
409 F->getContents().append(EntrySize, '\x00');
411 // Write the symbol table entries.
412 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
413 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
414 ELFSymbolData &MSD = LocalSymbolData[i];
415 WriteSymbol(F, MSD, Layout);
418 // Write out a symbol table entry for each section.
419 // leaving out the just added .symtab which is at
422 for (MCAssembler::const_iterator it = Asm.begin(),
423 ie = Asm.end(); it != ie; ++it, ++Index) {
424 const MCSectionELF &Section =
425 static_cast<const MCSectionELF&>(it->getSection());
426 // Leave out relocations so we don't have indexes within
427 // the relocations messed up
428 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
430 if (Index == Asm.size())
432 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
433 LastLocalSymbolIndex++;
436 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
437 ELFSymbolData &MSD = ExternalSymbolData[i];
438 MCSymbolData &Data = *MSD.SymbolData;
439 assert((Data.getFlags() & ELF_STB_Global) &&
440 "External symbol requires STB_GLOBAL flag");
441 WriteSymbol(F, MSD, Layout);
442 if (Data.getFlags() & ELF_STB_Local)
443 LastLocalSymbolIndex++;
446 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
447 ELFSymbolData &MSD = UndefinedSymbolData[i];
448 MCSymbolData &Data = *MSD.SymbolData;
449 Data.setFlags(Data.getFlags() | ELF_STB_Global);
450 WriteSymbol(F, MSD, Layout);
451 if (Data.getFlags() & ELF_STB_Local)
452 LastLocalSymbolIndex++;
456 // FIXME: this is currently X86/X86_64 only
457 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
458 const MCAsmLayout &Layout,
459 const MCFragment *Fragment,
460 const MCFixup &Fixup,
462 uint64_t &FixedValue) {
463 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
465 uint64_t FixupOffset =
466 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
472 Value = Target.getConstant();
474 if (!Target.isAbsolute()) {
475 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
476 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
477 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
480 if (MCFragment *F = SD.getFragment()) {
481 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
482 Value += Layout.getSymbolAddress(&SD);
484 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
486 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
490 MCFragment *F = SD.getFragment();
492 // Index of the section in .symtab against this symbol
493 // is being relocated + 2 (empty section + abs. symbols).
494 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
496 MCSectionData *FSD = F->getParent();
497 // Offset of the symbol in the section
498 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
506 // determine the type of the relocation
509 Type = ELF::R_X86_64_PC32;
511 switch ((unsigned)Fixup.getKind()) {
512 default: llvm_unreachable("invalid fixup kind!");
513 case FK_Data_8: Type = ELF::R_X86_64_64; break;
514 case X86::reloc_pcrel_4byte:
516 // check that the offset fits within a signed long
517 if (isInt<32>(Target.getConstant()))
518 Type = ELF::R_X86_64_32S;
520 Type = ELF::R_X86_64_32;
522 case FK_Data_2: Type = ELF::R_X86_64_16; break;
523 case X86::reloc_pcrel_1byte:
524 case FK_Data_1: Type = ELF::R_X86_64_8; break;
529 Type = ELF::R_386_PC32;
531 switch ((unsigned)Fixup.getKind()) {
532 default: llvm_unreachable("invalid fixup kind!");
533 case X86::reloc_pcrel_4byte:
534 case FK_Data_4: Type = ELF::R_386_32; break;
535 case FK_Data_2: Type = ELF::R_386_16; break;
536 case X86::reloc_pcrel_1byte:
537 case FK_Data_1: Type = ELF::R_386_8; break;
544 ELFRelocationEntry ERE;
547 struct ELF::Elf64_Rela ERE64;
548 ERE64.setSymbolAndType(Index, Type);
549 ERE.r_info = ERE64.r_info;
551 struct ELF::Elf32_Rela ERE32;
552 ERE32.setSymbolAndType(Index, Type);
553 ERE.r_info = ERE32.r_info;
556 ERE.r_offset = FixupOffset;
558 if (HasRelocationAddend)
559 ERE.r_addend = Addend;
561 ERE.r_addend = 0; // Silence compiler warning.
563 Relocations[Fragment->getParent()].push_back(ERE);
567 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
569 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
570 if (&LocalSymbolData[i].SymbolData->getSymbol() == S)
571 return i + /* empty symbol */ 1;
572 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
573 if (&ExternalSymbolData[i].SymbolData->getSymbol() == S)
574 return i + LocalSymbolData.size() + Asm.size() + /* empty symbol */ 1;
575 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
576 if (&UndefinedSymbolData[i].SymbolData->getSymbol() == S)
577 return i + LocalSymbolData.size() + ExternalSymbolData.size() +
578 Asm.size() + /* empty symbol */ 1;
580 llvm_unreachable("Cannot find symbol which should exist!");
583 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
584 // Build section lookup table.
585 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
587 for (MCAssembler::iterator it = Asm.begin(),
588 ie = Asm.end(); it != ie; ++it, ++Index)
589 SectionIndexMap[&it->getSection()] = Index;
591 // Index 0 is always the empty string.
592 StringMap<uint64_t> StringIndexMap;
593 StringTable += '\x00';
595 // Add the data for local symbols.
596 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
597 ie = Asm.symbol_end(); it != ie; ++it) {
598 const MCSymbol &Symbol = it->getSymbol();
600 // Ignore non-linker visible symbols.
601 if (!Asm.isSymbolLinkerVisible(Symbol))
604 if (it->isExternal() || Symbol.isUndefined())
607 uint64_t &Entry = StringIndexMap[Symbol.getName()];
609 Entry = StringTable.size();
610 StringTable += Symbol.getName();
611 StringTable += '\x00';
616 MSD.StringIndex = Entry;
618 if (Symbol.isAbsolute()) {
619 MSD.SectionIndex = ELF::SHN_ABS;
620 LocalSymbolData.push_back(MSD);
622 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
623 assert(MSD.SectionIndex && "Invalid section index!");
624 LocalSymbolData.push_back(MSD);
628 // Now add non-local symbols.
629 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
630 ie = Asm.symbol_end(); it != ie; ++it) {
631 const MCSymbol &Symbol = it->getSymbol();
633 // Ignore non-linker visible symbols.
634 if (!Asm.isSymbolLinkerVisible(Symbol))
637 if (!it->isExternal() && !Symbol.isUndefined())
640 uint64_t &Entry = StringIndexMap[Symbol.getName()];
642 Entry = StringTable.size();
643 StringTable += Symbol.getName();
644 StringTable += '\x00';
649 MSD.StringIndex = Entry;
651 if (Symbol.isUndefined()) {
652 MSD.SectionIndex = ELF::SHN_UNDEF;
653 // XXX: for some reason we dont Emit* this
654 it->setFlags(it->getFlags() | ELF_STB_Global);
655 UndefinedSymbolData.push_back(MSD);
656 } else if (Symbol.isAbsolute()) {
657 MSD.SectionIndex = ELF::SHN_ABS;
658 ExternalSymbolData.push_back(MSD);
659 } else if (it->isCommon()) {
660 MSD.SectionIndex = ELF::SHN_COMMON;
661 ExternalSymbolData.push_back(MSD);
663 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
664 assert(MSD.SectionIndex && "Invalid section index!");
665 ExternalSymbolData.push_back(MSD);
669 // Symbols are required to be in lexicographic order.
670 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
671 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
672 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
674 // Set the symbol indices. Local symbols must come before all other
675 // symbols with non-local bindings.
677 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
678 LocalSymbolData[i].SymbolData->setIndex(Index++);
679 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
680 ExternalSymbolData[i].SymbolData->setIndex(Index++);
681 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
682 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
685 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
686 const MCSectionData &SD) {
687 if (!Relocations[&SD].empty()) {
688 MCContext &Ctx = Asm.getContext();
689 const MCSection *RelaSection;
690 const MCSectionELF &Section =
691 static_cast<const MCSectionELF&>(SD.getSection());
693 const StringRef SectionName = Section.getSectionName();
694 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
695 RelaSectionName += SectionName;
698 if (HasRelocationAddend)
699 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
701 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
703 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
704 ELF::SHT_RELA : ELF::SHT_REL, 0,
705 SectionKind::getReadOnly(),
708 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
709 RelaSD.setAlignment(1);
711 MCDataFragment *F = new MCDataFragment(&RelaSD);
713 WriteRelocationsFragment(Asm, F, &SD);
715 Asm.AddSectionToTheEnd(RelaSD, Layout);
719 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
720 uint64_t Flags, uint64_t Address,
721 uint64_t Offset, uint64_t Size,
722 uint32_t Link, uint32_t Info,
724 uint64_t EntrySize) {
725 Write32(Name); // sh_name: index into string table
726 Write32(Type); // sh_type
727 WriteWord(Flags); // sh_flags
728 WriteWord(Address); // sh_addr
729 WriteWord(Offset); // sh_offset
730 WriteWord(Size); // sh_size
731 Write32(Link); // sh_link
732 Write32(Info); // sh_info
733 WriteWord(Alignment); // sh_addralign
734 WriteWord(EntrySize); // sh_entsize
737 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
739 const MCSectionData *SD) {
740 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
741 // sort by the r_offset just like gnu as does
742 array_pod_sort(Relocs.begin(), Relocs.end());
744 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
745 ELFRelocationEntry entry = Relocs[e - i - 1];
747 unsigned WordSize = Is64Bit ? 8 : 4;
748 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
749 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
751 if (HasRelocationAddend)
752 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
756 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
757 MCAsmLayout &Layout) {
758 MCContext &Ctx = Asm.getContext();
761 WriteRelocations(Asm, Layout);
763 const MCSection *SymtabSection;
764 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
766 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
767 SectionKind::getReadOnly(),
770 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
772 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
774 F = new MCDataFragment(&SymtabSD);
777 WriteSymbolTable(F, Asm, Layout);
778 Asm.AddSectionToTheEnd(SymtabSD, Layout);
780 const MCSection *StrtabSection;
781 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
782 SectionKind::getReadOnly(), false);
784 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
785 StrtabSD.setAlignment(1);
787 // FIXME: This isn't right. If the sections get rearranged this will
788 // be wrong. We need a proper lookup.
789 StringTableIndex = Asm.size();
791 F = new MCDataFragment(&StrtabSD);
792 F->getContents().append(StringTable.begin(), StringTable.end());
793 Asm.AddSectionToTheEnd(StrtabSD, Layout);
795 const MCSection *ShstrtabSection;
796 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
797 SectionKind::getReadOnly(), false);
799 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
800 ShstrtabSD.setAlignment(1);
802 F = new MCDataFragment(&ShstrtabSD);
804 // FIXME: This isn't right. If the sections get rearranged this will
805 // be wrong. We need a proper lookup.
806 ShstrtabIndex = Asm.size();
808 // Section header string table.
810 // The first entry of a string table holds a null character so skip
813 F->getContents() += '\x00';
815 for (MCAssembler::const_iterator it = Asm.begin(),
816 ie = Asm.end(); it != ie; ++it) {
817 const MCSectionELF &Section =
818 static_cast<const MCSectionELF&>(it->getSection());
820 // Remember the index into the string table so we can write it
821 // into the sh_name field of the section header table.
822 SectionStringTableIndex[&it->getSection()] = Index;
824 Index += Section.getSectionName().size() + 1;
825 F->getContents() += Section.getSectionName();
826 F->getContents() += '\x00';
829 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
832 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
833 const MCAsmLayout &Layout) {
834 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
835 const_cast<MCAsmLayout&>(Layout));
837 // Add 1 for the null section.
838 unsigned NumSections = Asm.size() + 1;
840 uint64_t SectionDataSize = 0;
842 for (MCAssembler::const_iterator it = Asm.begin(),
843 ie = Asm.end(); it != ie; ++it) {
844 const MCSectionData &SD = *it;
846 // Get the size of the section in the output file (including padding).
847 uint64_t Size = Layout.getSectionFileSize(&SD);
848 SectionDataSize += Size;
851 // Write out the ELF header ...
852 WriteHeader(SectionDataSize, NumSections);
853 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
855 // ... then all of the sections ...
856 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
858 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
861 for (MCAssembler::const_iterator it = Asm.begin(),
862 ie = Asm.end(); it != ie; ++it) {
863 // Remember the offset into the file for this section.
864 SectionOffsetMap[&it->getSection()] = FileOff;
866 SectionIndexMap[&it->getSection()] = Index++;
868 const MCSectionData &SD = *it;
869 FileOff += Layout.getSectionFileSize(&SD);
871 Asm.WriteSectionData(it, Layout, Writer);
874 // ... and then the section header table.
875 // Should we align the section header table?
877 // Null section first.
878 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
880 for (MCAssembler::const_iterator it = Asm.begin(),
881 ie = Asm.end(); it != ie; ++it) {
882 const MCSectionData &SD = *it;
883 const MCSectionELF &Section =
884 static_cast<const MCSectionELF&>(SD.getSection());
886 uint64_t sh_link = 0;
887 uint64_t sh_info = 0;
889 switch(Section.getType()) {
890 case ELF::SHT_DYNAMIC:
891 sh_link = SectionStringTableIndex[&it->getSection()];
896 case ELF::SHT_RELA: {
897 const MCSection *SymtabSection;
898 const MCSection *InfoSection;
900 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
901 SectionKind::getReadOnly(),
903 sh_link = SectionIndexMap[SymtabSection];
905 // Remove ".rel" and ".rela" prefixes.
906 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
907 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
909 InfoSection = Asm.getContext().getELFSection(SectionName,
910 ELF::SHT_PROGBITS, 0,
911 SectionKind::getReadOnly(),
913 sh_info = SectionIndexMap[InfoSection];
917 case ELF::SHT_SYMTAB:
918 case ELF::SHT_DYNSYM:
919 sh_link = StringTableIndex;
920 sh_info = LastLocalSymbolIndex;
923 case ELF::SHT_PROGBITS:
924 case ELF::SHT_STRTAB:
925 case ELF::SHT_NOBITS:
931 case ELF::SHT_SYMTAB_SHNDX:
933 assert(0 && "FIXME: sh_type value not supported!");
937 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
938 Section.getType(), Section.getFlags(),
939 Layout.getSectionAddress(&SD),
940 SectionOffsetMap.lookup(&SD.getSection()),
941 Layout.getSectionSize(&SD), sh_link,
942 sh_info, SD.getAlignment(),
943 Section.getEntrySize());
947 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
950 bool HasRelocationAddend)
951 : MCObjectWriter(OS, IsLittleEndian)
953 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
956 ELFObjectWriter::~ELFObjectWriter() {
957 delete (ELFObjectWriterImpl*) Impl;
960 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
961 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
964 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
965 const MCAsmLayout &Layout,
966 const MCFragment *Fragment,
967 const MCFixup &Fixup, MCValue Target,
968 uint64_t &FixedValue) {
969 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
973 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
974 const MCAsmLayout &Layout) {
975 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);