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/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCAssembler.h"
19 #include "llvm/MC/MCAsmLayout.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCELFSymbolFlags.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Target/TargetAsmBackend.h"
32 #include "../Target/X86/X86FixupKinds.h"
37 static unsigned GetType(const MCSymbolData &SD) {
38 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
39 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
40 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
41 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
42 Type == ELF::STT_TLS);
46 static unsigned GetBinding(const MCSymbolData &SD) {
47 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
48 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
49 Binding == ELF::STB_WEAK);
53 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
54 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
55 Binding == ELF::STB_WEAK);
56 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
57 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
60 static unsigned GetVisibility(MCSymbolData &SD) {
62 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
63 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
64 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
68 static bool isFixupKindX86PCRel(unsigned Kind) {
72 case X86::reloc_pcrel_1byte:
73 case X86::reloc_pcrel_4byte:
74 case X86::reloc_riprel_4byte:
75 case X86::reloc_riprel_4byte_movq_load:
80 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
84 case MCSymbolRefExpr::VK_GOT:
85 case MCSymbolRefExpr::VK_PLT:
86 case MCSymbolRefExpr::VK_GOTPCREL:
87 case MCSymbolRefExpr::VK_TPOFF:
88 case MCSymbolRefExpr::VK_TLSGD:
89 case MCSymbolRefExpr::VK_GOTTPOFF:
90 case MCSymbolRefExpr::VK_INDNTPOFF:
91 case MCSymbolRefExpr::VK_NTPOFF:
92 case MCSymbolRefExpr::VK_GOTNTPOFF:
93 case MCSymbolRefExpr::VK_TLSLDM:
94 case MCSymbolRefExpr::VK_DTPOFF:
95 case MCSymbolRefExpr::VK_TLSLD:
101 class ELFObjectWriter : public MCObjectWriter {
102 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
103 return Kind == X86::reloc_riprel_4byte ||
104 Kind == X86::reloc_riprel_4byte_movq_load;
108 /// ELFSymbolData - Helper struct for containing some precomputed information
110 struct ELFSymbolData {
111 MCSymbolData *SymbolData;
112 uint64_t StringIndex;
113 uint32_t SectionIndex;
115 // Support lexicographic sorting.
116 bool operator<(const ELFSymbolData &RHS) const {
117 if (GetType(*SymbolData) == ELF::STT_FILE)
119 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
121 return SymbolData->getSymbol().getName() <
122 RHS.SymbolData->getSymbol().getName();
126 /// @name Relocation Data
129 struct ELFRelocationEntry {
130 // Make these big enough for both 32-bit and 64-bit
134 const MCSymbol *Symbol;
137 // Support lexicographic sorting.
138 bool operator<(const ELFRelocationEntry &RE) const {
139 return RE.r_offset < r_offset;
143 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
144 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
145 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
147 llvm::DenseMap<const MCSectionData*,
148 std::vector<ELFRelocationEntry> > Relocations;
149 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
152 /// @name Symbol Table Data
155 SmallString<256> StringTable;
156 std::vector<ELFSymbolData> LocalSymbolData;
157 std::vector<ELFSymbolData> ExternalSymbolData;
158 std::vector<ELFSymbolData> UndefinedSymbolData;
162 int NumRegularSections;
166 bool NeedsSymtabShndx;
168 unsigned Is64Bit : 1;
170 bool HasRelocationAddend;
172 Triple::OSType OSType;
176 // This holds the symbol table index of the last local symbol.
177 unsigned LastLocalSymbolIndex;
178 // This holds the .strtab section index.
179 unsigned StringTableIndex;
180 // This holds the .symtab section index.
181 unsigned SymbolTableIndex;
183 unsigned ShstrtabIndex;
186 ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
187 uint16_t _EMachine, bool _HasRelAddend,
188 Triple::OSType _OSType)
189 : MCObjectWriter(_OS, IsLittleEndian),
190 NeedsGOT(false), NeedsSymtabShndx(false),
191 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
192 OSType(_OSType), EMachine(_EMachine) {
195 void WriteWord(uint64_t W) {
202 void StringLE16(char *buf, uint16_t Value) {
203 buf[0] = char(Value >> 0);
204 buf[1] = char(Value >> 8);
207 void StringLE32(char *buf, uint32_t Value) {
208 StringLE16(buf, uint16_t(Value >> 0));
209 StringLE16(buf + 2, uint16_t(Value >> 16));
212 void StringLE64(char *buf, uint64_t Value) {
213 StringLE32(buf, uint32_t(Value >> 0));
214 StringLE32(buf + 4, uint32_t(Value >> 32));
217 void StringBE16(char *buf ,uint16_t Value) {
218 buf[0] = char(Value >> 8);
219 buf[1] = char(Value >> 0);
222 void StringBE32(char *buf, uint32_t Value) {
223 StringBE16(buf, uint16_t(Value >> 16));
224 StringBE16(buf + 2, uint16_t(Value >> 0));
227 void StringBE64(char *buf, uint64_t Value) {
228 StringBE32(buf, uint32_t(Value >> 32));
229 StringBE32(buf + 4, uint32_t(Value >> 0));
232 void String8(MCDataFragment &F, uint8_t Value) {
235 F.getContents() += StringRef(buf, 1);
238 void String16(MCDataFragment &F, uint16_t Value) {
240 if (isLittleEndian())
241 StringLE16(buf, Value);
243 StringBE16(buf, Value);
244 F.getContents() += StringRef(buf, 2);
247 void String32(MCDataFragment &F, uint32_t Value) {
249 if (isLittleEndian())
250 StringLE32(buf, Value);
252 StringBE32(buf, Value);
253 F.getContents() += StringRef(buf, 4);
256 void String64(MCDataFragment &F, uint64_t Value) {
258 if (isLittleEndian())
259 StringLE64(buf, Value);
261 StringBE64(buf, Value);
262 F.getContents() += StringRef(buf, 8);
265 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
267 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
268 uint64_t name, uint8_t info,
269 uint64_t value, uint64_t size,
270 uint8_t other, uint32_t shndx,
273 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
275 const MCAsmLayout &Layout);
277 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
278 void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
279 const MCAssembler &Asm,
280 const MCAsmLayout &Layout,
281 const SectionIndexMapTy &SectionIndexMap);
283 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
284 const MCFragment *Fragment, const MCFixup &Fixup,
285 MCValue Target, uint64_t &FixedValue);
287 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
290 /// ComputeSymbolTable - Compute the symbol table data
292 /// \param StringTable [out] - The string table data.
293 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
295 void ComputeSymbolTable(MCAssembler &Asm,
296 const SectionIndexMapTy &SectionIndexMap);
298 void ComputeIndexMap(MCAssembler &Asm,
299 SectionIndexMapTy &SectionIndexMap);
301 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
302 const MCSectionData &SD);
304 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
305 for (MCAssembler::const_iterator it = Asm.begin(),
306 ie = Asm.end(); it != ie; ++it) {
307 WriteRelocation(Asm, Layout, *it);
311 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
312 const SectionIndexMapTy &SectionIndexMap);
314 // Map from a group section to the signature symbol
315 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
316 void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
317 GroupMapTy &GroupMap);
319 void ExecutePostLayoutBinding(MCAssembler &Asm);
321 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
322 uint64_t Address, uint64_t Offset,
323 uint64_t Size, uint32_t Link, uint32_t Info,
324 uint64_t Alignment, uint64_t EntrySize);
326 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
327 const MCSectionData *SD);
329 bool IsFixupFullyResolved(const MCAssembler &Asm,
330 const MCValue Target,
332 const MCFragment *DF) const;
334 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
335 void WriteSection(MCAssembler &Asm,
336 const SectionIndexMapTy &SectionIndexMap,
337 uint32_t GroupSymbolIndex,
338 uint64_t Offset, uint64_t Size, uint64_t Alignment,
339 const MCSectionELF &Section);
344 // Emit the ELF header.
345 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
346 unsigned NumberOfSections) {
352 // emitWord method behaves differently for ELF32 and ELF64, writing
353 // 4 bytes in the former and 8 in the latter.
355 Write8(0x7f); // e_ident[EI_MAG0]
356 Write8('E'); // e_ident[EI_MAG1]
357 Write8('L'); // e_ident[EI_MAG2]
358 Write8('F'); // e_ident[EI_MAG3]
360 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
363 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
365 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
368 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
369 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
370 default: Write8(ELF::ELFOSABI_NONE); break;
372 Write8(0); // e_ident[EI_ABIVERSION]
374 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
376 Write16(ELF::ET_REL); // e_type
378 Write16(EMachine); // e_machine = target
380 Write32(ELF::EV_CURRENT); // e_version
381 WriteWord(0); // e_entry, no entry point in .o file
382 WriteWord(0); // e_phoff, no program header for .o
383 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
384 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
386 // FIXME: Make this configurable.
387 Write32(0); // e_flags = whatever the target wants
389 // e_ehsize = ELF header size
390 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
392 Write16(0); // e_phentsize = prog header entry size
393 Write16(0); // e_phnum = # prog header entries = 0
395 // e_shentsize = Section header entry size
396 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
398 // e_shnum = # of section header ents
399 if (NumberOfSections >= ELF::SHN_LORESERVE)
402 Write16(NumberOfSections);
404 // e_shstrndx = Section # of '.shstrtab'
405 if (NumberOfSections >= ELF::SHN_LORESERVE)
406 Write16(ELF::SHN_XINDEX);
408 Write16(ShstrtabIndex);
411 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
412 MCDataFragment *ShndxF,
414 uint8_t info, uint64_t value,
415 uint64_t size, uint8_t other,
419 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
420 String32(*ShndxF, shndx);
422 String32(*ShndxF, 0);
425 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
426 uint16_t(ELF::SHN_XINDEX) : shndx;
429 String32(*SymtabF, name); // st_name
430 String8(*SymtabF, info); // st_info
431 String8(*SymtabF, other); // st_other
432 String16(*SymtabF, Index); // st_shndx
433 String64(*SymtabF, value); // st_value
434 String64(*SymtabF, size); // st_size
436 String32(*SymtabF, name); // st_name
437 String32(*SymtabF, value); // st_value
438 String32(*SymtabF, size); // st_size
439 String8(*SymtabF, info); // st_info
440 String8(*SymtabF, other); // st_other
441 String16(*SymtabF, Index); // st_shndx
445 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
446 if (Data.isCommon() && Data.isExternal())
447 return Data.getCommonAlignment();
449 const MCSymbol &Symbol = Data.getSymbol();
450 if (!Symbol.isInSection())
453 if (MCFragment *FF = Data.getFragment())
454 return Layout.getSymbolAddress(&Data) -
455 Layout.getSectionAddress(FF->getParent());
460 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
461 const MCSymbol *S = &Symbol;
462 while (S->isVariable()) {
463 const MCExpr *Value = S->getVariableValue();
464 MCExpr::ExprKind Kind = Value->getKind();
466 case MCExpr::SymbolRef: {
467 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
468 S = &Ref->getSymbol();
471 case MCExpr::Target: {
472 const MCTargetExpr *TExp = static_cast<const MCTargetExpr*>(Value);
474 TExp->EvaluateAsRelocatableImpl(Res, NULL);
475 S = &Res.getSymA()->getSymbol();
485 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
486 // The presence of symbol versions causes undefined symbols and
487 // versions declared with @@@ to be renamed.
489 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
490 ie = Asm.symbol_end(); it != ie; ++it) {
491 const MCSymbol &Alias = it->getSymbol();
492 const MCSymbol &Symbol = AliasedSymbol(Alias);
493 MCSymbolData &SD = Asm.getSymbolData(Symbol);
495 // Undefined symbols are global, but this is the first place we
496 // are able to set it.
497 if (Symbol.isUndefined() && !Symbol.isVariable()) {
498 if (GetBinding(SD) == ELF::STB_LOCAL) {
499 SetBinding(SD, ELF::STB_GLOBAL);
500 SetBinding(*it, ELF::STB_GLOBAL);
505 if (&Symbol == &Alias)
508 StringRef AliasName = Alias.getName();
509 size_t Pos = AliasName.find('@');
510 if (Pos == StringRef::npos)
513 // Aliases defined with .symvar copy the binding from the symbol they alias.
514 // This is the first place we are able to copy this information.
515 it->setExternal(SD.isExternal());
516 SetBinding(*it, GetBinding(SD));
518 StringRef Rest = AliasName.substr(Pos);
519 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
522 // FIXME: produce a better error message.
523 if (Symbol.isUndefined() && Rest.startswith("@@") &&
524 !Rest.startswith("@@@"))
525 report_fatal_error("A @@ version cannot be undefined");
527 Renames.insert(std::make_pair(&Symbol, &Alias));
531 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
532 MCDataFragment *ShndxF,
534 const MCAsmLayout &Layout) {
535 MCSymbolData &OrigData = *MSD.SymbolData;
537 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
539 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
540 Data.getSymbol().isVariable();
542 uint8_t Binding = GetBinding(OrigData);
543 uint8_t Visibility = GetVisibility(OrigData);
544 uint8_t Type = GetType(Data);
546 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
547 uint8_t Other = Visibility;
549 uint64_t Value = SymbolValue(Data, Layout);
553 assert(!(Data.isCommon() && !Data.isExternal()));
555 ESize = Data.getSize();
556 if (Data.getSize()) {
558 if (ESize->getKind() == MCExpr::Binary) {
559 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
561 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
562 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
563 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
564 Size = Res.getConstant();
566 } else if (ESize->getKind() == MCExpr::Constant) {
567 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
569 assert(0 && "Unsupported size expression");
573 // Write out the symbol table entry
574 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
575 Size, Other, MSD.SectionIndex, IsReserved);
578 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
579 MCDataFragment *ShndxF,
580 const MCAssembler &Asm,
581 const MCAsmLayout &Layout,
582 const SectionIndexMapTy &SectionIndexMap) {
583 // The string table must be emitted first because we need the index
584 // into the string table for all the symbol names.
585 assert(StringTable.size() && "Missing string table");
587 // FIXME: Make sure the start of the symbol table is aligned.
589 // The first entry is the undefined symbol entry.
590 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
592 // Write the symbol table entries.
593 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
594 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
595 ELFSymbolData &MSD = LocalSymbolData[i];
596 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
599 // Write out a symbol table entry for each regular section.
600 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
602 const MCSectionELF &Section =
603 static_cast<const MCSectionELF&>(i->getSection());
604 if (Section.getType() == ELF::SHT_RELA ||
605 Section.getType() == ELF::SHT_REL ||
606 Section.getType() == ELF::SHT_STRTAB ||
607 Section.getType() == ELF::SHT_SYMTAB)
609 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
610 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
611 LastLocalSymbolIndex++;
614 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
615 ELFSymbolData &MSD = ExternalSymbolData[i];
616 MCSymbolData &Data = *MSD.SymbolData;
617 assert(((Data.getFlags() & ELF_STB_Global) ||
618 (Data.getFlags() & ELF_STB_Weak)) &&
619 "External symbol requires STB_GLOBAL or STB_WEAK flag");
620 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
621 if (GetBinding(Data) == ELF::STB_LOCAL)
622 LastLocalSymbolIndex++;
625 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
626 ELFSymbolData &MSD = UndefinedSymbolData[i];
627 MCSymbolData &Data = *MSD.SymbolData;
628 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
629 if (GetBinding(Data) == ELF::STB_LOCAL)
630 LastLocalSymbolIndex++;
634 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
635 const MCValue &Target,
636 const MCFragment &F) {
637 const MCSymbol &Symbol = SD.getSymbol();
638 if (Symbol.isUndefined())
641 const MCSectionELF &Section =
642 static_cast<const MCSectionELF&>(Symbol.getSection());
647 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
648 const MCSectionELF &Sec2 =
649 static_cast<const MCSectionELF&>(F.getParent()->getSection());
651 if (Section.getKind().isBSS())
654 if (&Sec2 != &Section &&
655 (Kind == MCSymbolRefExpr::VK_PLT ||
656 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
657 Kind == MCSymbolRefExpr::VK_GOTOFF))
660 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
661 return Target.getConstant() != 0;
666 // FIXME: this is currently X86/X86_64 only
667 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
668 const MCAsmLayout &Layout,
669 const MCFragment *Fragment,
670 const MCFixup &Fixup,
672 uint64_t &FixedValue) {
675 int64_t Value = Target.getConstant();
676 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
677 const MCSymbol &ASymbol = AliasedSymbol(Symbol);
678 const MCSymbol *RenamedP = Renames.lookup(&Symbol);
681 const MCSymbol &Renamed = *RenamedP;
683 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
684 if (!Target.isAbsolute()) {
685 MCSymbolData &SD = Asm.getSymbolData(Symbol);
686 MCFragment *F = SD.getFragment();
688 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
689 const MCSymbol &SymbolB = RefB->getSymbol();
690 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
692 MCSectionData *Sec = Fragment->getParent();
694 // Offset of the symbol in the section
695 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
697 // Ofeset of the relocation in the section
698 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
702 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
703 if (!RelocOnSymbol) {
704 Index = F->getParent()->getOrdinal();
706 MCSectionData *FSD = F->getParent();
707 // Offset of the symbol in the section
708 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
710 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
711 WeakrefUsedInReloc.insert(&Renamed);
713 UsedInReloc.insert(&Renamed);
717 // Compensate for the addend on i386.
724 // determine the type of the relocation
726 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
732 llvm_unreachable("Unimplemented");
733 case MCSymbolRefExpr::VK_None:
734 Type = ELF::R_X86_64_PC32;
736 case MCSymbolRefExpr::VK_PLT:
737 Type = ELF::R_X86_64_PLT32;
739 case MCSymbolRefExpr::VK_GOTPCREL:
740 Type = ELF::R_X86_64_GOTPCREL;
742 case MCSymbolRefExpr::VK_GOTTPOFF:
743 Type = ELF::R_X86_64_GOTTPOFF;
745 case MCSymbolRefExpr::VK_TLSGD:
746 Type = ELF::R_X86_64_TLSGD;
748 case MCSymbolRefExpr::VK_TLSLD:
749 Type = ELF::R_X86_64_TLSLD;
753 switch ((unsigned)Fixup.getKind()) {
754 default: llvm_unreachable("invalid fixup kind!");
755 case FK_Data_8: Type = ELF::R_X86_64_64; break;
756 case X86::reloc_signed_4byte:
757 case X86::reloc_pcrel_4byte:
758 assert(isInt<32>(Target.getConstant()));
761 llvm_unreachable("Unimplemented");
762 case MCSymbolRefExpr::VK_None:
763 Type = ELF::R_X86_64_32S;
765 case MCSymbolRefExpr::VK_GOT:
766 Type = ELF::R_X86_64_GOT32;
768 case MCSymbolRefExpr::VK_GOTPCREL:
769 Type = ELF::R_X86_64_GOTPCREL;
771 case MCSymbolRefExpr::VK_TPOFF:
772 Type = ELF::R_X86_64_TPOFF32;
774 case MCSymbolRefExpr::VK_DTPOFF:
775 Type = ELF::R_X86_64_DTPOFF32;
780 Type = ELF::R_X86_64_32;
782 case FK_Data_2: Type = ELF::R_X86_64_16; break;
783 case X86::reloc_pcrel_1byte:
784 case FK_Data_1: Type = ELF::R_X86_64_8; break;
791 llvm_unreachable("Unimplemented");
792 case MCSymbolRefExpr::VK_None:
793 Type = ELF::R_386_PC32;
795 case MCSymbolRefExpr::VK_PLT:
796 Type = ELF::R_386_PLT32;
800 switch ((unsigned)Fixup.getKind()) {
801 default: llvm_unreachable("invalid fixup kind!");
803 case X86::reloc_global_offset_table:
804 Type = ELF::R_386_GOTPC;
807 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
809 case X86::reloc_signed_4byte:
810 case X86::reloc_pcrel_4byte:
814 llvm_unreachable("Unimplemented");
815 case MCSymbolRefExpr::VK_None:
816 Type = ELF::R_386_32;
818 case MCSymbolRefExpr::VK_GOT:
819 Type = ELF::R_386_GOT32;
821 case MCSymbolRefExpr::VK_GOTOFF:
822 Type = ELF::R_386_GOTOFF;
824 case MCSymbolRefExpr::VK_TLSGD:
825 Type = ELF::R_386_TLS_GD;
827 case MCSymbolRefExpr::VK_TPOFF:
828 Type = ELF::R_386_TLS_LE_32;
830 case MCSymbolRefExpr::VK_INDNTPOFF:
831 Type = ELF::R_386_TLS_IE;
833 case MCSymbolRefExpr::VK_NTPOFF:
834 Type = ELF::R_386_TLS_LE;
836 case MCSymbolRefExpr::VK_GOTNTPOFF:
837 Type = ELF::R_386_TLS_GOTIE;
839 case MCSymbolRefExpr::VK_TLSLDM:
840 Type = ELF::R_386_TLS_LDM;
842 case MCSymbolRefExpr::VK_DTPOFF:
843 Type = ELF::R_386_TLS_LDO_32;
847 case FK_Data_2: Type = ELF::R_386_16; break;
848 case X86::reloc_pcrel_1byte:
849 case FK_Data_1: Type = ELF::R_386_8; break;
854 if (RelocNeedsGOT(Modifier))
857 ELFRelocationEntry ERE;
861 ERE.Symbol = &Renamed;
863 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
865 if (HasRelocationAddend)
866 ERE.r_addend = Addend;
868 ERE.r_addend = 0; // Silence compiler warning.
870 Relocations[Fragment->getParent()].push_back(ERE);
874 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
876 MCSymbolData &SD = Asm.getSymbolData(*S);
879 if (!SD.isExternal() && !S->isUndefined())
880 return SD.getIndex() + /* empty symbol */ 1;
882 // External or undefined symbol.
883 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
886 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
887 bool Used, bool Renamed) {
888 if (Data.getFlags() & ELF_Other_Weakref)
897 const MCSymbol &Symbol = Data.getSymbol();
899 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
902 const MCSymbol &A = AliasedSymbol(Symbol);
903 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
906 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
909 if (Symbol.isTemporary())
915 static bool isLocal(const MCSymbolData &Data) {
916 if (Data.isExternal())
919 const MCSymbol &Symbol = Data.getSymbol();
920 if (Symbol.isUndefined() && !Symbol.isVariable())
926 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
927 SectionIndexMapTy &SectionIndexMap) {
929 for (MCAssembler::iterator it = Asm.begin(),
930 ie = Asm.end(); it != ie; ++it) {
931 const MCSectionELF &Section =
932 static_cast<const MCSectionELF &>(it->getSection());
933 if (Section.getType() != ELF::SHT_GROUP)
935 SectionIndexMap[&Section] = Index++;
938 for (MCAssembler::iterator it = Asm.begin(),
939 ie = Asm.end(); it != ie; ++it) {
940 const MCSectionELF &Section =
941 static_cast<const MCSectionELF &>(it->getSection());
942 if (Section.getType() == ELF::SHT_GROUP)
944 SectionIndexMap[&Section] = Index++;
948 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
949 const SectionIndexMapTy &SectionIndexMap) {
950 // FIXME: Is this the correct place to do this?
952 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
953 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
954 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
955 Data.setExternal(true);
956 SetBinding(Data, ELF::STB_GLOBAL);
959 // Build section lookup table.
960 NumRegularSections = Asm.size();
962 // Index 0 is always the empty string.
963 StringMap<uint64_t> StringIndexMap;
964 StringTable += '\x00';
966 // Add the data for the symbols.
967 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
968 ie = Asm.symbol_end(); it != ie; ++it) {
969 const MCSymbol &Symbol = it->getSymbol();
971 bool Used = UsedInReloc.count(&Symbol);
972 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
973 if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
974 Renames.count(&Symbol)))
979 bool Local = isLocal(*it);
980 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
982 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
983 SetBinding(*it, ELF::STB_WEAK);
985 if (it->isCommon()) {
987 MSD.SectionIndex = ELF::SHN_COMMON;
988 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
989 MSD.SectionIndex = ELF::SHN_ABS;
990 } else if (RefSymbol.isUndefined()) {
991 MSD.SectionIndex = ELF::SHN_UNDEF;
993 const MCSectionELF &Section =
994 static_cast<const MCSectionELF&>(RefSymbol.getSection());
995 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
996 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
997 NeedsSymtabShndx = true;
998 assert(MSD.SectionIndex && "Invalid section index!");
1001 // The @@@ in symbol version is replaced with @ in undefined symbols and
1002 // @@ in defined ones.
1003 StringRef Name = Symbol.getName();
1004 SmallString<32> Buf;
1006 size_t Pos = Name.find("@@@");
1007 if (Pos != StringRef::npos) {
1008 Buf += Name.substr(0, Pos);
1009 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1010 Buf += Name.substr(Pos + Skip);
1014 uint64_t &Entry = StringIndexMap[Name];
1016 Entry = StringTable.size();
1017 StringTable += Name;
1018 StringTable += '\x00';
1020 MSD.StringIndex = Entry;
1021 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1022 UndefinedSymbolData.push_back(MSD);
1024 LocalSymbolData.push_back(MSD);
1026 ExternalSymbolData.push_back(MSD);
1029 // Symbols are required to be in lexicographic order.
1030 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1031 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1032 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1034 // Set the symbol indices. Local symbols must come before all other
1035 // symbols with non-local bindings.
1037 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1038 LocalSymbolData[i].SymbolData->setIndex(Index++);
1039 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1040 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1041 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1042 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1045 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1046 const MCSectionData &SD) {
1047 if (!Relocations[&SD].empty()) {
1048 MCContext &Ctx = Asm.getContext();
1049 const MCSectionELF *RelaSection;
1050 const MCSectionELF &Section =
1051 static_cast<const MCSectionELF&>(SD.getSection());
1053 const StringRef SectionName = Section.getSectionName();
1054 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1055 RelaSectionName += SectionName;
1058 if (HasRelocationAddend)
1059 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1061 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1063 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1064 ELF::SHT_RELA : ELF::SHT_REL, 0,
1065 SectionKind::getReadOnly(),
1068 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1069 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1071 MCDataFragment *F = new MCDataFragment(&RelaSD);
1073 WriteRelocationsFragment(Asm, F, &SD);
1075 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
1079 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1080 uint64_t Flags, uint64_t Address,
1081 uint64_t Offset, uint64_t Size,
1082 uint32_t Link, uint32_t Info,
1084 uint64_t EntrySize) {
1085 Write32(Name); // sh_name: index into string table
1086 Write32(Type); // sh_type
1087 WriteWord(Flags); // sh_flags
1088 WriteWord(Address); // sh_addr
1089 WriteWord(Offset); // sh_offset
1090 WriteWord(Size); // sh_size
1091 Write32(Link); // sh_link
1092 Write32(Info); // sh_info
1093 WriteWord(Alignment); // sh_addralign
1094 WriteWord(EntrySize); // sh_entsize
1097 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1099 const MCSectionData *SD) {
1100 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1101 // sort by the r_offset just like gnu as does
1102 array_pod_sort(Relocs.begin(), Relocs.end());
1104 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1105 ELFRelocationEntry entry = Relocs[e - i - 1];
1107 if (entry.Index < 0)
1108 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1110 entry.Index += LocalSymbolData.size() + 1;
1112 String64(*F, entry.r_offset);
1114 struct ELF::Elf64_Rela ERE64;
1115 ERE64.setSymbolAndType(entry.Index, entry.Type);
1116 String64(*F, ERE64.r_info);
1118 if (HasRelocationAddend)
1119 String64(*F, entry.r_addend);
1121 String32(*F, entry.r_offset);
1123 struct ELF::Elf32_Rela ERE32;
1124 ERE32.setSymbolAndType(entry.Index, entry.Type);
1125 String32(*F, ERE32.r_info);
1127 if (HasRelocationAddend)
1128 String32(*F, entry.r_addend);
1133 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1134 MCAsmLayout &Layout,
1135 const SectionIndexMapTy &SectionIndexMap) {
1136 MCContext &Ctx = Asm.getContext();
1139 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1141 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1142 const MCSectionELF *ShstrtabSection =
1143 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1144 SectionKind::getReadOnly());
1145 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1146 ShstrtabSD.setAlignment(1);
1147 ShstrtabIndex = Asm.size();
1149 const MCSectionELF *SymtabSection =
1150 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1151 SectionKind::getReadOnly(),
1153 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1154 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1155 SymbolTableIndex = Asm.size();
1157 MCSectionData *SymtabShndxSD = NULL;
1159 if (NeedsSymtabShndx) {
1160 const MCSectionELF *SymtabShndxSection =
1161 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1162 SectionKind::getReadOnly(), 4, "");
1163 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1164 SymtabShndxSD->setAlignment(4);
1167 const MCSection *StrtabSection;
1168 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1169 SectionKind::getReadOnly());
1170 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1171 StrtabSD.setAlignment(1);
1172 StringTableIndex = Asm.size();
1174 WriteRelocations(Asm, Layout);
1177 F = new MCDataFragment(&SymtabSD);
1178 MCDataFragment *ShndxF = NULL;
1179 if (NeedsSymtabShndx) {
1180 ShndxF = new MCDataFragment(SymtabShndxSD);
1181 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1183 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1184 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1186 F = new MCDataFragment(&StrtabSD);
1187 F->getContents().append(StringTable.begin(), StringTable.end());
1188 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1190 F = new MCDataFragment(&ShstrtabSD);
1192 // Section header string table.
1194 // The first entry of a string table holds a null character so skip
1197 F->getContents() += '\x00';
1199 StringMap<uint64_t> SecStringMap;
1200 for (MCAssembler::const_iterator it = Asm.begin(),
1201 ie = Asm.end(); it != ie; ++it) {
1202 const MCSectionELF &Section =
1203 static_cast<const MCSectionELF&>(it->getSection());
1204 // FIXME: We could merge suffixes like in .text and .rela.text.
1206 StringRef Name = Section.getSectionName();
1207 if (SecStringMap.count(Name)) {
1208 SectionStringTableIndex[&Section] = SecStringMap[Name];
1211 // Remember the index into the string table so we can write it
1212 // into the sh_name field of the section header table.
1213 SectionStringTableIndex[&Section] = Index;
1214 SecStringMap[Name] = Index;
1216 Index += Name.size() + 1;
1217 F->getContents() += Name;
1218 F->getContents() += '\x00';
1221 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1224 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1225 const MCValue Target,
1227 const MCFragment *DF) const {
1228 // If this is a PCrel relocation, find the section this fixup value is
1230 const MCSection *BaseSection = 0;
1232 BaseSection = &DF->getParent()->getSection();
1233 assert(BaseSection);
1236 const MCSection *SectionA = 0;
1237 const MCSymbol *SymbolA = 0;
1238 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1239 SymbolA = &A->getSymbol();
1240 SectionA = &SymbolA->getSection();
1243 const MCSection *SectionB = 0;
1244 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1245 SectionB = &B->getSymbol().getSection();
1249 return SectionA == SectionB;
1251 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1252 if (DataA.isExternal())
1255 return !SectionB && BaseSection == SectionA;
1258 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1259 MCAsmLayout &Layout,
1260 GroupMapTy &GroupMap) {
1261 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
1263 RevGroupMapTy Groups;
1264 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1266 const MCSectionELF &Section =
1267 static_cast<const MCSectionELF&>(it->getSection());
1268 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1271 const MCSymbol *SignatureSymbol = Section.getGroup();
1272 Asm.getOrCreateSymbolData(*SignatureSymbol);
1273 const MCSectionELF *&Group = Groups[SignatureSymbol];
1275 Group = Asm.getContext().CreateELFGroupSection();
1276 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1277 Data.setAlignment(4);
1278 MCDataFragment *F = new MCDataFragment(&Data);
1279 String32(*F, ELF::GRP_COMDAT);
1281 GroupMap[Group] = SignatureSymbol;
1284 // Add sections to the groups
1286 unsigned NumGroups = Groups.size();
1287 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1288 it != ie; ++it, ++Index) {
1289 const MCSectionELF &Section =
1290 static_cast<const MCSectionELF&>(it->getSection());
1291 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1293 const MCSectionELF *Group = Groups[Section.getGroup()];
1294 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1295 // FIXME: we could use the previous fragment
1296 MCDataFragment *F = new MCDataFragment(&Data);
1297 String32(*F, NumGroups + Index);
1300 for (RevGroupMapTy::const_iterator i = Groups.begin(), e = Groups.end();
1302 const MCSectionELF *Group = i->second;
1303 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1304 Asm.AddSectionToTheEnd(*this, Data, Layout);
1308 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1309 const SectionIndexMapTy &SectionIndexMap,
1310 uint32_t GroupSymbolIndex,
1311 uint64_t Offset, uint64_t Size,
1313 const MCSectionELF &Section) {
1314 uint64_t sh_link = 0;
1315 uint64_t sh_info = 0;
1317 switch(Section.getType()) {
1318 case ELF::SHT_DYNAMIC:
1319 sh_link = SectionStringTableIndex[&Section];
1324 case ELF::SHT_RELA: {
1325 const MCSectionELF *SymtabSection;
1326 const MCSectionELF *InfoSection;
1327 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1329 SectionKind::getReadOnly());
1330 sh_link = SectionIndexMap.lookup(SymtabSection);
1331 assert(sh_link && ".symtab not found");
1333 // Remove ".rel" and ".rela" prefixes.
1334 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1335 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1337 InfoSection = Asm.getContext().getELFSection(SectionName,
1338 ELF::SHT_PROGBITS, 0,
1339 SectionKind::getReadOnly());
1340 sh_info = SectionIndexMap.lookup(InfoSection);
1344 case ELF::SHT_SYMTAB:
1345 case ELF::SHT_DYNSYM:
1346 sh_link = StringTableIndex;
1347 sh_info = LastLocalSymbolIndex;
1350 case ELF::SHT_SYMTAB_SHNDX:
1351 sh_link = SymbolTableIndex;
1354 case ELF::SHT_PROGBITS:
1355 case ELF::SHT_STRTAB:
1356 case ELF::SHT_NOBITS:
1358 case ELF::SHT_ARM_ATTRIBUTES:
1362 case ELF::SHT_GROUP: {
1363 sh_link = SymbolTableIndex;
1364 sh_info = GroupSymbolIndex;
1369 assert(0 && "FIXME: sh_type value not supported!");
1373 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1374 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1375 Alignment, Section.getEntrySize());
1378 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1379 const MCAsmLayout &Layout) {
1380 GroupMapTy GroupMap;
1381 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap);
1383 SectionIndexMapTy SectionIndexMap;
1385 ComputeIndexMap(Asm, SectionIndexMap);
1387 // Compute symbol table information.
1388 ComputeSymbolTable(Asm, SectionIndexMap);
1390 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1391 const_cast<MCAsmLayout&>(Layout),
1394 // Update to include the metadata sections.
1395 ComputeIndexMap(Asm, SectionIndexMap);
1397 // Add 1 for the null section.
1398 unsigned NumSections = Asm.size() + 1;
1399 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1400 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1401 uint64_t FileOff = HeaderSize;
1403 std::vector<const MCSectionELF*> Sections;
1404 Sections.resize(NumSections);
1406 for (SectionIndexMapTy::const_iterator i=
1407 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1408 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1409 Sections[p.second] = p.first;
1412 for (unsigned i = 1; i < NumSections; ++i) {
1413 const MCSectionELF &Section = *Sections[i];
1414 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1416 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1418 // Get the size of the section in the output file (including padding).
1419 uint64_t Size = Layout.getSectionFileSize(&SD);
1424 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1426 // Write out the ELF header ...
1427 WriteHeader(FileOff - HeaderSize, NumSections);
1429 FileOff = HeaderSize;
1431 // ... then all of the sections ...
1432 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1434 for (unsigned i = 1; i < NumSections; ++i) {
1435 const MCSectionELF &Section = *Sections[i];
1436 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1438 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1439 WriteZeros(Padding);
1442 // Remember the offset into the file for this section.
1443 SectionOffsetMap[&Section] = FileOff;
1445 FileOff += Layout.getSectionFileSize(&SD);
1447 Asm.WriteSectionData(&SD, Layout, this);
1450 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1451 WriteZeros(Padding);
1454 // ... and then the section header table.
1455 // Should we align the section header table?
1457 // Null section first.
1458 uint64_t FirstSectionSize =
1459 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1460 uint32_t FirstSectionLink =
1461 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1462 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1464 for (unsigned i = 1; i < NumSections; ++i) {
1465 const MCSectionELF &Section = *Sections[i];
1466 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1467 uint32_t GroupSymbolIndex;
1468 if (Section.getType() != ELF::SHT_GROUP)
1469 GroupSymbolIndex = 0;
1471 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1473 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1474 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1475 SD.getAlignment(), Section);
1479 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1481 Triple::OSType OSType,
1483 bool IsLittleEndian,
1484 bool HasRelocationAddend) {
1485 return new ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1486 HasRelocationAddend, OSType);