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);
46 static unsigned GetBinding(const MCSymbolData &SD) {
47 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
48 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
49 Binding == ELF::STB_WEAK);
53 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
54 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
55 Binding == ELF::STB_WEAK);
56 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
57 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
62 class ELFObjectWriterImpl {
63 static bool isFixupKindX86PCRel(unsigned Kind) {
67 case X86::reloc_pcrel_1byte:
68 case X86::reloc_pcrel_4byte:
69 case X86::reloc_riprel_4byte:
70 case X86::reloc_riprel_4byte_movq_load:
75 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
76 return Kind == X86::reloc_riprel_4byte ||
77 Kind == X86::reloc_riprel_4byte_movq_load;
81 /// ELFSymbolData - Helper struct for containing some precomputed information
83 struct ELFSymbolData {
84 MCSymbolData *SymbolData;
86 uint32_t SectionIndex;
88 // Support lexicographic sorting.
89 bool operator<(const ELFSymbolData &RHS) const {
90 if (GetType(*SymbolData) == ELF::STT_FILE)
92 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
94 return SymbolData->getSymbol().getName() <
95 RHS.SymbolData->getSymbol().getName();
99 /// @name Relocation Data
102 struct ELFRelocationEntry {
103 // Make these big enough for both 32-bit and 64-bit
108 // Support lexicographic sorting.
109 bool operator<(const ELFRelocationEntry &RE) const {
110 return RE.r_offset < r_offset;
114 llvm::DenseMap<const MCSectionData*,
115 std::vector<ELFRelocationEntry> > Relocations;
116 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
119 /// @name Symbol Table Data
122 SmallString<256> StringTable;
123 std::vector<ELFSymbolData> LocalSymbolData;
124 std::vector<ELFSymbolData> ExternalSymbolData;
125 std::vector<ELFSymbolData> UndefinedSymbolData;
129 ELFObjectWriter *Writer;
133 unsigned Is64Bit : 1;
135 bool HasRelocationAddend;
137 Triple::OSType OSType;
139 // This holds the symbol table index of the last local symbol.
140 unsigned LastLocalSymbolIndex;
141 // This holds the .strtab section index.
142 unsigned StringTableIndex;
144 unsigned ShstrtabIndex;
147 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
148 bool _HasRelAddend, Triple::OSType _OSType)
149 : Writer(_Writer), OS(Writer->getStream()),
150 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
154 void Write8(uint8_t Value) { Writer->Write8(Value); }
155 void Write16(uint16_t Value) { Writer->Write16(Value); }
156 void Write32(uint32_t Value) { Writer->Write32(Value); }
157 //void Write64(uint64_t Value) { Writer->Write64(Value); }
158 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
159 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
160 // Writer->WriteBytes(Str, ZeroFillSize);
163 void WriteWord(uint64_t W) {
170 void String8(char *buf, uint8_t Value) {
174 void StringLE16(char *buf, uint16_t Value) {
175 buf[0] = char(Value >> 0);
176 buf[1] = char(Value >> 8);
179 void StringLE32(char *buf, uint32_t Value) {
180 StringLE16(buf, uint16_t(Value >> 0));
181 StringLE16(buf + 2, uint16_t(Value >> 16));
184 void StringLE64(char *buf, uint64_t Value) {
185 StringLE32(buf, uint32_t(Value >> 0));
186 StringLE32(buf + 4, uint32_t(Value >> 32));
189 void StringBE16(char *buf ,uint16_t Value) {
190 buf[0] = char(Value >> 8);
191 buf[1] = char(Value >> 0);
194 void StringBE32(char *buf, uint32_t Value) {
195 StringBE16(buf, uint16_t(Value >> 16));
196 StringBE16(buf + 2, uint16_t(Value >> 0));
199 void StringBE64(char *buf, uint64_t Value) {
200 StringBE32(buf, uint32_t(Value >> 32));
201 StringBE32(buf + 4, uint32_t(Value >> 0));
204 void String16(char *buf, uint16_t Value) {
205 if (Writer->isLittleEndian())
206 StringLE16(buf, Value);
208 StringBE16(buf, Value);
211 void String32(char *buf, uint32_t Value) {
212 if (Writer->isLittleEndian())
213 StringLE32(buf, Value);
215 StringBE32(buf, Value);
218 void String64(char *buf, uint64_t Value) {
219 if (Writer->isLittleEndian())
220 StringLE64(buf, Value);
222 StringBE64(buf, Value);
225 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
227 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
228 uint64_t value, uint64_t size,
229 uint8_t other, uint16_t shndx);
231 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
232 const MCAsmLayout &Layout);
234 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
235 const MCAsmLayout &Layout,
236 unsigned NumRegularSections);
238 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
239 const MCFragment *Fragment, const MCFixup &Fixup,
240 MCValue Target, uint64_t &FixedValue);
242 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
245 /// ComputeSymbolTable - Compute the symbol table data
247 /// \param StringTable [out] - The string table data.
248 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
250 void ComputeSymbolTable(MCAssembler &Asm);
252 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
253 const MCSectionData &SD);
255 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
256 for (MCAssembler::const_iterator it = Asm.begin(),
257 ie = Asm.end(); it != ie; ++it) {
258 WriteRelocation(Asm, Layout, *it);
262 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
264 void ExecutePostLayoutBinding(MCAssembler &Asm) {
265 // Compute symbol table information.
266 ComputeSymbolTable(Asm);
269 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
270 uint64_t Address, uint64_t Offset,
271 uint64_t Size, uint32_t Link, uint32_t Info,
272 uint64_t Alignment, uint64_t EntrySize);
274 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
275 const MCSectionData *SD);
277 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
282 // Emit the ELF header.
283 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
284 unsigned NumberOfSections) {
290 // emitWord method behaves differently for ELF32 and ELF64, writing
291 // 4 bytes in the former and 8 in the latter.
293 Write8(0x7f); // e_ident[EI_MAG0]
294 Write8('E'); // e_ident[EI_MAG1]
295 Write8('L'); // e_ident[EI_MAG2]
296 Write8('F'); // e_ident[EI_MAG3]
298 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
301 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
303 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
306 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
307 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
308 default: Write8(ELF::ELFOSABI_NONE); break;
310 Write8(0); // e_ident[EI_ABIVERSION]
312 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
314 Write16(ELF::ET_REL); // e_type
316 // FIXME: Make this configurable
317 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
319 Write32(ELF::EV_CURRENT); // e_version
320 WriteWord(0); // e_entry, no entry point in .o file
321 WriteWord(0); // e_phoff, no program header for .o
322 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
323 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
325 // FIXME: Make this configurable.
326 Write32(0); // e_flags = whatever the target wants
328 // e_ehsize = ELF header size
329 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
331 Write16(0); // e_phentsize = prog header entry size
332 Write16(0); // e_phnum = # prog header entries = 0
334 // e_shentsize = Section header entry size
335 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
337 // e_shnum = # of section header ents
338 Write16(NumberOfSections);
340 // e_shstrndx = Section # of '.shstrtab'
341 Write16(ShstrtabIndex);
344 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
345 uint8_t info, uint64_t value,
346 uint64_t size, uint8_t other,
352 F->getContents() += StringRef(buf, 4); // st_name
355 F->getContents() += StringRef(buf, 1); // st_info
358 F->getContents() += StringRef(buf, 1); // st_other
360 String16(buf, shndx);
361 F->getContents() += StringRef(buf, 2); // st_shndx
363 String64(buf, value);
364 F->getContents() += StringRef(buf, 8); // st_value
367 F->getContents() += StringRef(buf, 8); // st_size
372 F->getContents() += StringRef(buf, 4); // st_name
374 String32(buf, value);
375 F->getContents() += StringRef(buf, 4); // st_value
378 F->getContents() += StringRef(buf, 4); // st_size
381 F->getContents() += StringRef(buf, 1); // st_info
384 F->getContents() += StringRef(buf, 1); // st_other
386 String16(buf, shndx);
387 F->getContents() += StringRef(buf, 2); // st_shndx
391 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
392 const MCAsmLayout &Layout) {
393 MCSymbolData &Data = *MSD.SymbolData;
394 uint8_t Info = (Data.getFlags() & 0xff);
395 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
400 if (Data.isCommon() && Data.isExternal())
401 Value = Data.getCommonAlignment();
403 assert(!(Data.isCommon() && !Data.isExternal()));
405 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
406 if (MCFragment *FF = Data.getFragment())
407 Value = Layout.getSymbolAddress(&Data) -
408 Layout.getSectionAddress(FF->getParent());
410 ESize = Data.getSize();
411 if (Data.getSize()) {
413 if (ESize->getKind() == MCExpr::Binary) {
414 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
416 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
418 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
420 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
422 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
424 } else if (ESize->getKind() == MCExpr::Constant) {
425 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
427 assert(0 && "Unsupported size expression");
431 // Write out the symbol table entry
432 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
433 Size, Other, MSD.SectionIndex);
436 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
437 const MCAssembler &Asm,
438 const MCAsmLayout &Layout,
439 unsigned NumRegularSections) {
440 // The string table must be emitted first because we need the index
441 // into the string table for all the symbol names.
442 assert(StringTable.size() && "Missing string table");
444 // FIXME: Make sure the start of the symbol table is aligned.
446 // The first entry is the undefined symbol entry.
447 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
448 F->getContents().append(EntrySize, '\x00');
450 // Write the symbol table entries.
451 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
452 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
453 ELFSymbolData &MSD = LocalSymbolData[i];
454 WriteSymbol(F, MSD, Layout);
457 // Write out a symbol table entry for each regular section.
459 for (MCAssembler::const_iterator it = Asm.begin();
460 Index <= NumRegularSections; ++it, ++Index) {
461 const MCSectionELF &Section =
462 static_cast<const MCSectionELF&>(it->getSection());
463 // Leave out relocations so we don't have indexes within
464 // the relocations messed up
465 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
467 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
468 LastLocalSymbolIndex++;
471 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
472 ELFSymbolData &MSD = ExternalSymbolData[i];
473 MCSymbolData &Data = *MSD.SymbolData;
474 assert((Data.getFlags() & ELF_STB_Global) &&
475 "External symbol requires STB_GLOBAL flag");
476 WriteSymbol(F, MSD, Layout);
477 if (GetBinding(Data) == ELF::STB_LOCAL)
478 LastLocalSymbolIndex++;
481 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
482 ELFSymbolData &MSD = UndefinedSymbolData[i];
483 MCSymbolData &Data = *MSD.SymbolData;
484 WriteSymbol(F, MSD, Layout);
485 if (GetBinding(Data) == 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) {
499 int64_t Value = Target.getConstant();
501 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
502 if (!Target.isAbsolute()) {
503 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
504 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
505 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
506 MCFragment *F = SD.getFragment();
508 // Avoid relocations for cases like jumps and calls in the same file.
509 if (Symbol->isDefined() && !SD.isExternal() &&
511 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
512 uint64_t FixupAddr = Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
513 FixedValue = Layout.getSymbolAddress(&SD) + Target.getConstant() - FixupAddr;
518 if (F && !SD.isExternal()) {
519 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
521 MCSectionData *FSD = F->getParent();
522 // Offset of the symbol in the section
523 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
525 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
527 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
529 // Compensate for the addend on i386.
534 // Index of the section in .symtab against this symbol
535 // is being relocated + 2 (empty section + abs. symbols).
536 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
538 MCSectionData *FSD = F->getParent();
539 // Offset of the symbol in the section
540 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
550 // determine the type of the relocation
554 Type = ELF::R_X86_64_PC32;
556 switch ((unsigned)Fixup.getKind()) {
557 default: llvm_unreachable("invalid fixup kind!");
558 case FK_Data_8: Type = ELF::R_X86_64_64; break;
559 case X86::reloc_pcrel_4byte:
561 // check that the offset fits within a signed long
562 if (Target.getConstant() < 0) {
563 assert(isInt<32>(Target.getConstant()));
564 Type = ELF::R_X86_64_32S;
566 assert(isUInt<32>(Target.getConstant()));
567 Type = ELF::R_X86_64_32;
570 case FK_Data_2: Type = ELF::R_X86_64_16; break;
571 case X86::reloc_pcrel_1byte:
572 case FK_Data_1: Type = ELF::R_X86_64_8; break;
577 Type = ELF::R_386_PC32;
579 switch ((unsigned)Fixup.getKind()) {
580 default: llvm_unreachable("invalid fixup kind!");
581 case X86::reloc_pcrel_4byte:
582 case FK_Data_4: Type = ELF::R_386_32; break;
583 case FK_Data_2: Type = ELF::R_386_16; break;
584 case X86::reloc_pcrel_1byte:
585 case FK_Data_1: Type = ELF::R_386_8; break;
590 ELFRelocationEntry ERE;
593 struct ELF::Elf64_Rela ERE64;
594 ERE64.setSymbolAndType(Index, Type);
595 ERE.r_info = ERE64.r_info;
597 struct ELF::Elf32_Rela ERE32;
598 ERE32.setSymbolAndType(Index, Type);
599 ERE.r_info = ERE32.r_info;
602 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
604 if (HasRelocationAddend)
605 ERE.r_addend = Addend;
607 ERE.r_addend = 0; // Silence compiler warning.
609 Relocations[Fragment->getParent()].push_back(ERE);
613 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
615 MCSymbolData &SD = Asm.getSymbolData(*S);
618 if (!SD.isExternal() && !S->isUndefined())
619 return SD.getIndex() + /* empty symbol */ 1;
621 // External or undefined symbol.
622 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
625 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
626 // Build section lookup table.
627 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
629 for (MCAssembler::iterator it = Asm.begin(),
630 ie = Asm.end(); it != ie; ++it, ++Index)
631 SectionIndexMap[&it->getSection()] = Index;
633 // Index 0 is always the empty string.
634 StringMap<uint64_t> StringIndexMap;
635 StringTable += '\x00';
637 // Add the data for local symbols.
638 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
639 ie = Asm.symbol_end(); it != ie; ++it) {
640 const MCSymbol &Symbol = it->getSymbol();
642 // Ignore non-linker visible symbols.
643 if (!Asm.isSymbolLinkerVisible(Symbol))
646 if (it->isExternal() || Symbol.isUndefined())
649 uint64_t &Entry = StringIndexMap[Symbol.getName()];
651 Entry = StringTable.size();
652 StringTable += Symbol.getName();
653 StringTable += '\x00';
658 MSD.StringIndex = Entry;
660 if (Symbol.isAbsolute()) {
661 MSD.SectionIndex = ELF::SHN_ABS;
662 LocalSymbolData.push_back(MSD);
664 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
665 assert(MSD.SectionIndex && "Invalid section index!");
666 LocalSymbolData.push_back(MSD);
670 // Now add non-local symbols.
671 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
672 ie = Asm.symbol_end(); it != ie; ++it) {
673 const MCSymbol &Symbol = it->getSymbol();
675 // Ignore non-linker visible symbols.
676 if (!Asm.isSymbolLinkerVisible(Symbol))
679 if (!it->isExternal() && !Symbol.isUndefined())
682 uint64_t &Entry = StringIndexMap[Symbol.getName()];
684 Entry = StringTable.size();
685 StringTable += Symbol.getName();
686 StringTable += '\x00';
691 MSD.StringIndex = Entry;
693 if (it->isCommon()) {
694 MSD.SectionIndex = ELF::SHN_COMMON;
695 ExternalSymbolData.push_back(MSD);
696 } else if (Symbol.isUndefined()) {
697 MSD.SectionIndex = ELF::SHN_UNDEF;
698 // FIXME: Undefined symbols are global, but this is the first place we
699 // are able to set it.
700 if (GetBinding(*it) == ELF::STB_LOCAL)
701 SetBinding(*it, ELF::STB_GLOBAL);
702 UndefinedSymbolData.push_back(MSD);
703 } else if (Symbol.isAbsolute()) {
704 MSD.SectionIndex = ELF::SHN_ABS;
705 ExternalSymbolData.push_back(MSD);
707 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
708 assert(MSD.SectionIndex && "Invalid section index!");
709 ExternalSymbolData.push_back(MSD);
713 // Symbols are required to be in lexicographic order.
714 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
715 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
716 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
718 // Set the symbol indices. Local symbols must come before all other
719 // symbols with non-local bindings.
721 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
722 LocalSymbolData[i].SymbolData->setIndex(Index++);
723 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
724 ExternalSymbolData[i].SymbolData->setIndex(Index++);
725 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
726 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
729 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
730 const MCSectionData &SD) {
731 if (!Relocations[&SD].empty()) {
732 MCContext &Ctx = Asm.getContext();
733 const MCSection *RelaSection;
734 const MCSectionELF &Section =
735 static_cast<const MCSectionELF&>(SD.getSection());
737 const StringRef SectionName = Section.getSectionName();
738 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
739 RelaSectionName += SectionName;
742 if (HasRelocationAddend)
743 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
745 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
747 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
748 ELF::SHT_RELA : ELF::SHT_REL, 0,
749 SectionKind::getReadOnly(),
752 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
753 RelaSD.setAlignment(Is64Bit ? 8 : 4);
755 MCDataFragment *F = new MCDataFragment(&RelaSD);
757 WriteRelocationsFragment(Asm, F, &SD);
759 Asm.AddSectionToTheEnd(RelaSD, Layout);
763 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
764 uint64_t Flags, uint64_t Address,
765 uint64_t Offset, uint64_t Size,
766 uint32_t Link, uint32_t Info,
768 uint64_t EntrySize) {
769 Write32(Name); // sh_name: index into string table
770 Write32(Type); // sh_type
771 WriteWord(Flags); // sh_flags
772 WriteWord(Address); // sh_addr
773 WriteWord(Offset); // sh_offset
774 WriteWord(Size); // sh_size
775 Write32(Link); // sh_link
776 Write32(Info); // sh_info
777 WriteWord(Alignment); // sh_addralign
778 WriteWord(EntrySize); // sh_entsize
781 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
783 const MCSectionData *SD) {
784 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
785 // sort by the r_offset just like gnu as does
786 array_pod_sort(Relocs.begin(), Relocs.end());
788 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
789 ELFRelocationEntry entry = Relocs[e - i - 1];
794 String64(buf, entry.r_offset);
795 F->getContents() += StringRef(buf, 8);
797 String64(buf, entry.r_info);
798 F->getContents() += StringRef(buf, 8);
800 if (HasRelocationAddend) {
801 String64(buf, entry.r_addend);
802 F->getContents() += StringRef(buf, 8);
807 String32(buf, entry.r_offset);
808 F->getContents() += StringRef(buf, 4);
810 String32(buf, entry.r_info);
811 F->getContents() += StringRef(buf, 4);
813 if (HasRelocationAddend) {
814 String32(buf, entry.r_addend);
815 F->getContents() += StringRef(buf, 4);
821 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
822 MCAsmLayout &Layout) {
823 MCContext &Ctx = Asm.getContext();
826 WriteRelocations(Asm, Layout);
828 const MCSection *SymtabSection;
829 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
831 unsigned NumRegularSections = Asm.size();
833 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
834 const MCSection *ShstrtabSection;
835 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
836 SectionKind::getReadOnly(), false);
837 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
838 ShstrtabSD.setAlignment(1);
839 ShstrtabIndex = Asm.size();
841 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
842 SectionKind::getReadOnly(),
844 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
845 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
847 const MCSection *StrtabSection;
848 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
849 SectionKind::getReadOnly(), false);
850 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
851 StrtabSD.setAlignment(1);
852 StringTableIndex = Asm.size();
856 F = new MCDataFragment(&SymtabSD);
857 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
858 Asm.AddSectionToTheEnd(SymtabSD, Layout);
860 F = new MCDataFragment(&StrtabSD);
861 F->getContents().append(StringTable.begin(), StringTable.end());
862 Asm.AddSectionToTheEnd(StrtabSD, Layout);
864 F = new MCDataFragment(&ShstrtabSD);
866 // Section header string table.
868 // The first entry of a string table holds a null character so skip
871 F->getContents() += '\x00';
873 for (MCAssembler::const_iterator it = Asm.begin(),
874 ie = Asm.end(); it != ie; ++it) {
875 const MCSectionELF &Section =
876 static_cast<const MCSectionELF&>(it->getSection());
877 // FIXME: We could merge suffixes like in .text and .rela.text.
879 // Remember the index into the string table so we can write it
880 // into the sh_name field of the section header table.
881 SectionStringTableIndex[&it->getSection()] = Index;
883 Index += Section.getSectionName().size() + 1;
884 F->getContents() += Section.getSectionName();
885 F->getContents() += '\x00';
888 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
891 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
892 const MCAsmLayout &Layout) {
893 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
894 const_cast<MCAsmLayout&>(Layout));
896 // Add 1 for the null section.
897 unsigned NumSections = Asm.size() + 1;
898 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
899 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
900 uint64_t FileOff = HeaderSize;
902 for (MCAssembler::const_iterator it = Asm.begin(),
903 ie = Asm.end(); it != ie; ++it) {
904 const MCSectionData &SD = *it;
906 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
908 // Get the size of the section in the output file (including padding).
909 uint64_t Size = Layout.getSectionFileSize(&SD);
914 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
916 // Write out the ELF header ...
917 WriteHeader(FileOff - HeaderSize, NumSections);
919 FileOff = HeaderSize;
921 // ... then all of the sections ...
922 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
924 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
927 for (MCAssembler::const_iterator it = Asm.begin(),
928 ie = Asm.end(); it != ie; ++it) {
929 const MCSectionData &SD = *it;
931 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
935 // Remember the offset into the file for this section.
936 SectionOffsetMap[&it->getSection()] = FileOff;
937 SectionIndexMap[&it->getSection()] = Index++;
939 FileOff += Layout.getSectionFileSize(&SD);
941 Asm.WriteSectionData(it, Layout, Writer);
944 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
948 // ... and then the section header table.
949 // Should we align the section header table?
951 // Null section first.
952 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
954 for (MCAssembler::const_iterator it = Asm.begin(),
955 ie = Asm.end(); it != ie; ++it) {
956 const MCSectionData &SD = *it;
957 const MCSectionELF &Section =
958 static_cast<const MCSectionELF&>(SD.getSection());
960 uint64_t sh_link = 0;
961 uint64_t sh_info = 0;
963 switch(Section.getType()) {
964 case ELF::SHT_DYNAMIC:
965 sh_link = SectionStringTableIndex[&it->getSection()];
970 case ELF::SHT_RELA: {
971 const MCSection *SymtabSection;
972 const MCSection *InfoSection;
974 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
975 SectionKind::getReadOnly(),
977 sh_link = SectionIndexMap[SymtabSection];
979 // Remove ".rel" and ".rela" prefixes.
980 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
981 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
983 InfoSection = Asm.getContext().getELFSection(SectionName,
984 ELF::SHT_PROGBITS, 0,
985 SectionKind::getReadOnly(),
987 sh_info = SectionIndexMap[InfoSection];
991 case ELF::SHT_SYMTAB:
992 case ELF::SHT_DYNSYM:
993 sh_link = StringTableIndex;
994 sh_info = LastLocalSymbolIndex;
997 case ELF::SHT_PROGBITS:
998 case ELF::SHT_STRTAB:
999 case ELF::SHT_NOBITS:
1005 case ELF::SHT_GROUP:
1006 case ELF::SHT_SYMTAB_SHNDX:
1008 assert(0 && "FIXME: sh_type value not supported!");
1012 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1013 Section.getType(), Section.getFlags(),
1015 SectionOffsetMap.lookup(&SD.getSection()),
1016 Layout.getSectionSize(&SD), sh_link,
1017 sh_info, SD.getAlignment(),
1018 Section.getEntrySize());
1022 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1024 Triple::OSType OSType,
1025 bool IsLittleEndian,
1026 bool HasRelocationAddend)
1027 : MCObjectWriter(OS, IsLittleEndian)
1029 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1032 ELFObjectWriter::~ELFObjectWriter() {
1033 delete (ELFObjectWriterImpl*) Impl;
1036 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1037 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1040 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1041 const MCAsmLayout &Layout,
1042 const MCFragment *Fragment,
1043 const MCFixup &Fixup, MCValue Target,
1044 uint64_t &FixedValue) {
1045 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1046 Target, FixedValue);
1049 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1050 const MCAsmLayout &Layout) {
1051 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);