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 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
234 /// ComputeSymbolTable - Compute the symbol table data
236 /// \param StringTable [out] - The string table data.
237 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
239 void ComputeSymbolTable(MCAssembler &Asm);
241 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
242 const MCSectionData &SD);
244 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
245 for (MCAssembler::const_iterator it = Asm.begin(),
246 ie = Asm.end(); it != ie; ++it) {
247 WriteRelocation(Asm, Layout, *it);
251 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
253 void ExecutePostLayoutBinding(MCAssembler &Asm) {
254 // Compute symbol table information.
255 ComputeSymbolTable(Asm);
258 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
259 uint64_t Address, uint64_t Offset,
260 uint64_t Size, uint32_t Link, uint32_t Info,
261 uint64_t Alignment, uint64_t EntrySize);
263 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
264 const MCSectionData *SD);
266 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
271 // Emit the ELF header.
272 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
273 unsigned NumberOfSections) {
279 // emitWord method behaves differently for ELF32 and ELF64, writing
280 // 4 bytes in the former and 8 in the latter.
282 Write8(0x7f); // e_ident[EI_MAG0]
283 Write8('E'); // e_ident[EI_MAG1]
284 Write8('L'); // e_ident[EI_MAG2]
285 Write8('F'); // e_ident[EI_MAG3]
287 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
290 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
292 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
293 Write8(ELF::ELFOSABI_LINUX); // e_ident[EI_OSABI]
294 Write8(0); // e_ident[EI_ABIVERSION]
296 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
298 Write16(ELF::ET_REL); // e_type
300 // FIXME: Make this configurable
301 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
303 Write32(ELF::EV_CURRENT); // e_version
304 WriteWord(0); // e_entry, no entry point in .o file
305 WriteWord(0); // e_phoff, no program header for .o
306 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
307 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
309 // FIXME: Make this configurable.
310 Write32(0); // e_flags = whatever the target wants
312 // e_ehsize = ELF header size
313 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
315 Write16(0); // e_phentsize = prog header entry size
316 Write16(0); // e_phnum = # prog header entries = 0
318 // e_shentsize = Section header entry size
319 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
321 // e_shnum = # of section header ents
322 Write16(NumberOfSections);
324 // e_shstrndx = Section # of '.shstrtab'
325 Write16(ShstrtabIndex);
328 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
329 uint8_t info, uint64_t value,
330 uint64_t size, uint8_t other,
336 F->getContents() += StringRef(buf, 4); // st_name
339 F->getContents() += StringRef(buf, 1); // st_info
342 F->getContents() += StringRef(buf, 1); // st_other
344 String16(buf, shndx);
345 F->getContents() += StringRef(buf, 2); // st_shndx
347 String64(buf, value);
348 F->getContents() += StringRef(buf, 8); // st_value
351 F->getContents() += StringRef(buf, 8); // st_size
356 F->getContents() += StringRef(buf, 4); // st_name
358 String32(buf, value);
359 F->getContents() += StringRef(buf, 4); // st_value
362 F->getContents() += StringRef(buf, 4); // st_size
365 F->getContents() += StringRef(buf, 1); // st_info
368 F->getContents() += StringRef(buf, 1); // st_other
370 String16(buf, shndx);
371 F->getContents() += StringRef(buf, 2); // st_shndx
375 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
376 const MCAsmLayout &Layout) {
377 MCSymbolData &Data = *MSD.SymbolData;
378 uint8_t Info = (Data.getFlags() & 0xff);
379 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
384 if (Data.isCommon() && Data.isExternal())
385 Value = Data.getCommonAlignment();
387 ESize = Data.getSize();
388 if (Data.getSize()) {
390 if (ESize->getKind() == MCExpr::Binary) {
391 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
393 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
395 Layout.getAssembler().getSymbolData(Res.getSymA()->getSymbol());
397 Layout.getAssembler().getSymbolData(Res.getSymB()->getSymbol());
399 Size = Layout.getSymbolAddress(&A) - Layout.getSymbolAddress(&B);
400 Value = Layout.getSymbolAddress(&Data);
402 } else if (ESize->getKind() == MCExpr::Constant) {
403 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
405 assert(0 && "Unsupported size expression");
409 // Write out the symbol table entry
410 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
411 Size, Other, MSD.SectionIndex);
414 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
415 const MCAssembler &Asm,
416 const MCAsmLayout &Layout) {
417 // The string table must be emitted first because we need the index
418 // into the string table for all the symbol names.
419 assert(StringTable.size() && "Missing string table");
421 // FIXME: Make sure the start of the symbol table is aligned.
423 // The first entry is the undefined symbol entry.
424 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
425 F->getContents().append(EntrySize, '\x00');
427 // Write the symbol table entries.
428 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
429 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
430 ELFSymbolData &MSD = LocalSymbolData[i];
431 WriteSymbol(F, MSD, Layout);
434 // Write out a symbol table entry for each section.
435 // leaving out the just added .symtab which is at
438 for (MCAssembler::const_iterator it = Asm.begin(),
439 ie = Asm.end(); it != ie; ++it, ++Index) {
440 const MCSectionELF &Section =
441 static_cast<const MCSectionELF&>(it->getSection());
442 // Leave out relocations so we don't have indexes within
443 // the relocations messed up
444 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
446 if (Index == Asm.size())
448 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
449 LastLocalSymbolIndex++;
452 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
453 ELFSymbolData &MSD = ExternalSymbolData[i];
454 MCSymbolData &Data = *MSD.SymbolData;
455 assert((Data.getFlags() & ELF_STB_Global) &&
456 "External symbol requires STB_GLOBAL flag");
457 WriteSymbol(F, MSD, Layout);
458 if (Data.getFlags() & ELF_STB_Local)
459 LastLocalSymbolIndex++;
462 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
463 ELFSymbolData &MSD = UndefinedSymbolData[i];
464 MCSymbolData &Data = *MSD.SymbolData;
465 Data.setFlags(Data.getFlags() | ELF_STB_Global);
466 WriteSymbol(F, MSD, Layout);
467 if (Data.getFlags() & ELF_STB_Local)
468 LastLocalSymbolIndex++;
472 // FIXME: this is currently X86/X86_64 only
473 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
474 const MCAsmLayout &Layout,
475 const MCFragment *Fragment,
476 const MCFixup &Fixup,
478 uint64_t &FixedValue) {
479 unsigned IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
481 uint64_t FixupOffset =
482 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
488 Value = Target.getConstant();
490 if (!Target.isAbsolute()) {
491 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
492 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
493 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
496 if (MCFragment *F = SD.getFragment()) {
497 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
498 Value += Layout.getSymbolAddress(&SD);
500 Index = getSymbolIndexInSymbolTable(Asm, Symbol);
502 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
506 MCFragment *F = SD.getFragment();
508 // Index of the section in .symtab against this symbol
509 // is being relocated + 2 (empty section + abs. symbols).
510 Index = F->getParent()->getOrdinal() + LocalSymbolData.size() + 1;
512 MCSectionData *FSD = F->getParent();
513 // Offset of the symbol in the section
514 Addend = Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
522 // determine the type of the relocation
525 Type = ELF::R_X86_64_PC32;
527 switch ((unsigned)Fixup.getKind()) {
528 default: llvm_unreachable("invalid fixup kind!");
529 case FK_Data_8: Type = ELF::R_X86_64_64; break;
530 case X86::reloc_pcrel_4byte:
532 // check that the offset fits within a signed long
533 if (isInt<32>(Target.getConstant()))
534 Type = ELF::R_X86_64_32S;
536 Type = ELF::R_X86_64_32;
538 case FK_Data_2: Type = ELF::R_X86_64_16; break;
539 case X86::reloc_pcrel_1byte:
540 case FK_Data_1: Type = ELF::R_X86_64_8; break;
545 Type = ELF::R_386_PC32;
547 switch ((unsigned)Fixup.getKind()) {
548 default: llvm_unreachable("invalid fixup kind!");
549 case X86::reloc_pcrel_4byte:
550 case FK_Data_4: Type = ELF::R_386_32; break;
551 case FK_Data_2: Type = ELF::R_386_16; break;
552 case X86::reloc_pcrel_1byte:
553 case FK_Data_1: Type = ELF::R_386_8; break;
560 ELFRelocationEntry ERE;
563 struct ELF::Elf64_Rela ERE64;
564 ERE64.setSymbolAndType(Index, Type);
565 ERE.r_info = ERE64.r_info;
567 struct ELF::Elf32_Rela ERE32;
568 ERE32.setSymbolAndType(Index, Type);
569 ERE.r_info = ERE32.r_info;
572 ERE.r_offset = FixupOffset;
574 if (HasRelocationAddend)
575 ERE.r_addend = Addend;
577 ERE.r_addend = 0; // Silence compiler warning.
579 Relocations[Fragment->getParent()].push_back(ERE);
583 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
585 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
586 if (&LocalSymbolData[i].SymbolData->getSymbol() == S)
587 return i + /* empty symbol */ 1;
588 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
589 if (&ExternalSymbolData[i].SymbolData->getSymbol() == S)
590 return i + LocalSymbolData.size() + Asm.size() + /* empty symbol */ 1;
591 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
592 if (&UndefinedSymbolData[i].SymbolData->getSymbol() == S)
593 return i + LocalSymbolData.size() + ExternalSymbolData.size() +
594 Asm.size() + /* empty symbol */ 1;
596 llvm_unreachable("Cannot find symbol which should exist!");
599 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
600 // Build section lookup table.
601 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
603 for (MCAssembler::iterator it = Asm.begin(),
604 ie = Asm.end(); it != ie; ++it, ++Index)
605 SectionIndexMap[&it->getSection()] = Index;
607 // Index 0 is always the empty string.
608 StringMap<uint64_t> StringIndexMap;
609 StringTable += '\x00';
611 // Add the data for local symbols.
612 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
613 ie = Asm.symbol_end(); it != ie; ++it) {
614 const MCSymbol &Symbol = it->getSymbol();
616 // Ignore non-linker visible symbols.
617 if (!Asm.isSymbolLinkerVisible(Symbol))
620 if (it->isExternal() || Symbol.isUndefined())
623 uint64_t &Entry = StringIndexMap[Symbol.getName()];
625 Entry = StringTable.size();
626 StringTable += Symbol.getName();
627 StringTable += '\x00';
632 MSD.StringIndex = Entry;
634 if (Symbol.isAbsolute()) {
635 MSD.SectionIndex = ELF::SHN_ABS;
636 LocalSymbolData.push_back(MSD);
638 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
639 assert(MSD.SectionIndex && "Invalid section index!");
640 LocalSymbolData.push_back(MSD);
644 // Now add non-local symbols.
645 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
646 ie = Asm.symbol_end(); it != ie; ++it) {
647 const MCSymbol &Symbol = it->getSymbol();
649 // Ignore non-linker visible symbols.
650 if (!Asm.isSymbolLinkerVisible(Symbol))
653 if (!it->isExternal() && !Symbol.isUndefined())
656 uint64_t &Entry = StringIndexMap[Symbol.getName()];
658 Entry = StringTable.size();
659 StringTable += Symbol.getName();
660 StringTable += '\x00';
665 MSD.StringIndex = Entry;
667 if (Symbol.isUndefined()) {
668 MSD.SectionIndex = ELF::SHN_UNDEF;
669 // XXX: for some reason we dont Emit* this
670 it->setFlags(it->getFlags() | ELF_STB_Global);
671 UndefinedSymbolData.push_back(MSD);
672 } else if (Symbol.isAbsolute()) {
673 MSD.SectionIndex = ELF::SHN_ABS;
674 ExternalSymbolData.push_back(MSD);
675 } else if (it->isCommon()) {
676 MSD.SectionIndex = ELF::SHN_COMMON;
677 ExternalSymbolData.push_back(MSD);
679 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
680 assert(MSD.SectionIndex && "Invalid section index!");
681 ExternalSymbolData.push_back(MSD);
685 // Symbols are required to be in lexicographic order.
686 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
687 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
688 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
690 // Set the symbol indices. Local symbols must come before all other
691 // symbols with non-local bindings.
693 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
694 LocalSymbolData[i].SymbolData->setIndex(Index++);
695 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
696 ExternalSymbolData[i].SymbolData->setIndex(Index++);
697 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
698 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
701 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
702 const MCSectionData &SD) {
703 if (!Relocations[&SD].empty()) {
704 MCContext &Ctx = Asm.getContext();
705 const MCSection *RelaSection;
706 const MCSectionELF &Section =
707 static_cast<const MCSectionELF&>(SD.getSection());
709 const StringRef SectionName = Section.getSectionName();
710 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
711 RelaSectionName += SectionName;
714 if (HasRelocationAddend)
715 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
717 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
719 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
720 ELF::SHT_RELA : ELF::SHT_REL, 0,
721 SectionKind::getReadOnly(),
724 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
725 RelaSD.setAlignment(1);
727 MCDataFragment *F = new MCDataFragment(&RelaSD);
729 WriteRelocationsFragment(Asm, F, &SD);
731 Asm.AddSectionToTheEnd(RelaSD, Layout);
735 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
736 uint64_t Flags, uint64_t Address,
737 uint64_t Offset, uint64_t Size,
738 uint32_t Link, uint32_t Info,
740 uint64_t EntrySize) {
741 Write32(Name); // sh_name: index into string table
742 Write32(Type); // sh_type
743 WriteWord(Flags); // sh_flags
744 WriteWord(Address); // sh_addr
745 WriteWord(Offset); // sh_offset
746 WriteWord(Size); // sh_size
747 Write32(Link); // sh_link
748 Write32(Info); // sh_info
749 WriteWord(Alignment); // sh_addralign
750 WriteWord(EntrySize); // sh_entsize
753 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
755 const MCSectionData *SD) {
756 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
757 // sort by the r_offset just like gnu as does
758 array_pod_sort(Relocs.begin(), Relocs.end());
760 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
761 ELFRelocationEntry entry = Relocs[e - i - 1];
763 unsigned WordSize = Is64Bit ? 8 : 4;
764 F->getContents() += StringRef((const char *)&entry.r_offset, WordSize);
765 F->getContents() += StringRef((const char *)&entry.r_info, WordSize);
767 if (HasRelocationAddend)
768 F->getContents() += StringRef((const char *)&entry.r_addend, WordSize);
772 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
773 MCAsmLayout &Layout) {
774 MCContext &Ctx = Asm.getContext();
777 WriteRelocations(Asm, Layout);
779 const MCSection *SymtabSection;
780 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
782 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
783 SectionKind::getReadOnly(),
786 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
788 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
790 F = new MCDataFragment(&SymtabSD);
793 WriteSymbolTable(F, Asm, Layout);
794 Asm.AddSectionToTheEnd(SymtabSD, Layout);
796 const MCSection *StrtabSection;
797 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
798 SectionKind::getReadOnly(), false);
800 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
801 StrtabSD.setAlignment(1);
803 // FIXME: This isn't right. If the sections get rearranged this will
804 // be wrong. We need a proper lookup.
805 StringTableIndex = Asm.size();
807 F = new MCDataFragment(&StrtabSD);
808 F->getContents().append(StringTable.begin(), StringTable.end());
809 Asm.AddSectionToTheEnd(StrtabSD, Layout);
811 const MCSection *ShstrtabSection;
812 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
813 SectionKind::getReadOnly(), false);
815 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
816 ShstrtabSD.setAlignment(1);
818 F = new MCDataFragment(&ShstrtabSD);
820 // FIXME: This isn't right. If the sections get rearranged this will
821 // be wrong. We need a proper lookup.
822 ShstrtabIndex = Asm.size();
824 // Section header string table.
826 // The first entry of a string table holds a null character so skip
829 F->getContents() += '\x00';
831 for (MCAssembler::const_iterator it = Asm.begin(),
832 ie = Asm.end(); it != ie; ++it) {
833 const MCSectionELF &Section =
834 static_cast<const MCSectionELF&>(it->getSection());
836 // Remember the index into the string table so we can write it
837 // into the sh_name field of the section header table.
838 SectionStringTableIndex[&it->getSection()] = Index;
840 Index += Section.getSectionName().size() + 1;
841 F->getContents() += Section.getSectionName();
842 F->getContents() += '\x00';
845 Asm.AddSectionToTheEnd(ShstrtabSD, Layout);
848 void ELFObjectWriterImpl::WriteObject(const MCAssembler &Asm,
849 const MCAsmLayout &Layout) {
850 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
851 const_cast<MCAsmLayout&>(Layout));
853 // Add 1 for the null section.
854 unsigned NumSections = Asm.size() + 1;
856 uint64_t SectionDataSize = 0;
858 for (MCAssembler::const_iterator it = Asm.begin(),
859 ie = Asm.end(); it != ie; ++it) {
860 const MCSectionData &SD = *it;
862 // Get the size of the section in the output file (including padding).
863 uint64_t Size = Layout.getSectionFileSize(&SD);
864 SectionDataSize += Size;
867 // Write out the ELF header ...
868 WriteHeader(SectionDataSize, NumSections);
869 FileOff = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
871 // ... then all of the sections ...
872 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
874 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
877 for (MCAssembler::const_iterator it = Asm.begin(),
878 ie = Asm.end(); it != ie; ++it) {
879 // Remember the offset into the file for this section.
880 SectionOffsetMap[&it->getSection()] = FileOff;
882 SectionIndexMap[&it->getSection()] = Index++;
884 const MCSectionData &SD = *it;
885 FileOff += Layout.getSectionFileSize(&SD);
887 Asm.WriteSectionData(it, Layout, Writer);
890 // ... and then the section header table.
891 // Should we align the section header table?
893 // Null section first.
894 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
896 for (MCAssembler::const_iterator it = Asm.begin(),
897 ie = Asm.end(); it != ie; ++it) {
898 const MCSectionData &SD = *it;
899 const MCSectionELF &Section =
900 static_cast<const MCSectionELF&>(SD.getSection());
902 uint64_t sh_link = 0;
903 uint64_t sh_info = 0;
905 switch(Section.getType()) {
906 case ELF::SHT_DYNAMIC:
907 sh_link = SectionStringTableIndex[&it->getSection()];
912 case ELF::SHT_RELA: {
913 const MCSection *SymtabSection;
914 const MCSection *InfoSection;
916 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
917 SectionKind::getReadOnly(),
919 sh_link = SectionIndexMap[SymtabSection];
921 // Remove ".rel" and ".rela" prefixes.
922 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
923 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
925 InfoSection = Asm.getContext().getELFSection(SectionName,
926 ELF::SHT_PROGBITS, 0,
927 SectionKind::getReadOnly(),
929 sh_info = SectionIndexMap[InfoSection];
933 case ELF::SHT_SYMTAB:
934 case ELF::SHT_DYNSYM:
935 sh_link = StringTableIndex;
936 sh_info = LastLocalSymbolIndex;
939 case ELF::SHT_PROGBITS:
940 case ELF::SHT_STRTAB:
941 case ELF::SHT_NOBITS:
947 case ELF::SHT_SYMTAB_SHNDX:
949 assert(0 && "FIXME: sh_type value not supported!");
953 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
954 Section.getType(), Section.getFlags(),
955 Layout.getSectionAddress(&SD),
956 SectionOffsetMap.lookup(&SD.getSection()),
957 Layout.getSectionSize(&SD), sh_link,
958 sh_info, SD.getAlignment(),
959 Section.getEntrySize());
963 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
966 bool HasRelocationAddend)
967 : MCObjectWriter(OS, IsLittleEndian)
969 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend);
972 ELFObjectWriter::~ELFObjectWriter() {
973 delete (ELFObjectWriterImpl*) Impl;
976 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
977 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
980 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
981 const MCAsmLayout &Layout,
982 const MCFragment *Fragment,
983 const MCFixup &Fixup, MCValue Target,
984 uint64_t &FixedValue) {
985 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
989 void ELFObjectWriter::WriteObject(const MCAssembler &Asm,
990 const MCAsmLayout &Layout) {
991 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);