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 unsigned GetVisibility(MCSymbolData &SD) {
63 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
69 static bool isFixupKindX86PCRel(unsigned Kind) {
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
76 case X86::reloc_riprel_4byte_movq_load:
81 static bool RelocNeedsGOT(unsigned Type) {
85 case ELF::R_X86_64_GOT32:
86 case ELF::R_X86_64_PLT32:
87 case ELF::R_X86_64_GOTPCREL:
88 case ELF::R_X86_64_TPOFF32:
89 case ELF::R_X86_64_TLSGD:
90 case ELF::R_X86_64_GOTTPOFF:
97 class ELFObjectWriterImpl {
98 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
99 return Kind == X86::reloc_riprel_4byte ||
100 Kind == X86::reloc_riprel_4byte_movq_load;
104 /// ELFSymbolData - Helper struct for containing some precomputed information
106 struct ELFSymbolData {
107 MCSymbolData *SymbolData;
108 uint64_t StringIndex;
109 uint32_t SectionIndex;
111 // Support lexicographic sorting.
112 bool operator<(const ELFSymbolData &RHS) const {
113 if (GetType(*SymbolData) == ELF::STT_FILE)
115 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
117 return SymbolData->getSymbol().getName() <
118 RHS.SymbolData->getSymbol().getName();
122 /// @name Relocation Data
125 struct ELFRelocationEntry {
126 // Make these big enough for both 32-bit and 64-bit
130 const MCSymbol *Symbol;
133 // Support lexicographic sorting.
134 bool operator<(const ELFRelocationEntry &RE) const {
135 return RE.r_offset < r_offset;
139 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
140 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
142 llvm::DenseMap<const MCSectionData*,
143 std::vector<ELFRelocationEntry> > Relocations;
144 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
147 /// @name Symbol Table Data
150 SmallString<256> StringTable;
151 std::vector<ELFSymbolData> LocalSymbolData;
152 std::vector<ELFSymbolData> ExternalSymbolData;
153 std::vector<ELFSymbolData> UndefinedSymbolData;
157 int NumRegularSections;
161 ELFObjectWriter *Writer;
165 unsigned Is64Bit : 1;
167 bool HasRelocationAddend;
169 Triple::OSType OSType;
173 // This holds the symbol table index of the last local symbol.
174 unsigned LastLocalSymbolIndex;
175 // This holds the .strtab section index.
176 unsigned StringTableIndex;
178 unsigned ShstrtabIndex;
181 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
182 uint16_t _EMachine, bool _HasRelAddend,
183 Triple::OSType _OSType)
184 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
185 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
186 OSType(_OSType), EMachine(_EMachine) {
189 void Write8(uint8_t Value) { Writer->Write8(Value); }
190 void Write16(uint16_t Value) { Writer->Write16(Value); }
191 void Write32(uint32_t Value) { Writer->Write32(Value); }
192 //void Write64(uint64_t Value) { Writer->Write64(Value); }
193 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
194 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
195 // Writer->WriteBytes(Str, ZeroFillSize);
198 void WriteWord(uint64_t W) {
205 void String8(char *buf, uint8_t Value) {
209 void StringLE16(char *buf, uint16_t Value) {
210 buf[0] = char(Value >> 0);
211 buf[1] = char(Value >> 8);
214 void StringLE32(char *buf, uint32_t Value) {
215 StringLE16(buf, uint16_t(Value >> 0));
216 StringLE16(buf + 2, uint16_t(Value >> 16));
219 void StringLE64(char *buf, uint64_t Value) {
220 StringLE32(buf, uint32_t(Value >> 0));
221 StringLE32(buf + 4, uint32_t(Value >> 32));
224 void StringBE16(char *buf ,uint16_t Value) {
225 buf[0] = char(Value >> 8);
226 buf[1] = char(Value >> 0);
229 void StringBE32(char *buf, uint32_t Value) {
230 StringBE16(buf, uint16_t(Value >> 16));
231 StringBE16(buf + 2, uint16_t(Value >> 0));
234 void StringBE64(char *buf, uint64_t Value) {
235 StringBE32(buf, uint32_t(Value >> 32));
236 StringBE32(buf + 4, uint32_t(Value >> 0));
239 void String16(char *buf, uint16_t Value) {
240 if (Writer->isLittleEndian())
241 StringLE16(buf, Value);
243 StringBE16(buf, Value);
246 void String32(char *buf, uint32_t Value) {
247 if (Writer->isLittleEndian())
248 StringLE32(buf, Value);
250 StringBE32(buf, Value);
253 void String64(char *buf, uint64_t Value) {
254 if (Writer->isLittleEndian())
255 StringLE64(buf, Value);
257 StringBE64(buf, Value);
260 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
262 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
263 uint64_t value, uint64_t size,
264 uint8_t other, uint16_t shndx);
266 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
267 const MCAsmLayout &Layout);
269 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
270 const MCAsmLayout &Layout,
271 unsigned NumRegularSections);
273 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
274 const MCFragment *Fragment, const MCFixup &Fixup,
275 MCValue Target, uint64_t &FixedValue);
277 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
280 /// ComputeSymbolTable - Compute the symbol table data
282 /// \param StringTable [out] - The string table data.
283 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
285 void ComputeSymbolTable(MCAssembler &Asm);
287 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
288 const MCSectionData &SD);
290 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
291 for (MCAssembler::const_iterator it = Asm.begin(),
292 ie = Asm.end(); it != ie; ++it) {
293 WriteRelocation(Asm, Layout, *it);
297 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
299 void ExecutePostLayoutBinding(MCAssembler &Asm);
301 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
302 uint64_t Address, uint64_t Offset,
303 uint64_t Size, uint32_t Link, uint32_t Info,
304 uint64_t Alignment, uint64_t EntrySize);
306 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
307 const MCSectionData *SD);
309 bool IsFixupFullyResolved(const MCAssembler &Asm,
310 const MCValue Target,
312 const MCFragment *DF) const;
314 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
319 // Emit the ELF header.
320 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
321 unsigned NumberOfSections) {
327 // emitWord method behaves differently for ELF32 and ELF64, writing
328 // 4 bytes in the former and 8 in the latter.
330 Write8(0x7f); // e_ident[EI_MAG0]
331 Write8('E'); // e_ident[EI_MAG1]
332 Write8('L'); // e_ident[EI_MAG2]
333 Write8('F'); // e_ident[EI_MAG3]
335 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
338 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
340 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
343 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
344 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
345 default: Write8(ELF::ELFOSABI_NONE); break;
347 Write8(0); // e_ident[EI_ABIVERSION]
349 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
351 Write16(ELF::ET_REL); // e_type
353 Write16(EMachine); // e_machine = target
355 Write32(ELF::EV_CURRENT); // e_version
356 WriteWord(0); // e_entry, no entry point in .o file
357 WriteWord(0); // e_phoff, no program header for .o
358 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
359 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
361 // FIXME: Make this configurable.
362 Write32(0); // e_flags = whatever the target wants
364 // e_ehsize = ELF header size
365 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
367 Write16(0); // e_phentsize = prog header entry size
368 Write16(0); // e_phnum = # prog header entries = 0
370 // e_shentsize = Section header entry size
371 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
373 // e_shnum = # of section header ents
374 Write16(NumberOfSections);
376 // e_shstrndx = Section # of '.shstrtab'
377 Write16(ShstrtabIndex);
380 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
381 uint8_t info, uint64_t value,
382 uint64_t size, uint8_t other,
388 F->getContents() += StringRef(buf, 4); // st_name
391 F->getContents() += StringRef(buf, 1); // st_info
394 F->getContents() += StringRef(buf, 1); // st_other
396 String16(buf, shndx);
397 F->getContents() += StringRef(buf, 2); // st_shndx
399 String64(buf, value);
400 F->getContents() += StringRef(buf, 8); // st_value
403 F->getContents() += StringRef(buf, 8); // st_size
408 F->getContents() += StringRef(buf, 4); // st_name
410 String32(buf, value);
411 F->getContents() += StringRef(buf, 4); // st_value
414 F->getContents() += StringRef(buf, 4); // st_size
417 F->getContents() += StringRef(buf, 1); // st_info
420 F->getContents() += StringRef(buf, 1); // st_other
422 String16(buf, shndx);
423 F->getContents() += StringRef(buf, 2); // st_shndx
427 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
428 if (Data.isCommon() && Data.isExternal())
429 return Data.getCommonAlignment();
431 const MCSymbol &Symbol = Data.getSymbol();
432 if (!Symbol.isInSection())
435 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
436 if (MCFragment *FF = Data.getFragment())
437 return Layout.getSymbolAddress(&Data) -
438 Layout.getSectionAddress(FF->getParent());
443 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
444 const MCSymbol *S = &Symbol;
445 while (S->isVariable()) {
446 const MCExpr *Value = S->getVariableValue();
447 if (Value->getKind() != MCExpr::SymbolRef)
449 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
450 S = &Ref->getSymbol();
455 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
456 // The presence of symbol versions causes undefined symbols and
457 // versions declared with @@@ to be renamed.
459 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
460 ie = Asm.symbol_end(); it != ie; ++it) {
461 const MCSymbol &Alias = it->getSymbol();
462 if (!Alias.isVariable())
464 const MCSymbol &Symbol = AliasedSymbol(Alias);
465 StringRef AliasName = Alias.getName();
466 size_t Pos = AliasName.find('@');
467 if (Pos == StringRef::npos)
470 StringRef Rest = AliasName.substr(Pos);
471 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
474 // FIXME: produce a better error message.
475 if (Symbol.isUndefined() && Rest.startswith("@@") &&
476 !Rest.startswith("@@@"))
477 report_fatal_error("A @@ version cannot be undefined");
479 Renames.insert(std::make_pair(&Symbol, &Alias));
483 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
484 const MCAsmLayout &Layout) {
485 MCSymbolData &OrigData = *MSD.SymbolData;
487 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
489 uint8_t Binding = GetBinding(OrigData);
490 uint8_t Visibility = GetVisibility(OrigData);
491 uint8_t Type = GetType(Data);
493 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
494 uint8_t Other = Visibility;
496 uint64_t Value = SymbolValue(Data, Layout);
500 assert(!(Data.isCommon() && !Data.isExternal()));
502 ESize = Data.getSize();
503 if (Data.getSize()) {
505 if (ESize->getKind() == MCExpr::Binary) {
506 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
508 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
509 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
510 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
511 Size = Res.getConstant();
513 } else if (ESize->getKind() == MCExpr::Constant) {
514 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
516 assert(0 && "Unsupported size expression");
520 // Write out the symbol table entry
521 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
522 Size, Other, MSD.SectionIndex);
525 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
526 const MCAssembler &Asm,
527 const MCAsmLayout &Layout,
528 unsigned NumRegularSections) {
529 // The string table must be emitted first because we need the index
530 // into the string table for all the symbol names.
531 assert(StringTable.size() && "Missing string table");
533 // FIXME: Make sure the start of the symbol table is aligned.
535 // The first entry is the undefined symbol entry.
536 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
537 F->getContents().append(EntrySize, '\x00');
539 // Write the symbol table entries.
540 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
541 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
542 ELFSymbolData &MSD = LocalSymbolData[i];
543 WriteSymbol(F, MSD, Layout);
546 // Write out a symbol table entry for each regular section.
548 for (MCAssembler::const_iterator it = Asm.begin();
549 Index <= NumRegularSections; ++it, ++Index) {
550 const MCSectionELF &Section =
551 static_cast<const MCSectionELF&>(it->getSection());
552 // Leave out relocations so we don't have indexes within
553 // the relocations messed up
554 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
556 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
557 LastLocalSymbolIndex++;
560 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
561 ELFSymbolData &MSD = ExternalSymbolData[i];
562 MCSymbolData &Data = *MSD.SymbolData;
563 assert(((Data.getFlags() & ELF_STB_Global) ||
564 (Data.getFlags() & ELF_STB_Weak)) &&
565 "External symbol requires STB_GLOBAL or STB_WEAK flag");
566 WriteSymbol(F, MSD, Layout);
567 if (GetBinding(Data) == ELF::STB_LOCAL)
568 LastLocalSymbolIndex++;
571 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
572 ELFSymbolData &MSD = UndefinedSymbolData[i];
573 MCSymbolData &Data = *MSD.SymbolData;
574 WriteSymbol(F, MSD, Layout);
575 if (GetBinding(Data) == ELF::STB_LOCAL)
576 LastLocalSymbolIndex++;
580 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
581 const MCValue &Target,
582 const MCFragment &F) {
583 const MCSymbol &Symbol = SD.getSymbol();
584 if (Symbol.isUndefined())
587 const MCSectionELF &Section =
588 static_cast<const MCSectionELF&>(Symbol.getSection());
593 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
594 const MCSectionELF &Sec2 =
595 static_cast<const MCSectionELF&>(F.getParent()->getSection());
597 if (Section.getKind().isBSS())
600 if (&Sec2 != &Section &&
601 (Kind == MCSymbolRefExpr::VK_PLT ||
602 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
603 Kind == MCSymbolRefExpr::VK_GOTOFF))
606 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
607 return Target.getConstant() != 0;
612 // FIXME: this is currently X86/X86_64 only
613 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
614 const MCAsmLayout &Layout,
615 const MCFragment *Fragment,
616 const MCFixup &Fixup,
618 uint64_t &FixedValue) {
621 int64_t Value = Target.getConstant();
622 const MCSymbol *Symbol = 0;
624 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
625 if (!Target.isAbsolute()) {
626 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
627 const MCSymbol *Renamed = Renames.lookup(Symbol);
630 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
631 MCFragment *F = SD.getFragment();
633 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
634 const MCSymbol &SymbolB = RefB->getSymbol();
635 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
637 MCSectionData *Sec = Fragment->getParent();
639 // Offset of the symbol in the section
640 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
642 // Ofeset of the relocation in the section
643 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
647 // Check that this case has already been fully resolved before we get
649 if (Symbol->isDefined() && !SD.isExternal() &&
651 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
652 llvm_unreachable("We don't need a relocation in this case.");
656 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
657 if (!RelocOnSymbol) {
658 Index = F->getParent()->getOrdinal();
660 MCSectionData *FSD = F->getParent();
661 // Offset of the symbol in the section
662 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
664 UsedInReloc.insert(Symbol);
668 // Compensate for the addend on i386.
675 // determine the type of the relocation
677 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
683 llvm_unreachable("Unimplemented");
684 case MCSymbolRefExpr::VK_None:
685 Type = ELF::R_X86_64_PC32;
687 case MCSymbolRefExpr::VK_PLT:
688 Type = ELF::R_X86_64_PLT32;
690 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
691 Type = ELF::R_X86_64_GOTPCREL;
693 case MCSymbolRefExpr::VK_GOTTPOFF:
694 Type = ELF::R_X86_64_GOTTPOFF;
696 case MCSymbolRefExpr::VK_TLSGD:
697 Type = ELF::R_X86_64_TLSGD;
701 switch ((unsigned)Fixup.getKind()) {
702 default: llvm_unreachable("invalid fixup kind!");
703 case FK_Data_8: Type = ELF::R_X86_64_64; break;
704 case X86::reloc_signed_4byte:
705 case X86::reloc_pcrel_4byte:
706 assert(isInt<32>(Target.getConstant()));
709 llvm_unreachable("Unimplemented");
710 case MCSymbolRefExpr::VK_None:
711 Type = ELF::R_X86_64_32S;
713 case MCSymbolRefExpr::VK_GOT:
714 Type = ELF::R_X86_64_GOT32;
716 case MCSymbolRefExpr::VK_GOTPCREL:
717 Type = ELF::R_X86_64_GOTPCREL;
719 case MCSymbolRefExpr::VK_TPOFF:
720 Type = ELF::R_X86_64_TPOFF32;
725 Type = ELF::R_X86_64_32;
727 case FK_Data_2: Type = ELF::R_X86_64_16; break;
728 case X86::reloc_pcrel_1byte:
729 case FK_Data_1: Type = ELF::R_X86_64_8; break;
736 llvm_unreachable("Unimplemented");
737 case MCSymbolRefExpr::VK_None:
738 Type = ELF::R_386_PC32;
740 case MCSymbolRefExpr::VK_PLT:
741 Type = ELF::R_386_PLT32;
745 switch ((unsigned)Fixup.getKind()) {
746 default: llvm_unreachable("invalid fixup kind!");
748 case X86::reloc_global_offset_table:
749 Type = ELF::R_386_GOTPC;
752 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
754 case X86::reloc_signed_4byte:
755 case X86::reloc_pcrel_4byte:
759 llvm_unreachable("Unimplemented");
760 case MCSymbolRefExpr::VK_None:
761 Type = ELF::R_386_32;
763 case MCSymbolRefExpr::VK_GOT:
764 Type = ELF::R_386_GOT32;
766 case MCSymbolRefExpr::VK_GOTOFF:
767 Type = ELF::R_386_GOTOFF;
771 case FK_Data_2: Type = ELF::R_386_16; break;
772 case X86::reloc_pcrel_1byte:
773 case FK_Data_1: Type = ELF::R_386_8; break;
778 if (RelocNeedsGOT(Type))
781 ELFRelocationEntry ERE;
787 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
789 if (HasRelocationAddend)
790 ERE.r_addend = Addend;
792 ERE.r_addend = 0; // Silence compiler warning.
794 Relocations[Fragment->getParent()].push_back(ERE);
798 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
800 MCSymbolData &SD = Asm.getSymbolData(*S);
803 if (!SD.isExternal() && !S->isUndefined())
804 return SD.getIndex() + /* empty symbol */ 1;
806 // External or undefined symbol.
807 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
810 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
811 bool Used, bool Renamed) {
818 const MCSymbol &Symbol = Data.getSymbol();
820 const MCSymbol &A = AliasedSymbol(Symbol);
821 if (&A != &Symbol && A.isUndefined())
824 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
827 if (Symbol.isTemporary())
833 static bool isLocal(const MCSymbolData &Data) {
834 if (Data.isExternal())
837 const MCSymbol &Symbol = Data.getSymbol();
838 if (Symbol.isUndefined() && !Symbol.isVariable())
844 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
845 // FIXME: Is this the correct place to do this?
847 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
848 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
849 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
850 Data.setExternal(true);
853 // Build section lookup table.
854 NumRegularSections = Asm.size();
855 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
857 for (MCAssembler::iterator it = Asm.begin(),
858 ie = Asm.end(); it != ie; ++it, ++Index)
859 SectionIndexMap[&it->getSection()] = Index;
861 // Index 0 is always the empty string.
862 StringMap<uint64_t> StringIndexMap;
863 StringTable += '\x00';
865 // Add the data for the symbols.
866 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
867 ie = Asm.symbol_end(); it != ie; ++it) {
868 const MCSymbol &Symbol = it->getSymbol();
870 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol),
871 Renames.count(&Symbol)))
876 bool Local = isLocal(*it);
877 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
879 if (it->isCommon()) {
881 MSD.SectionIndex = ELF::SHN_COMMON;
882 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
883 MSD.SectionIndex = ELF::SHN_ABS;
884 } else if (RefSymbol.isUndefined()) {
885 MSD.SectionIndex = ELF::SHN_UNDEF;
886 // FIXME: Undefined symbols are global, but this is the first place we
887 // are able to set it.
888 if (GetBinding(*it) == ELF::STB_LOCAL)
889 SetBinding(*it, ELF::STB_GLOBAL);
891 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
892 assert(MSD.SectionIndex && "Invalid section index!");
895 // The @@@ in symbol version is replaced with @ in undefined symbols and
896 // @@ in defined ones.
897 StringRef Name = Symbol.getName();
898 size_t Pos = Name.find("@@@");
899 std::string FinalName;
900 if (Pos != StringRef::npos) {
901 StringRef Prefix = Name.substr(0, Pos);
902 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
903 StringRef Suffix = Name.substr(Pos + n);
904 FinalName = Prefix.str() + Suffix.str();
906 FinalName = Name.str();
909 uint64_t &Entry = StringIndexMap[FinalName];
911 Entry = StringTable.size();
912 StringTable += FinalName;
913 StringTable += '\x00';
915 MSD.StringIndex = Entry;
916 if (MSD.SectionIndex == ELF::SHN_UNDEF)
917 UndefinedSymbolData.push_back(MSD);
919 LocalSymbolData.push_back(MSD);
921 ExternalSymbolData.push_back(MSD);
924 // Symbols are required to be in lexicographic order.
925 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
926 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
927 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
929 // Set the symbol indices. Local symbols must come before all other
930 // symbols with non-local bindings.
932 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
933 LocalSymbolData[i].SymbolData->setIndex(Index++);
934 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
935 ExternalSymbolData[i].SymbolData->setIndex(Index++);
936 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
937 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
940 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
941 const MCSectionData &SD) {
942 if (!Relocations[&SD].empty()) {
943 MCContext &Ctx = Asm.getContext();
944 const MCSection *RelaSection;
945 const MCSectionELF &Section =
946 static_cast<const MCSectionELF&>(SD.getSection());
948 const StringRef SectionName = Section.getSectionName();
949 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
950 RelaSectionName += SectionName;
953 if (HasRelocationAddend)
954 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
956 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
958 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
959 ELF::SHT_RELA : ELF::SHT_REL, 0,
960 SectionKind::getReadOnly(),
963 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
964 RelaSD.setAlignment(Is64Bit ? 8 : 4);
966 MCDataFragment *F = new MCDataFragment(&RelaSD);
968 WriteRelocationsFragment(Asm, F, &SD);
970 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
974 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
975 uint64_t Flags, uint64_t Address,
976 uint64_t Offset, uint64_t Size,
977 uint32_t Link, uint32_t Info,
979 uint64_t EntrySize) {
980 Write32(Name); // sh_name: index into string table
981 Write32(Type); // sh_type
982 WriteWord(Flags); // sh_flags
983 WriteWord(Address); // sh_addr
984 WriteWord(Offset); // sh_offset
985 WriteWord(Size); // sh_size
986 Write32(Link); // sh_link
987 Write32(Info); // sh_info
988 WriteWord(Alignment); // sh_addralign
989 WriteWord(EntrySize); // sh_entsize
992 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
994 const MCSectionData *SD) {
995 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
996 // sort by the r_offset just like gnu as does
997 array_pod_sort(Relocs.begin(), Relocs.end());
999 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1000 ELFRelocationEntry entry = Relocs[e - i - 1];
1002 if (entry.Index < 0)
1003 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1005 entry.Index += LocalSymbolData.size() + 1;
1009 String64(buf, entry.r_offset);
1010 F->getContents() += StringRef(buf, 8);
1012 struct ELF::Elf64_Rela ERE64;
1013 ERE64.setSymbolAndType(entry.Index, entry.Type);
1014 String64(buf, ERE64.r_info);
1015 F->getContents() += StringRef(buf, 8);
1017 if (HasRelocationAddend) {
1018 String64(buf, entry.r_addend);
1019 F->getContents() += StringRef(buf, 8);
1024 String32(buf, entry.r_offset);
1025 F->getContents() += StringRef(buf, 4);
1027 struct ELF::Elf32_Rela ERE32;
1028 ERE32.setSymbolAndType(entry.Index, entry.Type);
1029 String32(buf, ERE32.r_info);
1030 F->getContents() += StringRef(buf, 4);
1032 if (HasRelocationAddend) {
1033 String32(buf, entry.r_addend);
1034 F->getContents() += StringRef(buf, 4);
1040 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1041 MCAsmLayout &Layout) {
1042 MCContext &Ctx = Asm.getContext();
1045 const MCSection *SymtabSection;
1046 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1048 unsigned NumRegularSections = Asm.size();
1050 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1051 const MCSection *ShstrtabSection;
1052 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1053 SectionKind::getReadOnly(), false);
1054 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1055 ShstrtabSD.setAlignment(1);
1056 ShstrtabIndex = Asm.size();
1058 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1059 SectionKind::getReadOnly(),
1061 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1062 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1064 const MCSection *StrtabSection;
1065 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1066 SectionKind::getReadOnly(), false);
1067 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1068 StrtabSD.setAlignment(1);
1069 StringTableIndex = Asm.size();
1071 WriteRelocations(Asm, Layout);
1074 F = new MCDataFragment(&SymtabSD);
1075 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
1076 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1078 F = new MCDataFragment(&StrtabSD);
1079 F->getContents().append(StringTable.begin(), StringTable.end());
1080 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1082 F = new MCDataFragment(&ShstrtabSD);
1084 // Section header string table.
1086 // The first entry of a string table holds a null character so skip
1089 F->getContents() += '\x00';
1091 for (MCAssembler::const_iterator it = Asm.begin(),
1092 ie = Asm.end(); it != ie; ++it) {
1093 const MCSectionELF &Section =
1094 static_cast<const MCSectionELF&>(it->getSection());
1095 // FIXME: We could merge suffixes like in .text and .rela.text.
1097 // Remember the index into the string table so we can write it
1098 // into the sh_name field of the section header table.
1099 SectionStringTableIndex[&it->getSection()] = Index;
1101 Index += Section.getSectionName().size() + 1;
1102 F->getContents() += Section.getSectionName();
1103 F->getContents() += '\x00';
1106 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1109 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1110 const MCValue Target,
1112 const MCFragment *DF) const {
1113 // If this is a PCrel relocation, find the section this fixup value is
1115 const MCSection *BaseSection = 0;
1117 BaseSection = &DF->getParent()->getSection();
1118 assert(BaseSection);
1121 const MCSection *SectionA = 0;
1122 const MCSymbol *SymbolA = 0;
1123 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1124 SymbolA = &A->getSymbol();
1125 SectionA = &SymbolA->getSection();
1128 const MCSection *SectionB = 0;
1129 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1130 SectionB = &B->getSymbol().getSection();
1134 return SectionA == SectionB;
1136 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1137 if (DataA.isExternal())
1140 return !SectionB && BaseSection == SectionA;
1143 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1144 const MCAsmLayout &Layout) {
1145 // Compute symbol table information.
1146 ComputeSymbolTable(Asm);
1148 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1149 const_cast<MCAsmLayout&>(Layout));
1151 // Add 1 for the null section.
1152 unsigned NumSections = Asm.size() + 1;
1153 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1154 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1155 uint64_t FileOff = HeaderSize;
1157 for (MCAssembler::const_iterator it = Asm.begin(),
1158 ie = Asm.end(); it != ie; ++it) {
1159 const MCSectionData &SD = *it;
1161 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1163 // Get the size of the section in the output file (including padding).
1164 uint64_t Size = Layout.getSectionFileSize(&SD);
1169 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1171 // Write out the ELF header ...
1172 WriteHeader(FileOff - HeaderSize, NumSections);
1174 FileOff = HeaderSize;
1176 // ... then all of the sections ...
1177 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1179 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
1182 for (MCAssembler::const_iterator it = Asm.begin(),
1183 ie = Asm.end(); it != ie; ++it) {
1184 const MCSectionData &SD = *it;
1186 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1187 WriteZeros(Padding);
1190 // Remember the offset into the file for this section.
1191 SectionOffsetMap[&it->getSection()] = FileOff;
1192 SectionIndexMap[&it->getSection()] = Index++;
1194 FileOff += Layout.getSectionFileSize(&SD);
1196 Asm.WriteSectionData(it, Layout, Writer);
1199 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1200 WriteZeros(Padding);
1203 // ... and then the section header table.
1204 // Should we align the section header table?
1206 // Null section first.
1207 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1209 for (MCAssembler::const_iterator it = Asm.begin(),
1210 ie = Asm.end(); it != ie; ++it) {
1211 const MCSectionData &SD = *it;
1212 const MCSectionELF &Section =
1213 static_cast<const MCSectionELF&>(SD.getSection());
1215 uint64_t sh_link = 0;
1216 uint64_t sh_info = 0;
1218 switch(Section.getType()) {
1219 case ELF::SHT_DYNAMIC:
1220 sh_link = SectionStringTableIndex[&it->getSection()];
1225 case ELF::SHT_RELA: {
1226 const MCSection *SymtabSection;
1227 const MCSection *InfoSection;
1229 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1230 SectionKind::getReadOnly(),
1232 sh_link = SectionIndexMap[SymtabSection];
1234 // Remove ".rel" and ".rela" prefixes.
1235 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1236 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1238 InfoSection = Asm.getContext().getELFSection(SectionName,
1239 ELF::SHT_PROGBITS, 0,
1240 SectionKind::getReadOnly(),
1242 sh_info = SectionIndexMap[InfoSection];
1246 case ELF::SHT_SYMTAB:
1247 case ELF::SHT_DYNSYM:
1248 sh_link = StringTableIndex;
1249 sh_info = LastLocalSymbolIndex;
1252 case ELF::SHT_PROGBITS:
1253 case ELF::SHT_STRTAB:
1254 case ELF::SHT_NOBITS:
1256 case ELF::SHT_ARM_ATTRIBUTES:
1261 assert(0 && "FIXME: sh_type value not supported!");
1265 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1266 Section.getType(), Section.getFlags(),
1268 SectionOffsetMap.lookup(&SD.getSection()),
1269 Layout.getSectionSize(&SD), sh_link,
1270 sh_info, SD.getAlignment(),
1271 Section.getEntrySize());
1275 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1277 Triple::OSType OSType,
1279 bool IsLittleEndian,
1280 bool HasRelocationAddend)
1281 : MCObjectWriter(OS, IsLittleEndian)
1283 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1284 HasRelocationAddend, OSType);
1287 ELFObjectWriter::~ELFObjectWriter() {
1288 delete (ELFObjectWriterImpl*) Impl;
1291 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1292 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1295 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1296 const MCAsmLayout &Layout,
1297 const MCFragment *Fragment,
1298 const MCFixup &Fixup, MCValue Target,
1299 uint64_t &FixedValue) {
1300 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1301 Target, FixedValue);
1304 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1305 const MCValue Target,
1307 const MCFragment *DF) const {
1308 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1312 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1313 const MCAsmLayout &Layout) {
1314 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);