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 unsigned Is64Bit : 1;
108 bool HasRelocationAddend;
110 Triple::OSType OSType;
112 // This holds the symbol table index of the last local symbol.
113 unsigned LastLocalSymbolIndex;
114 // This holds the .strtab section index.
115 unsigned StringTableIndex;
117 unsigned ShstrtabIndex;
120 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
121 bool _HasRelAddend, Triple::OSType _OSType)
122 : Writer(_Writer), OS(Writer->getStream()),
123 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) {
143 void String8(char *buf, uint8_t Value) {
147 void StringLE16(char *buf, uint16_t Value) {
148 buf[0] = char(Value >> 0);
149 buf[1] = char(Value >> 8);
152 void StringLE32(char *buf, uint32_t Value) {
153 StringLE16(buf, uint16_t(Value >> 0));
154 StringLE16(buf + 2, uint16_t(Value >> 16));
157 void StringLE64(char *buf, uint64_t Value) {
158 StringLE32(buf, uint32_t(Value >> 0));
159 StringLE32(buf + 4, uint32_t(Value >> 32));
162 void StringBE16(char *buf ,uint16_t Value) {
163 buf[0] = char(Value >> 8);
164 buf[1] = char(Value >> 0);
167 void StringBE32(char *buf, uint32_t Value) {
168 StringBE16(buf, uint16_t(Value >> 16));
169 StringBE16(buf + 2, uint16_t(Value >> 0));
172 void StringBE64(char *buf, uint64_t Value) {
173 StringBE32(buf, uint32_t(Value >> 32));
174 StringBE32(buf + 4, uint32_t(Value >> 0));
177 void String16(char *buf, uint16_t Value) {
178 if (Writer->isLittleEndian())
179 StringLE16(buf, Value);
181 StringBE16(buf, Value);
184 void String32(char *buf, uint32_t Value) {
185 if (Writer->isLittleEndian())
186 StringLE32(buf, Value);
188 StringBE32(buf, Value);
191 void String64(char *buf, uint64_t Value) {
192 if (Writer->isLittleEndian())
193 StringLE64(buf, Value);
195 StringBE64(buf, Value);
198 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
200 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
201 uint64_t value, uint64_t size,
202 uint8_t other, uint16_t shndx);
204 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
205 const MCAsmLayout &Layout);
207 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
208 const MCAsmLayout &Layout);
210 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
211 const MCFragment *Fragment, const MCFixup &Fixup,
212 MCValue Target, uint64_t &FixedValue);
214 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
217 /// ComputeSymbolTable - Compute the symbol table data
219 /// \param StringTable [out] - The string table data.
220 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
222 void ComputeSymbolTable(MCAssembler &Asm);
224 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
225 const MCSectionData &SD);
227 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
228 for (MCAssembler::const_iterator it = Asm.begin(),
229 ie = Asm.end(); it != ie; ++it) {
230 WriteRelocation(Asm, Layout, *it);
234 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
236 void ExecutePostLayoutBinding(MCAssembler &Asm) {
237 // Compute symbol table information.
238 ComputeSymbolTable(Asm);
241 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
242 uint64_t Address, uint64_t Offset,
243 uint64_t Size, uint32_t Link, uint32_t Info,
244 uint64_t Alignment, uint64_t EntrySize);
246 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
247 const MCSectionData *SD);
249 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
254 // Emit the ELF header.
255 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
256 unsigned NumberOfSections) {
262 // emitWord method behaves differently for ELF32 and ELF64, writing
263 // 4 bytes in the former and 8 in the latter.
265 Write8(0x7f); // e_ident[EI_MAG0]
266 Write8('E'); // e_ident[EI_MAG1]
267 Write8('L'); // e_ident[EI_MAG2]
268 Write8('F'); // e_ident[EI_MAG3]
270 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
273 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
275 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
278 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
279 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
280 default: Write8(ELF::ELFOSABI_NONE); break;
282 Write8(0); // e_ident[EI_ABIVERSION]
284 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
286 Write16(ELF::ET_REL); // e_type
288 // FIXME: Make this configurable
289 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
291 Write32(ELF::EV_CURRENT); // e_version
292 WriteWord(0); // e_entry, no entry point in .o file
293 WriteWord(0); // e_phoff, no program header for .o
294 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
295 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
297 // FIXME: Make this configurable.
298 Write32(0); // e_flags = whatever the target wants
300 // e_ehsize = ELF header size
301 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
303 Write16(0); // e_phentsize = prog header entry size
304 Write16(0); // e_phnum = # prog header entries = 0
306 // e_shentsize = Section header entry size
307 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
309 // e_shnum = # of section header ents
310 Write16(NumberOfSections);
312 // e_shstrndx = Section # of '.shstrtab'
313 Write16(ShstrtabIndex);
316 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
317 uint8_t info, uint64_t value,
318 uint64_t size, uint8_t other,
324 F->getContents() += StringRef(buf, 4); // st_name
327 F->getContents() += StringRef(buf, 1); // st_info
330 F->getContents() += StringRef(buf, 1); // st_other
332 String16(buf, shndx);
333 F->getContents() += StringRef(buf, 2); // st_shndx
335 String64(buf, value);
336 F->getContents() += StringRef(buf, 8); // st_value
339 F->getContents() += StringRef(buf, 8); // st_size
344 F->getContents() += StringRef(buf, 4); // st_name
346 String32(buf, value);
347 F->getContents() += StringRef(buf, 4); // st_value
350 F->getContents() += StringRef(buf, 4); // st_size
353 F->getContents() += StringRef(buf, 1); // st_info
356 F->getContents() += StringRef(buf, 1); // st_other
358 String16(buf, shndx);
359 F->getContents() += StringRef(buf, 2); // st_shndx
363 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
364 const MCAsmLayout &Layout) {
365 MCSymbolData &Data = *MSD.SymbolData;
366 uint8_t Info = (Data.getFlags() & 0xff);
367 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
372 if (Data.isCommon() && Data.isExternal())
373 Value = Data.getCommonAlignment();
375 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
376 if (MCFragment *FF = Data.getFragment())
377 Value = Layout.getSymbolAddress(&Data) -
378 Layout.getSectionAddress(FF->getParent());
380 ESize = Data.getSize();
381 if (Data.getSize()) {
383 if (ESize->getKind() == MCExpr::Binary) {
384 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
386 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
388 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
390 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
392 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
394 } else if (ESize->getKind() == MCExpr::Constant) {
395 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
397 assert(0 && "Unsupported size expression");
401 // Write out the symbol table entry
402 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
403 Size, Other, MSD.SectionIndex);
406 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
407 const MCAssembler &Asm,
408 const MCAsmLayout &Layout) {
409 // The string table must be emitted first because we need the index
410 // into the string table for all the symbol names.
411 assert(StringTable.size() && "Missing string table");
413 // FIXME: Make sure the start of the symbol table is aligned.
415 // The first entry is the undefined symbol entry.
416 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
417 F->getContents().append(EntrySize, '\x00');
419 // Write the symbol table entries.
420 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
421 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
422 ELFSymbolData &MSD = LocalSymbolData[i];
423 WriteSymbol(F, MSD, Layout);
426 // Write out a symbol table entry for each section.
427 // leaving out the just added .symtab which is at
430 for (MCAssembler::const_iterator it = Asm.begin(),
431 ie = Asm.end(); it != ie; ++it, ++Index) {
432 const MCSectionELF &Section =
433 static_cast<const MCSectionELF&>(it->getSection());
434 // Leave out relocations so we don't have indexes within
435 // the relocations messed up
436 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
438 if (Index == Asm.size())
440 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
441 LastLocalSymbolIndex++;
444 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
445 ELFSymbolData &MSD = ExternalSymbolData[i];
446 MCSymbolData &Data = *MSD.SymbolData;
447 assert((Data.getFlags() & ELF_STB_Global) &&
448 "External symbol requires STB_GLOBAL flag");
449 WriteSymbol(F, MSD, Layout);
450 if ((Data.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local)
451 LastLocalSymbolIndex++;
454 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
455 ELFSymbolData &MSD = UndefinedSymbolData[i];
456 MCSymbolData &Data = *MSD.SymbolData;
457 Data.setFlags(Data.getFlags() | ELF_STB_Global);
458 WriteSymbol(F, MSD, Layout);
459 if ((Data.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local)
460 LastLocalSymbolIndex++;
464 // FIXME: this is currently X86/X86_64 only
465 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
466 const MCAsmLayout &Layout,
467 const MCFragment *Fragment,
468 const MCFixup &Fixup,
470 uint64_t &FixedValue) {
473 int64_t Value = Target.getConstant();
475 if (!Target.isAbsolute()) {
476 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
477 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
478 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
479 MCFragment *F = SD.getFragment();
482 if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
483 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
484 Value += Layout.getSymbolAddress(&SD);
486 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
488 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
490 // Compensate for the addend on i386.
495 // Index of the section in .symtab against this symbol
496 // is being relocated + 2 (empty section + abs. symbols).
497 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
499 MCSectionData *FSD = F->getParent();
500 // Offset of the symbol in the section
501 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
511 // determine the type of the relocation
512 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
516 Type = ELF::R_X86_64_PC32;
518 switch ((unsigned)Fixup.getKind()) {
519 default: llvm_unreachable("invalid fixup kind!");
520 case FK_Data_8: Type = ELF::R_X86_64_64; break;
521 case X86::reloc_pcrel_4byte:
523 // check that the offset fits within a signed long
524 if (isInt<32>(Target.getConstant()))
525 Type = ELF::R_X86_64_32S;
527 Type = ELF::R_X86_64_32;
529 case FK_Data_2: Type = ELF::R_X86_64_16; break;
530 case X86::reloc_pcrel_1byte:
531 case FK_Data_1: Type = ELF::R_X86_64_8; break;
536 Type = ELF::R_386_PC32;
538 switch ((unsigned)Fixup.getKind()) {
539 default: llvm_unreachable("invalid fixup kind!");
540 case X86::reloc_pcrel_4byte:
541 case FK_Data_4: Type = ELF::R_386_32; break;
542 case FK_Data_2: Type = ELF::R_386_16; break;
543 case X86::reloc_pcrel_1byte:
544 case FK_Data_1: Type = ELF::R_386_8; break;
549 ELFRelocationEntry ERE;
552 struct ELF::Elf64_Rela ERE64;
553 ERE64.setSymbolAndType(Index, Type);
554 ERE.r_info = ERE64.r_info;
556 struct ELF::Elf32_Rela ERE32;
557 ERE32.setSymbolAndType(Index, Type);
558 ERE.r_info = ERE32.r_info;
561 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
563 if (HasRelocationAddend)
564 ERE.r_addend = Addend;
566 ERE.r_addend = 0; // Silence compiler warning.
568 Relocations[Fragment->getParent()].push_back(ERE);
572 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
574 MCSymbolData &SD = Asm.getSymbolData(*S);
577 if (!SD.isExternal() && !S->isUndefined())
578 return SD.getIndex() + /* empty symbol */ 1;
580 // External or undefined symbol.
581 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
584 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
585 // Build section lookup table.
586 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
588 for (MCAssembler::iterator it = Asm.begin(),
589 ie = Asm.end(); it != ie; ++it, ++Index)
590 SectionIndexMap[&it->getSection()] = Index;
592 // Index 0 is always the empty string.
593 StringMap<uint64_t> StringIndexMap;
594 StringTable += '\x00';
596 // Add the data for local symbols.
597 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
598 ie = Asm.symbol_end(); it != ie; ++it) {
599 const MCSymbol &Symbol = it->getSymbol();
601 // Ignore non-linker visible symbols.
602 if (!Asm.isSymbolLinkerVisible(Symbol))
605 if (it->isExternal() || Symbol.isUndefined())
608 uint64_t &Entry = StringIndexMap[Symbol.getName()];
610 Entry = StringTable.size();
611 StringTable += Symbol.getName();
612 StringTable += '\x00';
617 MSD.StringIndex = Entry;
619 if (Symbol.isAbsolute()) {
620 MSD.SectionIndex = ELF::SHN_ABS;
621 LocalSymbolData.push_back(MSD);
623 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
624 assert(MSD.SectionIndex && "Invalid section index!");
625 LocalSymbolData.push_back(MSD);
629 // Now add non-local symbols.
630 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
631 ie = Asm.symbol_end(); it != ie; ++it) {
632 const MCSymbol &Symbol = it->getSymbol();
634 // Ignore non-linker visible symbols.
635 if (!Asm.isSymbolLinkerVisible(Symbol))
638 if (!it->isExternal() && !Symbol.isUndefined())
641 uint64_t &Entry = StringIndexMap[Symbol.getName()];
643 Entry = StringTable.size();
644 StringTable += Symbol.getName();
645 StringTable += '\x00';
650 MSD.StringIndex = Entry;
652 if (Symbol.isUndefined()) {
653 MSD.SectionIndex = ELF::SHN_UNDEF;
654 // XXX: for some reason we dont Emit* this
655 it->setFlags(it->getFlags() | ELF_STB_Global);
656 UndefinedSymbolData.push_back(MSD);
657 } else if (Symbol.isAbsolute()) {
658 MSD.SectionIndex = ELF::SHN_ABS;
659 ExternalSymbolData.push_back(MSD);
660 } else if (it->isCommon()) {
661 MSD.SectionIndex = ELF::SHN_COMMON;
662 ExternalSymbolData.push_back(MSD);
664 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
665 assert(MSD.SectionIndex && "Invalid section index!");
666 ExternalSymbolData.push_back(MSD);
670 // Symbols are required to be in lexicographic order.
671 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
672 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
673 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
675 // Set the symbol indices. Local symbols must come before all other
676 // symbols with non-local bindings.
678 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
679 LocalSymbolData[i].SymbolData->setIndex(Index++);
680 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
681 ExternalSymbolData[i].SymbolData->setIndex(Index++);
682 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
683 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
686 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
687 const MCSectionData &SD) {
688 if (!Relocations[&SD].empty()) {
689 MCContext &Ctx = Asm.getContext();
690 const MCSection *RelaSection;
691 const MCSectionELF &Section =
692 static_cast<const MCSectionELF&>(SD.getSection());
694 const StringRef SectionName = Section.getSectionName();
695 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
696 RelaSectionName += SectionName;
699 if (HasRelocationAddend)
700 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
702 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
704 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
705 ELF::SHT_RELA : ELF::SHT_REL, 0,
706 SectionKind::getReadOnly(),
709 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
710 RelaSD.setAlignment(Is64Bit ? 8 : 4);
712 MCDataFragment *F = new MCDataFragment(&RelaSD);
714 WriteRelocationsFragment(Asm, F, &SD);
716 Asm.AddSectionToTheEnd(RelaSD, Layout);
720 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
721 uint64_t Flags, uint64_t Address,
722 uint64_t Offset, uint64_t Size,
723 uint32_t Link, uint32_t Info,
725 uint64_t EntrySize) {
726 Write32(Name); // sh_name: index into string table
727 Write32(Type); // sh_type
728 WriteWord(Flags); // sh_flags
729 WriteWord(Address); // sh_addr
730 WriteWord(Offset); // sh_offset
731 WriteWord(Size); // sh_size
732 Write32(Link); // sh_link
733 Write32(Info); // sh_info
734 WriteWord(Alignment); // sh_addralign
735 WriteWord(EntrySize); // sh_entsize
738 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
740 const MCSectionData *SD) {
741 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
742 // sort by the r_offset just like gnu as does
743 array_pod_sort(Relocs.begin(), Relocs.end());
745 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
746 ELFRelocationEntry entry = Relocs[e - i - 1];
751 String64(buf, entry.r_offset);
752 F->getContents() += StringRef(buf, 8);
754 String64(buf, entry.r_info);
755 F->getContents() += StringRef(buf, 8);
757 if (HasRelocationAddend) {
758 String64(buf, entry.r_addend);
759 F->getContents() += StringRef(buf, 8);
764 String32(buf, entry.r_offset);
765 F->getContents() += StringRef(buf, 4);
767 String32(buf, entry.r_info);
768 F->getContents() += StringRef(buf, 4);
770 if (HasRelocationAddend) {
771 String32(buf, entry.r_addend);
772 F->getContents() += StringRef(buf, 4);
778 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
779 MCAsmLayout &Layout) {
780 MCContext &Ctx = Asm.getContext();
783 WriteRelocations(Asm, Layout);
785 const MCSection *SymtabSection;
786 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
788 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
789 SectionKind::getReadOnly(),
792 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
794 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
796 F = new MCDataFragment(&SymtabSD);
799 WriteSymbolTable(F, Asm, Layout);
800 Asm.AddSectionToTheEnd(SymtabSD, Layout);
802 const MCSection *StrtabSection;
803 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
804 SectionKind::getReadOnly(), false);
806 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
807 StrtabSD.setAlignment(1);
809 // FIXME: This isn't right. If the sections get rearranged this will
810 // be wrong. We need a proper lookup.
811 StringTableIndex = Asm.size();
813 F = new MCDataFragment(&StrtabSD);
814 F->getContents().append(StringTable.begin(), StringTable.end());
815 Asm.AddSectionToTheEnd(StrtabSD, Layout);
817 const MCSection *ShstrtabSection;
818 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
819 SectionKind::getReadOnly(), false);
821 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
822 ShstrtabSD.setAlignment(1);
824 F = new MCDataFragment(&ShstrtabSD);
826 // FIXME: This isn't right. If the sections get rearranged this will
827 // be wrong. We need a proper lookup.
828 ShstrtabIndex = Asm.size();
830 // Section header string table.
832 // The first entry of a string table holds a null character so skip
835 F->getContents() += '\x00';
837 for (MCAssembler::const_iterator it = Asm.begin(),
838 ie = Asm.end(); it != ie; ++it) {
839 const MCSectionELF &Section =
840 static_cast<const MCSectionELF&>(it->getSection());
842 // Remember the index into the string table so we can write it
843 // into the sh_name field of the section header table.
844 SectionStringTableIndex[&it->getSection()] = Index;
846 Index += Section.getSectionName().size() + 1;
847 F->getContents() += Section.getSectionName();
848 F->getContents() += '\x00';
851 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
854 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
855 const MCAsmLayout &Layout) {
856 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
857 const_cast<MCAsmLayout&>(Layout));
859 // Add 1 for the null section.
860 unsigned NumSections = Asm.size() + 1;
861 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
862 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
863 uint64_t FileOff = HeaderSize;
865 for (MCAssembler::const_iterator it = Asm.begin(),
866 ie = Asm.end(); it != ie; ++it) {
867 const MCSectionData &SD = *it;
869 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
871 // Get the size of the section in the output file (including padding).
872 uint64_t Size = Layout.getSectionFileSize(&SD);
877 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
879 // Write out the ELF header ...
880 WriteHeader(FileOff - HeaderSize, NumSections);
882 FileOff = HeaderSize;
884 // ... then all of the sections ...
885 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
887 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
890 for (MCAssembler::const_iterator it = Asm.begin(),
891 ie = Asm.end(); it != ie; ++it) {
892 const MCSectionData &SD = *it;
894 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
898 // Remember the offset into the file for this section.
899 SectionOffsetMap[&it->getSection()] = FileOff;
900 SectionIndexMap[&it->getSection()] = Index++;
902 FileOff += Layout.getSectionFileSize(&SD);
904 Asm.WriteSectionData(it, Layout, Writer);
907 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
911 // ... and then the section header table.
912 // Should we align the section header table?
914 // Null section first.
915 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
917 for (MCAssembler::const_iterator it = Asm.begin(),
918 ie = Asm.end(); it != ie; ++it) {
919 const MCSectionData &SD = *it;
920 const MCSectionELF &Section =
921 static_cast<const MCSectionELF&>(SD.getSection());
923 uint64_t sh_link = 0;
924 uint64_t sh_info = 0;
926 switch(Section.getType()) {
927 case ELF::SHT_DYNAMIC:
928 sh_link = SectionStringTableIndex[&it->getSection()];
933 case ELF::SHT_RELA: {
934 const MCSection *SymtabSection;
935 const MCSection *InfoSection;
937 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
938 SectionKind::getReadOnly(),
940 sh_link = SectionIndexMap[SymtabSection];
942 // Remove ".rel" and ".rela" prefixes.
943 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
944 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
946 InfoSection = Asm.getContext().getELFSection(SectionName,
947 ELF::SHT_PROGBITS, 0,
948 SectionKind::getReadOnly(),
950 sh_info = SectionIndexMap[InfoSection];
954 case ELF::SHT_SYMTAB:
955 case ELF::SHT_DYNSYM:
956 sh_link = StringTableIndex;
957 sh_info = LastLocalSymbolIndex;
960 case ELF::SHT_PROGBITS:
961 case ELF::SHT_STRTAB:
962 case ELF::SHT_NOBITS:
969 case ELF::SHT_SYMTAB_SHNDX:
971 assert(0 && "FIXME: sh_type value not supported!");
975 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
976 Section.getType(), Section.getFlags(),
977 Layout.getSectionAddress(&SD),
978 SectionOffsetMap.lookup(&SD.getSection()),
979 Layout.getSectionSize(&SD), sh_link,
980 sh_info, SD.getAlignment(),
981 Section.getEntrySize());
985 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
987 Triple::OSType OSType,
989 bool HasRelocationAddend)
990 : MCObjectWriter(OS, IsLittleEndian)
992 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
995 ELFObjectWriter::~ELFObjectWriter() {
996 delete (ELFObjectWriterImpl*) Impl;
999 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1000 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1003 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1004 const MCAsmLayout &Layout,
1005 const MCFragment *Fragment,
1006 const MCFixup &Fixup, MCValue Target,
1007 uint64_t &FixedValue) {
1008 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1009 Target, FixedValue);
1012 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1013 const MCAsmLayout &Layout) {
1014 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);