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) {
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]
276 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
277 Write8(0); // e_ident[EI_ABIVERSION]
279 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
281 Write16(ELF::ET_REL); // e_type
283 // FIXME: Make this configurable
284 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
286 Write32(ELF::EV_CURRENT); // e_version
287 WriteWord(0); // e_entry, no entry point in .o file
288 WriteWord(0); // e_phoff, no program header for .o
289 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
290 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
292 // FIXME: Make this configurable.
293 Write32(0); // e_flags = whatever the target wants
295 // e_ehsize = ELF header size
296 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
298 Write16(0); // e_phentsize = prog header entry size
299 Write16(0); // e_phnum = # prog header entries = 0
301 // e_shentsize = Section header entry size
302 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
304 // e_shnum = # of section header ents
305 Write16(NumberOfSections);
307 // e_shstrndx = Section # of '.shstrtab'
308 Write16(ShstrtabIndex);
311 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
312 uint8_t info, uint64_t value,
313 uint64_t size, uint8_t other,
319 F->getContents() += StringRef(buf, 4); // st_name
322 F->getContents() += StringRef(buf, 1); // st_info
325 F->getContents() += StringRef(buf, 1); // st_other
327 String16(buf, shndx);
328 F->getContents() += StringRef(buf, 2); // st_shndx
330 String64(buf, value);
331 F->getContents() += StringRef(buf, 8); // st_value
334 F->getContents() += StringRef(buf, 8); // st_size
339 F->getContents() += StringRef(buf, 4); // st_name
341 String32(buf, value);
342 F->getContents() += StringRef(buf, 4); // st_value
345 F->getContents() += StringRef(buf, 4); // st_size
348 F->getContents() += StringRef(buf, 1); // st_info
351 F->getContents() += StringRef(buf, 1); // st_other
353 String16(buf, shndx);
354 F->getContents() += StringRef(buf, 2); // st_shndx
358 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
359 const MCAsmLayout &Layout) {
360 MCSymbolData &Data = *MSD.SymbolData;
361 uint8_t Info = (Data.getFlags() & 0xff);
362 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
367 if (Data.isCommon() && Data.isExternal())
368 Value = Data.getCommonAlignment();
370 ESize = Data.getSize();
371 if (Data.getSize()) {
373 if (ESize->getKind() == MCExpr::Binary) {
374 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
376 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
378 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
380 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
382 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
383 Value = Layout.getSymbolAddress(&Data);
385 } else if (ESize->getKind() == MCExpr::Constant) {
386 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
387 MCFragment *F = Data.getFragment();
388 Value = Layout.getSymbolAddress(&Data) - Layout.getSectionAddress(F->getParent());
390 assert(0 && "Unsupported size expression");
394 // Write out the symbol table entry
395 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
396 Size, Other, MSD.SectionIndex);
399 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
400 const MCAssembler &Asm,
401 const MCAsmLayout &Layout) {
402 // The string table must be emitted first because we need the index
403 // into the string table for all the symbol names.
404 assert(StringTable.size() && "Missing string table");
406 // FIXME: Make sure the start of the symbol table is aligned.
408 // The first entry is the undefined symbol entry.
409 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
410 F->getContents().append(EntrySize, '\x00');
412 // Write the symbol table entries.
413 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
414 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
415 ELFSymbolData &MSD = LocalSymbolData[i];
416 WriteSymbol(F, MSD, Layout);
419 // Write out a symbol table entry for each section.
420 // leaving out the just added .symtab which is at
423 for (MCAssembler::const_iterator it = Asm.begin(),
424 ie = Asm.end(); it != ie; ++it, ++Index) {
425 const MCSectionELF &Section =
426 static_cast<const MCSectionELF&>(it->getSection());
427 // Leave out relocations so we don't have indexes within
428 // the relocations messed up
429 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
431 if (Index == Asm.size())
433 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
434 LastLocalSymbolIndex++;
437 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
438 ELFSymbolData &MSD = ExternalSymbolData[i];
439 MCSymbolData &Data = *MSD.SymbolData;
440 assert((Data.getFlags() & ELF_STB_Global) &&
441 "External symbol requires STB_GLOBAL flag");
442 WriteSymbol(F, MSD, Layout);
443 if (Data.getFlags() & ELF_STB_Local)
444 LastLocalSymbolIndex++;
447 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
448 ELFSymbolData &MSD = UndefinedSymbolData[i];
449 MCSymbolData &Data = *MSD.SymbolData;
450 Data.setFlags(Data.getFlags() | ELF_STB_Global);
451 WriteSymbol(F, MSD, Layout);
452 if (Data.getFlags() & ELF_STB_Local)
453 LastLocalSymbolIndex++;
457 // FIXME: this is currently X86/X86_64 only
458 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
459 const MCAsmLayout &Layout,
460 const MCFragment *Fragment,
461 const MCFixup &Fixup,
463 uint64_t &FixedValue) {
466 int64_t Value = Target.getConstant();
468 if (!Target.isAbsolute()) {
469 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
470 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
471 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
472 MCFragment *F = SD.getFragment();
475 if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
476 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
477 Value += Layout.getSymbolAddress(&SD);
479 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
481 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
483 // Compensate for the addend on i386.
488 // Index of the section in .symtab against this symbol
489 // is being relocated + 2 (empty section + abs. symbols).
490 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
492 MCSectionData *FSD = F->getParent();
493 // Offset of the symbol in the section
494 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
504 // determine the type of the relocation
505 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
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;
542 ELFRelocationEntry ERE;
545 struct ELF::Elf64_Rela ERE64;
546 ERE64.setSymbolAndType(Index, Type);
547 ERE.r_info = ERE64.r_info;
549 struct ELF::Elf32_Rela ERE32;
550 ERE32.setSymbolAndType(Index, Type);
551 ERE.r_info = ERE32.r_info;
554 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
556 if (HasRelocationAddend)
557 ERE.r_addend = Addend;
559 ERE.r_addend = 0; // Silence compiler warning.
561 Relocations[Fragment->getParent()].push_back(ERE);
565 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
567 MCSymbolData &SD = Asm.getSymbolData(*S);
570 if (!SD.isExternal() && !S->isUndefined())
571 return SD.getIndex() + /* empty symbol */ 1;
573 // External or undefined symbol.
574 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
577 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
578 // Build section lookup table.
579 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
581 for (MCAssembler::iterator it = Asm.begin(),
582 ie = Asm.end(); it != ie; ++it, ++Index)
583 SectionIndexMap[&it->getSection()] = Index;
585 // Index 0 is always the empty string.
586 StringMap<uint64_t> StringIndexMap;
587 StringTable += '\x00';
589 // Add the data for local symbols.
590 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
591 ie = Asm.symbol_end(); it != ie; ++it) {
592 const MCSymbol &Symbol = it->getSymbol();
594 // Ignore non-linker visible symbols.
595 if (!Asm.isSymbolLinkerVisible(Symbol))
598 if (it->isExternal() || Symbol.isUndefined())
601 uint64_t &Entry = StringIndexMap[Symbol.getName()];
603 Entry = StringTable.size();
604 StringTable += Symbol.getName();
605 StringTable += '\x00';
610 MSD.StringIndex = Entry;
612 if (Symbol.isAbsolute()) {
613 MSD.SectionIndex = ELF::SHN_ABS;
614 LocalSymbolData.push_back(MSD);
616 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
617 assert(MSD.SectionIndex && "Invalid section index!");
618 LocalSymbolData.push_back(MSD);
622 // Now add non-local symbols.
623 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
624 ie = Asm.symbol_end(); it != ie; ++it) {
625 const MCSymbol &Symbol = it->getSymbol();
627 // Ignore non-linker visible symbols.
628 if (!Asm.isSymbolLinkerVisible(Symbol))
631 if (!it->isExternal() && !Symbol.isUndefined())
634 uint64_t &Entry = StringIndexMap[Symbol.getName()];
636 Entry = StringTable.size();
637 StringTable += Symbol.getName();
638 StringTable += '\x00';
643 MSD.StringIndex = Entry;
645 if (Symbol.isUndefined()) {
646 MSD.SectionIndex = ELF::SHN_UNDEF;
647 // XXX: for some reason we dont Emit* this
648 it->setFlags(it->getFlags() | ELF_STB_Global);
649 UndefinedSymbolData.push_back(MSD);
650 } else if (Symbol.isAbsolute()) {
651 MSD.SectionIndex = ELF::SHN_ABS;
652 ExternalSymbolData.push_back(MSD);
653 } else if (it->isCommon()) {
654 MSD.SectionIndex = ELF::SHN_COMMON;
655 ExternalSymbolData.push_back(MSD);
657 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
658 assert(MSD.SectionIndex && "Invalid section index!");
659 ExternalSymbolData.push_back(MSD);
663 // Symbols are required to be in lexicographic order.
664 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
665 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
666 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
668 // Set the symbol indices. Local symbols must come before all other
669 // symbols with non-local bindings.
671 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
672 LocalSymbolData[i].SymbolData->setIndex(Index++);
673 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
674 ExternalSymbolData[i].SymbolData->setIndex(Index++);
675 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
676 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
679 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
680 const MCSectionData &SD) {
681 if (!Relocations[&SD].empty()) {
682 MCContext &Ctx = Asm.getContext();
683 const MCSection *RelaSection;
684 const MCSectionELF &Section =
685 static_cast<const MCSectionELF&>(SD.getSection());
687 const StringRef SectionName = Section.getSectionName();
688 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
689 RelaSectionName += SectionName;
692 if (HasRelocationAddend)
693 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
695 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
697 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
698 ELF::SHT_RELA : ELF::SHT_REL, 0,
699 SectionKind::getReadOnly(),
702 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
703 RelaSD.setAlignment(1);
705 MCDataFragment *F = new MCDataFragment(&RelaSD);
707 WriteRelocationsFragment(Asm, F, &SD);
709 Asm.AddSectionToTheEnd(RelaSD, Layout);
713 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
714 uint64_t Flags, uint64_t Address,
715 uint64_t Offset, uint64_t Size,
716 uint32_t Link, uint32_t Info,
718 uint64_t EntrySize) {
719 Write32(Name); // sh_name: index into string table
720 Write32(Type); // sh_type
721 WriteWord(Flags); // sh_flags
722 WriteWord(Address); // sh_addr
723 WriteWord(Offset); // sh_offset
724 WriteWord(Size); // sh_size
725 Write32(Link); // sh_link
726 Write32(Info); // sh_info
727 WriteWord(Alignment); // sh_addralign
728 WriteWord(EntrySize); // sh_entsize
731 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
733 const MCSectionData *SD) {
734 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
735 // sort by the r_offset just like gnu as does
736 array_pod_sort(Relocs.begin(), Relocs.end());
738 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
739 ELFRelocationEntry entry = Relocs[e - i - 1];
741 unsigned WordSize = Is64Bit ? 8 : 4;
742 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
743 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
745 if (HasRelocationAddend)
746 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
750 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
751 MCAsmLayout &Layout) {
752 MCContext &Ctx = Asm.getContext();
755 WriteRelocations(Asm, Layout);
757 const MCSection *SymtabSection;
758 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
760 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
761 SectionKind::getReadOnly(),
764 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
766 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
768 F = new MCDataFragment(&SymtabSD);
771 WriteSymbolTable(F, Asm, Layout);
772 Asm.AddSectionToTheEnd(SymtabSD, Layout);
774 const MCSection *StrtabSection;
775 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
776 SectionKind::getReadOnly(), false);
778 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
779 StrtabSD.setAlignment(1);
781 // FIXME: This isn't right. If the sections get rearranged this will
782 // be wrong. We need a proper lookup.
783 StringTableIndex = Asm.size();
785 F = new MCDataFragment(&StrtabSD);
786 F->getContents().append(StringTable.begin(), StringTable.end());
787 Asm.AddSectionToTheEnd(StrtabSD, Layout);
789 const MCSection *ShstrtabSection;
790 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
791 SectionKind::getReadOnly(), false);
793 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
794 ShstrtabSD.setAlignment(1);
796 F = new MCDataFragment(&ShstrtabSD);
798 // FIXME: This isn't right. If the sections get rearranged this will
799 // be wrong. We need a proper lookup.
800 ShstrtabIndex = Asm.size();
802 // Section header string table.
804 // The first entry of a string table holds a null character so skip
807 F->getContents() += '\x00';
809 for (MCAssembler::const_iterator it = Asm.begin(),
810 ie = Asm.end(); it != ie; ++it) {
811 const MCSectionELF &Section =
812 static_cast<const MCSectionELF&>(it->getSection());
814 // Remember the index into the string table so we can write it
815 // into the sh_name field of the section header table.
816 SectionStringTableIndex[&it->getSection()] = Index;
818 Index += Section.getSectionName().size() + 1;
819 F->getContents() += Section.getSectionName();
820 F->getContents() += '\x00';
823 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
826 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
827 const MCAsmLayout &Layout) {
828 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
829 const_cast<MCAsmLayout&>(Layout));
831 // Add 1 for the null section.
832 unsigned NumSections = Asm.size() + 1;
834 uint64_t SectionDataSize = 0;
836 for (MCAssembler::const_iterator it = Asm.begin(),
837 ie = Asm.end(); it != ie; ++it) {
838 const MCSectionData &SD = *it;
840 // Get the size of the section in the output file (including padding).
841 uint64_t Size = Layout.getSectionFileSize(&SD);
842 SectionDataSize += Size;
845 // Write out the ELF header ...
846 WriteHeader(SectionDataSize, NumSections);
847 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
849 // ... then all of the sections ...
850 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
852 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
855 for (MCAssembler::const_iterator it = Asm.begin(),
856 ie = Asm.end(); it != ie; ++it) {
857 // Remember the offset into the file for this section.
858 SectionOffsetMap[&it->getSection()] = FileOff;
860 SectionIndexMap[&it->getSection()] = Index++;
862 const MCSectionData &SD = *it;
863 FileOff += Layout.getSectionFileSize(&SD);
865 Asm.WriteSectionData(it, Layout, Writer);
868 // ... and then the section header table.
869 // Should we align the section header table?
871 // Null section first.
872 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
874 for (MCAssembler::const_iterator it = Asm.begin(),
875 ie = Asm.end(); it != ie; ++it) {
876 const MCSectionData &SD = *it;
877 const MCSectionELF &Section =
878 static_cast<const MCSectionELF&>(SD.getSection());
880 uint64_t sh_link = 0;
881 uint64_t sh_info = 0;
883 switch(Section.getType()) {
884 case ELF::SHT_DYNAMIC:
885 sh_link = SectionStringTableIndex[&it->getSection()];
890 case ELF::SHT_RELA: {
891 const MCSection *SymtabSection;
892 const MCSection *InfoSection;
894 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
895 SectionKind::getReadOnly(),
897 sh_link = SectionIndexMap[SymtabSection];
899 // Remove ".rel" and ".rela" prefixes.
900 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
901 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
903 InfoSection = Asm.getContext().getELFSection(SectionName,
904 ELF::SHT_PROGBITS, 0,
905 SectionKind::getReadOnly(),
907 sh_info = SectionIndexMap[InfoSection];
911 case ELF::SHT_SYMTAB:
912 case ELF::SHT_DYNSYM:
913 sh_link = StringTableIndex;
914 sh_info = LastLocalSymbolIndex;
917 case ELF::SHT_PROGBITS:
918 case ELF::SHT_STRTAB:
919 case ELF::SHT_NOBITS:
925 case ELF::SHT_SYMTAB_SHNDX:
927 assert(0 && "FIXME: sh_type value not supported!");
931 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
932 Section.getType(), Section.getFlags(),
933 Layout.getSectionAddress(&SD),
934 SectionOffsetMap.lookup(&SD.getSection()),
935 Layout.getSectionSize(&SD), sh_link,
936 sh_info, SD.getAlignment(),
937 Section.getEntrySize());
941 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
944 bool HasRelocationAddend)
945 : MCObjectWriter(OS, IsLittleEndian)
947 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
950 ELFObjectWriter::~ELFObjectWriter() {
951 delete (ELFObjectWriterImpl*) Impl;
954 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
955 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
958 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
959 const MCAsmLayout &Layout,
960 const MCFragment *Fragment,
961 const MCFixup &Fixup, MCValue Target,
962 uint64_t &FixedValue) {
963 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
967 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
968 const MCAsmLayout &Layout) {
969 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);