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 bool IsFixupFullyResolved(const MCAssembler &Asm,
278 const MCValue Target,
280 const MCFragment *DF) const;
282 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
287 // Emit the ELF header.
288 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
289 unsigned NumberOfSections) {
295 // emitWord method behaves differently for ELF32 and ELF64, writing
296 // 4 bytes in the former and 8 in the latter.
298 Write8(0x7f); // e_ident[EI_MAG0]
299 Write8('E'); // e_ident[EI_MAG1]
300 Write8('L'); // e_ident[EI_MAG2]
301 Write8('F'); // e_ident[EI_MAG3]
303 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
306 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
308 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
311 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
312 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
313 default: Write8(ELF::ELFOSABI_NONE); break;
315 Write8(0); // e_ident[EI_ABIVERSION]
317 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
319 Write16(ELF::ET_REL); // e_type
321 // FIXME: Make this configurable
322 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
324 Write32(ELF::EV_CURRENT); // e_version
325 WriteWord(0); // e_entry, no entry point in .o file
326 WriteWord(0); // e_phoff, no program header for .o
327 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
328 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
330 // FIXME: Make this configurable.
331 Write32(0); // e_flags = whatever the target wants
333 // e_ehsize = ELF header size
334 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
336 Write16(0); // e_phentsize = prog header entry size
337 Write16(0); // e_phnum = # prog header entries = 0
339 // e_shentsize = Section header entry size
340 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
342 // e_shnum = # of section header ents
343 Write16(NumberOfSections);
345 // e_shstrndx = Section # of '.shstrtab'
346 Write16(ShstrtabIndex);
349 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
350 uint8_t info, uint64_t value,
351 uint64_t size, uint8_t other,
357 F->getContents() += StringRef(buf, 4); // st_name
360 F->getContents() += StringRef(buf, 1); // st_info
363 F->getContents() += StringRef(buf, 1); // st_other
365 String16(buf, shndx);
366 F->getContents() += StringRef(buf, 2); // st_shndx
368 String64(buf, value);
369 F->getContents() += StringRef(buf, 8); // st_value
372 F->getContents() += StringRef(buf, 8); // st_size
377 F->getContents() += StringRef(buf, 4); // st_name
379 String32(buf, value);
380 F->getContents() += StringRef(buf, 4); // st_value
383 F->getContents() += StringRef(buf, 4); // st_size
386 F->getContents() += StringRef(buf, 1); // st_info
389 F->getContents() += StringRef(buf, 1); // st_other
391 String16(buf, shndx);
392 F->getContents() += StringRef(buf, 2); // st_shndx
396 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
397 if (Data.isCommon() && Data.isExternal())
398 return Data.getCommonAlignment();
400 const MCSymbol &Symbol = Data.getSymbol();
401 if (!Symbol.isInSection())
404 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
405 if (MCFragment *FF = Data.getFragment())
406 return Layout.getSymbolAddress(&Data) -
407 Layout.getSectionAddress(FF->getParent());
412 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
413 const MCAsmLayout &Layout) {
414 MCSymbolData &Data = *MSD.SymbolData;
415 uint8_t Info = (Data.getFlags() & 0xff);
416 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
417 uint64_t Value = SymbolValue(Data, Layout);
421 assert(!(Data.isCommon() && !Data.isExternal()));
423 ESize = Data.getSize();
424 if (Data.getSize()) {
426 if (ESize->getKind() == MCExpr::Binary) {
427 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
429 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
431 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
433 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
435 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
437 } else if (ESize->getKind() == MCExpr::Constant) {
438 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
440 assert(0 && "Unsupported size expression");
444 // Write out the symbol table entry
445 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
446 Size, Other, MSD.SectionIndex);
449 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
450 const MCAssembler &Asm,
451 const MCAsmLayout &Layout,
452 unsigned NumRegularSections) {
453 // The string table must be emitted first because we need the index
454 // into the string table for all the symbol names.
455 assert(StringTable.size() && "Missing string table");
457 // FIXME: Make sure the start of the symbol table is aligned.
459 // The first entry is the undefined symbol entry.
460 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
461 F->getContents().append(EntrySize, '\x00');
463 // Write the symbol table entries.
464 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
465 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
466 ELFSymbolData &MSD = LocalSymbolData[i];
467 WriteSymbol(F, MSD, Layout);
470 // Write out a symbol table entry for each regular section.
472 for (MCAssembler::const_iterator it = Asm.begin();
473 Index <= NumRegularSections; ++it, ++Index) {
474 const MCSectionELF &Section =
475 static_cast<const MCSectionELF&>(it->getSection());
476 // Leave out relocations so we don't have indexes within
477 // the relocations messed up
478 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
480 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
481 LastLocalSymbolIndex++;
484 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
485 ELFSymbolData &MSD = ExternalSymbolData[i];
486 MCSymbolData &Data = *MSD.SymbolData;
487 assert((Data.getFlags() & ELF_STB_Global) &&
488 "External symbol requires STB_GLOBAL flag");
489 WriteSymbol(F, MSD, Layout);
490 if (GetBinding(Data) == ELF::STB_LOCAL)
491 LastLocalSymbolIndex++;
494 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
495 ELFSymbolData &MSD = UndefinedSymbolData[i];
496 MCSymbolData &Data = *MSD.SymbolData;
497 WriteSymbol(F, MSD, Layout);
498 if (GetBinding(Data) == ELF::STB_LOCAL)
499 LastLocalSymbolIndex++;
503 static const MCSymbolData *getAtom(const MCSymbolData &SD) {
504 if (!SD.getFragment())
507 return SD.getFragment()->getAtom();
510 // FIXME: this is currently X86/X86_64 only
511 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
512 const MCAsmLayout &Layout,
513 const MCFragment *Fragment,
514 const MCFixup &Fixup,
516 uint64_t &FixedValue) {
519 int64_t Value = Target.getConstant();
521 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
522 if (!Target.isAbsolute()) {
523 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
524 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
525 const MCSymbolData *Base = getAtom(SD);
526 MCFragment *F = SD.getFragment();
528 // Avoid relocations for cases like jumps and calls in the same file.
529 if (Symbol->isDefined() && !SD.isExternal() &&
531 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
532 uint64_t FixupAddr = Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
533 FixedValue = Layout.getSymbolAddress(&SD) + Target.getConstant() - FixupAddr;
539 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
541 MCSectionData *FSD = F->getParent();
542 // Offset of the symbol in the section
543 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
545 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
547 // Compensate for the addend on i386.
552 // Index of the section in .symtab against this symbol
553 // is being relocated + 2 (empty section + abs. symbols).
554 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
556 MCSectionData *FSD = F->getParent();
557 // Offset of the symbol in the section
558 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
560 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
563 // Compensate for the addend on i386.
571 // determine the type of the relocation
575 Type = ELF::R_X86_64_PC32;
577 switch ((unsigned)Fixup.getKind()) {
578 default: llvm_unreachable("invalid fixup kind!");
579 case FK_Data_8: Type = ELF::R_X86_64_64; break;
580 case X86::reloc_pcrel_4byte:
582 // check that the offset fits within a signed long
583 if (Target.getConstant() < 0) {
584 assert(isInt<32>(Target.getConstant()));
585 Type = ELF::R_X86_64_32S;
587 assert(isUInt<32>(Target.getConstant()));
588 Type = ELF::R_X86_64_32;
591 case FK_Data_2: Type = ELF::R_X86_64_16; break;
592 case X86::reloc_pcrel_1byte:
593 case FK_Data_1: Type = ELF::R_X86_64_8; break;
598 Type = ELF::R_386_PC32;
600 switch ((unsigned)Fixup.getKind()) {
601 default: llvm_unreachable("invalid fixup kind!");
602 case X86::reloc_pcrel_4byte:
603 case FK_Data_4: Type = ELF::R_386_32; break;
604 case FK_Data_2: Type = ELF::R_386_16; break;
605 case X86::reloc_pcrel_1byte:
606 case FK_Data_1: Type = ELF::R_386_8; break;
611 ELFRelocationEntry ERE;
614 struct ELF::Elf64_Rela ERE64;
615 ERE64.setSymbolAndType(Index, Type);
616 ERE.r_info = ERE64.r_info;
618 struct ELF::Elf32_Rela ERE32;
619 ERE32.setSymbolAndType(Index, Type);
620 ERE.r_info = ERE32.r_info;
623 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
625 if (HasRelocationAddend)
626 ERE.r_addend = Addend;
628 ERE.r_addend = 0; // Silence compiler warning.
630 Relocations[Fragment->getParent()].push_back(ERE);
634 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
636 MCSymbolData &SD = Asm.getSymbolData(*S);
639 if (!SD.isExternal() && !S->isUndefined())
640 return SD.getIndex() + /* empty symbol */ 1;
642 // External or undefined symbol.
643 return SD.getIndex() + Asm.size() + /* empty symbol */ 1;
646 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
647 // Build section lookup table.
648 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
650 for (MCAssembler::iterator it = Asm.begin(),
651 ie = Asm.end(); it != ie; ++it, ++Index)
652 SectionIndexMap[&it->getSection()] = Index;
654 // Index 0 is always the empty string.
655 StringMap<uint64_t> StringIndexMap;
656 StringTable += '\x00';
658 // Add the data for local symbols.
659 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
660 ie = Asm.symbol_end(); it != ie; ++it) {
661 const MCSymbol &Symbol = it->getSymbol();
663 // Ignore non-linker visible symbols.
664 if (!Asm.isSymbolLinkerVisible(Symbol))
667 if (it->isExternal() || Symbol.isUndefined())
670 uint64_t &Entry = StringIndexMap[Symbol.getName()];
672 Entry = StringTable.size();
673 StringTable += Symbol.getName();
674 StringTable += '\x00';
679 MSD.StringIndex = Entry;
681 if (Symbol.isAbsolute()) {
682 MSD.SectionIndex = ELF::SHN_ABS;
683 LocalSymbolData.push_back(MSD);
685 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
686 assert(MSD.SectionIndex && "Invalid section index!");
687 LocalSymbolData.push_back(MSD);
691 // Now add non-local symbols.
692 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
693 ie = Asm.symbol_end(); it != ie; ++it) {
694 const MCSymbol &Symbol = it->getSymbol();
696 // Ignore non-linker visible symbols.
697 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
700 if (!it->isExternal() && !Symbol.isUndefined())
703 if (Symbol.isVariable())
706 uint64_t &Entry = StringIndexMap[Symbol.getName()];
708 Entry = StringTable.size();
709 StringTable += Symbol.getName();
710 StringTable += '\x00';
715 MSD.StringIndex = Entry;
717 if (it->isCommon()) {
718 MSD.SectionIndex = ELF::SHN_COMMON;
719 ExternalSymbolData.push_back(MSD);
720 } else if (Symbol.isUndefined()) {
721 MSD.SectionIndex = ELF::SHN_UNDEF;
722 // FIXME: Undefined symbols are global, but this is the first place we
723 // are able to set it.
724 if (GetBinding(*it) == ELF::STB_LOCAL)
725 SetBinding(*it, ELF::STB_GLOBAL);
726 UndefinedSymbolData.push_back(MSD);
727 } else if (Symbol.isAbsolute()) {
728 MSD.SectionIndex = ELF::SHN_ABS;
729 ExternalSymbolData.push_back(MSD);
731 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
732 assert(MSD.SectionIndex && "Invalid section index!");
733 ExternalSymbolData.push_back(MSD);
737 // Symbols are required to be in lexicographic order.
738 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
739 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
740 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
742 // Set the symbol indices. Local symbols must come before all other
743 // symbols with non-local bindings.
745 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
746 LocalSymbolData[i].SymbolData->setIndex(Index++);
747 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
748 ExternalSymbolData[i].SymbolData->setIndex(Index++);
749 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
750 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
753 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
754 const MCSectionData &SD) {
755 if (!Relocations[&SD].empty()) {
756 MCContext &Ctx = Asm.getContext();
757 const MCSection *RelaSection;
758 const MCSectionELF &Section =
759 static_cast<const MCSectionELF&>(SD.getSection());
761 const StringRef SectionName = Section.getSectionName();
762 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
763 RelaSectionName += SectionName;
766 if (HasRelocationAddend)
767 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
769 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
771 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
772 ELF::SHT_RELA : ELF::SHT_REL, 0,
773 SectionKind::getReadOnly(),
776 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
777 RelaSD.setAlignment(Is64Bit ? 8 : 4);
779 MCDataFragment *F = new MCDataFragment(&RelaSD);
781 WriteRelocationsFragment(Asm, F, &SD);
783 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
787 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
788 uint64_t Flags, uint64_t Address,
789 uint64_t Offset, uint64_t Size,
790 uint32_t Link, uint32_t Info,
792 uint64_t EntrySize) {
793 Write32(Name); // sh_name: index into string table
794 Write32(Type); // sh_type
795 WriteWord(Flags); // sh_flags
796 WriteWord(Address); // sh_addr
797 WriteWord(Offset); // sh_offset
798 WriteWord(Size); // sh_size
799 Write32(Link); // sh_link
800 Write32(Info); // sh_info
801 WriteWord(Alignment); // sh_addralign
802 WriteWord(EntrySize); // sh_entsize
805 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
807 const MCSectionData *SD) {
808 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
809 // sort by the r_offset just like gnu as does
810 array_pod_sort(Relocs.begin(), Relocs.end());
812 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
813 ELFRelocationEntry entry = Relocs[e - i - 1];
818 String64(buf, entry.r_offset);
819 F->getContents() += StringRef(buf, 8);
821 String64(buf, entry.r_info);
822 F->getContents() += StringRef(buf, 8);
824 if (HasRelocationAddend) {
825 String64(buf, entry.r_addend);
826 F->getContents() += StringRef(buf, 8);
831 String32(buf, entry.r_offset);
832 F->getContents() += StringRef(buf, 4);
834 String32(buf, entry.r_info);
835 F->getContents() += StringRef(buf, 4);
837 if (HasRelocationAddend) {
838 String32(buf, entry.r_addend);
839 F->getContents() += StringRef(buf, 4);
845 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
846 MCAsmLayout &Layout) {
847 MCContext &Ctx = Asm.getContext();
850 const MCSection *SymtabSection;
851 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
853 unsigned NumRegularSections = Asm.size();
855 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
856 const MCSection *ShstrtabSection;
857 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
858 SectionKind::getReadOnly(), false);
859 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
860 ShstrtabSD.setAlignment(1);
861 ShstrtabIndex = Asm.size();
863 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
864 SectionKind::getReadOnly(),
866 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
867 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
869 const MCSection *StrtabSection;
870 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
871 SectionKind::getReadOnly(), false);
872 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
873 StrtabSD.setAlignment(1);
874 StringTableIndex = Asm.size();
876 WriteRelocations(Asm, Layout);
879 F = new MCDataFragment(&SymtabSD);
880 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
881 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
883 F = new MCDataFragment(&StrtabSD);
884 F->getContents().append(StringTable.begin(), StringTable.end());
885 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
887 F = new MCDataFragment(&ShstrtabSD);
889 // Section header string table.
891 // The first entry of a string table holds a null character so skip
894 F->getContents() += '\x00';
896 for (MCAssembler::const_iterator it = Asm.begin(),
897 ie = Asm.end(); it != ie; ++it) {
898 const MCSectionELF &Section =
899 static_cast<const MCSectionELF&>(it->getSection());
900 // FIXME: We could merge suffixes like in .text and .rela.text.
902 // Remember the index into the string table so we can write it
903 // into the sh_name field of the section header table.
904 SectionStringTableIndex[&it->getSection()] = Index;
906 Index += Section.getSectionName().size() + 1;
907 F->getContents() += Section.getSectionName();
908 F->getContents() += '\x00';
911 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
914 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
915 const MCValue Target,
917 const MCFragment *DF) const {
918 // If this is a PCrel relocation, find the section this fixup value is
920 const MCSection *BaseSection = 0;
922 BaseSection = &DF->getParent()->getSection();
926 const MCSection *SectionA = 0;
927 const MCSymbol *SymbolA = 0;
928 if (const MCSymbolRefExpr *A = Target.getSymA()) {
929 SymbolA = &A->getSymbol();
930 SectionA = &SymbolA->getSection();
933 const MCSection *SectionB = 0;
934 if (const MCSymbolRefExpr *B = Target.getSymB()) {
935 SectionB = &B->getSymbol().getSection();
939 return SectionA == SectionB;
941 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
942 if (DataA.isExternal())
945 return !SectionB && BaseSection == SectionA;
948 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
949 const MCAsmLayout &Layout) {
950 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
951 const_cast<MCAsmLayout&>(Layout));
953 // Add 1 for the null section.
954 unsigned NumSections = Asm.size() + 1;
955 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
956 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
957 uint64_t FileOff = HeaderSize;
959 for (MCAssembler::const_iterator it = Asm.begin(),
960 ie = Asm.end(); it != ie; ++it) {
961 const MCSectionData &SD = *it;
963 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
965 // Get the size of the section in the output file (including padding).
966 uint64_t Size = Layout.getSectionFileSize(&SD);
971 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
973 // Write out the ELF header ...
974 WriteHeader(FileOff - HeaderSize, NumSections);
976 FileOff = HeaderSize;
978 // ... then all of the sections ...
979 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
981 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
984 for (MCAssembler::const_iterator it = Asm.begin(),
985 ie = Asm.end(); it != ie; ++it) {
986 const MCSectionData &SD = *it;
988 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
992 // Remember the offset into the file for this section.
993 SectionOffsetMap[&it->getSection()] = FileOff;
994 SectionIndexMap[&it->getSection()] = Index++;
996 FileOff += Layout.getSectionFileSize(&SD);
998 Asm.WriteSectionData(it, Layout, Writer);
1001 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1002 WriteZeros(Padding);
1005 // ... and then the section header table.
1006 // Should we align the section header table?
1008 // Null section first.
1009 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1011 for (MCAssembler::const_iterator it = Asm.begin(),
1012 ie = Asm.end(); it != ie; ++it) {
1013 const MCSectionData &SD = *it;
1014 const MCSectionELF &Section =
1015 static_cast<const MCSectionELF&>(SD.getSection());
1017 uint64_t sh_link = 0;
1018 uint64_t sh_info = 0;
1020 switch(Section.getType()) {
1021 case ELF::SHT_DYNAMIC:
1022 sh_link = SectionStringTableIndex[&it->getSection()];
1027 case ELF::SHT_RELA: {
1028 const MCSection *SymtabSection;
1029 const MCSection *InfoSection;
1031 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1032 SectionKind::getReadOnly(),
1034 sh_link = SectionIndexMap[SymtabSection];
1036 // Remove ".rel" and ".rela" prefixes.
1037 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1038 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1040 InfoSection = Asm.getContext().getELFSection(SectionName,
1041 ELF::SHT_PROGBITS, 0,
1042 SectionKind::getReadOnly(),
1044 sh_info = SectionIndexMap[InfoSection];
1048 case ELF::SHT_SYMTAB:
1049 case ELF::SHT_DYNSYM:
1050 sh_link = StringTableIndex;
1051 sh_info = LastLocalSymbolIndex;
1054 case ELF::SHT_PROGBITS:
1055 case ELF::SHT_STRTAB:
1056 case ELF::SHT_NOBITS:
1062 case ELF::SHT_GROUP:
1063 case ELF::SHT_SYMTAB_SHNDX:
1065 assert(0 && "FIXME: sh_type value not supported!");
1069 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1070 Section.getType(), Section.getFlags(),
1072 SectionOffsetMap.lookup(&SD.getSection()),
1073 Layout.getSectionSize(&SD), sh_link,
1074 sh_info, SD.getAlignment(),
1075 Section.getEntrySize());
1079 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1081 Triple::OSType OSType,
1082 bool IsLittleEndian,
1083 bool HasRelocationAddend)
1084 : MCObjectWriter(OS, IsLittleEndian)
1086 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1089 ELFObjectWriter::~ELFObjectWriter() {
1090 delete (ELFObjectWriterImpl*) Impl;
1093 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1094 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1097 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1098 const MCAsmLayout &Layout,
1099 const MCFragment *Fragment,
1100 const MCFixup &Fixup, MCValue Target,
1101 uint64_t &FixedValue) {
1102 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1103 Target, FixedValue);
1106 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1107 const MCValue Target,
1109 const MCFragment *DF) const {
1110 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1114 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
1115 const MCAsmLayout &Layout) {
1116 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);