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(MCSymbolRefExpr::VariantKind Variant) {
85 case MCSymbolRefExpr::VK_GOT:
86 case MCSymbolRefExpr::VK_PLT:
87 case MCSymbolRefExpr::VK_GOTPCREL:
88 case MCSymbolRefExpr::VK_TPOFF:
89 case MCSymbolRefExpr::VK_TLSGD:
90 case MCSymbolRefExpr::VK_GOTTPOFF:
91 case MCSymbolRefExpr::VK_INDNTPOFF:
92 case MCSymbolRefExpr::VK_NTPOFF:
93 case MCSymbolRefExpr::VK_GOTNTPOFF:
94 case MCSymbolRefExpr::VK_TLSLDM:
95 case MCSymbolRefExpr::VK_DTPOFF:
96 case MCSymbolRefExpr::VK_TLSLD:
103 class ELFObjectWriterImpl {
104 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
105 return Kind == X86::reloc_riprel_4byte ||
106 Kind == X86::reloc_riprel_4byte_movq_load;
110 /// ELFSymbolData - Helper struct for containing some precomputed information
112 struct ELFSymbolData {
113 MCSymbolData *SymbolData;
114 uint64_t StringIndex;
115 uint32_t SectionIndex;
117 // Support lexicographic sorting.
118 bool operator<(const ELFSymbolData &RHS) const {
119 if (GetType(*SymbolData) == ELF::STT_FILE)
121 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
123 return SymbolData->getSymbol().getName() <
124 RHS.SymbolData->getSymbol().getName();
128 /// @name Relocation Data
131 struct ELFRelocationEntry {
132 // Make these big enough for both 32-bit and 64-bit
136 const MCSymbol *Symbol;
139 // Support lexicographic sorting.
140 bool operator<(const ELFRelocationEntry &RE) const {
141 return RE.r_offset < r_offset;
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
149 llvm::DenseMap<const MCSectionData*,
150 std::vector<ELFRelocationEntry> > Relocations;
151 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
154 /// @name Symbol Table Data
157 SmallString<256> StringTable;
158 std::vector<ELFSymbolData> LocalSymbolData;
159 std::vector<ELFSymbolData> ExternalSymbolData;
160 std::vector<ELFSymbolData> UndefinedSymbolData;
164 int NumRegularSections;
168 bool NeedsSymtabShndx;
170 ELFObjectWriter *Writer;
174 unsigned Is64Bit : 1;
176 bool HasRelocationAddend;
178 Triple::OSType OSType;
182 // This holds the symbol table index of the last local symbol.
183 unsigned LastLocalSymbolIndex;
184 // This holds the .strtab section index.
185 unsigned StringTableIndex;
186 // This holds the .symtab section index.
187 unsigned SymbolTableIndex;
189 unsigned ShstrtabIndex;
192 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
193 uint16_t _EMachine, bool _HasRelAddend,
194 Triple::OSType _OSType)
195 : NeedsGOT(false), NeedsSymtabShndx(false), Writer(_Writer),
196 OS(Writer->getStream()),
197 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
198 OSType(_OSType), EMachine(_EMachine) {
201 void Write8(uint8_t Value) { Writer->Write8(Value); }
202 void Write16(uint16_t Value) { Writer->Write16(Value); }
203 void Write32(uint32_t Value) { Writer->Write32(Value); }
204 //void Write64(uint64_t Value) { Writer->Write64(Value); }
205 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
206 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
207 // Writer->WriteBytes(Str, ZeroFillSize);
210 void WriteWord(uint64_t W) {
217 void StringLE16(char *buf, uint16_t Value) {
218 buf[0] = char(Value >> 0);
219 buf[1] = char(Value >> 8);
222 void StringLE32(char *buf, uint32_t Value) {
223 StringLE16(buf, uint16_t(Value >> 0));
224 StringLE16(buf + 2, uint16_t(Value >> 16));
227 void StringLE64(char *buf, uint64_t Value) {
228 StringLE32(buf, uint32_t(Value >> 0));
229 StringLE32(buf + 4, uint32_t(Value >> 32));
232 void StringBE16(char *buf ,uint16_t Value) {
233 buf[0] = char(Value >> 8);
234 buf[1] = char(Value >> 0);
237 void StringBE32(char *buf, uint32_t Value) {
238 StringBE16(buf, uint16_t(Value >> 16));
239 StringBE16(buf + 2, uint16_t(Value >> 0));
242 void StringBE64(char *buf, uint64_t Value) {
243 StringBE32(buf, uint32_t(Value >> 32));
244 StringBE32(buf + 4, uint32_t(Value >> 0));
247 void String8(MCDataFragment &F, uint8_t Value) {
250 F.getContents() += StringRef(buf, 1);
253 void String16(MCDataFragment &F, uint16_t Value) {
255 if (Writer->isLittleEndian())
256 StringLE16(buf, Value);
258 StringBE16(buf, Value);
259 F.getContents() += StringRef(buf, 2);
262 void String32(MCDataFragment &F, uint32_t Value) {
264 if (Writer->isLittleEndian())
265 StringLE32(buf, Value);
267 StringBE32(buf, Value);
268 F.getContents() += StringRef(buf, 4);
271 void String64(MCDataFragment &F, uint64_t Value) {
273 if (Writer->isLittleEndian())
274 StringLE64(buf, Value);
276 StringBE64(buf, Value);
277 F.getContents() += StringRef(buf, 8);
280 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
282 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
283 uint64_t name, uint8_t info,
284 uint64_t value, uint64_t size,
285 uint8_t other, uint32_t shndx,
288 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
290 const MCAsmLayout &Layout);
292 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
293 void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
294 const MCAssembler &Asm,
295 const MCAsmLayout &Layout,
296 const SectionIndexMapTy &SectionIndexMap);
298 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
299 const MCFragment *Fragment, const MCFixup &Fixup,
300 MCValue Target, uint64_t &FixedValue);
302 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
305 /// ComputeSymbolTable - Compute the symbol table data
307 /// \param StringTable [out] - The string table data.
308 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
310 void ComputeSymbolTable(MCAssembler &Asm,
311 const SectionIndexMapTy &SectionIndexMap);
313 void ComputeIndexMap(MCAssembler &Asm,
314 SectionIndexMapTy &SectionIndexMap);
316 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
317 const MCSectionData &SD);
319 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
320 for (MCAssembler::const_iterator it = Asm.begin(),
321 ie = Asm.end(); it != ie; ++it) {
322 WriteRelocation(Asm, Layout, *it);
326 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
327 const SectionIndexMapTy &SectionIndexMap);
329 // Map from a group section to the signature symbol
330 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
331 void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
332 GroupMapTy &GroupMap);
334 void ExecutePostLayoutBinding(MCAssembler &Asm);
336 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
337 uint64_t Address, uint64_t Offset,
338 uint64_t Size, uint32_t Link, uint32_t Info,
339 uint64_t Alignment, uint64_t EntrySize);
341 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
342 const MCSectionData *SD);
344 bool IsFixupFullyResolved(const MCAssembler &Asm,
345 const MCValue Target,
347 const MCFragment *DF) const;
349 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
350 void WriteSection(MCAssembler &Asm,
351 const SectionIndexMapTy &SectionIndexMap,
352 uint32_t GroupSymbolIndex,
353 uint64_t Offset, uint64_t Size, uint64_t Alignment,
354 const MCSectionELF &Section);
359 // Emit the ELF header.
360 void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
361 unsigned NumberOfSections) {
367 // emitWord method behaves differently for ELF32 and ELF64, writing
368 // 4 bytes in the former and 8 in the latter.
370 Write8(0x7f); // e_ident[EI_MAG0]
371 Write8('E'); // e_ident[EI_MAG1]
372 Write8('L'); // e_ident[EI_MAG2]
373 Write8('F'); // e_ident[EI_MAG3]
375 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
378 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
380 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
383 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
384 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
385 default: Write8(ELF::ELFOSABI_NONE); break;
387 Write8(0); // e_ident[EI_ABIVERSION]
389 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
391 Write16(ELF::ET_REL); // e_type
393 Write16(EMachine); // e_machine = target
395 Write32(ELF::EV_CURRENT); // e_version
396 WriteWord(0); // e_entry, no entry point in .o file
397 WriteWord(0); // e_phoff, no program header for .o
398 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
399 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
401 // FIXME: Make this configurable.
402 Write32(0); // e_flags = whatever the target wants
404 // e_ehsize = ELF header size
405 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
407 Write16(0); // e_phentsize = prog header entry size
408 Write16(0); // e_phnum = # prog header entries = 0
410 // e_shentsize = Section header entry size
411 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
413 // e_shnum = # of section header ents
414 if (NumberOfSections >= ELF::SHN_LORESERVE)
417 Write16(NumberOfSections);
419 // e_shstrndx = Section # of '.shstrtab'
420 if (NumberOfSections >= ELF::SHN_LORESERVE)
421 Write16(ELF::SHN_XINDEX);
423 Write16(ShstrtabIndex);
426 void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *SymtabF,
427 MCDataFragment *ShndxF,
429 uint8_t info, uint64_t value,
430 uint64_t size, uint8_t other,
434 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
435 String32(*ShndxF, shndx);
437 String32(*ShndxF, 0);
440 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
441 uint16_t(ELF::SHN_XINDEX) : shndx;
444 String32(*SymtabF, name); // st_name
445 String8(*SymtabF, info); // st_info
446 String8(*SymtabF, other); // st_other
447 String16(*SymtabF, Index); // st_shndx
448 String64(*SymtabF, value); // st_value
449 String64(*SymtabF, size); // st_size
451 String32(*SymtabF, name); // st_name
452 String32(*SymtabF, value); // st_value
453 String32(*SymtabF, size); // st_size
454 String8(*SymtabF, info); // st_info
455 String8(*SymtabF, other); // st_other
456 String16(*SymtabF, Index); // st_shndx
460 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
461 if (Data.isCommon() && Data.isExternal())
462 return Data.getCommonAlignment();
464 const MCSymbol &Symbol = Data.getSymbol();
465 if (!Symbol.isInSection())
468 if (MCFragment *FF = Data.getFragment())
469 return Layout.getSymbolAddress(&Data) -
470 Layout.getSectionAddress(FF->getParent());
475 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
476 const MCSymbol *S = &Symbol;
477 while (S->isVariable()) {
478 const MCExpr *Value = S->getVariableValue();
479 MCExpr::ExprKind Kind = Value->getKind();
481 case MCExpr::SymbolRef: {
482 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
483 S = &Ref->getSymbol();
486 case MCExpr::Target: {
487 const MCTargetExpr *TExp = static_cast<const MCTargetExpr*>(Value);
489 TExp->EvaluateAsRelocatableImpl(Res, NULL);
490 S = &Res.getSymA()->getSymbol();
500 void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
501 // The presence of symbol versions causes undefined symbols and
502 // versions declared with @@@ to be renamed.
504 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
505 ie = Asm.symbol_end(); it != ie; ++it) {
506 const MCSymbol &Alias = it->getSymbol();
507 const MCSymbol &Symbol = AliasedSymbol(Alias);
508 MCSymbolData &SD = Asm.getSymbolData(Symbol);
510 // Undefined symbols are global, but this is the first place we
511 // are able to set it.
512 if (Symbol.isUndefined() && !Symbol.isVariable()) {
513 if (GetBinding(SD) == ELF::STB_LOCAL) {
514 SetBinding(SD, ELF::STB_GLOBAL);
515 SetBinding(*it, ELF::STB_GLOBAL);
520 if (&Symbol == &Alias)
523 StringRef AliasName = Alias.getName();
524 size_t Pos = AliasName.find('@');
525 if (Pos == StringRef::npos)
528 // Aliases defined with .symvar copy the binding from the symbol they alias.
529 // This is the first place we are able to copy this information.
530 it->setExternal(SD.isExternal());
531 SetBinding(*it, GetBinding(SD));
533 StringRef Rest = AliasName.substr(Pos);
534 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
537 // FIXME: produce a better error message.
538 if (Symbol.isUndefined() && Rest.startswith("@@") &&
539 !Rest.startswith("@@@"))
540 report_fatal_error("A @@ version cannot be undefined");
542 Renames.insert(std::make_pair(&Symbol, &Alias));
546 void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *SymtabF,
547 MCDataFragment *ShndxF,
549 const MCAsmLayout &Layout) {
550 MCSymbolData &OrigData = *MSD.SymbolData;
552 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
554 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
555 Data.getSymbol().isVariable();
557 uint8_t Binding = GetBinding(OrigData);
558 uint8_t Visibility = GetVisibility(OrigData);
559 uint8_t Type = GetType(Data);
561 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
562 uint8_t Other = Visibility;
564 uint64_t Value = SymbolValue(Data, Layout);
568 assert(!(Data.isCommon() && !Data.isExternal()));
570 ESize = Data.getSize();
571 if (Data.getSize()) {
573 if (ESize->getKind() == MCExpr::Binary) {
574 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
576 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
577 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
578 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
579 Size = Res.getConstant();
581 } else if (ESize->getKind() == MCExpr::Constant) {
582 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
584 assert(0 && "Unsupported size expression");
588 // Write out the symbol table entry
589 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
590 Size, Other, MSD.SectionIndex, IsReserved);
593 void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *SymtabF,
594 MCDataFragment *ShndxF,
595 const MCAssembler &Asm,
596 const MCAsmLayout &Layout,
597 const SectionIndexMapTy &SectionIndexMap) {
598 // The string table must be emitted first because we need the index
599 // into the string table for all the symbol names.
600 assert(StringTable.size() && "Missing string table");
602 // FIXME: Make sure the start of the symbol table is aligned.
604 // The first entry is the undefined symbol entry.
605 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
607 // Write the symbol table entries.
608 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
609 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
610 ELFSymbolData &MSD = LocalSymbolData[i];
611 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
614 // Write out a symbol table entry for each regular section.
615 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
617 const MCSectionELF &Section =
618 static_cast<const MCSectionELF&>(i->getSection());
619 if (Section.getType() == ELF::SHT_RELA ||
620 Section.getType() == ELF::SHT_REL ||
621 Section.getType() == ELF::SHT_STRTAB ||
622 Section.getType() == ELF::SHT_SYMTAB)
624 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
625 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
626 LastLocalSymbolIndex++;
629 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
630 ELFSymbolData &MSD = ExternalSymbolData[i];
631 MCSymbolData &Data = *MSD.SymbolData;
632 assert(((Data.getFlags() & ELF_STB_Global) ||
633 (Data.getFlags() & ELF_STB_Weak)) &&
634 "External symbol requires STB_GLOBAL or STB_WEAK flag");
635 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
636 if (GetBinding(Data) == ELF::STB_LOCAL)
637 LastLocalSymbolIndex++;
640 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
641 ELFSymbolData &MSD = UndefinedSymbolData[i];
642 MCSymbolData &Data = *MSD.SymbolData;
643 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
644 if (GetBinding(Data) == ELF::STB_LOCAL)
645 LastLocalSymbolIndex++;
649 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
650 const MCValue &Target,
651 const MCFragment &F) {
652 const MCSymbol &Symbol = SD.getSymbol();
653 if (Symbol.isUndefined())
656 const MCSectionELF &Section =
657 static_cast<const MCSectionELF&>(Symbol.getSection());
662 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
663 const MCSectionELF &Sec2 =
664 static_cast<const MCSectionELF&>(F.getParent()->getSection());
666 if (Section.getKind().isBSS())
669 if (&Sec2 != &Section &&
670 (Kind == MCSymbolRefExpr::VK_PLT ||
671 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
672 Kind == MCSymbolRefExpr::VK_GOTOFF))
675 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
676 return Target.getConstant() != 0;
681 // FIXME: this is currently X86/X86_64 only
682 void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
683 const MCAsmLayout &Layout,
684 const MCFragment *Fragment,
685 const MCFixup &Fixup,
687 uint64_t &FixedValue) {
690 int64_t Value = Target.getConstant();
691 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
692 const MCSymbol &ASymbol = AliasedSymbol(Symbol);
693 const MCSymbol *RenamedP = Renames.lookup(&Symbol);
696 const MCSymbol &Renamed = *RenamedP;
698 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
699 if (!Target.isAbsolute()) {
700 MCSymbolData &SD = Asm.getSymbolData(Symbol);
701 MCFragment *F = SD.getFragment();
703 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
704 const MCSymbol &SymbolB = RefB->getSymbol();
705 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
707 MCSectionData *Sec = Fragment->getParent();
709 // Offset of the symbol in the section
710 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
712 // Ofeset of the relocation in the section
713 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
717 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
718 if (!RelocOnSymbol) {
719 Index = F->getParent()->getOrdinal();
721 MCSectionData *FSD = F->getParent();
722 // Offset of the symbol in the section
723 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
725 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
726 WeakrefUsedInReloc.insert(&Renamed);
728 UsedInReloc.insert(&Renamed);
732 // Compensate for the addend on i386.
739 // determine the type of the relocation
741 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
747 llvm_unreachable("Unimplemented");
748 case MCSymbolRefExpr::VK_None:
749 Type = ELF::R_X86_64_PC32;
751 case MCSymbolRefExpr::VK_PLT:
752 Type = ELF::R_X86_64_PLT32;
754 case MCSymbolRefExpr::VK_GOTPCREL:
755 Type = ELF::R_X86_64_GOTPCREL;
757 case MCSymbolRefExpr::VK_GOTTPOFF:
758 Type = ELF::R_X86_64_GOTTPOFF;
760 case MCSymbolRefExpr::VK_TLSGD:
761 Type = ELF::R_X86_64_TLSGD;
763 case MCSymbolRefExpr::VK_TLSLD:
764 Type = ELF::R_X86_64_TLSLD;
768 switch ((unsigned)Fixup.getKind()) {
769 default: llvm_unreachable("invalid fixup kind!");
770 case FK_Data_8: Type = ELF::R_X86_64_64; break;
771 case X86::reloc_signed_4byte:
772 case X86::reloc_pcrel_4byte:
773 assert(isInt<32>(Target.getConstant()));
776 llvm_unreachable("Unimplemented");
777 case MCSymbolRefExpr::VK_None:
778 Type = ELF::R_X86_64_32S;
780 case MCSymbolRefExpr::VK_GOT:
781 Type = ELF::R_X86_64_GOT32;
783 case MCSymbolRefExpr::VK_GOTPCREL:
784 Type = ELF::R_X86_64_GOTPCREL;
786 case MCSymbolRefExpr::VK_TPOFF:
787 Type = ELF::R_X86_64_TPOFF32;
789 case MCSymbolRefExpr::VK_DTPOFF:
790 Type = ELF::R_X86_64_DTPOFF32;
795 Type = ELF::R_X86_64_32;
797 case FK_Data_2: Type = ELF::R_X86_64_16; break;
798 case X86::reloc_pcrel_1byte:
799 case FK_Data_1: Type = ELF::R_X86_64_8; break;
806 llvm_unreachable("Unimplemented");
807 case MCSymbolRefExpr::VK_None:
808 Type = ELF::R_386_PC32;
810 case MCSymbolRefExpr::VK_PLT:
811 Type = ELF::R_386_PLT32;
815 switch ((unsigned)Fixup.getKind()) {
816 default: llvm_unreachable("invalid fixup kind!");
818 case X86::reloc_global_offset_table:
819 Type = ELF::R_386_GOTPC;
822 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
824 case X86::reloc_signed_4byte:
825 case X86::reloc_pcrel_4byte:
829 llvm_unreachable("Unimplemented");
830 case MCSymbolRefExpr::VK_None:
831 Type = ELF::R_386_32;
833 case MCSymbolRefExpr::VK_GOT:
834 Type = ELF::R_386_GOT32;
836 case MCSymbolRefExpr::VK_GOTOFF:
837 Type = ELF::R_386_GOTOFF;
839 case MCSymbolRefExpr::VK_TLSGD:
840 Type = ELF::R_386_TLS_GD;
842 case MCSymbolRefExpr::VK_TPOFF:
843 Type = ELF::R_386_TLS_LE_32;
845 case MCSymbolRefExpr::VK_INDNTPOFF:
846 Type = ELF::R_386_TLS_IE;
848 case MCSymbolRefExpr::VK_NTPOFF:
849 Type = ELF::R_386_TLS_LE;
851 case MCSymbolRefExpr::VK_GOTNTPOFF:
852 Type = ELF::R_386_TLS_GOTIE;
854 case MCSymbolRefExpr::VK_TLSLDM:
855 Type = ELF::R_386_TLS_LDM;
857 case MCSymbolRefExpr::VK_DTPOFF:
858 Type = ELF::R_386_TLS_LDO_32;
862 case FK_Data_2: Type = ELF::R_386_16; break;
863 case X86::reloc_pcrel_1byte:
864 case FK_Data_1: Type = ELF::R_386_8; break;
869 if (RelocNeedsGOT(Modifier))
872 ELFRelocationEntry ERE;
876 ERE.Symbol = &Renamed;
878 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
880 if (HasRelocationAddend)
881 ERE.r_addend = Addend;
883 ERE.r_addend = 0; // Silence compiler warning.
885 Relocations[Fragment->getParent()].push_back(ERE);
889 ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
891 MCSymbolData &SD = Asm.getSymbolData(*S);
894 if (!SD.isExternal() && !S->isUndefined())
895 return SD.getIndex() + /* empty symbol */ 1;
897 // External or undefined symbol.
898 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
901 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
902 bool Used, bool Renamed) {
903 if (Data.getFlags() & ELF_Other_Weakref)
912 const MCSymbol &Symbol = Data.getSymbol();
914 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
917 const MCSymbol &A = AliasedSymbol(Symbol);
918 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
921 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
924 if (Symbol.isTemporary())
930 static bool isLocal(const MCSymbolData &Data) {
931 if (Data.isExternal())
934 const MCSymbol &Symbol = Data.getSymbol();
935 if (Symbol.isUndefined() && !Symbol.isVariable())
941 void ELFObjectWriterImpl::ComputeIndexMap(MCAssembler &Asm,
942 SectionIndexMapTy &SectionIndexMap) {
944 for (MCAssembler::iterator it = Asm.begin(),
945 ie = Asm.end(); it != ie; ++it) {
946 const MCSectionELF &Section =
947 static_cast<const MCSectionELF &>(it->getSection());
948 if (Section.getType() != ELF::SHT_GROUP)
950 SectionIndexMap[&Section] = Index++;
953 for (MCAssembler::iterator it = Asm.begin(),
954 ie = Asm.end(); it != ie; ++it) {
955 const MCSectionELF &Section =
956 static_cast<const MCSectionELF &>(it->getSection());
957 if (Section.getType() == ELF::SHT_GROUP)
959 SectionIndexMap[&Section] = Index++;
963 void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm,
964 const SectionIndexMapTy &SectionIndexMap) {
965 // FIXME: Is this the correct place to do this?
967 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
968 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
969 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
970 Data.setExternal(true);
971 SetBinding(Data, ELF::STB_GLOBAL);
974 // Build section lookup table.
975 NumRegularSections = Asm.size();
977 // Index 0 is always the empty string.
978 StringMap<uint64_t> StringIndexMap;
979 StringTable += '\x00';
981 // Add the data for the symbols.
982 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
983 ie = Asm.symbol_end(); it != ie; ++it) {
984 const MCSymbol &Symbol = it->getSymbol();
986 bool Used = UsedInReloc.count(&Symbol);
987 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
988 if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
989 Renames.count(&Symbol)))
994 bool Local = isLocal(*it);
995 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
997 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
998 SetBinding(*it, ELF::STB_WEAK);
1000 if (it->isCommon()) {
1002 MSD.SectionIndex = ELF::SHN_COMMON;
1003 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
1004 MSD.SectionIndex = ELF::SHN_ABS;
1005 } else if (RefSymbol.isUndefined()) {
1006 MSD.SectionIndex = ELF::SHN_UNDEF;
1008 const MCSectionELF &Section =
1009 static_cast<const MCSectionELF&>(RefSymbol.getSection());
1010 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1011 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
1012 NeedsSymtabShndx = true;
1013 assert(MSD.SectionIndex && "Invalid section index!");
1016 // The @@@ in symbol version is replaced with @ in undefined symbols and
1017 // @@ in defined ones.
1018 StringRef Name = Symbol.getName();
1019 size_t Pos = Name.find("@@@");
1020 std::string FinalName;
1021 if (Pos != StringRef::npos) {
1022 StringRef Prefix = Name.substr(0, Pos);
1023 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1024 StringRef Suffix = Name.substr(Pos + n);
1025 FinalName = Prefix.str() + Suffix.str();
1027 FinalName = Name.str();
1030 uint64_t &Entry = StringIndexMap[FinalName];
1032 Entry = StringTable.size();
1033 StringTable += FinalName;
1034 StringTable += '\x00';
1036 MSD.StringIndex = Entry;
1037 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1038 UndefinedSymbolData.push_back(MSD);
1040 LocalSymbolData.push_back(MSD);
1042 ExternalSymbolData.push_back(MSD);
1045 // Symbols are required to be in lexicographic order.
1046 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1047 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1048 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1050 // Set the symbol indices. Local symbols must come before all other
1051 // symbols with non-local bindings.
1053 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1054 LocalSymbolData[i].SymbolData->setIndex(Index++);
1055 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1056 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1057 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1058 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1061 void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1062 const MCSectionData &SD) {
1063 if (!Relocations[&SD].empty()) {
1064 MCContext &Ctx = Asm.getContext();
1065 const MCSectionELF *RelaSection;
1066 const MCSectionELF &Section =
1067 static_cast<const MCSectionELF&>(SD.getSection());
1069 const StringRef SectionName = Section.getSectionName();
1070 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1071 RelaSectionName += SectionName;
1074 if (HasRelocationAddend)
1075 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1077 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1079 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1080 ELF::SHT_RELA : ELF::SHT_REL, 0,
1081 SectionKind::getReadOnly(),
1084 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1085 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1087 MCDataFragment *F = new MCDataFragment(&RelaSD);
1089 WriteRelocationsFragment(Asm, F, &SD);
1091 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
1095 void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1096 uint64_t Flags, uint64_t Address,
1097 uint64_t Offset, uint64_t Size,
1098 uint32_t Link, uint32_t Info,
1100 uint64_t EntrySize) {
1101 Write32(Name); // sh_name: index into string table
1102 Write32(Type); // sh_type
1103 WriteWord(Flags); // sh_flags
1104 WriteWord(Address); // sh_addr
1105 WriteWord(Offset); // sh_offset
1106 WriteWord(Size); // sh_size
1107 Write32(Link); // sh_link
1108 Write32(Info); // sh_info
1109 WriteWord(Alignment); // sh_addralign
1110 WriteWord(EntrySize); // sh_entsize
1113 void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1115 const MCSectionData *SD) {
1116 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1117 // sort by the r_offset just like gnu as does
1118 array_pod_sort(Relocs.begin(), Relocs.end());
1120 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1121 ELFRelocationEntry entry = Relocs[e - i - 1];
1123 if (entry.Index < 0)
1124 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1126 entry.Index += LocalSymbolData.size() + 1;
1128 String64(*F, entry.r_offset);
1130 struct ELF::Elf64_Rela ERE64;
1131 ERE64.setSymbolAndType(entry.Index, entry.Type);
1132 String64(*F, ERE64.r_info);
1134 if (HasRelocationAddend)
1135 String64(*F, entry.r_addend);
1137 String32(*F, entry.r_offset);
1139 struct ELF::Elf32_Rela ERE32;
1140 ERE32.setSymbolAndType(entry.Index, entry.Type);
1141 String32(*F, ERE32.r_info);
1143 if (HasRelocationAddend)
1144 String32(*F, entry.r_addend);
1149 void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1150 MCAsmLayout &Layout,
1151 const SectionIndexMapTy &SectionIndexMap) {
1152 MCContext &Ctx = Asm.getContext();
1155 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1157 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1158 const MCSectionELF *ShstrtabSection =
1159 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1160 SectionKind::getReadOnly());
1161 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1162 ShstrtabSD.setAlignment(1);
1163 ShstrtabIndex = Asm.size();
1165 const MCSectionELF *SymtabSection =
1166 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1167 SectionKind::getReadOnly(),
1169 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1170 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1171 SymbolTableIndex = Asm.size();
1173 MCSectionData *SymtabShndxSD = NULL;
1175 if (NeedsSymtabShndx) {
1176 const MCSectionELF *SymtabShndxSection =
1177 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1178 SectionKind::getReadOnly(), 4, "");
1179 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1180 SymtabShndxSD->setAlignment(4);
1183 const MCSection *StrtabSection;
1184 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1185 SectionKind::getReadOnly());
1186 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1187 StrtabSD.setAlignment(1);
1188 StringTableIndex = Asm.size();
1190 WriteRelocations(Asm, Layout);
1193 F = new MCDataFragment(&SymtabSD);
1194 MCDataFragment *ShndxF = NULL;
1195 if (NeedsSymtabShndx) {
1196 ShndxF = new MCDataFragment(SymtabShndxSD);
1197 Asm.AddSectionToTheEnd(*Writer, *SymtabShndxSD, Layout);
1199 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1200 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
1202 F = new MCDataFragment(&StrtabSD);
1203 F->getContents().append(StringTable.begin(), StringTable.end());
1204 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
1206 F = new MCDataFragment(&ShstrtabSD);
1208 // Section header string table.
1210 // The first entry of a string table holds a null character so skip
1213 F->getContents() += '\x00';
1215 StringMap<uint64_t> SecStringMap;
1216 for (MCAssembler::const_iterator it = Asm.begin(),
1217 ie = Asm.end(); it != ie; ++it) {
1218 const MCSectionELF &Section =
1219 static_cast<const MCSectionELF&>(it->getSection());
1220 // FIXME: We could merge suffixes like in .text and .rela.text.
1222 StringRef Name = Section.getSectionName();
1223 if (SecStringMap.count(Name)) {
1224 SectionStringTableIndex[&Section] = SecStringMap[Name];
1227 // Remember the index into the string table so we can write it
1228 // into the sh_name field of the section header table.
1229 SectionStringTableIndex[&Section] = Index;
1230 SecStringMap[Name] = Index;
1232 Index += Name.size() + 1;
1233 F->getContents() += Name;
1234 F->getContents() += '\x00';
1237 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1240 bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1241 const MCValue Target,
1243 const MCFragment *DF) const {
1244 // If this is a PCrel relocation, find the section this fixup value is
1246 const MCSection *BaseSection = 0;
1248 BaseSection = &DF->getParent()->getSection();
1249 assert(BaseSection);
1252 const MCSection *SectionA = 0;
1253 const MCSymbol *SymbolA = 0;
1254 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1255 SymbolA = &A->getSymbol();
1256 SectionA = &SymbolA->getSection();
1259 const MCSection *SectionB = 0;
1260 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1261 SectionB = &B->getSymbol().getSection();
1265 return SectionA == SectionB;
1267 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1268 if (DataA.isExternal())
1271 return !SectionB && BaseSection == SectionA;
1274 void ELFObjectWriterImpl::CreateGroupSections(MCAssembler &Asm,
1275 MCAsmLayout &Layout,
1276 GroupMapTy &GroupMap) {
1277 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
1279 RevGroupMapTy Groups;
1280 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1282 const MCSectionELF &Section =
1283 static_cast<const MCSectionELF&>(it->getSection());
1284 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1287 const MCSymbol *SignatureSymbol = Section.getGroup();
1288 Asm.getOrCreateSymbolData(*SignatureSymbol);
1289 const MCSectionELF *&Group = Groups[SignatureSymbol];
1291 Group = Asm.getContext().CreateELFGroupSection();
1292 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1293 Data.setAlignment(4);
1294 MCDataFragment *F = new MCDataFragment(&Data);
1295 String32(*F, ELF::GRP_COMDAT);
1297 GroupMap[Group] = SignatureSymbol;
1300 // Add sections to the groups
1302 unsigned NumGroups = Groups.size();
1303 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1304 it != ie; ++it, ++Index) {
1305 const MCSectionELF &Section =
1306 static_cast<const MCSectionELF&>(it->getSection());
1307 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1309 const MCSectionELF *Group = Groups[Section.getGroup()];
1310 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1311 // FIXME: we could use the previous fragment
1312 MCDataFragment *F = new MCDataFragment(&Data);
1313 String32(*F, NumGroups + Index);
1316 for (RevGroupMapTy::const_iterator i = Groups.begin(), e = Groups.end();
1318 const MCSectionELF *Group = i->second;
1319 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1320 Asm.AddSectionToTheEnd(*Writer, Data, Layout);
1324 void ELFObjectWriterImpl::WriteSection(MCAssembler &Asm,
1325 const SectionIndexMapTy &SectionIndexMap,
1326 uint32_t GroupSymbolIndex,
1327 uint64_t Offset, uint64_t Size,
1329 const MCSectionELF &Section) {
1330 uint64_t sh_link = 0;
1331 uint64_t sh_info = 0;
1333 switch(Section.getType()) {
1334 case ELF::SHT_DYNAMIC:
1335 sh_link = SectionStringTableIndex[&Section];
1340 case ELF::SHT_RELA: {
1341 const MCSectionELF *SymtabSection;
1342 const MCSectionELF *InfoSection;
1343 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1345 SectionKind::getReadOnly());
1346 sh_link = SectionIndexMap.lookup(SymtabSection);
1347 assert(sh_link && ".symtab not found");
1349 // Remove ".rel" and ".rela" prefixes.
1350 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1351 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1353 InfoSection = Asm.getContext().getELFSection(SectionName,
1354 ELF::SHT_PROGBITS, 0,
1355 SectionKind::getReadOnly());
1356 sh_info = SectionIndexMap.lookup(InfoSection);
1360 case ELF::SHT_SYMTAB:
1361 case ELF::SHT_DYNSYM:
1362 sh_link = StringTableIndex;
1363 sh_info = LastLocalSymbolIndex;
1366 case ELF::SHT_SYMTAB_SHNDX:
1367 sh_link = SymbolTableIndex;
1370 case ELF::SHT_PROGBITS:
1371 case ELF::SHT_STRTAB:
1372 case ELF::SHT_NOBITS:
1374 case ELF::SHT_ARM_ATTRIBUTES:
1378 case ELF::SHT_GROUP: {
1379 sh_link = SymbolTableIndex;
1380 sh_info = GroupSymbolIndex;
1385 assert(0 && "FIXME: sh_type value not supported!");
1389 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1390 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1391 Alignment, Section.getEntrySize());
1394 void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
1395 const MCAsmLayout &Layout) {
1397 GroupMapTy GroupMap;
1398 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap);
1400 SectionIndexMapTy SectionIndexMap;
1402 ComputeIndexMap(Asm, SectionIndexMap);
1404 // Compute symbol table information.
1405 ComputeSymbolTable(Asm, SectionIndexMap);
1407 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1408 const_cast<MCAsmLayout&>(Layout),
1411 // Update to include the metadata sections.
1412 ComputeIndexMap(Asm, SectionIndexMap);
1414 // Add 1 for the null section.
1415 unsigned NumSections = Asm.size() + 1;
1416 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1417 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1418 uint64_t FileOff = HeaderSize;
1420 std::vector<const MCSectionELF*> Sections;
1421 Sections.resize(NumSections);
1423 for (SectionIndexMapTy::const_iterator i=
1424 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1425 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1426 Sections[p.second] = p.first;
1429 for (unsigned i = 1; i < NumSections; ++i) {
1430 const MCSectionELF &Section = *Sections[i];
1431 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1433 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1435 // Get the size of the section in the output file (including padding).
1436 uint64_t Size = Layout.getSectionFileSize(&SD);
1441 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1443 // Write out the ELF header ...
1444 WriteHeader(FileOff - HeaderSize, NumSections);
1446 FileOff = HeaderSize;
1448 // ... then all of the sections ...
1449 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1451 for (unsigned i = 1; i < NumSections; ++i) {
1452 const MCSectionELF &Section = *Sections[i];
1453 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1455 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1456 WriteZeros(Padding);
1459 // Remember the offset into the file for this section.
1460 SectionOffsetMap[&Section] = FileOff;
1462 FileOff += Layout.getSectionFileSize(&SD);
1464 Asm.WriteSectionData(&SD, Layout, Writer);
1467 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1468 WriteZeros(Padding);
1471 // ... and then the section header table.
1472 // Should we align the section header table?
1474 // Null section first.
1475 uint64_t FirstSectionSize =
1476 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1477 uint32_t FirstSectionLink =
1478 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1479 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1481 for (unsigned i = 1; i < NumSections; ++i) {
1482 const MCSectionELF &Section = *Sections[i];
1483 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1484 uint32_t GroupSymbolIndex;
1485 if (Section.getType() != ELF::SHT_GROUP)
1486 GroupSymbolIndex = 0;
1488 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1490 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1491 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1492 SD.getAlignment(), Section);
1496 ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1498 Triple::OSType OSType,
1500 bool IsLittleEndian,
1501 bool HasRelocationAddend)
1502 : MCObjectWriter(OS, IsLittleEndian)
1504 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1505 HasRelocationAddend, OSType);
1508 ELFObjectWriter::~ELFObjectWriter() {
1509 delete (ELFObjectWriterImpl*) Impl;
1512 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1513 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1516 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1517 const MCAsmLayout &Layout,
1518 const MCFragment *Fragment,
1519 const MCFixup &Fixup, MCValue Target,
1520 uint64_t &FixedValue) {
1521 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1522 Target, FixedValue);
1525 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1526 const MCValue Target,
1528 const MCFragment *DF) const {
1529 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1533 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1534 const MCAsmLayout &Layout) {
1535 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);