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;
164 bool NeedsSymtabShndx;
166 unsigned Is64Bit : 1;
168 bool HasRelocationAddend;
170 Triple::OSType OSType;
174 // This holds the symbol table index of the last local symbol.
175 unsigned LastLocalSymbolIndex;
176 // This holds the .strtab section index.
177 unsigned StringTableIndex;
178 // This holds the .symtab section index.
179 unsigned SymbolTableIndex;
181 unsigned ShstrtabIndex;
184 ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
185 uint16_t _EMachine, bool _HasRelAddend,
186 Triple::OSType _OSType)
187 : MCObjectWriter(_OS, IsLittleEndian),
188 NeedsGOT(false), NeedsSymtabShndx(false),
189 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
190 OSType(_OSType), EMachine(_EMachine) {
193 void WriteWord(uint64_t W) {
200 void StringLE16(char *buf, uint16_t Value) {
201 buf[0] = char(Value >> 0);
202 buf[1] = char(Value >> 8);
205 void StringLE32(char *buf, uint32_t Value) {
206 StringLE16(buf, uint16_t(Value >> 0));
207 StringLE16(buf + 2, uint16_t(Value >> 16));
210 void StringLE64(char *buf, uint64_t Value) {
211 StringLE32(buf, uint32_t(Value >> 0));
212 StringLE32(buf + 4, uint32_t(Value >> 32));
215 void StringBE16(char *buf ,uint16_t Value) {
216 buf[0] = char(Value >> 8);
217 buf[1] = char(Value >> 0);
220 void StringBE32(char *buf, uint32_t Value) {
221 StringBE16(buf, uint16_t(Value >> 16));
222 StringBE16(buf + 2, uint16_t(Value >> 0));
225 void StringBE64(char *buf, uint64_t Value) {
226 StringBE32(buf, uint32_t(Value >> 32));
227 StringBE32(buf + 4, uint32_t(Value >> 0));
230 void String8(MCDataFragment &F, uint8_t Value) {
233 F.getContents() += StringRef(buf, 1);
236 void String16(MCDataFragment &F, uint16_t Value) {
238 if (isLittleEndian())
239 StringLE16(buf, Value);
241 StringBE16(buf, Value);
242 F.getContents() += StringRef(buf, 2);
245 void String32(MCDataFragment &F, uint32_t Value) {
247 if (isLittleEndian())
248 StringLE32(buf, Value);
250 StringBE32(buf, Value);
251 F.getContents() += StringRef(buf, 4);
254 void String64(MCDataFragment &F, uint64_t Value) {
256 if (isLittleEndian())
257 StringLE64(buf, Value);
259 StringBE64(buf, Value);
260 F.getContents() += StringRef(buf, 8);
263 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
265 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
266 uint64_t name, uint8_t info,
267 uint64_t value, uint64_t size,
268 uint8_t other, uint32_t shndx,
271 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
273 const MCAsmLayout &Layout);
275 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
276 void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
277 const MCAssembler &Asm,
278 const MCAsmLayout &Layout,
279 const SectionIndexMapTy &SectionIndexMap);
281 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
282 const MCFragment *Fragment, const MCFixup &Fixup,
283 MCValue Target, uint64_t &FixedValue);
285 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
288 /// ComputeSymbolTable - Compute the symbol table data
290 /// \param StringTable [out] - The string table data.
291 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
293 void ComputeSymbolTable(MCAssembler &Asm,
294 const SectionIndexMapTy &SectionIndexMap);
296 void ComputeIndexMap(MCAssembler &Asm,
297 SectionIndexMapTy &SectionIndexMap);
299 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
300 const MCSectionData &SD);
302 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
303 for (MCAssembler::const_iterator it = Asm.begin(),
304 ie = Asm.end(); it != ie; ++it) {
305 WriteRelocation(Asm, Layout, *it);
309 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
310 const SectionIndexMapTy &SectionIndexMap);
312 // Map from a group section to the signature symbol
313 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
314 void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
315 GroupMapTy &GroupMap);
317 void ExecutePostLayoutBinding(MCAssembler &Asm);
319 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
320 uint64_t Address, uint64_t Offset,
321 uint64_t Size, uint32_t Link, uint32_t Info,
322 uint64_t Alignment, uint64_t EntrySize);
324 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
325 const MCSectionData *SD);
327 bool IsFixupFullyResolved(const MCAssembler &Asm,
328 const MCValue Target,
330 const MCFragment *DF) const;
332 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
333 void WriteSection(MCAssembler &Asm,
334 const SectionIndexMapTy &SectionIndexMap,
335 uint32_t GroupSymbolIndex,
336 uint64_t Offset, uint64_t Size, uint64_t Alignment,
337 const MCSectionELF &Section);
342 // Emit the ELF header.
343 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
344 unsigned NumberOfSections) {
350 // emitWord method behaves differently for ELF32 and ELF64, writing
351 // 4 bytes in the former and 8 in the latter.
353 Write8(0x7f); // e_ident[EI_MAG0]
354 Write8('E'); // e_ident[EI_MAG1]
355 Write8('L'); // e_ident[EI_MAG2]
356 Write8('F'); // e_ident[EI_MAG3]
358 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
361 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
363 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
366 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
367 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
368 default: Write8(ELF::ELFOSABI_NONE); break;
370 Write8(0); // e_ident[EI_ABIVERSION]
372 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
374 Write16(ELF::ET_REL); // e_type
376 Write16(EMachine); // e_machine = target
378 Write32(ELF::EV_CURRENT); // e_version
379 WriteWord(0); // e_entry, no entry point in .o file
380 WriteWord(0); // e_phoff, no program header for .o
381 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
382 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
384 // FIXME: Make this configurable.
385 Write32(0); // e_flags = whatever the target wants
387 // e_ehsize = ELF header size
388 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
390 Write16(0); // e_phentsize = prog header entry size
391 Write16(0); // e_phnum = # prog header entries = 0
393 // e_shentsize = Section header entry size
394 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
396 // e_shnum = # of section header ents
397 if (NumberOfSections >= ELF::SHN_LORESERVE)
400 Write16(NumberOfSections);
402 // e_shstrndx = Section # of '.shstrtab'
403 if (NumberOfSections >= ELF::SHN_LORESERVE)
404 Write16(ELF::SHN_XINDEX);
406 Write16(ShstrtabIndex);
409 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
410 MCDataFragment *ShndxF,
412 uint8_t info, uint64_t value,
413 uint64_t size, uint8_t other,
417 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
418 String32(*ShndxF, shndx);
420 String32(*ShndxF, 0);
423 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
424 uint16_t(ELF::SHN_XINDEX) : shndx;
427 String32(*SymtabF, name); // st_name
428 String8(*SymtabF, info); // st_info
429 String8(*SymtabF, other); // st_other
430 String16(*SymtabF, Index); // st_shndx
431 String64(*SymtabF, value); // st_value
432 String64(*SymtabF, size); // st_size
434 String32(*SymtabF, name); // st_name
435 String32(*SymtabF, value); // st_value
436 String32(*SymtabF, size); // st_size
437 String8(*SymtabF, info); // st_info
438 String8(*SymtabF, other); // st_other
439 String16(*SymtabF, Index); // st_shndx
443 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
444 if (Data.isCommon() && Data.isExternal())
445 return Data.getCommonAlignment();
447 const MCSymbol &Symbol = Data.getSymbol();
448 if (!Symbol.isInSection())
451 if (MCFragment *FF = Data.getFragment())
452 return Layout.getSymbolAddress(&Data) -
453 Layout.getSectionAddress(FF->getParent());
458 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
459 const MCSymbol *S = &Symbol;
460 while (S->isVariable()) {
461 const MCExpr *Value = S->getVariableValue();
462 MCExpr::ExprKind Kind = Value->getKind();
464 case MCExpr::SymbolRef: {
465 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
466 S = &Ref->getSymbol();
469 case MCExpr::Target: {
470 const MCTargetExpr *TExp = static_cast<const MCTargetExpr*>(Value);
472 TExp->EvaluateAsRelocatableImpl(Res, NULL);
473 S = &Res.getSymA()->getSymbol();
483 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
484 // The presence of symbol versions causes undefined symbols and
485 // versions declared with @@@ to be renamed.
487 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
488 ie = Asm.symbol_end(); it != ie; ++it) {
489 const MCSymbol &Alias = it->getSymbol();
490 const MCSymbol &Symbol = AliasedSymbol(Alias);
491 MCSymbolData &SD = Asm.getSymbolData(Symbol);
493 // Undefined symbols are global, but this is the first place we
494 // are able to set it.
495 if (Symbol.isUndefined() && !Symbol.isVariable()) {
496 if (GetBinding(SD) == ELF::STB_LOCAL) {
497 SetBinding(SD, ELF::STB_GLOBAL);
498 SetBinding(*it, ELF::STB_GLOBAL);
503 if (&Symbol == &Alias)
506 StringRef AliasName = Alias.getName();
507 size_t Pos = AliasName.find('@');
508 if (Pos == StringRef::npos)
511 // Aliases defined with .symvar copy the binding from the symbol they alias.
512 // This is the first place we are able to copy this information.
513 it->setExternal(SD.isExternal());
514 SetBinding(*it, GetBinding(SD));
516 StringRef Rest = AliasName.substr(Pos);
517 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
520 // FIXME: produce a better error message.
521 if (Symbol.isUndefined() && Rest.startswith("@@") &&
522 !Rest.startswith("@@@"))
523 report_fatal_error("A @@ version cannot be undefined");
525 Renames.insert(std::make_pair(&Symbol, &Alias));
529 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
530 MCDataFragment *ShndxF,
532 const MCAsmLayout &Layout) {
533 MCSymbolData &OrigData = *MSD.SymbolData;
535 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
537 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
538 Data.getSymbol().isVariable();
540 uint8_t Binding = GetBinding(OrigData);
541 uint8_t Visibility = GetVisibility(OrigData);
542 uint8_t Type = GetType(Data);
544 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
545 uint8_t Other = Visibility;
547 uint64_t Value = SymbolValue(Data, Layout);
551 assert(!(Data.isCommon() && !Data.isExternal()));
553 ESize = Data.getSize();
554 if (Data.getSize()) {
556 if (ESize->getKind() == MCExpr::Binary) {
557 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
559 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
560 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
561 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
562 Size = Res.getConstant();
564 } else if (ESize->getKind() == MCExpr::Constant) {
565 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
567 assert(0 && "Unsupported size expression");
571 // Write out the symbol table entry
572 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
573 Size, Other, MSD.SectionIndex, IsReserved);
576 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
577 MCDataFragment *ShndxF,
578 const MCAssembler &Asm,
579 const MCAsmLayout &Layout,
580 const SectionIndexMapTy &SectionIndexMap) {
581 // The string table must be emitted first because we need the index
582 // into the string table for all the symbol names.
583 assert(StringTable.size() && "Missing string table");
585 // FIXME: Make sure the start of the symbol table is aligned.
587 // The first entry is the undefined symbol entry.
588 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
590 // Write the symbol table entries.
591 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
592 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
593 ELFSymbolData &MSD = LocalSymbolData[i];
594 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
597 // Write out a symbol table entry for each regular section.
598 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
600 const MCSectionELF &Section =
601 static_cast<const MCSectionELF&>(i->getSection());
602 if (Section.getType() == ELF::SHT_RELA ||
603 Section.getType() == ELF::SHT_REL ||
604 Section.getType() == ELF::SHT_STRTAB ||
605 Section.getType() == ELF::SHT_SYMTAB)
607 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
608 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
609 LastLocalSymbolIndex++;
612 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
613 ELFSymbolData &MSD = ExternalSymbolData[i];
614 MCSymbolData &Data = *MSD.SymbolData;
615 assert(((Data.getFlags() & ELF_STB_Global) ||
616 (Data.getFlags() & ELF_STB_Weak)) &&
617 "External symbol requires STB_GLOBAL or STB_WEAK flag");
618 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
619 if (GetBinding(Data) == ELF::STB_LOCAL)
620 LastLocalSymbolIndex++;
623 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
624 ELFSymbolData &MSD = UndefinedSymbolData[i];
625 MCSymbolData &Data = *MSD.SymbolData;
626 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
627 if (GetBinding(Data) == ELF::STB_LOCAL)
628 LastLocalSymbolIndex++;
632 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
633 const MCValue &Target,
634 const MCFragment &F) {
635 const MCSymbol &Symbol = SD.getSymbol();
636 if (Symbol.isUndefined())
639 const MCSectionELF &Section =
640 static_cast<const MCSectionELF&>(Symbol.getSection());
645 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
646 const MCSectionELF &Sec2 =
647 static_cast<const MCSectionELF&>(F.getParent()->getSection());
649 if (Section.getKind().isBSS())
652 if (&Sec2 != &Section &&
653 (Kind == MCSymbolRefExpr::VK_PLT ||
654 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
655 Kind == MCSymbolRefExpr::VK_GOTOFF))
658 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
659 return Target.getConstant() != 0;
664 // FIXME: this is currently X86/X86_64 only
665 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
666 const MCAsmLayout &Layout,
667 const MCFragment *Fragment,
668 const MCFixup &Fixup,
670 uint64_t &FixedValue) {
673 int64_t Value = Target.getConstant();
674 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
675 const MCSymbol &ASymbol = AliasedSymbol(Symbol);
676 const MCSymbol *RenamedP = Renames.lookup(&Symbol);
679 const MCSymbol &Renamed = *RenamedP;
681 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
682 if (!Target.isAbsolute()) {
683 MCSymbolData &SD = Asm.getSymbolData(Symbol);
684 MCFragment *F = SD.getFragment();
686 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
687 const MCSymbol &SymbolB = RefB->getSymbol();
688 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
690 MCSectionData *Sec = Fragment->getParent();
692 // Offset of the symbol in the section
693 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
695 // Ofeset of the relocation in the section
696 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
700 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
701 if (!RelocOnSymbol) {
702 Index = F->getParent()->getOrdinal();
704 MCSectionData *FSD = F->getParent();
705 // Offset of the symbol in the section
706 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
708 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
709 WeakrefUsedInReloc.insert(&Renamed);
711 UsedInReloc.insert(&Renamed);
715 // Compensate for the addend on i386.
722 // determine the type of the relocation
724 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
730 llvm_unreachable("Unimplemented");
731 case MCSymbolRefExpr::VK_None:
732 Type = ELF::R_X86_64_PC32;
734 case MCSymbolRefExpr::VK_PLT:
735 Type = ELF::R_X86_64_PLT32;
737 case MCSymbolRefExpr::VK_GOTPCREL:
738 Type = ELF::R_X86_64_GOTPCREL;
740 case MCSymbolRefExpr::VK_GOTTPOFF:
741 Type = ELF::R_X86_64_GOTTPOFF;
743 case MCSymbolRefExpr::VK_TLSGD:
744 Type = ELF::R_X86_64_TLSGD;
746 case MCSymbolRefExpr::VK_TLSLD:
747 Type = ELF::R_X86_64_TLSLD;
751 switch ((unsigned)Fixup.getKind()) {
752 default: llvm_unreachable("invalid fixup kind!");
753 case FK_Data_8: Type = ELF::R_X86_64_64; break;
754 case X86::reloc_signed_4byte:
755 case X86::reloc_pcrel_4byte:
756 assert(isInt<32>(Target.getConstant()));
759 llvm_unreachable("Unimplemented");
760 case MCSymbolRefExpr::VK_None:
761 Type = ELF::R_X86_64_32S;
763 case MCSymbolRefExpr::VK_GOT:
764 Type = ELF::R_X86_64_GOT32;
766 case MCSymbolRefExpr::VK_GOTPCREL:
767 Type = ELF::R_X86_64_GOTPCREL;
769 case MCSymbolRefExpr::VK_TPOFF:
770 Type = ELF::R_X86_64_TPOFF32;
772 case MCSymbolRefExpr::VK_DTPOFF:
773 Type = ELF::R_X86_64_DTPOFF32;
778 Type = ELF::R_X86_64_32;
780 case FK_Data_2: Type = ELF::R_X86_64_16; break;
781 case X86::reloc_pcrel_1byte:
782 case FK_Data_1: Type = ELF::R_X86_64_8; break;
789 llvm_unreachable("Unimplemented");
790 case MCSymbolRefExpr::VK_None:
791 Type = ELF::R_386_PC32;
793 case MCSymbolRefExpr::VK_PLT:
794 Type = ELF::R_386_PLT32;
798 switch ((unsigned)Fixup.getKind()) {
799 default: llvm_unreachable("invalid fixup kind!");
801 case X86::reloc_global_offset_table:
802 Type = ELF::R_386_GOTPC;
805 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
807 case X86::reloc_signed_4byte:
808 case X86::reloc_pcrel_4byte:
812 llvm_unreachable("Unimplemented");
813 case MCSymbolRefExpr::VK_None:
814 Type = ELF::R_386_32;
816 case MCSymbolRefExpr::VK_GOT:
817 Type = ELF::R_386_GOT32;
819 case MCSymbolRefExpr::VK_GOTOFF:
820 Type = ELF::R_386_GOTOFF;
822 case MCSymbolRefExpr::VK_TLSGD:
823 Type = ELF::R_386_TLS_GD;
825 case MCSymbolRefExpr::VK_TPOFF:
826 Type = ELF::R_386_TLS_LE_32;
828 case MCSymbolRefExpr::VK_INDNTPOFF:
829 Type = ELF::R_386_TLS_IE;
831 case MCSymbolRefExpr::VK_NTPOFF:
832 Type = ELF::R_386_TLS_LE;
834 case MCSymbolRefExpr::VK_GOTNTPOFF:
835 Type = ELF::R_386_TLS_GOTIE;
837 case MCSymbolRefExpr::VK_TLSLDM:
838 Type = ELF::R_386_TLS_LDM;
840 case MCSymbolRefExpr::VK_DTPOFF:
841 Type = ELF::R_386_TLS_LDO_32;
845 case FK_Data_2: Type = ELF::R_386_16; break;
846 case X86::reloc_pcrel_1byte:
847 case FK_Data_1: Type = ELF::R_386_8; break;
852 if (RelocNeedsGOT(Modifier))
855 ELFRelocationEntry ERE;
859 ERE.Symbol = &Renamed;
861 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
863 if (HasRelocationAddend)
864 ERE.r_addend = Addend;
866 ERE.r_addend = 0; // Silence compiler warning.
868 Relocations[Fragment->getParent()].push_back(ERE);
872 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
874 MCSymbolData &SD = Asm.getSymbolData(*S);
875 return SD.getIndex();
878 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
879 bool Used, bool Renamed) {
880 if (Data.getFlags() & ELF_Other_Weakref)
889 const MCSymbol &Symbol = Data.getSymbol();
891 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
894 const MCSymbol &A = AliasedSymbol(Symbol);
895 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
898 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
901 if (Symbol.isTemporary())
907 static bool isLocal(const MCSymbolData &Data) {
908 if (Data.isExternal())
911 const MCSymbol &Symbol = Data.getSymbol();
912 if (Symbol.isUndefined() && !Symbol.isVariable())
918 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
919 SectionIndexMapTy &SectionIndexMap) {
921 for (MCAssembler::iterator it = Asm.begin(),
922 ie = Asm.end(); it != ie; ++it) {
923 const MCSectionELF &Section =
924 static_cast<const MCSectionELF &>(it->getSection());
925 if (Section.getType() != ELF::SHT_GROUP)
927 SectionIndexMap[&Section] = Index++;
930 for (MCAssembler::iterator it = Asm.begin(),
931 ie = Asm.end(); it != ie; ++it) {
932 const MCSectionELF &Section =
933 static_cast<const MCSectionELF &>(it->getSection());
934 if (Section.getType() == ELF::SHT_GROUP)
936 SectionIndexMap[&Section] = Index++;
940 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
941 const SectionIndexMapTy &SectionIndexMap) {
942 // FIXME: Is this the correct place to do this?
944 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
945 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
946 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
947 Data.setExternal(true);
948 SetBinding(Data, ELF::STB_GLOBAL);
951 // Build section lookup table.
952 int NumRegularSections = Asm.size();
954 // Index 0 is always the empty string.
955 StringMap<uint64_t> StringIndexMap;
956 StringTable += '\x00';
958 // Add the data for the symbols.
959 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
960 ie = Asm.symbol_end(); it != ie; ++it) {
961 const MCSymbol &Symbol = it->getSymbol();
963 bool Used = UsedInReloc.count(&Symbol);
964 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
965 if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
966 Renames.count(&Symbol)))
971 bool Local = isLocal(*it);
972 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
974 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
975 SetBinding(*it, ELF::STB_WEAK);
977 if (it->isCommon()) {
979 MSD.SectionIndex = ELF::SHN_COMMON;
980 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
981 MSD.SectionIndex = ELF::SHN_ABS;
982 } else if (RefSymbol.isUndefined()) {
983 MSD.SectionIndex = ELF::SHN_UNDEF;
985 const MCSectionELF &Section =
986 static_cast<const MCSectionELF&>(RefSymbol.getSection());
987 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
988 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
989 NeedsSymtabShndx = true;
990 assert(MSD.SectionIndex && "Invalid section index!");
993 // The @@@ in symbol version is replaced with @ in undefined symbols and
994 // @@ in defined ones.
995 StringRef Name = Symbol.getName();
998 size_t Pos = Name.find("@@@");
999 if (Pos != StringRef::npos) {
1000 Buf += Name.substr(0, Pos);
1001 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1002 Buf += Name.substr(Pos + Skip);
1006 uint64_t &Entry = StringIndexMap[Name];
1008 Entry = StringTable.size();
1009 StringTable += Name;
1010 StringTable += '\x00';
1012 MSD.StringIndex = Entry;
1013 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1014 UndefinedSymbolData.push_back(MSD);
1016 LocalSymbolData.push_back(MSD);
1018 ExternalSymbolData.push_back(MSD);
1021 // Symbols are required to be in lexicographic order.
1022 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1023 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1024 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1026 // Set the symbol indices. Local symbols must come before all other
1027 // symbols with non-local bindings.
1029 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1030 LocalSymbolData[i].SymbolData->setIndex(Index++);
1032 Index += NumRegularSections;
1034 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1035 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1036 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1037 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1040 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1041 const MCSectionData &SD) {
1042 if (!Relocations[&SD].empty()) {
1043 MCContext &Ctx = Asm.getContext();
1044 const MCSectionELF *RelaSection;
1045 const MCSectionELF &Section =
1046 static_cast<const MCSectionELF&>(SD.getSection());
1048 const StringRef SectionName = Section.getSectionName();
1049 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1050 RelaSectionName += SectionName;
1053 if (HasRelocationAddend)
1054 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1056 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1058 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1059 ELF::SHT_RELA : ELF::SHT_REL, 0,
1060 SectionKind::getReadOnly(),
1063 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1064 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1066 MCDataFragment *F = new MCDataFragment(&RelaSD);
1068 WriteRelocationsFragment(Asm, F, &SD);
1070 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
1074 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1075 uint64_t Flags, uint64_t Address,
1076 uint64_t Offset, uint64_t Size,
1077 uint32_t Link, uint32_t Info,
1079 uint64_t EntrySize) {
1080 Write32(Name); // sh_name: index into string table
1081 Write32(Type); // sh_type
1082 WriteWord(Flags); // sh_flags
1083 WriteWord(Address); // sh_addr
1084 WriteWord(Offset); // sh_offset
1085 WriteWord(Size); // sh_size
1086 Write32(Link); // sh_link
1087 Write32(Info); // sh_info
1088 WriteWord(Alignment); // sh_addralign
1089 WriteWord(EntrySize); // sh_entsize
1092 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1094 const MCSectionData *SD) {
1095 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1096 // sort by the r_offset just like gnu as does
1097 array_pod_sort(Relocs.begin(), Relocs.end());
1099 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1100 ELFRelocationEntry entry = Relocs[e - i - 1];
1102 if (entry.Index < 0)
1103 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1105 entry.Index += LocalSymbolData.size() + 1;
1107 String64(*F, entry.r_offset);
1109 struct ELF::Elf64_Rela ERE64;
1110 ERE64.setSymbolAndType(entry.Index, entry.Type);
1111 String64(*F, ERE64.r_info);
1113 if (HasRelocationAddend)
1114 String64(*F, entry.r_addend);
1116 String32(*F, entry.r_offset);
1118 struct ELF::Elf32_Rela ERE32;
1119 ERE32.setSymbolAndType(entry.Index, entry.Type);
1120 String32(*F, ERE32.r_info);
1122 if (HasRelocationAddend)
1123 String32(*F, entry.r_addend);
1128 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1129 MCAsmLayout &Layout,
1130 const SectionIndexMapTy &SectionIndexMap) {
1131 MCContext &Ctx = Asm.getContext();
1134 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1136 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1137 const MCSectionELF *ShstrtabSection =
1138 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1139 SectionKind::getReadOnly());
1140 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1141 ShstrtabSD.setAlignment(1);
1142 ShstrtabIndex = Asm.size();
1144 const MCSectionELF *SymtabSection =
1145 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1146 SectionKind::getReadOnly(),
1148 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1149 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1150 SymbolTableIndex = Asm.size();
1152 MCSectionData *SymtabShndxSD = NULL;
1154 if (NeedsSymtabShndx) {
1155 const MCSectionELF *SymtabShndxSection =
1156 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1157 SectionKind::getReadOnly(), 4, "");
1158 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1159 SymtabShndxSD->setAlignment(4);
1162 const MCSection *StrtabSection;
1163 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1164 SectionKind::getReadOnly());
1165 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1166 StrtabSD.setAlignment(1);
1167 StringTableIndex = Asm.size();
1169 WriteRelocations(Asm, Layout);
1172 F = new MCDataFragment(&SymtabSD);
1173 MCDataFragment *ShndxF = NULL;
1174 if (NeedsSymtabShndx) {
1175 ShndxF = new MCDataFragment(SymtabShndxSD);
1176 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1178 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1179 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1181 F = new MCDataFragment(&StrtabSD);
1182 F->getContents().append(StringTable.begin(), StringTable.end());
1183 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1185 F = new MCDataFragment(&ShstrtabSD);
1187 // Section header string table.
1189 // The first entry of a string table holds a null character so skip
1192 F->getContents() += '\x00';
1194 StringMap<uint64_t> SecStringMap;
1195 for (MCAssembler::const_iterator it = Asm.begin(),
1196 ie = Asm.end(); it != ie; ++it) {
1197 const MCSectionELF &Section =
1198 static_cast<const MCSectionELF&>(it->getSection());
1199 // FIXME: We could merge suffixes like in .text and .rela.text.
1201 StringRef Name = Section.getSectionName();
1202 if (SecStringMap.count(Name)) {
1203 SectionStringTableIndex[&Section] = SecStringMap[Name];
1206 // Remember the index into the string table so we can write it
1207 // into the sh_name field of the section header table.
1208 SectionStringTableIndex[&Section] = Index;
1209 SecStringMap[Name] = Index;
1211 Index += Name.size() + 1;
1212 F->getContents() += Name;
1213 F->getContents() += '\x00';
1216 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1219 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1220 const MCValue Target,
1222 const MCFragment *DF) const {
1223 // If this is a PCrel relocation, find the section this fixup value is
1225 const MCSection *BaseSection = 0;
1227 BaseSection = &DF->getParent()->getSection();
1228 assert(BaseSection);
1231 const MCSection *SectionA = 0;
1232 const MCSymbol *SymbolA = 0;
1233 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1234 SymbolA = &A->getSymbol();
1235 SectionA = &SymbolA->getSection();
1238 const MCSection *SectionB = 0;
1239 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1240 SectionB = &B->getSymbol().getSection();
1244 return SectionA == SectionB;
1246 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1247 if (DataA.isExternal())
1250 return !SectionB && BaseSection == SectionA;
1253 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1254 MCAsmLayout &Layout,
1255 GroupMapTy &GroupMap) {
1256 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
1258 RevGroupMapTy Groups;
1259 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1261 const MCSectionELF &Section =
1262 static_cast<const MCSectionELF&>(it->getSection());
1263 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1266 const MCSymbol *SignatureSymbol = Section.getGroup();
1267 Asm.getOrCreateSymbolData(*SignatureSymbol);
1268 const MCSectionELF *&Group = Groups[SignatureSymbol];
1270 Group = Asm.getContext().CreateELFGroupSection();
1271 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1272 Data.setAlignment(4);
1273 MCDataFragment *F = new MCDataFragment(&Data);
1274 String32(*F, ELF::GRP_COMDAT);
1276 GroupMap[Group] = SignatureSymbol;
1279 // Add sections to the groups
1281 unsigned NumGroups = Groups.size();
1282 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1283 it != ie; ++it, ++Index) {
1284 const MCSectionELF &Section =
1285 static_cast<const MCSectionELF&>(it->getSection());
1286 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1288 const MCSectionELF *Group = Groups[Section.getGroup()];
1289 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1290 // FIXME: we could use the previous fragment
1291 MCDataFragment *F = new MCDataFragment(&Data);
1292 String32(*F, NumGroups + Index);
1295 for (RevGroupMapTy::const_iterator i = Groups.begin(), e = Groups.end();
1297 const MCSectionELF *Group = i->second;
1298 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1299 Asm.AddSectionToTheEnd(*this, Data, Layout);
1303 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1304 const SectionIndexMapTy &SectionIndexMap,
1305 uint32_t GroupSymbolIndex,
1306 uint64_t Offset, uint64_t Size,
1308 const MCSectionELF &Section) {
1309 uint64_t sh_link = 0;
1310 uint64_t sh_info = 0;
1312 switch(Section.getType()) {
1313 case ELF::SHT_DYNAMIC:
1314 sh_link = SectionStringTableIndex[&Section];
1319 case ELF::SHT_RELA: {
1320 const MCSectionELF *SymtabSection;
1321 const MCSectionELF *InfoSection;
1322 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1324 SectionKind::getReadOnly());
1325 sh_link = SectionIndexMap.lookup(SymtabSection);
1326 assert(sh_link && ".symtab not found");
1328 // Remove ".rel" and ".rela" prefixes.
1329 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1330 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1332 InfoSection = Asm.getContext().getELFSection(SectionName,
1333 ELF::SHT_PROGBITS, 0,
1334 SectionKind::getReadOnly());
1335 sh_info = SectionIndexMap.lookup(InfoSection);
1339 case ELF::SHT_SYMTAB:
1340 case ELF::SHT_DYNSYM:
1341 sh_link = StringTableIndex;
1342 sh_info = LastLocalSymbolIndex;
1345 case ELF::SHT_SYMTAB_SHNDX:
1346 sh_link = SymbolTableIndex;
1349 case ELF::SHT_PROGBITS:
1350 case ELF::SHT_STRTAB:
1351 case ELF::SHT_NOBITS:
1353 case ELF::SHT_ARM_ATTRIBUTES:
1357 case ELF::SHT_GROUP: {
1358 sh_link = SymbolTableIndex;
1359 sh_info = GroupSymbolIndex;
1364 assert(0 && "FIXME: sh_type value not supported!");
1368 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1369 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1370 Alignment, Section.getEntrySize());
1373 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1374 const MCAsmLayout &Layout) {
1375 GroupMapTy GroupMap;
1376 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap);
1378 SectionIndexMapTy SectionIndexMap;
1380 ComputeIndexMap(Asm, SectionIndexMap);
1382 // Compute symbol table information.
1383 ComputeSymbolTable(Asm, SectionIndexMap);
1385 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1386 const_cast<MCAsmLayout&>(Layout),
1389 // Update to include the metadata sections.
1390 ComputeIndexMap(Asm, SectionIndexMap);
1392 // Add 1 for the null section.
1393 unsigned NumSections = Asm.size() + 1;
1394 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1395 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1396 uint64_t FileOff = HeaderSize;
1398 std::vector<const MCSectionELF*> Sections;
1399 Sections.resize(NumSections);
1401 for (SectionIndexMapTy::const_iterator i=
1402 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1403 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1404 Sections[p.second] = p.first;
1407 for (unsigned i = 1; i < NumSections; ++i) {
1408 const MCSectionELF &Section = *Sections[i];
1409 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1411 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1413 // Get the size of the section in the output file (including padding).
1414 uint64_t Size = Layout.getSectionFileSize(&SD);
1419 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1421 // Write out the ELF header ...
1422 WriteHeader(FileOff - HeaderSize, NumSections);
1424 FileOff = HeaderSize;
1426 // ... then all of the sections ...
1427 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1429 for (unsigned i = 1; i < NumSections; ++i) {
1430 const MCSectionELF &Section = *Sections[i];
1431 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1433 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1434 WriteZeros(Padding);
1437 // Remember the offset into the file for this section.
1438 SectionOffsetMap[&Section] = FileOff;
1440 FileOff += Layout.getSectionFileSize(&SD);
1442 Asm.WriteSectionData(&SD, Layout, this);
1445 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1446 WriteZeros(Padding);
1449 // ... and then the section header table.
1450 // Should we align the section header table?
1452 // Null section first.
1453 uint64_t FirstSectionSize =
1454 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1455 uint32_t FirstSectionLink =
1456 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1457 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1459 for (unsigned i = 1; i < NumSections; ++i) {
1460 const MCSectionELF &Section = *Sections[i];
1461 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1462 uint32_t GroupSymbolIndex;
1463 if (Section.getType() != ELF::SHT_GROUP)
1464 GroupSymbolIndex = 0;
1466 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1468 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1469 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1470 SD.getAlignment(), Section);
1474 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1476 Triple::OSType OSType,
1478 bool IsLittleEndian,
1479 bool HasRelocationAddend) {
1480 return new ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1481 HasRelocationAddend, OSType);