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"
37 static unsigned GetType(const MCSymbolData &SD) {
38 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
39 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
40 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
41 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
42 Type == ELF::STT_TLS);
48 class ELFObjectWriterImpl {
49 static bool isFixupKindX86PCRel(unsigned Kind) {
53 case X86::reloc_pcrel_1byte:
54 case X86::reloc_pcrel_4byte:
55 case X86::reloc_riprel_4byte:
56 case X86::reloc_riprel_4byte_movq_load:
61 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
62 return Kind == X86::reloc_riprel_4byte ||
63 Kind == X86::reloc_riprel_4byte_movq_load;
67 /// ELFSymbolData - Helper struct for containing some precomputed information
69 struct ELFSymbolData {
70 MCSymbolData *SymbolData;
72 uint32_t SectionIndex;
74 // Support lexicographic sorting.
75 bool operator<(const ELFSymbolData &RHS) const {
76 if (GetType(*SymbolData) == ELF::STT_FILE)
78 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
80 return SymbolData->getSymbol().getName() <
81 RHS.SymbolData->getSymbol().getName();
85 /// @name Relocation Data
88 struct ELFRelocationEntry {
89 // Make these big enough for both 32-bit and 64-bit
94 // Support lexicographic sorting.
95 bool operator<(const ELFRelocationEntry &RE) const {
96 return RE.r_offset < r_offset;
100 llvm::DenseMap<const MCSectionData*,
101 std::vector<ELFRelocationEntry> > Relocations;
102 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
105 /// @name Symbol Table Data
108 SmallString<256> StringTable;
109 std::vector<ELFSymbolData> LocalSymbolData;
110 std::vector<ELFSymbolData> ExternalSymbolData;
111 std::vector<ELFSymbolData> UndefinedSymbolData;
115 ELFObjectWriter *Writer;
119 unsigned Is64Bit : 1;
121 bool HasRelocationAddend;
123 Triple::OSType OSType;
125 // This holds the symbol table index of the last local symbol.
126 unsigned LastLocalSymbolIndex;
127 // This holds the .strtab section index.
128 unsigned StringTableIndex;
130 unsigned ShstrtabIndex;
133 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
134 bool _HasRelAddend, Triple::OSType _OSType)
135 : Writer(_Writer), OS(Writer->getStream()),
136 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
140 void Write8(uint8_t Value) { Writer->Write8(Value); }
141 void Write16(uint16_t Value) { Writer->Write16(Value); }
142 void Write32(uint32_t Value) { Writer->Write32(Value); }
143 //void Write64(uint64_t Value) { Writer->Write64(Value); }
144 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
145 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
146 // Writer->WriteBytes(Str, ZeroFillSize);
149 void WriteWord(uint64_t W) {
156 void String8(char *buf, uint8_t Value) {
160 void StringLE16(char *buf, uint16_t Value) {
161 buf[0] = char(Value >> 0);
162 buf[1] = char(Value >> 8);
165 void StringLE32(char *buf, uint32_t Value) {
166 StringLE16(buf, uint16_t(Value >> 0));
167 StringLE16(buf + 2, uint16_t(Value >> 16));
170 void StringLE64(char *buf, uint64_t Value) {
171 StringLE32(buf, uint32_t(Value >> 0));
172 StringLE32(buf + 4, uint32_t(Value >> 32));
175 void StringBE16(char *buf ,uint16_t Value) {
176 buf[0] = char(Value >> 8);
177 buf[1] = char(Value >> 0);
180 void StringBE32(char *buf, uint32_t Value) {
181 StringBE16(buf, uint16_t(Value >> 16));
182 StringBE16(buf + 2, uint16_t(Value >> 0));
185 void StringBE64(char *buf, uint64_t Value) {
186 StringBE32(buf, uint32_t(Value >> 32));
187 StringBE32(buf + 4, uint32_t(Value >> 0));
190 void String16(char *buf, uint16_t Value) {
191 if (Writer->isLittleEndian())
192 StringLE16(buf, Value);
194 StringBE16(buf, Value);
197 void String32(char *buf, uint32_t Value) {
198 if (Writer->isLittleEndian())
199 StringLE32(buf, Value);
201 StringBE32(buf, Value);
204 void String64(char *buf, uint64_t Value) {
205 if (Writer->isLittleEndian())
206 StringLE64(buf, Value);
208 StringBE64(buf, Value);
211 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
213 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
214 uint64_t value, uint64_t size,
215 uint8_t other, uint16_t shndx);
217 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
218 const MCAsmLayout &Layout);
220 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
221 const MCAsmLayout &Layout,
222 unsigned NumRegularSections);
224 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
225 const MCFragment *Fragment, const MCFixup &Fixup,
226 MCValue Target, uint64_t &FixedValue);
228 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
231 /// ComputeSymbolTable - Compute the symbol table data
233 /// \param StringTable [out] - The string table data.
234 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
236 void ComputeSymbolTable(MCAssembler &Asm);
238 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
239 const MCSectionData &SD);
241 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
242 for (MCAssembler::const_iterator it = Asm.begin(),
243 ie = Asm.end(); it != ie; ++it) {
244 WriteRelocation(Asm, Layout, *it);
248 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
250 void ExecutePostLayoutBinding(MCAssembler &Asm) {
251 // Compute symbol table information.
252 ComputeSymbolTable(Asm);
255 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
256 uint64_t Address, uint64_t Offset,
257 uint64_t Size, uint32_t Link, uint32_t Info,
258 uint64_t Alignment, uint64_t EntrySize);
260 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
261 const MCSectionData *SD);
263 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
268 // Emit the ELF header.
269 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
270 unsigned NumberOfSections) {
276 // emitWord method behaves differently for ELF32 and ELF64, writing
277 // 4 bytes in the former and 8 in the latter.
279 Write8(0x7f); // e_ident[EI_MAG0]
280 Write8('E'); // e_ident[EI_MAG1]
281 Write8('L'); // e_ident[EI_MAG2]
282 Write8('F'); // e_ident[EI_MAG3]
284 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
287 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
289 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
292 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
293 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
294 default: Write8(ELF::ELFOSABI_NONE); break;
296 Write8(0); // e_ident[EI_ABIVERSION]
298 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
300 Write16(ELF::ET_REL); // e_type
302 // FIXME: Make this configurable
303 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
305 Write32(ELF::EV_CURRENT); // e_version
306 WriteWord(0); // e_entry, no entry point in .o file
307 WriteWord(0); // e_phoff, no program header for .o
308 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
309 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
311 // FIXME: Make this configurable.
312 Write32(0); // e_flags = whatever the target wants
314 // e_ehsize = ELF header size
315 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
317 Write16(0); // e_phentsize = prog header entry size
318 Write16(0); // e_phnum = # prog header entries = 0
320 // e_shentsize = Section header entry size
321 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
323 // e_shnum = # of section header ents
324 Write16(NumberOfSections);
326 // e_shstrndx = Section # of '.shstrtab'
327 Write16(ShstrtabIndex);
330 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
331 uint8_t info, uint64_t value,
332 uint64_t size, uint8_t other,
338 F->getContents() += StringRef(buf, 4); // st_name
341 F->getContents() += StringRef(buf, 1); // st_info
344 F->getContents() += StringRef(buf, 1); // st_other
346 String16(buf, shndx);
347 F->getContents() += StringRef(buf, 2); // st_shndx
349 String64(buf, value);
350 F->getContents() += StringRef(buf, 8); // st_value
353 F->getContents() += StringRef(buf, 8); // st_size
358 F->getContents() += StringRef(buf, 4); // st_name
360 String32(buf, value);
361 F->getContents() += StringRef(buf, 4); // st_value
364 F->getContents() += StringRef(buf, 4); // st_size
367 F->getContents() += StringRef(buf, 1); // st_info
370 F->getContents() += StringRef(buf, 1); // st_other
372 String16(buf, shndx);
373 F->getContents() += StringRef(buf, 2); // st_shndx
377 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
378 const MCAsmLayout &Layout) {
379 MCSymbolData &Data = *MSD.SymbolData;
380 uint8_t Info = (Data.getFlags() & 0xff);
381 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
386 if (Data.isCommon() && Data.isExternal())
387 Value = Data.getCommonAlignment();
389 assert(!(Data.isCommon() && !Data.isExternal()));
391 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
392 if (MCFragment *FF = Data.getFragment())
393 Value = Layout.getSymbolAddress(&Data) -
394 Layout.getSectionAddress(FF->getParent());
396 ESize = Data.getSize();
397 if (Data.getSize()) {
399 if (ESize->getKind() == MCExpr::Binary) {
400 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
402 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
404 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
406 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
408 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
410 } else if (ESize->getKind() == MCExpr::Constant) {
411 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
413 assert(0 && "Unsupported size expression");
417 // Write out the symbol table entry
418 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
419 Size, Other, MSD.SectionIndex);
422 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
423 const MCAssembler &Asm,
424 const MCAsmLayout &Layout,
425 unsigned NumRegularSections) {
426 // The string table must be emitted first because we need the index
427 // into the string table for all the symbol names.
428 assert(StringTable.size() && "Missing string table");
430 // FIXME: Make sure the start of the symbol table is aligned.
432 // The first entry is the undefined symbol entry.
433 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
434 F->getContents().append(EntrySize, '\x00');
436 // Write the symbol table entries.
437 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
438 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
439 ELFSymbolData &MSD = LocalSymbolData[i];
440 WriteSymbol(F, MSD, Layout);
443 // Write out a symbol table entry for each regular section.
445 for (MCAssembler::const_iterator it = Asm.begin();
446 Index <= NumRegularSections; ++it, ++Index) {
447 const MCSectionELF &Section =
448 static_cast<const MCSectionELF&>(it->getSection());
449 // Leave out relocations so we don't have indexes within
450 // the relocations messed up
451 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
453 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
454 LastLocalSymbolIndex++;
457 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
458 ELFSymbolData &MSD = ExternalSymbolData[i];
459 MCSymbolData &Data = *MSD.SymbolData;
460 assert((Data.getFlags() & ELF_STB_Global) &&
461 "External symbol requires STB_GLOBAL flag");
462 WriteSymbol(F, MSD, Layout);
463 if ((Data.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local)
464 LastLocalSymbolIndex++;
467 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
468 ELFSymbolData &MSD = UndefinedSymbolData[i];
469 MCSymbolData &Data = *MSD.SymbolData;
470 Data.setFlags(Data.getFlags() | ELF_STB_Global);
471 WriteSymbol(F, MSD, Layout);
472 if ((Data.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local)
473 LastLocalSymbolIndex++;
477 // FIXME: this is currently X86/X86_64 only
478 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
479 const MCAsmLayout &Layout,
480 const MCFragment *Fragment,
481 const MCFixup &Fixup,
483 uint64_t &FixedValue) {
486 int64_t Value = Target.getConstant();
488 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
489 if (!Target.isAbsolute()) {
490 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
491 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
492 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
493 MCFragment *F = SD.getFragment();
495 // Avoid relocations for cases like jumps and calls in the same file.
496 if (Symbol->isDefined() && !SD.isExternal() &&
498 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
499 uint64_t FixupAddr = Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
500 FixedValue = Layout.getSymbolAddress(&SD) + Target.getConstant() - FixupAddr;
505 if (F && (!Symbol->isInSection() || SD.isCommon()) && !SD.isExternal()) {
506 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
508 MCSectionData *FSD = F->getParent();
509 // Offset of the symbol in the section
510 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
512 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
514 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
516 // Compensate for the addend on i386.
521 // Index of the section in .symtab against this symbol
522 // is being relocated + 2 (empty section + abs. symbols).
523 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
525 MCSectionData *FSD = F->getParent();
526 // Offset of the symbol in the section
527 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
537 // determine the type of the relocation
541 Type = ELF::R_X86_64_PC32;
543 switch ((unsigned)Fixup.getKind()) {
544 default: llvm_unreachable("invalid fixup kind!");
545 case FK_Data_8: Type = ELF::R_X86_64_64; break;
546 case X86::reloc_pcrel_4byte:
548 // check that the offset fits within a signed long
549 if (Target.getConstant() < 0) {
550 assert(isInt<32>(Target.getConstant()));
551 Type = ELF::R_X86_64_32S;
553 assert(isUInt<32>(Target.getConstant()));
554 Type = ELF::R_X86_64_32;
557 case FK_Data_2: Type = ELF::R_X86_64_16; break;
558 case X86::reloc_pcrel_1byte:
559 case FK_Data_1: Type = ELF::R_X86_64_8; break;
564 Type = ELF::R_386_PC32;
566 switch ((unsigned)Fixup.getKind()) {
567 default: llvm_unreachable("invalid fixup kind!");
568 case X86::reloc_pcrel_4byte:
569 case FK_Data_4: Type = ELF::R_386_32; break;
570 case FK_Data_2: Type = ELF::R_386_16; break;
571 case X86::reloc_pcrel_1byte:
572 case FK_Data_1: Type = ELF::R_386_8; break;
577 ELFRelocationEntry ERE;
580 struct ELF::Elf64_Rela ERE64;
581 ERE64.setSymbolAndType(Index, Type);
582 ERE.r_info = ERE64.r_info;
584 struct ELF::Elf32_Rela ERE32;
585 ERE32.setSymbolAndType(Index, Type);
586 ERE.r_info = ERE32.r_info;
589 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
591 if (HasRelocationAddend)
592 ERE.r_addend = Addend;
594 ERE.r_addend = 0; // Silence compiler warning.
596 Relocations[Fragment->getParent()].push_back(ERE);
600 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
602 MCSymbolData &SD = Asm.getSymbolData(*S);
605 if (!SD.isExternal() && !S->isUndefined())
606 return SD.getIndex() + /* empty symbol */ 1;
608 // External or undefined symbol.
609 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
612 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
613 // Build section lookup table.
614 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
616 for (MCAssembler::iterator it = Asm.begin(),
617 ie = Asm.end(); it != ie; ++it, ++Index)
618 SectionIndexMap[&it->getSection()] = Index;
620 // Index 0 is always the empty string.
621 StringMap<uint64_t> StringIndexMap;
622 StringTable += '\x00';
624 // Add the data for 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.isAbsolute()) {
648 MSD.SectionIndex = ELF::SHN_ABS;
649 LocalSymbolData.push_back(MSD);
651 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
652 assert(MSD.SectionIndex && "Invalid section index!");
653 LocalSymbolData.push_back(MSD);
657 // Now add non-local symbols.
658 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
659 ie = Asm.symbol_end(); it != ie; ++it) {
660 const MCSymbol &Symbol = it->getSymbol();
662 // Ignore non-linker visible symbols.
663 if (!Asm.isSymbolLinkerVisible(Symbol))
666 if (!it->isExternal() && !Symbol.isUndefined())
669 uint64_t &Entry = StringIndexMap[Symbol.getName()];
671 Entry = StringTable.size();
672 StringTable += Symbol.getName();
673 StringTable += '\x00';
678 MSD.StringIndex = Entry;
680 if (it->isCommon()) {
681 MSD.SectionIndex = ELF::SHN_COMMON;
682 ExternalSymbolData.push_back(MSD);
683 } else if (Symbol.isUndefined()) {
684 MSD.SectionIndex = ELF::SHN_UNDEF;
685 // XXX: for some reason we dont Emit* this
686 it->setFlags(it->getFlags() | ELF_STB_Global);
687 UndefinedSymbolData.push_back(MSD);
688 } else if (Symbol.isAbsolute()) {
689 MSD.SectionIndex = ELF::SHN_ABS;
690 ExternalSymbolData.push_back(MSD);
692 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
693 assert(MSD.SectionIndex && "Invalid section index!");
694 ExternalSymbolData.push_back(MSD);
698 // Symbols are required to be in lexicographic order.
699 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
700 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
701 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
703 // Set the symbol indices. Local symbols must come before all other
704 // symbols with non-local bindings.
706 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
707 LocalSymbolData[i].SymbolData->setIndex(Index++);
708 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
709 ExternalSymbolData[i].SymbolData->setIndex(Index++);
710 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
711 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
714 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
715 const MCSectionData &SD) {
716 if (!Relocations[&SD].empty()) {
717 MCContext &Ctx = Asm.getContext();
718 const MCSection *RelaSection;
719 const MCSectionELF &Section =
720 static_cast<const MCSectionELF&>(SD.getSection());
722 const StringRef SectionName = Section.getSectionName();
723 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
724 RelaSectionName += SectionName;
727 if (HasRelocationAddend)
728 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
730 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
732 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
733 ELF::SHT_RELA : ELF::SHT_REL, 0,
734 SectionKind::getReadOnly(),
737 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
738 RelaSD.setAlignment(Is64Bit ? 8 : 4);
740 MCDataFragment *F = new MCDataFragment(&RelaSD);
742 WriteRelocationsFragment(Asm, F, &SD);
744 Asm.AddSectionToTheEnd(RelaSD, Layout);
748 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
749 uint64_t Flags, uint64_t Address,
750 uint64_t Offset, uint64_t Size,
751 uint32_t Link, uint32_t Info,
753 uint64_t EntrySize) {
754 Write32(Name); // sh_name: index into string table
755 Write32(Type); // sh_type
756 WriteWord(Flags); // sh_flags
757 WriteWord(Address); // sh_addr
758 WriteWord(Offset); // sh_offset
759 WriteWord(Size); // sh_size
760 Write32(Link); // sh_link
761 Write32(Info); // sh_info
762 WriteWord(Alignment); // sh_addralign
763 WriteWord(EntrySize); // sh_entsize
766 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
768 const MCSectionData *SD) {
769 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
770 // sort by the r_offset just like gnu as does
771 array_pod_sort(Relocs.begin(), Relocs.end());
773 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
774 ELFRelocationEntry entry = Relocs[e - i - 1];
779 String64(buf, entry.r_offset);
780 F->getContents() += StringRef(buf, 8);
782 String64(buf, entry.r_info);
783 F->getContents() += StringRef(buf, 8);
785 if (HasRelocationAddend) {
786 String64(buf, entry.r_addend);
787 F->getContents() += StringRef(buf, 8);
792 String32(buf, entry.r_offset);
793 F->getContents() += StringRef(buf, 4);
795 String32(buf, entry.r_info);
796 F->getContents() += StringRef(buf, 4);
798 if (HasRelocationAddend) {
799 String32(buf, entry.r_addend);
800 F->getContents() += StringRef(buf, 4);
806 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
807 MCAsmLayout &Layout) {
808 MCContext &Ctx = Asm.getContext();
811 WriteRelocations(Asm, Layout);
813 const MCSection *SymtabSection;
814 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
816 unsigned NumRegularSections = Asm.size();
818 // We construct .shstrtab, .symtab and .strtab is this order to match gnu as.
819 const MCSection *ShstrtabSection;
820 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
821 SectionKind::getReadOnly(), false);
822 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
823 ShstrtabSD.setAlignment(1);
824 ShstrtabIndex = Asm.size();
826 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
827 SectionKind::getReadOnly(),
829 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
830 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
832 const MCSection *StrtabSection;
833 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
834 SectionKind::getReadOnly(), false);
835 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
836 StrtabSD.setAlignment(1);
837 StringTableIndex = Asm.size();
841 F = new MCDataFragment(&SymtabSD);
842 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
843 Asm.AddSectionToTheEnd(SymtabSD, Layout);
845 F = new MCDataFragment(&StrtabSD);
846 F->getContents().append(StringTable.begin(), StringTable.end());
847 Asm.AddSectionToTheEnd(StrtabSD, Layout);
849 F = new MCDataFragment(&ShstrtabSD);
851 // Section header string table.
853 // The first entry of a string table holds a null character so skip
856 F->getContents() += '\x00';
858 for (MCAssembler::const_iterator it = Asm.begin(),
859 ie = Asm.end(); it != ie; ++it) {
860 const MCSectionELF &Section =
861 static_cast<const MCSectionELF&>(it->getSection());
863 // Remember the index into the string table so we can write it
864 // into the sh_name field of the section header table.
865 SectionStringTableIndex[&it->getSection()] = Index;
867 Index += Section.getSectionName().size() + 1;
868 F->getContents() += Section.getSectionName();
869 F->getContents() += '\x00';
872 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
875 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
876 const MCAsmLayout &Layout) {
877 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
878 const_cast<MCAsmLayout&>(Layout));
880 // Add 1 for the null section.
881 unsigned NumSections = Asm.size() + 1;
882 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
883 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
884 uint64_t FileOff = HeaderSize;
886 for (MCAssembler::const_iterator it = Asm.begin(),
887 ie = Asm.end(); it != ie; ++it) {
888 const MCSectionData &SD = *it;
890 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
892 // Get the size of the section in the output file (including padding).
893 uint64_t Size = Layout.getSectionFileSize(&SD);
898 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
900 // Write out the ELF header ...
901 WriteHeader(FileOff - HeaderSize, NumSections);
903 FileOff = HeaderSize;
905 // ... then all of the sections ...
906 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
908 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
911 for (MCAssembler::const_iterator it = Asm.begin(),
912 ie = Asm.end(); it != ie; ++it) {
913 const MCSectionData &SD = *it;
915 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
919 // Remember the offset into the file for this section.
920 SectionOffsetMap[&it->getSection()] = FileOff;
921 SectionIndexMap[&it->getSection()] = Index++;
923 FileOff += Layout.getSectionFileSize(&SD);
925 Asm.WriteSectionData(it, Layout, Writer);
928 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
932 // ... and then the section header table.
933 // Should we align the section header table?
935 // Null section first.
936 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
938 for (MCAssembler::const_iterator it = Asm.begin(),
939 ie = Asm.end(); it != ie; ++it) {
940 const MCSectionData &SD = *it;
941 const MCSectionELF &Section =
942 static_cast<const MCSectionELF&>(SD.getSection());
944 uint64_t sh_link = 0;
945 uint64_t sh_info = 0;
947 switch(Section.getType()) {
948 case ELF::SHT_DYNAMIC:
949 sh_link = SectionStringTableIndex[&it->getSection()];
954 case ELF::SHT_RELA: {
955 const MCSection *SymtabSection;
956 const MCSection *InfoSection;
958 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
959 SectionKind::getReadOnly(),
961 sh_link = SectionIndexMap[SymtabSection];
963 // Remove ".rel" and ".rela" prefixes.
964 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
965 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
967 InfoSection = Asm.getContext().getELFSection(SectionName,
968 ELF::SHT_PROGBITS, 0,
969 SectionKind::getReadOnly(),
971 sh_info = SectionIndexMap[InfoSection];
975 case ELF::SHT_SYMTAB:
976 case ELF::SHT_DYNSYM:
977 sh_link = StringTableIndex;
978 sh_info = LastLocalSymbolIndex;
981 case ELF::SHT_PROGBITS:
982 case ELF::SHT_STRTAB:
983 case ELF::SHT_NOBITS:
990 case ELF::SHT_SYMTAB_SHNDX:
992 assert(0 && "FIXME: sh_type value not supported!");
996 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
997 Section.getType(), Section.getFlags(),
999 SectionOffsetMap.lookup(&SD.getSection()),
1000 Layout.getSectionSize(&SD), sh_link,
1001 sh_info, SD.getAlignment(),
1002 Section.getEntrySize());
1006 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1008 Triple::OSType OSType,
1009 bool IsLittleEndian,
1010 bool HasRelocationAddend)
1011 : MCObjectWriter(OS, IsLittleEndian)
1013 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1016 ELFObjectWriter::~ELFObjectWriter() {
1017 delete (ELFObjectWriterImpl*) Impl;
1020 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1021 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1024 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1025 const MCAsmLayout &Layout,
1026 const MCFragment *Fragment,
1027 const MCFixup &Fixup, MCValue Target,
1028 uint64_t &FixedValue) {
1029 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1030 Target, FixedValue);
1033 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1034 const MCAsmLayout &Layout) {
1035 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);