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(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // 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 + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
325 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
327 // FIXME: Make this configurable.
328 Write32(0); // e_flags = whatever the target wants
330 // e_ehsize = ELF header size
331 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
333 Write16(0); // e_phentsize = prog header entry size
334 Write16(0); // e_phnum = # prog header entries = 0
336 // e_shentsize = Section header entry size
337 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
339 // e_shnum = # of section header ents
340 Write16(NumberOfSections);
342 // e_shstrndx = Section # of '.shstrtab'
343 Write16(ShstrtabIndex);
346 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
347 uint8_t info, uint64_t value,
348 uint64_t size, uint8_t other,
354 F->getContents() += StringRef(buf, 4); // st_name
357 F->getContents() += StringRef(buf, 1); // st_info
360 F->getContents() += StringRef(buf, 1); // st_other
362 String16(buf, shndx);
363 F->getContents() += StringRef(buf, 2); // st_shndx
365 String64(buf, value);
366 F->getContents() += StringRef(buf, 8); // st_value
369 F->getContents() += StringRef(buf, 8); // st_size
374 F->getContents() += StringRef(buf, 4); // st_name
376 String32(buf, value);
377 F->getContents() += StringRef(buf, 4); // st_value
380 F->getContents() += StringRef(buf, 4); // st_size
383 F->getContents() += StringRef(buf, 1); // st_info
386 F->getContents() += StringRef(buf, 1); // st_other
388 String16(buf, shndx);
389 F->getContents() += StringRef(buf, 2); // st_shndx
393 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
394 const MCAsmLayout &Layout) {
395 MCSymbolData &Data = *MSD.SymbolData;
396 uint8_t Info = (Data.getFlags() & 0xff);
397 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
402 if (Data.isCommon() && Data.isExternal())
403 Value = Data.getCommonAlignment();
405 ESize = Data.getSize();
406 if (Data.getSize()) {
408 if (ESize->getKind() == MCExpr::Binary) {
409 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
411 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
413 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
415 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
417 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
418 Value = Layout.getSymbolAddress(&Data);
420 } else if (ESize->getKind() == MCExpr::Constant) {
421 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
423 assert(0 && "Unsupported size expression");
427 // Write out the symbol table entry
428 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
429 Size, Other, MSD.SectionIndex);
432 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
433 const MCAssembler &Asm,
434 const MCAsmLayout &Layout) {
435 // The string table must be emitted first because we need the index
436 // into the string table for all the symbol names.
437 assert(StringTable.size() && "Missing string table");
439 // FIXME: Make sure the start of the symbol table is aligned.
441 // The first entry is the undefined symbol entry.
442 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
443 F->getContents().append(EntrySize, '\x00');
445 // Write the symbol table entries.
446 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
447 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
448 ELFSymbolData &MSD = LocalSymbolData[i];
449 WriteSymbol(F, MSD, Layout);
452 // Write out a symbol table entry for each section.
453 // leaving out the just added .symtab which is at
456 for (MCAssembler::const_iterator it = Asm.begin(),
457 ie = Asm.end(); it != ie; ++it, ++Index) {
458 const MCSectionELF &Section =
459 static_cast<const MCSectionELF&>(it->getSection());
460 // Leave out relocations so we don't have indexes within
461 // the relocations messed up
462 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
464 if (Index == Asm.size())
466 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
467 LastLocalSymbolIndex++;
470 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
471 ELFSymbolData &MSD = ExternalSymbolData[i];
472 MCSymbolData &Data = *MSD.SymbolData;
473 assert((Data.getFlags() & ELF_STB_Global) &&
474 "External symbol requires STB_GLOBAL flag");
475 WriteSymbol(F, MSD, Layout);
476 if (Data.getFlags() & ELF_STB_Local)
477 LastLocalSymbolIndex++;
480 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
481 ELFSymbolData &MSD = UndefinedSymbolData[i];
482 MCSymbolData &Data = *MSD.SymbolData;
483 Data.setFlags(Data.getFlags() | ELF_STB_Global);
484 WriteSymbol(F, MSD, Layout);
485 if (Data.getFlags() & ELF_STB_Local)
486 LastLocalSymbolIndex++;
490 // FIXME: this is currently X86/X86_64 only
491 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
492 const MCAsmLayout &Layout,
493 const MCFragment *Fragment,
494 const MCFixup &Fixup,
496 uint64_t &FixedValue) {
497 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
499 uint64_t FixupOffset =
500 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
506 Value = Target.getConstant();
508 if (!Target.isAbsolute()) {
509 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
510 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
511 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
514 if (MCFragment *F = SD.getFragment())
515 Index = F->getParent()->getOrdinal() + getNumOfLocalSymbols(Asm) + 1;
517 Index = getSymbolIndexInSymbolTable(const_cast<MCAssembler &>(Asm), Symbol);
519 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
523 MCFragment *F = SD.getFragment();
525 // Index of the section in .symtab against this symbol
526 // is being relocated + 2 (empty section + abs. symbols).
527 Index = F->getParent()->getOrdinal() + getNumOfLocalSymbols(Asm) + 1;
529 MCSectionData *FSD = F->getParent();
530 // Offset of the symbol in the section
531 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
539 // determine the type of the relocation
542 Type = ELF::R_X86_64_PC32;
544 switch ((unsigned)Fixup.getKind()) {
545 default: llvm_unreachable("invalid fixup kind!");
546 case FK_Data_8: Type = ELF::R_X86_64_64; break;
547 case X86::reloc_pcrel_4byte:
549 // check that the offset fits within a signed long
550 if (isInt<32>(Target.getConstant()))
551 Type = ELF::R_X86_64_32S;
553 Type = ELF::R_X86_64_32;
555 case FK_Data_2: Type = ELF::R_X86_64_16; break;
556 case X86::reloc_pcrel_1byte:
557 case FK_Data_1: Type = ELF::R_X86_64_8; break;
562 Type = ELF::R_386_PC32;
564 switch ((unsigned)Fixup.getKind()) {
565 default: llvm_unreachable("invalid fixup kind!");
566 case X86::reloc_pcrel_4byte:
567 case FK_Data_4: Type = ELF::R_386_32; break;
568 case FK_Data_2: Type = ELF::R_386_16; break;
569 case X86::reloc_pcrel_1byte:
570 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 = FixupOffset;
591 if (HasRelocationAddend)
592 ERE.r_addend = Addend;
594 ERE.r_addend = 0; // Silence compiler warning.
596 Relocations[Fragment->getParent()].push_back(ERE);
599 // XXX-PERF: this should be cached
600 uint64_t ELFObjectWriterImpl::getSymbolIndexInSymbolTable(MCAssembler &Asm,
602 std::vector<ELFSymbolData> Local;
603 std::vector<ELFSymbolData> External;
604 std::vector<ELFSymbolData> Undefined;
606 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
607 ie = Asm.symbol_end(); it != ie; ++it) {
608 const MCSymbol &Symbol = it->getSymbol();
610 // Ignore non-linker visible symbols.
611 if (!Asm.isSymbolLinkerVisible(Symbol))
614 if (it->isExternal() || Symbol.isUndefined())
620 Local.push_back(MSD);
622 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
623 ie = Asm.symbol_end(); it != ie; ++it) {
624 const MCSymbol &Symbol = it->getSymbol();
626 // Ignore non-linker visible symbols.
627 if (!Asm.isSymbolLinkerVisible(Symbol))
630 if (!it->isExternal() && !Symbol.isUndefined())
636 if (Symbol.isUndefined())
637 Undefined.push_back(MSD);
639 External.push_back(MSD);
642 array_pod_sort(Local.begin(), Local.end());
643 array_pod_sort(External.begin(), External.end());
644 array_pod_sort(Undefined.begin(), Undefined.end());
646 for (unsigned i = 0, e = Local.size(); i != e; ++i)
647 if (&Local[i].SymbolData->getSymbol() == S)
648 return i + /* empty symbol */ 1;
649 for (unsigned i = 0, e = External.size(); i != e; ++i)
650 if (&External[i].SymbolData->getSymbol() == S)
651 return i + Local.size() + Asm.size() + /* empty symbol */ 1;
652 for (unsigned i = 0, e = Undefined.size(); i != e; ++i)
653 if (&Undefined[i].SymbolData->getSymbol() == S)
654 return i + Local.size() + External.size() + Asm.size() + /* empty symbol */ 1;
656 llvm_unreachable("Cannot find symbol which should exist!");
659 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
660 // Build section lookup table.
661 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
663 for (MCAssembler::iterator it = Asm.begin(),
664 ie = Asm.end(); it != ie; ++it, ++Index)
665 SectionIndexMap[&it->getSection()] = Index;
667 // Index 0 is always the empty string.
668 StringMap<uint64_t> StringIndexMap;
669 StringTable += '\x00';
671 // Add the data for local symbols.
672 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
673 ie = Asm.symbol_end(); it != ie; ++it) {
674 const MCSymbol &Symbol = it->getSymbol();
676 // Ignore non-linker visible symbols.
677 if (!Asm.isSymbolLinkerVisible(Symbol))
680 if (it->isExternal() || Symbol.isUndefined())
683 uint64_t &Entry = StringIndexMap[Symbol.getName()];
685 Entry = StringTable.size();
686 StringTable += Symbol.getName();
687 StringTable += '\x00';
692 MSD.StringIndex = Entry;
694 if (Symbol.isAbsolute()) {
695 MSD.SectionIndex = ELF::SHN_ABS;
696 LocalSymbolData.push_back(MSD);
698 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
699 assert(MSD.SectionIndex && "Invalid section index!");
700 LocalSymbolData.push_back(MSD);
704 // Now add non-local symbols.
705 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
706 ie = Asm.symbol_end(); it != ie; ++it) {
707 const MCSymbol &Symbol = it->getSymbol();
709 // Ignore non-linker visible symbols.
710 if (!Asm.isSymbolLinkerVisible(Symbol))
713 if (!it->isExternal() && !Symbol.isUndefined())
716 uint64_t &Entry = StringIndexMap[Symbol.getName()];
718 Entry = StringTable.size();
719 StringTable += Symbol.getName();
720 StringTable += '\x00';
725 MSD.StringIndex = Entry;
727 if (Symbol.isUndefined()) {
728 MSD.SectionIndex = ELF::SHN_UNDEF;
729 // XXX: for some reason we dont Emit* this
730 it->setFlags(it->getFlags() | ELF_STB_Global);
731 UndefinedSymbolData.push_back(MSD);
732 } else if (Symbol.isAbsolute()) {
733 MSD.SectionIndex = ELF::SHN_ABS;
734 ExternalSymbolData.push_back(MSD);
735 } else if (it->isCommon()) {
736 MSD.SectionIndex = ELF::SHN_COMMON;
737 ExternalSymbolData.push_back(MSD);
739 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
740 assert(MSD.SectionIndex && "Invalid section index!");
741 ExternalSymbolData.push_back(MSD);
745 // Symbols are required to be in lexicographic order.
746 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
747 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
748 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
750 // Set the symbol indices. Local symbols must come before all other
751 // symbols with non-local bindings.
753 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
754 LocalSymbolData[i].SymbolData->setIndex(Index++);
755 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
756 ExternalSymbolData[i].SymbolData->setIndex(Index++);
757 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
758 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
761 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
762 const MCSectionData &SD) {
763 if (!Relocations[&SD].empty()) {
764 MCContext &Ctx = Asm.getContext();
765 const MCSection *RelaSection;
766 const MCSectionELF &Section =
767 static_cast<const MCSectionELF&>(SD.getSection());
769 const StringRef SectionName = Section.getSectionName();
770 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
771 RelaSectionName += SectionName;
774 if (HasRelocationAddend)
775 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
777 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
779 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
780 ELF::SHT_RELA : ELF::SHT_REL, 0,
781 SectionKind::getReadOnly(),
784 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
785 RelaSD.setAlignment(1);
787 MCDataFragment *F = new MCDataFragment(&RelaSD);
789 WriteRelocationsFragment(Asm, F, &SD);
791 Asm.AddSectionToTheEnd(RelaSD, Layout);
795 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
796 uint64_t Flags, uint64_t Address,
797 uint64_t Offset, uint64_t Size,
798 uint32_t Link, uint32_t Info,
800 uint64_t EntrySize) {
801 Write32(Name); // sh_name: index into string table
802 Write32(Type); // sh_type
803 WriteWord(Flags); // sh_flags
804 WriteWord(Address); // sh_addr
805 WriteWord(Offset); // sh_offset
806 WriteWord(Size); // sh_size
807 Write32(Link); // sh_link
808 Write32(Info); // sh_info
809 WriteWord(Alignment); // sh_addralign
810 WriteWord(EntrySize); // sh_entsize
813 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
815 const MCSectionData *SD) {
816 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
817 // sort by the r_offset just like gnu as does
818 array_pod_sort(Relocs.begin(), Relocs.end());
820 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
821 ELFRelocationEntry entry = Relocs[e - i - 1];
823 unsigned WordSize = Is64Bit ? 8 : 4;
824 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
825 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
827 if (HasRelocationAddend)
828 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
832 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
833 MCAsmLayout &Layout) {
834 MCContext &Ctx = Asm.getContext();
837 WriteRelocations(Asm, Layout);
839 const MCSection *SymtabSection;
840 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
842 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
843 SectionKind::getReadOnly(),
846 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
848 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
850 F = new MCDataFragment(&SymtabSD);
853 WriteSymbolTable(F, Asm, Layout);
854 Asm.AddSectionToTheEnd(SymtabSD, Layout);
856 const MCSection *StrtabSection;
857 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
858 SectionKind::getReadOnly(), false);
860 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
861 StrtabSD.setAlignment(1);
863 // FIXME: This isn't right. If the sections get rearranged this will
864 // be wrong. We need a proper lookup.
865 StringTableIndex = Asm.size();
867 F = new MCDataFragment(&StrtabSD);
868 F->getContents().append(StringTable.begin(), StringTable.end());
869 Asm.AddSectionToTheEnd(StrtabSD, Layout);
871 const MCSection *ShstrtabSection;
872 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
873 SectionKind::getReadOnly(), false);
875 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
876 ShstrtabSD.setAlignment(1);
878 F = new MCDataFragment(&ShstrtabSD);
880 // FIXME: This isn't right. If the sections get rearranged this will
881 // be wrong. We need a proper lookup.
882 ShstrtabIndex = Asm.size();
884 // Section header string table.
886 // The first entry of a string table holds a null character so skip
889 F->getContents() += '\x00';
891 for (MCAssembler::const_iterator it = Asm.begin(),
892 ie = Asm.end(); it != ie; ++it) {
893 const MCSectionELF &Section =
894 static_cast<const MCSectionELF&>(it->getSection());
896 // Remember the index into the string table so we can write it
897 // into the sh_name field of the section header table.
898 SectionStringTableIndex[&it->getSection()] = Index;
900 Index += Section.getSectionName().size() + 1;
901 F->getContents() += Section.getSectionName();
902 F->getContents() += '\x00';
905 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
908 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
909 const MCAsmLayout &Layout) {
910 // Compute symbol table information.
911 ComputeSymbolTable(const_cast<MCAssembler&>(Asm));
913 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
914 const_cast<MCAsmLayout&>(Layout));
916 // Add 1 for the null section.
917 unsigned NumSections = Asm.size() + 1;
919 uint64_t SectionDataSize = 0;
921 for (MCAssembler::const_iterator it = Asm.begin(),
922 ie = Asm.end(); it != ie; ++it) {
923 const MCSectionData &SD = *it;
925 // Get the size of the section in the output file (including padding).
926 uint64_t Size = Layout.getSectionFileSize(&SD);
927 SectionDataSize += Size;
930 // Write out the ELF header ...
931 WriteHeader(SectionDataSize, NumSections);
932 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
934 // ... then all of the sections ...
935 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
937 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
940 for (MCAssembler::const_iterator it = Asm.begin(),
941 ie = Asm.end(); it != ie; ++it) {
942 // Remember the offset into the file for this section.
943 SectionOffsetMap[&it->getSection()] = FileOff;
945 SectionIndexMap[&it->getSection()] = Index++;
947 const MCSectionData &SD = *it;
948 FileOff += Layout.getSectionFileSize(&SD);
950 Asm.WriteSectionData(it, Layout, Writer);
953 // ... and then the section header table.
954 // Should we align the section header table?
956 // Null section first.
957 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
959 for (MCAssembler::const_iterator it = Asm.begin(),
960 ie = Asm.end(); it != ie; ++it) {
961 const MCSectionData &SD = *it;
962 const MCSectionELF &Section =
963 static_cast<const MCSectionELF&>(SD.getSection());
965 uint64_t sh_link = 0;
966 uint64_t sh_info = 0;
968 switch(Section.getType()) {
969 case ELF::SHT_DYNAMIC:
970 sh_link = SectionStringTableIndex[&it->getSection()];
975 case ELF::SHT_RELA: {
976 const MCSection *SymtabSection;
977 const MCSection *InfoSection;
979 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
980 SectionKind::getReadOnly(),
982 sh_link = SectionIndexMap[SymtabSection];
984 // Remove ".rel" and ".rela" prefixes.
985 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
986 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
988 InfoSection = Asm.getContext().getELFSection(SectionName,
989 ELF::SHT_PROGBITS, 0,
990 SectionKind::getReadOnly(),
992 sh_info = SectionIndexMap[InfoSection];
996 case ELF::SHT_SYMTAB:
997 case ELF::SHT_DYNSYM:
998 sh_link = StringTableIndex;
999 sh_info = LastLocalSymbolIndex;
1002 case ELF::SHT_PROGBITS:
1003 case ELF::SHT_STRTAB:
1004 case ELF::SHT_NOBITS:
1009 case ELF::SHT_GROUP:
1010 case ELF::SHT_SYMTAB_SHNDX:
1012 assert(0 && "FIXME: sh_type value not supported!");
1016 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1017 Section.getType(), Section.getFlags(),
1018 Layout.getSectionAddress(&SD),
1019 SectionOffsetMap.lookup(&SD.getSection()),
1020 Layout.getSectionSize(&SD), sh_link,
1021 sh_info, SD.getAlignment(),
1022 Section.getEntrySize());
1026 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1028 bool IsLittleEndian,
1029 bool HasRelocationAddend)
1030 : MCObjectWriter(OS, IsLittleEndian)
1032 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
1035 ELFObjectWriter::~ELFObjectWriter() {
1036 delete (ELFObjectWriterImpl*) Impl;
1039 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1040 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1043 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1044 const MCAsmLayout &Layout,
1045 const MCFragment *Fragment,
1046 const MCFixup &Fixup, MCValue Target,
1047 uint64_t &FixedValue) {
1048 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1049 Target, FixedValue);
1052 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1053 const MCAsmLayout &Layout) {
1054 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);