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 const std::string &Name = SymbolData->getSymbol().getName();
68 return Name < RHS.SymbolData->getSymbol().getName();
72 /// @name Relocation Data
75 struct ELFRelocationEntry {
76 // Make these big enough for both 32-bit and 64-bit
81 // Support lexicographic sorting.
82 bool operator<(const ELFRelocationEntry &RE) const {
83 return RE.r_offset < r_offset;
87 llvm::DenseMap<const MCSectionData*,
88 std::vector<ELFRelocationEntry> > Relocations;
89 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
92 /// @name Symbol Table Data
95 SmallString<256> StringTable;
96 std::vector<ELFSymbolData> LocalSymbolData;
97 std::vector<ELFSymbolData> ExternalSymbolData;
98 std::vector<ELFSymbolData> UndefinedSymbolData;
102 ELFObjectWriter *Writer;
106 // This holds the current offset into the object file.
109 unsigned Is64Bit : 1;
111 bool HasRelocationAddend;
113 // This holds the symbol table index of the last local symbol.
114 unsigned LastLocalSymbolIndex;
115 // This holds the .strtab section index.
116 unsigned StringTableIndex;
118 unsigned ShstrtabIndex;
121 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
123 : Writer(_Writer), OS(Writer->getStream()), FileOff(0),
124 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend) {
127 void Write8(uint8_t Value) { Writer->Write8(Value); }
128 void Write16(uint16_t Value) { Writer->Write16(Value); }
129 void Write32(uint32_t Value) { Writer->Write32(Value); }
130 void Write64(uint64_t Value) { Writer->Write64(Value); }
131 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
132 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
133 Writer->WriteBytes(Str, ZeroFillSize);
136 void WriteWord(uint64_t W) {
144 void String8(char *buf, uint8_t Value) {
148 void StringLE16(char *buf, uint16_t Value) {
149 buf[0] = char(Value >> 0);
150 buf[1] = char(Value >> 8);
153 void StringLE32(char *buf, uint32_t Value) {
154 buf[0] = char(Value >> 0);
155 buf[1] = char(Value >> 8);
156 buf[2] = char(Value >> 16);
157 buf[3] = char(Value >> 24);
160 void StringLE64(char *buf, uint64_t Value) {
161 buf[0] = char(Value >> 0);
162 buf[1] = char(Value >> 8);
163 buf[2] = char(Value >> 16);
164 buf[3] = char(Value >> 24);
165 buf[4] = char(Value >> 32);
166 buf[5] = char(Value >> 40);
167 buf[6] = char(Value >> 48);
168 buf[7] = char(Value >> 56);
171 void StringBE16(char *buf ,uint16_t Value) {
172 buf[0] = char(Value >> 8);
173 buf[1] = char(Value >> 0);
176 void StringBE32(char *buf, uint32_t Value) {
177 buf[0] = char(Value >> 24);
178 buf[1] = char(Value >> 16);
179 buf[2] = char(Value >> 8);
180 buf[3] = char(Value >> 0);
183 void StringBE64(char *buf, uint64_t Value) {
184 buf[0] = char(Value >> 56);
185 buf[1] = char(Value >> 48);
186 buf[2] = char(Value >> 40);
187 buf[3] = char(Value >> 32);
188 buf[4] = char(Value >> 24);
189 buf[5] = char(Value >> 16);
190 buf[6] = char(Value >> 8);
191 buf[7] = char(Value >> 0);
194 void String16(char *buf, uint16_t Value) {
195 if (Writer->isLittleEndian())
196 StringLE16(buf, Value);
198 StringBE16(buf, Value);
201 void String32(char *buf, uint32_t Value) {
202 if (Writer->isLittleEndian())
203 StringLE32(buf, Value);
205 StringBE32(buf, Value);
208 void String64(char *buf, uint64_t Value) {
209 if (Writer->isLittleEndian())
210 StringLE64(buf, Value);
212 StringBE64(buf, Value);
215 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
217 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
218 uint64_t value, uint64_t size,
219 uint8_t other, uint16_t shndx);
221 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
222 const MCAsmLayout &Layout);
224 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
225 const MCAsmLayout &Layout);
227 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
228 const MCFragment *Fragment, const MCFixup &Fixup,
229 MCValue Target, uint64_t &FixedValue);
231 // XXX-PERF: this should be cached
232 uint64_t getNumOfLocalSymbols(const MCAssembler &Asm) {
233 std::vector<const MCSymbol*> Local;
236 for (MCAssembler::const_symbol_iterator it = Asm.symbol_begin(),
237 ie = Asm.symbol_end(); it != ie; ++it) {
238 const MCSymbol &Symbol = it->getSymbol();
240 // Ignore non-linker visible symbols.
241 if (!Asm.isSymbolLinkerVisible(Symbol))
244 if (it->isExternal() || Symbol.isUndefined())
253 uint64_t getSymbolIndexInSymbolTable(MCAssembler &Asm, const MCSymbol *S);
255 /// ComputeSymbolTable - Compute the symbol table data
257 /// \param StringTable [out] - The string table data.
258 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
260 void ComputeSymbolTable(MCAssembler &Asm);
262 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
263 const MCSectionData &SD);
265 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
266 for (MCAssembler::const_iterator it = Asm.begin(),
267 ie = Asm.end(); it != ie; ++it) {
268 WriteRelocation(Asm, Layout, *it);
272 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
274 void ExecutePostLayoutBinding(MCAssembler &Asm) {}
276 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
277 uint64_t Address, uint64_t Offset,
278 uint64_t Size, uint32_t Link, uint32_t Info,
279 uint64_t Alignment, uint64_t EntrySize);
281 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
282 const MCSectionData *SD);
284 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
289 // Emit the ELF header.
290 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
291 unsigned NumberOfSections) {
297 // emitWord method behaves differently for ELF32 and ELF64, writing
298 // 4 bytes in the former and 8 in the latter.
300 Write8(0x7f); // e_ident[EI_MAG0]
301 Write8('E'); // e_ident[EI_MAG1]
302 Write8('L'); // e_ident[EI_MAG2]
303 Write8('F'); // e_ident[EI_MAG3]
305 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
308 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
310 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
311 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
312 Write8(0); // e_ident[EI_ABIVERSION]
314 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
316 Write16(ELF::ET_REL); // e_type
318 // FIXME: Make this configurable
319 Write16(ELF::EM_X86_64); // e_machine = target
321 Write32(ELF::EV_CURRENT); // e_version
322 WriteWord(0); // e_entry, no entry point in .o file
323 WriteWord(0); // e_phoff, no program header for .o
324 WriteWord(SectionDataSize + 64); // e_shoff = sec hdr table off in bytes
326 // FIXME: Make this configurable.
327 Write32(0); // e_flags = whatever the target wants
329 // e_ehsize = ELF header size
330 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
332 Write16(0); // e_phentsize = prog header entry size
333 Write16(0); // e_phnum = # prog header entries = 0
335 // e_shentsize = Section header entry size
336 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
338 // e_shnum = # of section header ents
339 Write16(NumberOfSections);
341 // e_shstrndx = Section # of '.shstrtab'
342 Write16(ShstrtabIndex);
345 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
346 uint8_t info, uint64_t value,
347 uint64_t size, uint8_t other,
353 F->getContents() += StringRef(buf, 4); // st_name
356 F->getContents() += StringRef(buf, 1); // st_info
359 F->getContents() += StringRef(buf, 1); // st_other
361 String16(buf, shndx);
362 F->getContents() += StringRef(buf, 2); // st_shndx
364 String64(buf, value);
365 F->getContents() += StringRef(buf, 8); // st_value
368 F->getContents() += StringRef(buf, 8); // st_size
373 F->getContents() += StringRef(buf, 4); // st_name
375 String32(buf, value);
376 F->getContents() += StringRef(buf, 4); // st_value
379 F->getContents() += StringRef(buf, 4); // st_size
382 F->getContents() += StringRef(buf, 1); // st_info
385 F->getContents() += StringRef(buf, 1); // st_other
387 String16(buf, shndx);
388 F->getContents() += StringRef(buf, 2); // st_shndx
392 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
393 const MCAsmLayout &Layout) {
394 MCSymbolData &Data = *MSD.SymbolData;
395 uint8_t Info = (Data.getFlags() & 0xff);
396 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
401 if (Data.isCommon() && Data.isExternal())
402 Value = Data.getCommonAlignment();
404 ESize = Data.getSize();
405 if (Data.getSize()) {
407 if (ESize->getKind() == MCExpr::Binary) {
408 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
410 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
412 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
414 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
416 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
417 Value = Layout.getSymbolAddress(&Data);
419 } else if (ESize->getKind() == MCExpr::Constant) {
420 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
422 assert(0 && "Unsupported size expression");
426 // Write out the symbol table entry
427 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
428 Size, Other, MSD.SectionIndex);
431 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
432 const MCAssembler &Asm,
433 const MCAsmLayout &Layout) {
434 // The string table must be emitted first because we need the index
435 // into the string table for all the symbol names.
436 assert(StringTable.size() && "Missing string table");
438 // FIXME: Make sure the start of the symbol table is aligned.
440 // The first entry is the undefined symbol entry.
441 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
442 F->getContents().append(EntrySize, '\x00');
444 // Write the symbol table entries.
445 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
446 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
447 ELFSymbolData &MSD = LocalSymbolData[i];
448 WriteSymbol(F, MSD, Layout);
451 // Write out a symbol table entry for each section.
452 // leaving out the just added .symtab which is at
455 for (MCAssembler::const_iterator it = Asm.begin(),
456 ie = Asm.end(); it != ie; ++it, ++Index) {
457 const MCSectionELF &Section =
458 static_cast<const MCSectionELF&>(it->getSection());
459 // Leave out relocations so we don't have indexes within
460 // the relocations messed up
461 if (Section.getType() == ELF::SHT_RELA)
463 if (Index == Asm.size())
465 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
466 LastLocalSymbolIndex++;
469 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
470 ELFSymbolData &MSD = ExternalSymbolData[i];
471 MCSymbolData &Data = *MSD.SymbolData;
472 assert((Data.getFlags() & ELF_STB_Global) &&
473 "External symbol requires STB_GLOBAL flag");
474 WriteSymbol(F, MSD, Layout);
475 if (Data.getFlags() & ELF_STB_Local)
476 LastLocalSymbolIndex++;
479 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
480 ELFSymbolData &MSD = UndefinedSymbolData[i];
481 MCSymbolData &Data = *MSD.SymbolData;
482 Data.setFlags(Data.getFlags() | ELF_STB_Global);
483 WriteSymbol(F, MSD, Layout);
484 if (Data.getFlags() & ELF_STB_Local)
485 LastLocalSymbolIndex++;
489 // FIXME: this is currently X86_64 only
490 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
491 const MCAsmLayout &Layout,
492 const MCFragment *Fragment,
493 const MCFixup &Fixup,
495 uint64_t &FixedValue) {
496 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
497 ELFRelocationEntry ERE;
498 struct ELF::Elf64_Rela ERE64;
500 uint64_t FixupOffset =
501 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
507 Value = Target.getConstant();
509 if (Target.isAbsolute()) {
510 Type = ELF::R_X86_64_NONE;
513 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
514 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
515 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
518 Index = getSymbolIndexInSymbolTable(const_cast<MCAssembler &>(Asm), &Base->getSymbol());
520 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
524 MCFragment *F = SD.getFragment();
526 // Index of the section in .symtab against this symbol
527 // is being relocated + 2 (empty section + abs. symbols).
528 Index = SD.getFragment()->getParent()->getOrdinal() +
529 getNumOfLocalSymbols(Asm) + 1;
531 MCSectionData *FSD = F->getParent();
532 // Offset of the symbol in the section
533 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
541 // determine the type of the relocation
543 Type = ELF::R_X86_64_PC32;
545 switch ((unsigned)Fixup.getKind()) {
546 default: llvm_unreachable("invalid fixup kind!");
547 case FK_Data_8: Type = ELF::R_X86_64_64; break;
548 case X86::reloc_pcrel_4byte:
550 // check that the offset fits within a signed long
551 if (isInt<32>(Target.getConstant()))
552 Type = ELF::R_X86_64_32S;
554 Type = ELF::R_X86_64_32;
556 case FK_Data_2: Type = ELF::R_X86_64_16; break;
557 case X86::reloc_pcrel_1byte:
559 Type = ELF::R_X86_64_8;
566 ERE64.setSymbolAndType(Index, Type);
568 ERE.r_offset = FixupOffset;
569 ERE.r_info = ERE64.r_info;
570 if (HasRelocationAddend)
571 ERE.r_addend = Addend;
573 Relocations[Fragment->getParent()].push_back(ERE);
576 // XXX-PERF: this should be cached
577 uint64_t ELFObjectWriterImpl::getSymbolIndexInSymbolTable(MCAssembler &Asm,
579 std::vector<ELFSymbolData> Local;
580 std::vector<ELFSymbolData> External;
581 std::vector<ELFSymbolData> Undefined;
583 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
584 ie = Asm.symbol_end(); it != ie; ++it) {
585 const MCSymbol &Symbol = it->getSymbol();
587 // Ignore non-linker visible symbols.
588 if (!Asm.isSymbolLinkerVisible(Symbol))
591 if (it->isExternal() || Symbol.isUndefined())
597 Local.push_back(MSD);
599 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
600 ie = Asm.symbol_end(); it != ie; ++it) {
601 const MCSymbol &Symbol = it->getSymbol();
603 // Ignore non-linker visible symbols.
604 if (!Asm.isSymbolLinkerVisible(Symbol))
607 if (!it->isExternal() && !Symbol.isUndefined())
613 if (Symbol.isUndefined())
614 Undefined.push_back(MSD);
616 External.push_back(MSD);
619 array_pod_sort(Local.begin(), Local.end());
620 array_pod_sort(External.begin(), External.end());
621 array_pod_sort(Undefined.begin(), Undefined.end());
623 for (unsigned i = 0, e = Local.size(); i != e; ++i)
624 if (&Local[i].SymbolData->getSymbol() == S)
625 return i + /* empty symbol */ 1;
626 for (unsigned i = 0, e = External.size(); i != e; ++i)
627 if (&External[i].SymbolData->getSymbol() == S)
628 return i + Local.size() + Asm.size() + /* empty symbol */ 1;
629 for (unsigned i = 0, e = Undefined.size(); i != e; ++i)
630 if (&Undefined[i].SymbolData->getSymbol() == S)
631 return i + Local.size() + External.size() + Asm.size() + /* empty symbol */ 1;
633 llvm_unreachable("Cannot find symbol which should exist!");
636 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
637 // Build section lookup table.
638 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
640 for (MCAssembler::iterator it = Asm.begin(),
641 ie = Asm.end(); it != ie; ++it, ++Index)
642 SectionIndexMap[&it->getSection()] = Index;
644 // Index 0 is always the empty string.
645 StringMap<uint64_t> StringIndexMap;
646 StringTable += '\x00';
648 // Add the data for local symbols.
649 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
650 ie = Asm.symbol_end(); it != ie; ++it) {
651 const MCSymbol &Symbol = it->getSymbol();
653 // Ignore non-linker visible symbols.
654 if (!Asm.isSymbolLinkerVisible(Symbol))
657 if (it->isExternal() || Symbol.isUndefined())
660 uint64_t &Entry = StringIndexMap[Symbol.getName()];
662 Entry = StringTable.size();
663 StringTable += Symbol.getName();
664 StringTable += '\x00';
669 MSD.StringIndex = Entry;
671 if (Symbol.isAbsolute()) {
672 MSD.SectionIndex = ELF::SHN_ABS;
673 LocalSymbolData.push_back(MSD);
675 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
676 assert(MSD.SectionIndex && "Invalid section index!");
677 LocalSymbolData.push_back(MSD);
681 // Now add non-local symbols.
682 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
683 ie = Asm.symbol_end(); it != ie; ++it) {
684 const MCSymbol &Symbol = it->getSymbol();
686 // Ignore non-linker visible symbols.
687 if (!Asm.isSymbolLinkerVisible(Symbol))
690 if (!it->isExternal() && !Symbol.isUndefined())
693 uint64_t &Entry = StringIndexMap[Symbol.getName()];
695 Entry = StringTable.size();
696 StringTable += Symbol.getName();
697 StringTable += '\x00';
702 MSD.StringIndex = Entry;
704 if (Symbol.isUndefined()) {
705 MSD.SectionIndex = ELF::SHN_UNDEF;
706 // XXX: for some reason we dont Emit* this
707 it->setFlags(it->getFlags() | ELF_STB_Global);
708 UndefinedSymbolData.push_back(MSD);
709 } else if (Symbol.isAbsolute()) {
710 MSD.SectionIndex = ELF::SHN_ABS;
711 ExternalSymbolData.push_back(MSD);
712 } else if (it->isCommon()) {
713 MSD.SectionIndex = ELF::SHN_COMMON;
714 ExternalSymbolData.push_back(MSD);
716 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
717 assert(MSD.SectionIndex && "Invalid section index!");
718 ExternalSymbolData.push_back(MSD);
722 // Symbols are required to be in lexicographic order.
723 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
724 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
725 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
727 // Set the symbol indices. Local symbols must come before all other
728 // symbols with non-local bindings.
730 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
731 LocalSymbolData[i].SymbolData->setIndex(Index++);
732 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
733 ExternalSymbolData[i].SymbolData->setIndex(Index++);
734 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
735 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
738 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
739 const MCSectionData &SD) {
740 if (!Relocations[&SD].empty()) {
741 MCContext &Ctx = Asm.getContext();
742 const MCSection *RelaSection;
743 const MCSectionELF &Section =
744 static_cast<const MCSectionELF&>(SD.getSection());
746 const StringRef SectionName = Section.getSectionName();
747 std::string RelaSectionName = ".rela";
749 RelaSectionName += SectionName;
750 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
752 RelaSection = Ctx.getELFSection(RelaSectionName, ELF::SHT_RELA, 0,
753 SectionKind::getReadOnly(),
756 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
757 RelaSD.setAlignment(1);
759 MCDataFragment *F = new MCDataFragment(&RelaSD);
761 WriteRelocationsFragment(Asm, F, &SD);
763 Asm.AddSectionToTheEnd(RelaSD, Layout);
767 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
768 uint64_t Flags, uint64_t Address,
769 uint64_t Offset, uint64_t Size,
770 uint32_t Link, uint32_t Info,
772 uint64_t EntrySize) {
773 Write32(Name); // sh_name: index into string table
774 Write32(Type); // sh_type
775 WriteWord(Flags); // sh_flags
776 WriteWord(Address); // sh_addr
777 WriteWord(Offset); // sh_offset
778 WriteWord(Size); // sh_size
779 Write32(Link); // sh_link
780 Write32(Info); // sh_info
781 WriteWord(Alignment); // sh_addralign
782 WriteWord(EntrySize); // sh_entsize
785 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
787 const MCSectionData *SD) {
788 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
789 // sort by the r_offset just like gnu as does
790 array_pod_sort(Relocs.begin(), Relocs.end());
792 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
793 ELFRelocationEntry entry = Relocs[e - i - 1];
795 unsigned WordSize = Is64Bit ? 8 : 4;
796 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
797 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
799 if (HasRelocationAddend)
800 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
804 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
805 MCAsmLayout &Layout) {
806 MCContext &Ctx = Asm.getContext();
809 WriteRelocations(Asm, Layout);
811 const MCSection *SymtabSection;
812 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
814 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
815 SectionKind::getReadOnly(),
818 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
820 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
822 F = new MCDataFragment(&SymtabSD);
825 WriteSymbolTable(F, Asm, Layout);
826 Asm.AddSectionToTheEnd(SymtabSD, Layout);
828 const MCSection *StrtabSection;
829 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
830 SectionKind::getReadOnly(), false);
832 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
833 StrtabSD.setAlignment(1);
835 // FIXME: This isn't right. If the sections get rearranged this will
836 // be wrong. We need a proper lookup.
837 StringTableIndex = Asm.size();
839 F = new MCDataFragment(&StrtabSD);
840 F->getContents().append(StringTable.begin(), StringTable.end());
841 Asm.AddSectionToTheEnd(StrtabSD, Layout);
843 const MCSection *ShstrtabSection;
844 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
845 SectionKind::getReadOnly(), false);
847 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
848 ShstrtabSD.setAlignment(1);
850 F = new MCDataFragment(&ShstrtabSD);
852 // FIXME: This isn't right. If the sections get rearranged this will
853 // be wrong. We need a proper lookup.
854 ShstrtabIndex = Asm.size();
856 // Section header string table.
858 // The first entry of a string table holds a null character so skip
861 F->getContents() += '\x00';
863 for (MCAssembler::const_iterator it = Asm.begin(),
864 ie = Asm.end(); it != ie; ++it) {
865 const MCSectionELF &Section =
866 static_cast<const MCSectionELF&>(it->getSection());
868 // Remember the index into the string table so we can write it
869 // into the sh_name field of the section header table.
870 SectionStringTableIndex[&it->getSection()] = Index;
872 Index += Section.getSectionName().size() + 1;
873 F->getContents() += Section.getSectionName();
874 F->getContents() += '\x00';
877 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
880 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
881 const MCAsmLayout &Layout) {
882 // Compute symbol table information.
883 ComputeSymbolTable(const_cast<MCAssembler&>(Asm));
885 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
886 const_cast<MCAsmLayout&>(Layout));
888 // Add 1 for the null section.
889 unsigned NumSections = Asm.size() + 1;
891 uint64_t SectionDataSize = 0;
893 for (MCAssembler::const_iterator it = Asm.begin(),
894 ie = Asm.end(); it != ie; ++it) {
895 const MCSectionData &SD = *it;
897 // Get the size of the section in the output file (including padding).
898 uint64_t Size = Layout.getSectionFileSize(&SD);
899 SectionDataSize += Size;
902 // Write out the ELF header ...
903 WriteHeader(SectionDataSize, NumSections);
904 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
906 // ... then all of the sections ...
907 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
909 for (MCAssembler::const_iterator it = Asm.begin(),
910 ie = Asm.end(); it != ie; ++it) {
911 // Remember the offset into the file for this section.
912 SectionOffsetMap[&it->getSection()] = FileOff;
914 const MCSectionData &SD = *it;
915 FileOff += Layout.getSectionFileSize(&SD);
917 Asm.WriteSectionData(it, Layout, Writer);
920 // ... and then the section header table.
921 // Should we align the section header table?
923 // Null section first.
924 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
926 for (MCAssembler::const_iterator it = Asm.begin(),
927 ie = Asm.end(); it != ie; ++it) {
928 const MCSectionData &SD = *it;
929 const MCSectionELF &Section =
930 static_cast<const MCSectionELF&>(SD.getSection());
932 uint64_t sh_link = 0;
933 uint64_t sh_info = 0;
935 switch(Section.getType()) {
936 case ELF::SHT_DYNAMIC:
937 sh_link = SectionStringTableIndex[&it->getSection()];
942 case ELF::SHT_RELA: {
943 const MCSection *SymtabSection;
944 const MCSection *InfoSection;
945 StringRef SectionName;
946 const MCSectionData *SymtabSD;
947 const MCSectionData *InfoSD;
949 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
950 SectionKind::getReadOnly(),
952 SymtabSD = &Asm.getSectionData(*SymtabSection);
953 // we have to count the empty section in too
954 sh_link = SymtabSD->getLayoutOrder() + 1;
956 SectionName = Section.getSectionName();
957 SectionName = SectionName.slice(5, SectionName.size());
958 InfoSection = Asm.getContext().getELFSection(SectionName,
959 ELF::SHT_PROGBITS, 0,
960 SectionKind::getReadOnly(),
962 InfoSD = &Asm.getSectionData(*InfoSection);
963 sh_info = InfoSD->getLayoutOrder() + 1;
967 case ELF::SHT_SYMTAB:
968 case ELF::SHT_DYNSYM:
969 sh_link = StringTableIndex;
970 sh_info = LastLocalSymbolIndex;
973 case ELF::SHT_PROGBITS:
974 case ELF::SHT_STRTAB:
975 case ELF::SHT_NOBITS:
981 case ELF::SHT_SYMTAB_SHNDX:
983 assert(0 && "FIXME: sh_type value not supported!");
987 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
988 Section.getType(), Section.getFlags(),
989 Layout.getSectionAddress(&SD),
990 SectionOffsetMap.lookup(&SD.getSection()),
991 Layout.getSectionSize(&SD), sh_link,
992 sh_info, SD.getAlignment(),
993 Section.getEntrySize());
997 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1000 bool HasRelocationAddend)
1001 : MCObjectWriter(OS, IsLittleEndian)
1003 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
1006 ELFObjectWriter::~ELFObjectWriter() {
1007 delete (ELFObjectWriterImpl*) Impl;
1010 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1011 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1014 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1015 const MCAsmLayout &Layout,
1016 const MCFragment *Fragment,
1017 const MCFixup &Fixup, MCValue Target,
1018 uint64_t &FixedValue) {
1019 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1020 Target, FixedValue);
1023 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1024 const MCAsmLayout &Layout) {
1025 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);