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 if (!Data.isCommon())
371 if (MCFragment *FF = Data.getFragment())
372 Value = Layout.getSymbolAddress(&Data) -
373 Layout.getSectionAddress(FF->getParent());
375 ESize = Data.getSize();
376 if (Data.getSize()) {
378 if (ESize->getKind() == MCExpr::Binary) {
379 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
381 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
383 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
385 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
387 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
389 } else if (ESize->getKind() == MCExpr::Constant) {
390 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
392 assert(0 && "Unsupported size expression");
396 // Write out the symbol table entry
397 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
398 Size, Other, MSD.SectionIndex);
401 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
402 const MCAssembler &Asm,
403 const MCAsmLayout &Layout) {
404 // The string table must be emitted first because we need the index
405 // into the string table for all the symbol names.
406 assert(StringTable.size() && "Missing string table");
408 // FIXME: Make sure the start of the symbol table is aligned.
410 // The first entry is the undefined symbol entry.
411 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
412 F->getContents().append(EntrySize, '\x00');
414 // Write the symbol table entries.
415 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
416 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
417 ELFSymbolData &MSD = LocalSymbolData[i];
418 WriteSymbol(F, MSD, Layout);
421 // Write out a symbol table entry for each section.
422 // leaving out the just added .symtab which is at
425 for (MCAssembler::const_iterator it = Asm.begin(),
426 ie = Asm.end(); it != ie; ++it, ++Index) {
427 const MCSectionELF &Section =
428 static_cast<const MCSectionELF&>(it->getSection());
429 // Leave out relocations so we don't have indexes within
430 // the relocations messed up
431 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
433 if (Index == Asm.size())
435 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
436 LastLocalSymbolIndex++;
439 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
440 ELFSymbolData &MSD = ExternalSymbolData[i];
441 MCSymbolData &Data = *MSD.SymbolData;
442 assert((Data.getFlags() & ELF_STB_Global) &&
443 "External symbol requires STB_GLOBAL flag");
444 WriteSymbol(F, MSD, Layout);
445 if (Data.getFlags() & ELF_STB_Local)
446 LastLocalSymbolIndex++;
449 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
450 ELFSymbolData &MSD = UndefinedSymbolData[i];
451 MCSymbolData &Data = *MSD.SymbolData;
452 Data.setFlags(Data.getFlags() | ELF_STB_Global);
453 WriteSymbol(F, MSD, Layout);
454 if (Data.getFlags() & ELF_STB_Local)
455 LastLocalSymbolIndex++;
459 // FIXME: this is currently X86/X86_64 only
460 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
461 const MCAsmLayout &Layout,
462 const MCFragment *Fragment,
463 const MCFixup &Fixup,
465 uint64_t &FixedValue) {
468 int64_t Value = Target.getConstant();
470 if (!Target.isAbsolute()) {
471 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
472 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
473 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
474 MCFragment *F = SD.getFragment();
477 if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
478 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
479 Value += Layout.getSymbolAddress(&SD);
481 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
483 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
485 // Compensate for the addend on i386.
490 // Index of the section in .symtab against this symbol
491 // is being relocated + 2 (empty section + abs. symbols).
492 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
494 MCSectionData *FSD = F->getParent();
495 // Offset of the symbol in the section
496 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
506 // determine the type of the relocation
507 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
511 Type = ELF::R_X86_64_PC32;
513 switch ((unsigned)Fixup.getKind()) {
514 default: llvm_unreachable("invalid fixup kind!");
515 case FK_Data_8: Type = ELF::R_X86_64_64; break;
516 case X86::reloc_pcrel_4byte:
518 // check that the offset fits within a signed long
519 if (isInt<32>(Target.getConstant()))
520 Type = ELF::R_X86_64_32S;
522 Type = ELF::R_X86_64_32;
524 case FK_Data_2: Type = ELF::R_X86_64_16; break;
525 case X86::reloc_pcrel_1byte:
526 case FK_Data_1: Type = ELF::R_X86_64_8; break;
531 Type = ELF::R_386_PC32;
533 switch ((unsigned)Fixup.getKind()) {
534 default: llvm_unreachable("invalid fixup kind!");
535 case X86::reloc_pcrel_4byte:
536 case FK_Data_4: Type = ELF::R_386_32; break;
537 case FK_Data_2: Type = ELF::R_386_16; break;
538 case X86::reloc_pcrel_1byte:
539 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 = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
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 MCSymbolData &SD = Asm.getSymbolData(*S);
572 if (!SD.isExternal() && !S->isUndefined())
573 return SD.getIndex() + /* empty symbol */ 1;
575 // External or undefined symbol.
576 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
579 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
580 // Build section lookup table.
581 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
583 for (MCAssembler::iterator it = Asm.begin(),
584 ie = Asm.end(); it != ie; ++it, ++Index)
585 SectionIndexMap[&it->getSection()] = Index;
587 // Index 0 is always the empty string.
588 StringMap<uint64_t> StringIndexMap;
589 StringTable += '\x00';
591 // Add the data for local symbols.
592 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
593 ie = Asm.symbol_end(); it != ie; ++it) {
594 const MCSymbol &Symbol = it->getSymbol();
596 // Ignore non-linker visible symbols.
597 if (!Asm.isSymbolLinkerVisible(Symbol))
600 if (it->isExternal() || Symbol.isUndefined())
603 uint64_t &Entry = StringIndexMap[Symbol.getName()];
605 Entry = StringTable.size();
606 StringTable += Symbol.getName();
607 StringTable += '\x00';
612 MSD.StringIndex = Entry;
614 if (Symbol.isAbsolute()) {
615 MSD.SectionIndex = ELF::SHN_ABS;
616 LocalSymbolData.push_back(MSD);
618 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
619 assert(MSD.SectionIndex && "Invalid section index!");
620 LocalSymbolData.push_back(MSD);
624 // Now add non-local symbols.
625 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
626 ie = Asm.symbol_end(); it != ie; ++it) {
627 const MCSymbol &Symbol = it->getSymbol();
629 // Ignore non-linker visible symbols.
630 if (!Asm.isSymbolLinkerVisible(Symbol))
633 if (!it->isExternal() && !Symbol.isUndefined())
636 uint64_t &Entry = StringIndexMap[Symbol.getName()];
638 Entry = StringTable.size();
639 StringTable += Symbol.getName();
640 StringTable += '\x00';
645 MSD.StringIndex = Entry;
647 if (Symbol.isUndefined()) {
648 MSD.SectionIndex = ELF::SHN_UNDEF;
649 // XXX: for some reason we dont Emit* this
650 it->setFlags(it->getFlags() | ELF_STB_Global);
651 UndefinedSymbolData.push_back(MSD);
652 } else if (Symbol.isAbsolute()) {
653 MSD.SectionIndex = ELF::SHN_ABS;
654 ExternalSymbolData.push_back(MSD);
655 } else if (it->isCommon()) {
656 MSD.SectionIndex = ELF::SHN_COMMON;
657 ExternalSymbolData.push_back(MSD);
659 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
660 assert(MSD.SectionIndex && "Invalid section index!");
661 ExternalSymbolData.push_back(MSD);
665 // Symbols are required to be in lexicographic order.
666 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
667 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
668 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
670 // Set the symbol indices. Local symbols must come before all other
671 // symbols with non-local bindings.
673 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
674 LocalSymbolData[i].SymbolData->setIndex(Index++);
675 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
676 ExternalSymbolData[i].SymbolData->setIndex(Index++);
677 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
678 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
681 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
682 const MCSectionData &SD) {
683 if (!Relocations[&SD].empty()) {
684 MCContext &Ctx = Asm.getContext();
685 const MCSection *RelaSection;
686 const MCSectionELF &Section =
687 static_cast<const MCSectionELF&>(SD.getSection());
689 const StringRef SectionName = Section.getSectionName();
690 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
691 RelaSectionName += SectionName;
694 if (HasRelocationAddend)
695 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
697 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
699 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
700 ELF::SHT_RELA : ELF::SHT_REL, 0,
701 SectionKind::getReadOnly(),
704 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
705 RelaSD.setAlignment(1);
707 MCDataFragment *F = new MCDataFragment(&RelaSD);
709 WriteRelocationsFragment(Asm, F, &SD);
711 Asm.AddSectionToTheEnd(RelaSD, Layout);
715 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
716 uint64_t Flags, uint64_t Address,
717 uint64_t Offset, uint64_t Size,
718 uint32_t Link, uint32_t Info,
720 uint64_t EntrySize) {
721 Write32(Name); // sh_name: index into string table
722 Write32(Type); // sh_type
723 WriteWord(Flags); // sh_flags
724 WriteWord(Address); // sh_addr
725 WriteWord(Offset); // sh_offset
726 WriteWord(Size); // sh_size
727 Write32(Link); // sh_link
728 Write32(Info); // sh_info
729 WriteWord(Alignment); // sh_addralign
730 WriteWord(EntrySize); // sh_entsize
733 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
735 const MCSectionData *SD) {
736 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
737 // sort by the r_offset just like gnu as does
738 array_pod_sort(Relocs.begin(), Relocs.end());
740 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
741 ELFRelocationEntry entry = Relocs[e - i - 1];
743 unsigned WordSize = Is64Bit ? 8 : 4;
744 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
745 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
747 if (HasRelocationAddend)
748 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
752 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
753 MCAsmLayout &Layout) {
754 MCContext &Ctx = Asm.getContext();
757 WriteRelocations(Asm, Layout);
759 const MCSection *SymtabSection;
760 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
762 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
763 SectionKind::getReadOnly(),
766 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
768 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
770 F = new MCDataFragment(&SymtabSD);
773 WriteSymbolTable(F, Asm, Layout);
774 Asm.AddSectionToTheEnd(SymtabSD, Layout);
776 const MCSection *StrtabSection;
777 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
778 SectionKind::getReadOnly(), false);
780 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
781 StrtabSD.setAlignment(1);
783 // FIXME: This isn't right. If the sections get rearranged this will
784 // be wrong. We need a proper lookup.
785 StringTableIndex = Asm.size();
787 F = new MCDataFragment(&StrtabSD);
788 F->getContents().append(StringTable.begin(), StringTable.end());
789 Asm.AddSectionToTheEnd(StrtabSD, Layout);
791 const MCSection *ShstrtabSection;
792 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
793 SectionKind::getReadOnly(), false);
795 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
796 ShstrtabSD.setAlignment(1);
798 F = new MCDataFragment(&ShstrtabSD);
800 // FIXME: This isn't right. If the sections get rearranged this will
801 // be wrong. We need a proper lookup.
802 ShstrtabIndex = Asm.size();
804 // Section header string table.
806 // The first entry of a string table holds a null character so skip
809 F->getContents() += '\x00';
811 for (MCAssembler::const_iterator it = Asm.begin(),
812 ie = Asm.end(); it != ie; ++it) {
813 const MCSectionELF &Section =
814 static_cast<const MCSectionELF&>(it->getSection());
816 // Remember the index into the string table so we can write it
817 // into the sh_name field of the section header table.
818 SectionStringTableIndex[&it->getSection()] = Index;
820 Index += Section.getSectionName().size() + 1;
821 F->getContents() += Section.getSectionName();
822 F->getContents() += '\x00';
825 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
828 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
829 const MCAsmLayout &Layout) {
830 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
831 const_cast<MCAsmLayout&>(Layout));
833 // Add 1 for the null section.
834 unsigned NumSections = Asm.size() + 1;
836 uint64_t SectionDataSize = 0;
838 for (MCAssembler::const_iterator it = Asm.begin(),
839 ie = Asm.end(); it != ie; ++it) {
840 const MCSectionData &SD = *it;
842 // Get the size of the section in the output file (including padding).
843 uint64_t Size = Layout.getSectionFileSize(&SD);
844 SectionDataSize += Size;
847 // Write out the ELF header ...
848 WriteHeader(SectionDataSize, NumSections);
849 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
851 // ... then all of the sections ...
852 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
854 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
857 for (MCAssembler::const_iterator it = Asm.begin(),
858 ie = Asm.end(); it != ie; ++it) {
859 // Remember the offset into the file for this section.
860 SectionOffsetMap[&it->getSection()] = FileOff;
862 SectionIndexMap[&it->getSection()] = Index++;
864 const MCSectionData &SD = *it;
865 FileOff += Layout.getSectionFileSize(&SD);
867 Asm.WriteSectionData(it, Layout, Writer);
870 // ... and then the section header table.
871 // Should we align the section header table?
873 // Null section first.
874 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
876 for (MCAssembler::const_iterator it = Asm.begin(),
877 ie = Asm.end(); it != ie; ++it) {
878 const MCSectionData &SD = *it;
879 const MCSectionELF &Section =
880 static_cast<const MCSectionELF&>(SD.getSection());
882 uint64_t sh_link = 0;
883 uint64_t sh_info = 0;
885 switch(Section.getType()) {
886 case ELF::SHT_DYNAMIC:
887 sh_link = SectionStringTableIndex[&it->getSection()];
892 case ELF::SHT_RELA: {
893 const MCSection *SymtabSection;
894 const MCSection *InfoSection;
896 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
897 SectionKind::getReadOnly(),
899 sh_link = SectionIndexMap[SymtabSection];
901 // Remove ".rel" and ".rela" prefixes.
902 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
903 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
905 InfoSection = Asm.getContext().getELFSection(SectionName,
906 ELF::SHT_PROGBITS, 0,
907 SectionKind::getReadOnly(),
909 sh_info = SectionIndexMap[InfoSection];
913 case ELF::SHT_SYMTAB:
914 case ELF::SHT_DYNSYM:
915 sh_link = StringTableIndex;
916 sh_info = LastLocalSymbolIndex;
919 case ELF::SHT_PROGBITS:
920 case ELF::SHT_STRTAB:
921 case ELF::SHT_NOBITS:
928 case ELF::SHT_SYMTAB_SHNDX:
930 assert(0 && "FIXME: sh_type value not supported!");
934 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
935 Section.getType(), Section.getFlags(),
936 Layout.getSectionAddress(&SD),
937 SectionOffsetMap.lookup(&SD.getSection()),
938 Layout.getSectionSize(&SD), sh_link,
939 sh_info, SD.getAlignment(),
940 Section.getEntrySize());
944 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
947 bool HasRelocationAddend)
948 : MCObjectWriter(OS, IsLittleEndian)
950 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
953 ELFObjectWriter::~ELFObjectWriter() {
954 delete (ELFObjectWriterImpl*) Impl;
957 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
958 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
961 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
962 const MCAsmLayout &Layout,
963 const MCFragment *Fragment,
964 const MCFixup &Fixup, MCValue Target,
965 uint64_t &FixedValue) {
966 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
970 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
971 const MCAsmLayout &Layout) {
972 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);