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/SmallPtrSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAssembler.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCELFSymbolFlags.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectWriter.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/ELF.h"
31 #include "llvm/Target/TargetAsmBackend.h"
33 #include "../Target/X86/X86FixupKinds.h"
38 static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
47 static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
54 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
61 static bool isFixupKindX86PCRel(unsigned Kind) {
65 case X86::reloc_pcrel_1byte:
66 case X86::reloc_pcrel_4byte:
67 case X86::reloc_riprel_4byte:
68 case X86::reloc_riprel_4byte_movq_load:
73 static bool RelocNeedsGOT(unsigned Type) {
77 case ELF::R_X86_64_GOT32:
78 case ELF::R_X86_64_PLT32:
79 case ELF::R_X86_64_GOTPCREL:
86 class ELFObjectWriterImpl {
87 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
88 return Kind == X86::reloc_riprel_4byte ||
89 Kind == X86::reloc_riprel_4byte_movq_load;
93 /// ELFSymbolData - Helper struct for containing some precomputed information
95 struct ELFSymbolData {
96 MCSymbolData *SymbolData;
98 uint32_t SectionIndex;
100 // Support lexicographic sorting.
101 bool operator<(const ELFSymbolData &RHS) const {
102 if (GetType(*SymbolData) == ELF::STT_FILE)
104 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
106 return SymbolData->getSymbol().getName() <
107 RHS.SymbolData->getSymbol().getName();
111 /// @name Relocation Data
114 struct ELFRelocationEntry {
115 // Make these big enough for both 32-bit and 64-bit
119 const MCSymbol *Symbol;
122 // Support lexicographic sorting.
123 bool operator<(const ELFRelocationEntry &RE) const {
124 return RE.r_offset < r_offset;
128 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
130 llvm::DenseMap<const MCSectionData*,
131 std::vector<ELFRelocationEntry> > Relocations;
132 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
135 /// @name Symbol Table Data
138 SmallString<256> StringTable;
139 std::vector<ELFSymbolData> LocalSymbolData;
140 std::vector<ELFSymbolData> ExternalSymbolData;
141 std::vector<ELFSymbolData> UndefinedSymbolData;
145 int NumRegularSections;
149 ELFObjectWriter *Writer;
153 unsigned Is64Bit : 1;
155 bool HasRelocationAddend;
157 Triple::OSType OSType;
159 // This holds the symbol table index of the last local symbol.
160 unsigned LastLocalSymbolIndex;
161 // This holds the .strtab section index.
162 unsigned StringTableIndex;
164 unsigned ShstrtabIndex;
167 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
168 bool _HasRelAddend, Triple::OSType _OSType)
169 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
170 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
174 void Write8(uint8_t Value) { Writer->Write8(Value); }
175 void Write16(uint16_t Value) { Writer->Write16(Value); }
176 void Write32(uint32_t Value) { Writer->Write32(Value); }
177 //void Write64(uint64_t Value) { Writer->Write64(Value); }
178 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
179 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
180 // Writer->WriteBytes(Str, ZeroFillSize);
183 void WriteWord(uint64_t W) {
190 void String8(char *buf, uint8_t Value) {
194 void StringLE16(char *buf, uint16_t Value) {
195 buf[0] = char(Value >> 0);
196 buf[1] = char(Value >> 8);
199 void StringLE32(char *buf, uint32_t Value) {
200 StringLE16(buf, uint16_t(Value >> 0));
201 StringLE16(buf + 2, uint16_t(Value >> 16));
204 void StringLE64(char *buf, uint64_t Value) {
205 StringLE32(buf, uint32_t(Value >> 0));
206 StringLE32(buf + 4, uint32_t(Value >> 32));
209 void StringBE16(char *buf ,uint16_t Value) {
210 buf[0] = char(Value >> 8);
211 buf[1] = char(Value >> 0);
214 void StringBE32(char *buf, uint32_t Value) {
215 StringBE16(buf, uint16_t(Value >> 16));
216 StringBE16(buf + 2, uint16_t(Value >> 0));
219 void StringBE64(char *buf, uint64_t Value) {
220 StringBE32(buf, uint32_t(Value >> 32));
221 StringBE32(buf + 4, uint32_t(Value >> 0));
224 void String16(char *buf, uint16_t Value) {
225 if (Writer->isLittleEndian())
226 StringLE16(buf, Value);
228 StringBE16(buf, Value);
231 void String32(char *buf, uint32_t Value) {
232 if (Writer->isLittleEndian())
233 StringLE32(buf, Value);
235 StringBE32(buf, Value);
238 void String64(char *buf, uint64_t Value) {
239 if (Writer->isLittleEndian())
240 StringLE64(buf, Value);
242 StringBE64(buf, Value);
245 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
247 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
248 uint64_t value, uint64_t size,
249 uint8_t other, uint16_t shndx);
251 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
252 const MCAsmLayout &Layout);
254 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
255 const MCAsmLayout &Layout,
256 unsigned NumRegularSections);
258 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
259 const MCFragment *Fragment, const MCFixup &Fixup,
260 MCValue Target, uint64_t &FixedValue);
262 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
265 /// ComputeSymbolTable - Compute the symbol table data
267 /// \param StringTable [out] - The string table data.
268 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
270 void ComputeSymbolTable(MCAssembler &Asm);
272 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
273 const MCSectionData &SD);
275 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
276 for (MCAssembler::const_iterator it = Asm.begin(),
277 ie = Asm.end(); it != ie; ++it) {
278 WriteRelocation(Asm, Layout, *it);
282 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
284 void ExecutePostLayoutBinding(MCAssembler &Asm) {
287 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
288 uint64_t Address, uint64_t Offset,
289 uint64_t Size, uint32_t Link, uint32_t Info,
290 uint64_t Alignment, uint64_t EntrySize);
292 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
293 const MCSectionData *SD);
295 bool IsFixupFullyResolved(const MCAssembler &Asm,
296 const MCValue Target,
298 const MCFragment *DF) const;
300 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
305 // Emit the ELF header.
306 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
307 unsigned NumberOfSections) {
313 // emitWord method behaves differently for ELF32 and ELF64, writing
314 // 4 bytes in the former and 8 in the latter.
316 Write8(0x7f); // e_ident[EI_MAG0]
317 Write8('E'); // e_ident[EI_MAG1]
318 Write8('L'); // e_ident[EI_MAG2]
319 Write8('F'); // e_ident[EI_MAG3]
321 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
324 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
326 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
329 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
330 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
331 default: Write8(ELF::ELFOSABI_NONE); break;
333 Write8(0); // e_ident[EI_ABIVERSION]
335 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
337 Write16(ELF::ET_REL); // e_type
339 // FIXME: Make this configurable
340 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
342 Write32(ELF::EV_CURRENT); // e_version
343 WriteWord(0); // e_entry, no entry point in .o file
344 WriteWord(0); // e_phoff, no program header for .o
345 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
346 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
348 // FIXME: Make this configurable.
349 Write32(0); // e_flags = whatever the target wants
351 // e_ehsize = ELF header size
352 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
354 Write16(0); // e_phentsize = prog header entry size
355 Write16(0); // e_phnum = # prog header entries = 0
357 // e_shentsize = Section header entry size
358 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
360 // e_shnum = # of section header ents
361 Write16(NumberOfSections);
363 // e_shstrndx = Section # of '.shstrtab'
364 Write16(ShstrtabIndex);
367 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
368 uint8_t info, uint64_t value,
369 uint64_t size, uint8_t other,
375 F->getContents() += StringRef(buf, 4); // st_name
378 F->getContents() += StringRef(buf, 1); // st_info
381 F->getContents() += StringRef(buf, 1); // st_other
383 String16(buf, shndx);
384 F->getContents() += StringRef(buf, 2); // st_shndx
386 String64(buf, value);
387 F->getContents() += StringRef(buf, 8); // st_value
390 F->getContents() += StringRef(buf, 8); // st_size
395 F->getContents() += StringRef(buf, 4); // st_name
397 String32(buf, value);
398 F->getContents() += StringRef(buf, 4); // st_value
401 F->getContents() += StringRef(buf, 4); // st_size
404 F->getContents() += StringRef(buf, 1); // st_info
407 F->getContents() += StringRef(buf, 1); // st_other
409 String16(buf, shndx);
410 F->getContents() += StringRef(buf, 2); // st_shndx
414 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
415 if (Data.isCommon() && Data.isExternal())
416 return Data.getCommonAlignment();
418 const MCSymbol &Symbol = Data.getSymbol();
419 if (!Symbol.isInSection())
422 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
423 if (MCFragment *FF = Data.getFragment())
424 return Layout.getSymbolAddress(&Data) -
425 Layout.getSectionAddress(FF->getParent());
430 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
431 const MCAsmLayout &Layout) {
432 MCSymbolData &Data = *MSD.SymbolData;
433 uint8_t Info = (Data.getFlags() & 0xff);
434 uint8_t Other = ((Data.getFlags() & 0xf00) >> ELF_STV_Shift);
435 uint64_t Value = SymbolValue(Data, Layout);
439 assert(!(Data.isCommon() && !Data.isExternal()));
441 ESize = Data.getSize();
442 if (Data.getSize()) {
444 if (ESize->getKind() == MCExpr::Binary) {
445 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
447 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
448 uint64_t AddressA = 0;
449 uint64_t AddressB = 0;
450 const MCSymbol &SymA = Res.getSymA()->getSymbol();
451 const MCSymbol &SymB = Res.getSymB()->getSymbol();
453 if (SymA.isDefined()) {
454 MCSymbolData &A = Layout.getAssembler().getSymbolData(SymA);
455 AddressA = Layout.getSymbolAddress(&A);
458 if (SymB.isDefined()) {
459 MCSymbolData &B = Layout.getAssembler().getSymbolData(SymB);
460 AddressB = Layout.getSymbolAddress(&B);
463 Size = AddressA - AddressB;
465 } else if (ESize->getKind() == MCExpr::Constant) {
466 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
468 assert(0 && "Unsupported size expression");
472 // Write out the symbol table entry
473 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
474 Size, Other, MSD.SectionIndex);
477 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
478 const MCAssembler &Asm,
479 const MCAsmLayout &Layout,
480 unsigned NumRegularSections) {
481 // The string table must be emitted first because we need the index
482 // into the string table for all the symbol names.
483 assert(StringTable.size() && "Missing string table");
485 // FIXME: Make sure the start of the symbol table is aligned.
487 // The first entry is the undefined symbol entry.
488 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
489 F->getContents().append(EntrySize, '\x00');
491 // Write the symbol table entries.
492 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
493 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
494 ELFSymbolData &MSD = LocalSymbolData[i];
495 WriteSymbol(F, MSD, Layout);
498 // Write out a symbol table entry for each regular section.
500 for (MCAssembler::const_iterator it = Asm.begin();
501 Index <= NumRegularSections; ++it, ++Index) {
502 const MCSectionELF &Section =
503 static_cast<const MCSectionELF&>(it->getSection());
504 // Leave out relocations so we don't have indexes within
505 // the relocations messed up
506 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
508 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
509 LastLocalSymbolIndex++;
512 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
513 ELFSymbolData &MSD = ExternalSymbolData[i];
514 MCSymbolData &Data = *MSD.SymbolData;
515 assert(((Data.getFlags() & ELF_STB_Global) ||
516 (Data.getFlags() & ELF_STB_Weak)) &&
517 "External symbol requires STB_GLOBAL or STB_WEAK flag");
518 WriteSymbol(F, MSD, Layout);
519 if (GetBinding(Data) == ELF::STB_LOCAL)
520 LastLocalSymbolIndex++;
523 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
524 ELFSymbolData &MSD = UndefinedSymbolData[i];
525 MCSymbolData &Data = *MSD.SymbolData;
526 WriteSymbol(F, MSD, Layout);
527 if (GetBinding(Data) == ELF::STB_LOCAL)
528 LastLocalSymbolIndex++;
532 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
533 const MCValue &Target,
534 const MCFragment &F) {
535 const MCSymbol &Symbol = SD.getSymbol();
536 if (Symbol.isUndefined())
539 const MCSectionELF &Section =
540 static_cast<const MCSectionELF&>(Symbol.getSection());
542 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
543 return Target.getConstant() != 0;
548 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
549 const MCSectionELF &Sec2 =
550 static_cast<const MCSectionELF&>(F.getParent()->getSection());
552 if (&Sec2 != &Section &&
553 (Kind == MCSymbolRefExpr::VK_PLT || Kind == MCSymbolRefExpr::VK_GOTPCREL))
559 // FIXME: this is currently X86/X86_64 only
560 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
561 const MCAsmLayout &Layout,
562 const MCFragment *Fragment,
563 const MCFixup &Fixup,
565 uint64_t &FixedValue) {
568 int64_t Value = Target.getConstant();
569 const MCSymbol *Symbol = 0;
571 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
572 if (!Target.isAbsolute()) {
573 Symbol = &Target.getSymA()->getSymbol();
574 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
575 MCFragment *F = SD.getFragment();
577 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
578 const MCSymbol &SymbolB = RefB->getSymbol();
579 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
581 MCSectionData *Sec = Fragment->getParent();
583 // Offset of the symbol in the section
584 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
586 // Ofeset of the relocation in the section
587 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
591 // Check that this case has already been fully resolved before we get
593 if (Symbol->isDefined() && !SD.isExternal() &&
595 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
596 llvm_unreachable("We don't need a relocation in this case.");
600 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
601 if (!RelocOnSymbol) {
602 Index = F->getParent()->getOrdinal();
604 MCSectionData *FSD = F->getParent();
605 // Offset of the symbol in the section
606 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
608 UsedInReloc.insert(Symbol);
612 // Compensate for the addend on i386.
619 // determine the type of the relocation
621 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
626 case MCSymbolRefExpr::VK_None:
627 Type = ELF::R_X86_64_PC32;
629 case MCSymbolRefExpr::VK_PLT:
630 Type = ELF::R_X86_64_PLT32;
632 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
633 Type = ELF::R_X86_64_GOTPCREL;
636 llvm_unreachable("Unimplemented");
639 switch ((unsigned)Fixup.getKind()) {
640 default: llvm_unreachable("invalid fixup kind!");
641 case FK_Data_8: Type = ELF::R_X86_64_64; break;
642 case X86::reloc_signed_4byte:
643 case X86::reloc_pcrel_4byte:
644 assert(isInt<32>(Target.getConstant()));
646 case MCSymbolRefExpr::VK_None:
647 Type = ELF::R_X86_64_32S;
649 case MCSymbolRefExpr::VK_GOT:
650 Type = ELF::R_X86_64_GOT32;
652 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
653 Type = ELF::R_X86_64_GOTPCREL;
656 llvm_unreachable("Unimplemented");
660 Type = ELF::R_X86_64_32;
662 case FK_Data_2: Type = ELF::R_X86_64_16; break;
663 case X86::reloc_pcrel_1byte:
664 case FK_Data_1: Type = ELF::R_X86_64_8; break;
669 Type = ELF::R_386_PC32;
671 switch ((unsigned)Fixup.getKind()) {
672 default: llvm_unreachable("invalid fixup kind!");
674 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
676 case X86::reloc_signed_4byte:
677 case X86::reloc_pcrel_4byte:
678 case FK_Data_4: Type = ELF::R_386_32; break;
679 case FK_Data_2: Type = ELF::R_386_16; break;
680 case X86::reloc_pcrel_1byte:
681 case FK_Data_1: Type = ELF::R_386_8; break;
686 if (RelocNeedsGOT(Type))
689 ELFRelocationEntry ERE;
695 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
697 if (HasRelocationAddend)
698 ERE.r_addend = Addend;
700 ERE.r_addend = 0; // Silence compiler warning.
702 Relocations[Fragment->getParent()].push_back(ERE);
706 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
708 MCSymbolData &SD = Asm.getSymbolData(*S);
711 if (!SD.isExternal() && !S->isUndefined())
712 return SD.getIndex() + /* empty symbol */ 1;
714 // External or undefined symbol.
715 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
718 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
720 const MCSymbol &Symbol = Data.getSymbol();
721 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
724 if (!Used && Symbol.isTemporary())
730 static bool isLocal(const MCSymbolData &Data) {
731 if (Data.isExternal())
734 const MCSymbol &Symbol = Data.getSymbol();
735 if (Symbol.isUndefined() && !Symbol.isVariable())
741 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
742 // FIXME: Is this the correct place to do this?
744 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
745 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
746 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
747 Data.setExternal(true);
750 // Build section lookup table.
751 NumRegularSections = Asm.size();
752 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
754 for (MCAssembler::iterator it = Asm.begin(),
755 ie = Asm.end(); it != ie; ++it, ++Index)
756 SectionIndexMap[&it->getSection()] = Index;
758 // Index 0 is always the empty string.
759 StringMap<uint64_t> StringIndexMap;
760 StringTable += '\x00';
762 // Add the data for local symbols.
763 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
764 ie = Asm.symbol_end(); it != ie; ++it) {
765 const MCSymbol &Symbol = it->getSymbol();
767 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol)))
773 uint64_t &Entry = StringIndexMap[Symbol.getName()];
775 Entry = StringTable.size();
776 StringTable += Symbol.getName();
777 StringTable += '\x00';
782 MSD.StringIndex = Entry;
784 if (Symbol.isAbsolute()) {
785 MSD.SectionIndex = ELF::SHN_ABS;
786 LocalSymbolData.push_back(MSD);
788 const MCSymbol *SymbolP = &Symbol;
789 if (Symbol.isVariable()) {
790 const MCExpr *Value = Symbol.getVariableValue();
791 assert (Value->getKind() == MCExpr::SymbolRef && "Unimplemented");
792 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
793 SymbolP = &Ref->getSymbol();
795 MSD.SectionIndex = SectionIndexMap.lookup(&SymbolP->getSection());
796 assert(MSD.SectionIndex && "Invalid section index!");
797 LocalSymbolData.push_back(MSD);
801 // Now add non-local symbols.
802 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
803 ie = Asm.symbol_end(); it != ie; ++it) {
804 const MCSymbol &Symbol = it->getSymbol();
806 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol)))
812 uint64_t &Entry = StringIndexMap[Symbol.getName()];
814 Entry = StringTable.size();
815 StringTable += Symbol.getName();
816 StringTable += '\x00';
821 MSD.StringIndex = Entry;
823 // FIXME: There is duplicated code with the local case.
824 if (it->isCommon()) {
825 MSD.SectionIndex = ELF::SHN_COMMON;
826 ExternalSymbolData.push_back(MSD);
827 } else if (Symbol.isVariable()) {
828 const MCExpr *Value = Symbol.getVariableValue();
829 assert (Value->getKind() == MCExpr::SymbolRef && "Unimplemented");
830 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
831 const MCSymbol &RefSymbol = Ref->getSymbol();
832 if (RefSymbol.isDefined()) {
833 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
834 assert(MSD.SectionIndex && "Invalid section index!");
835 ExternalSymbolData.push_back(MSD);
837 } else if (Symbol.isUndefined()) {
838 MSD.SectionIndex = ELF::SHN_UNDEF;
839 // FIXME: Undefined symbols are global, but this is the first place we
840 // are able to set it.
841 if (GetBinding(*it) == ELF::STB_LOCAL)
842 SetBinding(*it, ELF::STB_GLOBAL);
843 UndefinedSymbolData.push_back(MSD);
844 } else if (Symbol.isAbsolute()) {
845 MSD.SectionIndex = ELF::SHN_ABS;
846 ExternalSymbolData.push_back(MSD);
848 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
849 assert(MSD.SectionIndex && "Invalid section index!");
850 ExternalSymbolData.push_back(MSD);
854 // Symbols are required to be in lexicographic order.
855 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
856 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
857 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
859 // Set the symbol indices. Local symbols must come before all other
860 // symbols with non-local bindings.
862 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
863 LocalSymbolData[i].SymbolData->setIndex(Index++);
864 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
865 ExternalSymbolData[i].SymbolData->setIndex(Index++);
866 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
867 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
870 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
871 const MCSectionData &SD) {
872 if (!Relocations[&SD].empty()) {
873 MCContext &Ctx = Asm.getContext();
874 const MCSection *RelaSection;
875 const MCSectionELF &Section =
876 static_cast<const MCSectionELF&>(SD.getSection());
878 const StringRef SectionName = Section.getSectionName();
879 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
880 RelaSectionName += SectionName;
883 if (HasRelocationAddend)
884 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
886 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
888 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
889 ELF::SHT_RELA : ELF::SHT_REL, 0,
890 SectionKind::getReadOnly(),
893 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
894 RelaSD.setAlignment(Is64Bit ? 8 : 4);
896 MCDataFragment *F = new MCDataFragment(&RelaSD);
898 WriteRelocationsFragment(Asm, F, &SD);
900 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
904 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
905 uint64_t Flags, uint64_t Address,
906 uint64_t Offset, uint64_t Size,
907 uint32_t Link, uint32_t Info,
909 uint64_t EntrySize) {
910 Write32(Name); // sh_name: index into string table
911 Write32(Type); // sh_type
912 WriteWord(Flags); // sh_flags
913 WriteWord(Address); // sh_addr
914 WriteWord(Offset); // sh_offset
915 WriteWord(Size); // sh_size
916 Write32(Link); // sh_link
917 Write32(Info); // sh_info
918 WriteWord(Alignment); // sh_addralign
919 WriteWord(EntrySize); // sh_entsize
922 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
924 const MCSectionData *SD) {
925 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
926 // sort by the r_offset just like gnu as does
927 array_pod_sort(Relocs.begin(), Relocs.end());
929 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
930 ELFRelocationEntry entry = Relocs[e - i - 1];
933 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
935 entry.Index += LocalSymbolData.size() + 1;
939 String64(buf, entry.r_offset);
940 F->getContents() += StringRef(buf, 8);
942 struct ELF::Elf64_Rela ERE64;
943 ERE64.setSymbolAndType(entry.Index, entry.Type);
944 String64(buf, ERE64.r_info);
945 F->getContents() += StringRef(buf, 8);
947 if (HasRelocationAddend) {
948 String64(buf, entry.r_addend);
949 F->getContents() += StringRef(buf, 8);
954 String32(buf, entry.r_offset);
955 F->getContents() += StringRef(buf, 4);
957 struct ELF::Elf32_Rela ERE32;
958 ERE32.setSymbolAndType(entry.Index, entry.Type);
959 String32(buf, ERE32.r_info);
960 F->getContents() += StringRef(buf, 4);
962 if (HasRelocationAddend) {
963 String32(buf, entry.r_addend);
964 F->getContents() += StringRef(buf, 4);
970 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
971 MCAsmLayout &Layout) {
972 MCContext &Ctx = Asm.getContext();
975 const MCSection *SymtabSection;
976 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
978 unsigned NumRegularSections = Asm.size();
980 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
981 const MCSection *ShstrtabSection;
982 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
983 SectionKind::getReadOnly(), false);
984 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
985 ShstrtabSD.setAlignment(1);
986 ShstrtabIndex = Asm.size();
988 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
989 SectionKind::getReadOnly(),
991 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
992 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
994 const MCSection *StrtabSection;
995 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
996 SectionKind::getReadOnly(), false);
997 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
998 StrtabSD.setAlignment(1);
999 StringTableIndex = Asm.size();
1001 WriteRelocations(Asm, Layout);
1004 F = new MCDataFragment(&SymtabSD);
1005 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1006 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1008 F = new MCDataFragment(&StrtabSD);
1009 F->getContents().append(StringTable.begin(), StringTable.end());
1010 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1012 F = new MCDataFragment(&ShstrtabSD);
1014 // Section header string table.
1016 // The first entry of a string table holds a null character so skip
1019 F->getContents() += '\x00';
1021 for (MCAssembler::const_iterator it = Asm.begin(),
1022 ie = Asm.end(); it != ie; ++it) {
1023 const MCSectionELF &Section =
1024 static_cast<const MCSectionELF&>(it->getSection());
1025 // FIXME: We could merge suffixes like in .text and .rela.text.
1027 // Remember the index into the string table so we can write it
1028 // into the sh_name field of the section header table.
1029 SectionStringTableIndex[&it->getSection()] = Index;
1031 Index += Section.getSectionName().size() + 1;
1032 F->getContents() += Section.getSectionName();
1033 F->getContents() += '\x00';
1036 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1039 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1040 const MCValue Target,
1042 const MCFragment *DF) const {
1043 // If this is a PCrel relocation, find the section this fixup value is
1045 const MCSection *BaseSection = 0;
1047 BaseSection = &DF->getParent()->getSection();
1048 assert(BaseSection);
1051 const MCSection *SectionA = 0;
1052 const MCSymbol *SymbolA = 0;
1053 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1054 SymbolA = &A->getSymbol();
1055 SectionA = &SymbolA->getSection();
1058 const MCSection *SectionB = 0;
1059 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1060 SectionB = &B->getSymbol().getSection();
1064 return SectionA == SectionB;
1066 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1067 if (DataA.isExternal())
1070 return !SectionB && BaseSection == SectionA;
1073 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1074 const MCAsmLayout &Layout) {
1075 // Compute symbol table information.
1076 ComputeSymbolTable(Asm);
1078 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1079 const_cast<MCAsmLayout&>(Layout));
1081 // Add 1 for the null section.
1082 unsigned NumSections = Asm.size() + 1;
1083 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1084 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1085 uint64_t FileOff = HeaderSize;
1087 for (MCAssembler::const_iterator it = Asm.begin(),
1088 ie = Asm.end(); it != ie; ++it) {
1089 const MCSectionData &SD = *it;
1091 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1093 // Get the size of the section in the output file (including padding).
1094 uint64_t Size = Layout.getSectionFileSize(&SD);
1099 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1101 // Write out the ELF header ...
1102 WriteHeader(FileOff - HeaderSize, NumSections);
1104 FileOff = HeaderSize;
1106 // ... then all of the sections ...
1107 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1109 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1112 for (MCAssembler::const_iterator it = Asm.begin(),
1113 ie = Asm.end(); it != ie; ++it) {
1114 const MCSectionData &SD = *it;
1116 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1117 WriteZeros(Padding);
1120 // Remember the offset into the file for this section.
1121 SectionOffsetMap[&it->getSection()] = FileOff;
1122 SectionIndexMap[&it->getSection()] = Index++;
1124 FileOff += Layout.getSectionFileSize(&SD);
1126 Asm.WriteSectionData(it, Layout, Writer);
1129 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1130 WriteZeros(Padding);
1133 // ... and then the section header table.
1134 // Should we align the section header table?
1136 // Null section first.
1137 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1139 for (MCAssembler::const_iterator it = Asm.begin(),
1140 ie = Asm.end(); it != ie; ++it) {
1141 const MCSectionData &SD = *it;
1142 const MCSectionELF &Section =
1143 static_cast<const MCSectionELF&>(SD.getSection());
1145 uint64_t sh_link = 0;
1146 uint64_t sh_info = 0;
1148 switch(Section.getType()) {
1149 case ELF::SHT_DYNAMIC:
1150 sh_link = SectionStringTableIndex[&it->getSection()];
1155 case ELF::SHT_RELA: {
1156 const MCSection *SymtabSection;
1157 const MCSection *InfoSection;
1159 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1160 SectionKind::getReadOnly(),
1162 sh_link = SectionIndexMap[SymtabSection];
1164 // Remove ".rel" and ".rela" prefixes.
1165 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1166 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1168 InfoSection = Asm.getContext().getELFSection(SectionName,
1169 ELF::SHT_PROGBITS, 0,
1170 SectionKind::getReadOnly(),
1172 sh_info = SectionIndexMap[InfoSection];
1176 case ELF::SHT_SYMTAB:
1177 case ELF::SHT_DYNSYM:
1178 sh_link = StringTableIndex;
1179 sh_info = LastLocalSymbolIndex;
1182 case ELF::SHT_PROGBITS:
1183 case ELF::SHT_STRTAB:
1184 case ELF::SHT_NOBITS:
1190 case ELF::SHT_GROUP:
1191 case ELF::SHT_SYMTAB_SHNDX:
1193 assert(0 && "FIXME: sh_type value not supported!");
1197 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1198 Section.getType(), Section.getFlags(),
1200 SectionOffsetMap.lookup(&SD.getSection()),
1201 Layout.getSectionSize(&SD), sh_link,
1202 sh_info, SD.getAlignment(),
1203 Section.getEntrySize());
1207 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1209 Triple::OSType OSType,
1210 bool IsLittleEndian,
1211 bool HasRelocationAddend)
1212 : MCObjectWriter(OS, IsLittleEndian)
1214 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
1217 ELFObjectWriter::~ELFObjectWriter() {
1218 delete (ELFObjectWriterImpl*) Impl;
1221 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1222 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1225 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1226 const MCAsmLayout &Layout,
1227 const MCFragment *Fragment,
1228 const MCFixup &Fixup, MCValue Target,
1229 uint64_t &FixedValue) {
1230 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1231 Target, FixedValue);
1234 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1235 const MCValue Target,
1237 const MCFragment *DF) const {
1238 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1242 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1243 const MCAsmLayout &Layout) {
1244 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);