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 // Map from a group section to the signature symbol
289 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
290 // Map from a signature symbol to the group section
291 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
293 /// ComputeSymbolTable - Compute the symbol table data
295 /// \param StringTable [out] - The string table data.
296 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
298 void ComputeSymbolTable(MCAssembler &Asm,
299 const SectionIndexMapTy &SectionIndexMap,
300 RevGroupMapTy RevGroupMap);
302 void ComputeIndexMap(MCAssembler &Asm,
303 SectionIndexMapTy &SectionIndexMap);
305 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
306 const MCSectionData &SD);
308 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
309 for (MCAssembler::const_iterator it = Asm.begin(),
310 ie = Asm.end(); it != ie; ++it) {
311 WriteRelocation(Asm, Layout, *it);
315 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
316 const SectionIndexMapTy &SectionIndexMap);
318 void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
319 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
321 void ExecutePostLayoutBinding(MCAssembler &Asm);
323 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
324 uint64_t Address, uint64_t Offset,
325 uint64_t Size, uint32_t Link, uint32_t Info,
326 uint64_t Alignment, uint64_t EntrySize);
328 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
329 const MCSectionData *SD);
331 bool IsFixupFullyResolved(const MCAssembler &Asm,
332 const MCValue Target,
334 const MCFragment *DF) const;
336 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
337 void WriteSection(MCAssembler &Asm,
338 const SectionIndexMapTy &SectionIndexMap,
339 uint32_t GroupSymbolIndex,
340 uint64_t Offset, uint64_t Size, uint64_t Alignment,
341 const MCSectionELF &Section);
346 // Emit the ELF header.
347 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
348 unsigned NumberOfSections) {
354 // emitWord method behaves differently for ELF32 and ELF64, writing
355 // 4 bytes in the former and 8 in the latter.
357 Write8(0x7f); // e_ident[EI_MAG0]
358 Write8('E'); // e_ident[EI_MAG1]
359 Write8('L'); // e_ident[EI_MAG2]
360 Write8('F'); // e_ident[EI_MAG3]
362 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
365 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
367 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
370 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
371 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
372 default: Write8(ELF::ELFOSABI_NONE); break;
374 Write8(0); // e_ident[EI_ABIVERSION]
376 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
378 Write16(ELF::ET_REL); // e_type
380 Write16(EMachine); // e_machine = target
382 Write32(ELF::EV_CURRENT); // e_version
383 WriteWord(0); // e_entry, no entry point in .o file
384 WriteWord(0); // e_phoff, no program header for .o
385 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
386 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
388 // FIXME: Make this configurable.
389 Write32(0); // e_flags = whatever the target wants
391 // e_ehsize = ELF header size
392 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
394 Write16(0); // e_phentsize = prog header entry size
395 Write16(0); // e_phnum = # prog header entries = 0
397 // e_shentsize = Section header entry size
398 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
400 // e_shnum = # of section header ents
401 if (NumberOfSections >= ELF::SHN_LORESERVE)
404 Write16(NumberOfSections);
406 // e_shstrndx = Section # of '.shstrtab'
407 if (NumberOfSections >= ELF::SHN_LORESERVE)
408 Write16(ELF::SHN_XINDEX);
410 Write16(ShstrtabIndex);
413 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
414 MCDataFragment *ShndxF,
416 uint8_t info, uint64_t value,
417 uint64_t size, uint8_t other,
421 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
422 String32(*ShndxF, shndx);
424 String32(*ShndxF, 0);
427 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
428 uint16_t(ELF::SHN_XINDEX) : shndx;
431 String32(*SymtabF, name); // st_name
432 String8(*SymtabF, info); // st_info
433 String8(*SymtabF, other); // st_other
434 String16(*SymtabF, Index); // st_shndx
435 String64(*SymtabF, value); // st_value
436 String64(*SymtabF, size); // st_size
438 String32(*SymtabF, name); // st_name
439 String32(*SymtabF, value); // st_value
440 String32(*SymtabF, size); // st_size
441 String8(*SymtabF, info); // st_info
442 String8(*SymtabF, other); // st_other
443 String16(*SymtabF, Index); // st_shndx
447 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
448 if (Data.isCommon() && Data.isExternal())
449 return Data.getCommonAlignment();
451 const MCSymbol &Symbol = Data.getSymbol();
452 if (!Symbol.isInSection())
455 if (MCFragment *FF = Data.getFragment())
456 return Layout.getSymbolAddress(&Data) -
457 Layout.getSectionAddress(FF->getParent());
462 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
463 const MCSymbol *S = &Symbol;
464 while (S->isVariable()) {
465 const MCExpr *Value = S->getVariableValue();
466 MCExpr::ExprKind Kind = Value->getKind();
468 case MCExpr::SymbolRef: {
469 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
470 S = &Ref->getSymbol();
473 case MCExpr::Target: {
474 const MCTargetExpr *TExp = static_cast<const MCTargetExpr*>(Value);
476 TExp->EvaluateAsRelocatableImpl(Res, NULL);
477 S = &Res.getSymA()->getSymbol();
487 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
488 // The presence of symbol versions causes undefined symbols and
489 // versions declared with @@@ to be renamed.
491 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
492 ie = Asm.symbol_end(); it != ie; ++it) {
493 const MCSymbol &Alias = it->getSymbol();
494 const MCSymbol &Symbol = AliasedSymbol(Alias);
495 MCSymbolData &SD = Asm.getSymbolData(Symbol);
498 if (&Symbol == &Alias)
501 StringRef AliasName = Alias.getName();
502 size_t Pos = AliasName.find('@');
503 if (Pos == StringRef::npos)
506 // Aliases defined with .symvar copy the binding from the symbol they alias.
507 // This is the first place we are able to copy this information.
508 it->setExternal(SD.isExternal());
509 SetBinding(*it, GetBinding(SD));
511 StringRef Rest = AliasName.substr(Pos);
512 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
515 // FIXME: produce a better error message.
516 if (Symbol.isUndefined() && Rest.startswith("@@") &&
517 !Rest.startswith("@@@"))
518 report_fatal_error("A @@ version cannot be undefined");
520 Renames.insert(std::make_pair(&Symbol, &Alias));
524 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
525 MCDataFragment *ShndxF,
527 const MCAsmLayout &Layout) {
528 MCSymbolData &OrigData = *MSD.SymbolData;
530 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
532 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
533 Data.getSymbol().isVariable();
535 uint8_t Binding = GetBinding(OrigData);
536 uint8_t Visibility = GetVisibility(OrigData);
537 uint8_t Type = GetType(Data);
539 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
540 uint8_t Other = Visibility;
542 uint64_t Value = SymbolValue(Data, Layout);
546 assert(!(Data.isCommon() && !Data.isExternal()));
548 ESize = Data.getSize();
549 if (Data.getSize()) {
551 if (ESize->getKind() == MCExpr::Binary) {
552 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
554 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
555 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
556 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
557 Size = Res.getConstant();
559 } else if (ESize->getKind() == MCExpr::Constant) {
560 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
562 assert(0 && "Unsupported size expression");
566 // Write out the symbol table entry
567 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
568 Size, Other, MSD.SectionIndex, IsReserved);
571 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
572 MCDataFragment *ShndxF,
573 const MCAssembler &Asm,
574 const MCAsmLayout &Layout,
575 const SectionIndexMapTy &SectionIndexMap) {
576 // The string table must be emitted first because we need the index
577 // into the string table for all the symbol names.
578 assert(StringTable.size() && "Missing string table");
580 // FIXME: Make sure the start of the symbol table is aligned.
582 // The first entry is the undefined symbol entry.
583 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
585 // Write the symbol table entries.
586 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
587 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
588 ELFSymbolData &MSD = LocalSymbolData[i];
589 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
592 // Write out a symbol table entry for each regular section.
593 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
595 const MCSectionELF &Section =
596 static_cast<const MCSectionELF&>(i->getSection());
597 if (Section.getType() == ELF::SHT_RELA ||
598 Section.getType() == ELF::SHT_REL ||
599 Section.getType() == ELF::SHT_STRTAB ||
600 Section.getType() == ELF::SHT_SYMTAB)
602 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
603 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), false);
604 LastLocalSymbolIndex++;
607 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
608 ELFSymbolData &MSD = ExternalSymbolData[i];
609 MCSymbolData &Data = *MSD.SymbolData;
610 assert(((Data.getFlags() & ELF_STB_Global) ||
611 (Data.getFlags() & ELF_STB_Weak)) &&
612 "External symbol requires STB_GLOBAL or STB_WEAK flag");
613 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
614 if (GetBinding(Data) == ELF::STB_LOCAL)
615 LastLocalSymbolIndex++;
618 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
619 ELFSymbolData &MSD = UndefinedSymbolData[i];
620 MCSymbolData &Data = *MSD.SymbolData;
621 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
622 if (GetBinding(Data) == ELF::STB_LOCAL)
623 LastLocalSymbolIndex++;
627 static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
628 const MCValue &Target,
629 const MCFragment &F) {
630 const MCSymbol &Symbol = SD.getSymbol();
631 if (Symbol.isUndefined())
634 const MCSectionELF &Section =
635 static_cast<const MCSectionELF&>(Symbol.getSection());
640 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
641 const MCSectionELF &Sec2 =
642 static_cast<const MCSectionELF&>(F.getParent()->getSection());
644 if (Section.getKind().isBSS())
647 if (&Sec2 != &Section &&
648 (Kind == MCSymbolRefExpr::VK_PLT ||
649 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
650 Kind == MCSymbolRefExpr::VK_GOTOFF))
653 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
654 return Target.getConstant() != 0;
659 // FIXME: this is currently X86/X86_64 only
660 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
661 const MCAsmLayout &Layout,
662 const MCFragment *Fragment,
663 const MCFixup &Fixup,
665 uint64_t &FixedValue) {
668 int64_t Value = Target.getConstant();
669 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
670 const MCSymbol &ASymbol = AliasedSymbol(Symbol);
671 const MCSymbol *RenamedP = Renames.lookup(&Symbol);
674 const MCSymbol &Renamed = *RenamedP;
676 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
677 if (!Target.isAbsolute()) {
678 MCSymbolData &SD = Asm.getSymbolData(Symbol);
679 MCFragment *F = SD.getFragment();
681 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
682 const MCSymbol &SymbolB = RefB->getSymbol();
683 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
685 MCSectionData *Sec = Fragment->getParent();
687 // Offset of the symbol in the section
688 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
690 // Ofeset of the relocation in the section
691 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
695 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
696 if (!RelocOnSymbol) {
697 Index = F->getParent()->getOrdinal();
699 MCSectionData *FSD = F->getParent();
700 // Offset of the symbol in the section
701 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
703 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
704 WeakrefUsedInReloc.insert(&Renamed);
706 UsedInReloc.insert(&Renamed);
710 // Compensate for the addend on i386.
717 // determine the type of the relocation
719 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
725 llvm_unreachable("Unimplemented");
726 case MCSymbolRefExpr::VK_None:
727 Type = ELF::R_X86_64_PC32;
729 case MCSymbolRefExpr::VK_PLT:
730 Type = ELF::R_X86_64_PLT32;
732 case MCSymbolRefExpr::VK_GOTPCREL:
733 Type = ELF::R_X86_64_GOTPCREL;
735 case MCSymbolRefExpr::VK_GOTTPOFF:
736 Type = ELF::R_X86_64_GOTTPOFF;
738 case MCSymbolRefExpr::VK_TLSGD:
739 Type = ELF::R_X86_64_TLSGD;
741 case MCSymbolRefExpr::VK_TLSLD:
742 Type = ELF::R_X86_64_TLSLD;
746 switch ((unsigned)Fixup.getKind()) {
747 default: llvm_unreachable("invalid fixup kind!");
748 case FK_Data_8: Type = ELF::R_X86_64_64; break;
749 case X86::reloc_signed_4byte:
750 case X86::reloc_pcrel_4byte:
751 assert(isInt<32>(Target.getConstant()));
754 llvm_unreachable("Unimplemented");
755 case MCSymbolRefExpr::VK_None:
756 Type = ELF::R_X86_64_32S;
758 case MCSymbolRefExpr::VK_GOT:
759 Type = ELF::R_X86_64_GOT32;
761 case MCSymbolRefExpr::VK_GOTPCREL:
762 Type = ELF::R_X86_64_GOTPCREL;
764 case MCSymbolRefExpr::VK_TPOFF:
765 Type = ELF::R_X86_64_TPOFF32;
767 case MCSymbolRefExpr::VK_DTPOFF:
768 Type = ELF::R_X86_64_DTPOFF32;
773 Type = ELF::R_X86_64_32;
775 case FK_Data_2: Type = ELF::R_X86_64_16; break;
776 case X86::reloc_pcrel_1byte:
777 case FK_Data_1: Type = ELF::R_X86_64_8; break;
784 llvm_unreachable("Unimplemented");
785 case MCSymbolRefExpr::VK_None:
786 Type = ELF::R_386_PC32;
788 case MCSymbolRefExpr::VK_PLT:
789 Type = ELF::R_386_PLT32;
793 switch ((unsigned)Fixup.getKind()) {
794 default: llvm_unreachable("invalid fixup kind!");
796 case X86::reloc_global_offset_table:
797 Type = ELF::R_386_GOTPC;
800 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
802 case X86::reloc_signed_4byte:
803 case X86::reloc_pcrel_4byte:
807 llvm_unreachable("Unimplemented");
808 case MCSymbolRefExpr::VK_None:
809 Type = ELF::R_386_32;
811 case MCSymbolRefExpr::VK_GOT:
812 Type = ELF::R_386_GOT32;
814 case MCSymbolRefExpr::VK_GOTOFF:
815 Type = ELF::R_386_GOTOFF;
817 case MCSymbolRefExpr::VK_TLSGD:
818 Type = ELF::R_386_TLS_GD;
820 case MCSymbolRefExpr::VK_TPOFF:
821 Type = ELF::R_386_TLS_LE_32;
823 case MCSymbolRefExpr::VK_INDNTPOFF:
824 Type = ELF::R_386_TLS_IE;
826 case MCSymbolRefExpr::VK_NTPOFF:
827 Type = ELF::R_386_TLS_LE;
829 case MCSymbolRefExpr::VK_GOTNTPOFF:
830 Type = ELF::R_386_TLS_GOTIE;
832 case MCSymbolRefExpr::VK_TLSLDM:
833 Type = ELF::R_386_TLS_LDM;
835 case MCSymbolRefExpr::VK_DTPOFF:
836 Type = ELF::R_386_TLS_LDO_32;
840 case FK_Data_2: Type = ELF::R_386_16; break;
841 case X86::reloc_pcrel_1byte:
842 case FK_Data_1: Type = ELF::R_386_8; break;
847 if (RelocNeedsGOT(Modifier))
850 ELFRelocationEntry ERE;
854 ERE.Symbol = &Renamed;
856 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
858 if (HasRelocationAddend)
859 ERE.r_addend = Addend;
861 ERE.r_addend = 0; // Silence compiler warning.
863 Relocations[Fragment->getParent()].push_back(ERE);
867 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
869 MCSymbolData &SD = Asm.getSymbolData(*S);
870 return SD.getIndex();
873 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
874 bool Used, bool Renamed) {
875 if (Data.getFlags() & ELF_Other_Weakref)
884 const MCSymbol &Symbol = Data.getSymbol();
886 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
889 const MCSymbol &A = AliasedSymbol(Symbol);
890 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
893 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
896 if (Symbol.isTemporary())
902 static bool isLocal(const MCSymbolData &Data, bool isSignature,
903 bool isUsedInReloc) {
904 if (Data.isExternal())
907 const MCSymbol &Symbol = Data.getSymbol();
908 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
910 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
911 if (isSignature && !isUsedInReloc)
920 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
921 SectionIndexMapTy &SectionIndexMap) {
923 for (MCAssembler::iterator it = Asm.begin(),
924 ie = Asm.end(); it != ie; ++it) {
925 const MCSectionELF &Section =
926 static_cast<const MCSectionELF &>(it->getSection());
927 if (Section.getType() != ELF::SHT_GROUP)
929 SectionIndexMap[&Section] = Index++;
932 for (MCAssembler::iterator it = Asm.begin(),
933 ie = Asm.end(); it != ie; ++it) {
934 const MCSectionELF &Section =
935 static_cast<const MCSectionELF &>(it->getSection());
936 if (Section.getType() == ELF::SHT_GROUP)
938 SectionIndexMap[&Section] = Index++;
942 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
943 const SectionIndexMapTy &SectionIndexMap,
944 RevGroupMapTy RevGroupMap) {
945 // FIXME: Is this the correct place to do this?
947 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
948 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
949 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
950 Data.setExternal(true);
951 SetBinding(Data, ELF::STB_GLOBAL);
954 // Build section lookup table.
955 int NumRegularSections = Asm.size();
957 // Index 0 is always the empty string.
958 StringMap<uint64_t> StringIndexMap;
959 StringTable += '\x00';
961 // Add the data for the symbols.
962 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
963 ie = Asm.symbol_end(); it != ie; ++it) {
964 const MCSymbol &Symbol = it->getSymbol();
966 bool Used = UsedInReloc.count(&Symbol);
967 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
968 bool isSignature = RevGroupMap.count(&Symbol);
970 if (!isInSymtab(Asm, *it,
971 Used || WeakrefUsed || isSignature,
972 Renames.count(&Symbol)))
977 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
979 // Undefined symbols are global, but this is the first place we
980 // are able to set it.
981 bool Local = isLocal(*it, isSignature, Used);
982 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
983 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
984 SetBinding(*it, ELF::STB_GLOBAL);
985 SetBinding(SD, ELF::STB_GLOBAL);
988 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
989 SetBinding(*it, ELF::STB_WEAK);
991 if (it->isCommon()) {
993 MSD.SectionIndex = ELF::SHN_COMMON;
994 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
995 MSD.SectionIndex = ELF::SHN_ABS;
996 } else if (RefSymbol.isUndefined()) {
997 if (isSignature && !Used)
998 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1000 MSD.SectionIndex = ELF::SHN_UNDEF;
1002 const MCSectionELF &Section =
1003 static_cast<const MCSectionELF&>(RefSymbol.getSection());
1004 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1005 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
1006 NeedsSymtabShndx = true;
1007 assert(MSD.SectionIndex && "Invalid section index!");
1010 // The @@@ in symbol version is replaced with @ in undefined symbols and
1011 // @@ in defined ones.
1012 StringRef Name = Symbol.getName();
1013 SmallString<32> Buf;
1015 size_t Pos = Name.find("@@@");
1016 if (Pos != StringRef::npos) {
1017 Buf += Name.substr(0, Pos);
1018 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1019 Buf += Name.substr(Pos + Skip);
1023 uint64_t &Entry = StringIndexMap[Name];
1025 Entry = StringTable.size();
1026 StringTable += Name;
1027 StringTable += '\x00';
1029 MSD.StringIndex = Entry;
1030 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1031 UndefinedSymbolData.push_back(MSD);
1033 LocalSymbolData.push_back(MSD);
1035 ExternalSymbolData.push_back(MSD);
1038 // Symbols are required to be in lexicographic order.
1039 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1040 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1041 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1043 // Set the symbol indices. Local symbols must come before all other
1044 // symbols with non-local bindings.
1046 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1047 LocalSymbolData[i].SymbolData->setIndex(Index++);
1049 Index += NumRegularSections;
1051 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1052 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1053 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1054 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1057 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1058 const MCSectionData &SD) {
1059 if (!Relocations[&SD].empty()) {
1060 MCContext &Ctx = Asm.getContext();
1061 const MCSectionELF *RelaSection;
1062 const MCSectionELF &Section =
1063 static_cast<const MCSectionELF&>(SD.getSection());
1065 const StringRef SectionName = Section.getSectionName();
1066 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1067 RelaSectionName += SectionName;
1070 if (HasRelocationAddend)
1071 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1073 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1075 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1076 ELF::SHT_RELA : ELF::SHT_REL, 0,
1077 SectionKind::getReadOnly(),
1080 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1081 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1083 MCDataFragment *F = new MCDataFragment(&RelaSD);
1085 WriteRelocationsFragment(Asm, F, &SD);
1087 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
1091 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1092 uint64_t Flags, uint64_t Address,
1093 uint64_t Offset, uint64_t Size,
1094 uint32_t Link, uint32_t Info,
1096 uint64_t EntrySize) {
1097 Write32(Name); // sh_name: index into string table
1098 Write32(Type); // sh_type
1099 WriteWord(Flags); // sh_flags
1100 WriteWord(Address); // sh_addr
1101 WriteWord(Offset); // sh_offset
1102 WriteWord(Size); // sh_size
1103 Write32(Link); // sh_link
1104 Write32(Info); // sh_info
1105 WriteWord(Alignment); // sh_addralign
1106 WriteWord(EntrySize); // sh_entsize
1109 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1111 const MCSectionData *SD) {
1112 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1113 // sort by the r_offset just like gnu as does
1114 array_pod_sort(Relocs.begin(), Relocs.end());
1116 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1117 ELFRelocationEntry entry = Relocs[e - i - 1];
1119 if (entry.Index < 0)
1120 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1122 entry.Index += LocalSymbolData.size() + 1;
1124 String64(*F, entry.r_offset);
1126 struct ELF::Elf64_Rela ERE64;
1127 ERE64.setSymbolAndType(entry.Index, entry.Type);
1128 String64(*F, ERE64.r_info);
1130 if (HasRelocationAddend)
1131 String64(*F, entry.r_addend);
1133 String32(*F, entry.r_offset);
1135 struct ELF::Elf32_Rela ERE32;
1136 ERE32.setSymbolAndType(entry.Index, entry.Type);
1137 String32(*F, ERE32.r_info);
1139 if (HasRelocationAddend)
1140 String32(*F, entry.r_addend);
1145 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1146 MCAsmLayout &Layout,
1147 const SectionIndexMapTy &SectionIndexMap) {
1148 MCContext &Ctx = Asm.getContext();
1151 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1153 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1154 const MCSectionELF *ShstrtabSection =
1155 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1156 SectionKind::getReadOnly());
1157 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1158 ShstrtabSD.setAlignment(1);
1159 ShstrtabIndex = Asm.size();
1161 const MCSectionELF *SymtabSection =
1162 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1163 SectionKind::getReadOnly(),
1165 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1166 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1167 SymbolTableIndex = Asm.size();
1169 MCSectionData *SymtabShndxSD = NULL;
1171 if (NeedsSymtabShndx) {
1172 const MCSectionELF *SymtabShndxSection =
1173 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1174 SectionKind::getReadOnly(), 4, "");
1175 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1176 SymtabShndxSD->setAlignment(4);
1179 const MCSection *StrtabSection;
1180 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1181 SectionKind::getReadOnly());
1182 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1183 StrtabSD.setAlignment(1);
1184 StringTableIndex = Asm.size();
1186 WriteRelocations(Asm, Layout);
1189 F = new MCDataFragment(&SymtabSD);
1190 MCDataFragment *ShndxF = NULL;
1191 if (NeedsSymtabShndx) {
1192 ShndxF = new MCDataFragment(SymtabShndxSD);
1193 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1195 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1196 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1198 F = new MCDataFragment(&StrtabSD);
1199 F->getContents().append(StringTable.begin(), StringTable.end());
1200 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1202 F = new MCDataFragment(&ShstrtabSD);
1204 // Section header string table.
1206 // The first entry of a string table holds a null character so skip
1209 F->getContents() += '\x00';
1211 StringMap<uint64_t> SecStringMap;
1212 for (MCAssembler::const_iterator it = Asm.begin(),
1213 ie = Asm.end(); it != ie; ++it) {
1214 const MCSectionELF &Section =
1215 static_cast<const MCSectionELF&>(it->getSection());
1216 // FIXME: We could merge suffixes like in .text and .rela.text.
1218 StringRef Name = Section.getSectionName();
1219 if (SecStringMap.count(Name)) {
1220 SectionStringTableIndex[&Section] = SecStringMap[Name];
1223 // Remember the index into the string table so we can write it
1224 // into the sh_name field of the section header table.
1225 SectionStringTableIndex[&Section] = Index;
1226 SecStringMap[Name] = Index;
1228 Index += Name.size() + 1;
1229 F->getContents() += Name;
1230 F->getContents() += '\x00';
1233 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1236 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1237 const MCValue Target,
1239 const MCFragment *DF) const {
1240 // If this is a PCrel relocation, find the section this fixup value is
1242 const MCSection *BaseSection = 0;
1244 BaseSection = &DF->getParent()->getSection();
1245 assert(BaseSection);
1248 const MCSection *SectionA = 0;
1249 const MCSymbol *SymbolA = 0;
1250 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1251 SymbolA = &A->getSymbol();
1252 SectionA = &SymbolA->getSection();
1255 const MCSection *SectionB = 0;
1256 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1257 SectionB = &B->getSymbol().getSection();
1261 return SectionA == SectionB;
1263 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1264 if (DataA.isExternal())
1267 return !SectionB && BaseSection == SectionA;
1270 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1271 MCAsmLayout &Layout,
1272 GroupMapTy &GroupMap,
1273 RevGroupMapTy &RevGroupMap) {
1275 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1277 const MCSectionELF &Section =
1278 static_cast<const MCSectionELF&>(it->getSection());
1279 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1282 const MCSymbol *SignatureSymbol = Section.getGroup();
1283 Asm.getOrCreateSymbolData(*SignatureSymbol);
1284 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1286 Group = Asm.getContext().CreateELFGroupSection();
1287 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1288 Data.setAlignment(4);
1289 MCDataFragment *F = new MCDataFragment(&Data);
1290 String32(*F, ELF::GRP_COMDAT);
1292 GroupMap[Group] = SignatureSymbol;
1295 // Add sections to the groups
1297 unsigned NumGroups = RevGroupMap.size();
1298 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1299 it != ie; ++it, ++Index) {
1300 const MCSectionELF &Section =
1301 static_cast<const MCSectionELF&>(it->getSection());
1302 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1304 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1305 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1306 // FIXME: we could use the previous fragment
1307 MCDataFragment *F = new MCDataFragment(&Data);
1308 String32(*F, NumGroups + Index);
1311 for (RevGroupMapTy::const_iterator i = RevGroupMap.begin(),
1312 e = RevGroupMap.end(); i != e; ++i) {
1313 const MCSectionELF *Group = i->second;
1314 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1315 Asm.AddSectionToTheEnd(*this, Data, Layout);
1319 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1320 const SectionIndexMapTy &SectionIndexMap,
1321 uint32_t GroupSymbolIndex,
1322 uint64_t Offset, uint64_t Size,
1324 const MCSectionELF &Section) {
1325 uint64_t sh_link = 0;
1326 uint64_t sh_info = 0;
1328 switch(Section.getType()) {
1329 case ELF::SHT_DYNAMIC:
1330 sh_link = SectionStringTableIndex[&Section];
1335 case ELF::SHT_RELA: {
1336 const MCSectionELF *SymtabSection;
1337 const MCSectionELF *InfoSection;
1338 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1340 SectionKind::getReadOnly());
1341 sh_link = SectionIndexMap.lookup(SymtabSection);
1342 assert(sh_link && ".symtab not found");
1344 // Remove ".rel" and ".rela" prefixes.
1345 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1346 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1348 InfoSection = Asm.getContext().getELFSection(SectionName,
1349 ELF::SHT_PROGBITS, 0,
1350 SectionKind::getReadOnly());
1351 sh_info = SectionIndexMap.lookup(InfoSection);
1355 case ELF::SHT_SYMTAB:
1356 case ELF::SHT_DYNSYM:
1357 sh_link = StringTableIndex;
1358 sh_info = LastLocalSymbolIndex;
1361 case ELF::SHT_SYMTAB_SHNDX:
1362 sh_link = SymbolTableIndex;
1365 case ELF::SHT_PROGBITS:
1366 case ELF::SHT_STRTAB:
1367 case ELF::SHT_NOBITS:
1369 case ELF::SHT_ARM_ATTRIBUTES:
1373 case ELF::SHT_GROUP: {
1374 sh_link = SymbolTableIndex;
1375 sh_info = GroupSymbolIndex;
1380 assert(0 && "FIXME: sh_type value not supported!");
1384 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1385 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1386 Alignment, Section.getEntrySize());
1389 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1390 const MCAsmLayout &Layout) {
1391 GroupMapTy GroupMap;
1392 RevGroupMapTy RevGroupMap;
1393 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1396 SectionIndexMapTy SectionIndexMap;
1398 ComputeIndexMap(Asm, SectionIndexMap);
1400 // Compute symbol table information.
1401 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1403 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1404 const_cast<MCAsmLayout&>(Layout),
1407 // Update to include the metadata sections.
1408 ComputeIndexMap(Asm, SectionIndexMap);
1410 // Add 1 for the null section.
1411 unsigned NumSections = Asm.size() + 1;
1412 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1413 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1414 uint64_t FileOff = HeaderSize;
1416 std::vector<const MCSectionELF*> Sections;
1417 Sections.resize(NumSections);
1419 for (SectionIndexMapTy::const_iterator i=
1420 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1421 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1422 Sections[p.second] = p.first;
1425 for (unsigned i = 1; i < NumSections; ++i) {
1426 const MCSectionELF &Section = *Sections[i];
1427 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1429 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1431 // Get the size of the section in the output file (including padding).
1432 uint64_t Size = Layout.getSectionFileSize(&SD);
1437 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1439 // Write out the ELF header ...
1440 WriteHeader(FileOff - HeaderSize, NumSections);
1442 FileOff = HeaderSize;
1444 // ... then all of the sections ...
1445 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1447 for (unsigned i = 1; i < NumSections; ++i) {
1448 const MCSectionELF &Section = *Sections[i];
1449 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1451 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1452 WriteZeros(Padding);
1455 // Remember the offset into the file for this section.
1456 SectionOffsetMap[&Section] = FileOff;
1458 FileOff += Layout.getSectionFileSize(&SD);
1460 Asm.WriteSectionData(&SD, Layout, this);
1463 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1464 WriteZeros(Padding);
1467 // ... and then the section header table.
1468 // Should we align the section header table?
1470 // Null section first.
1471 uint64_t FirstSectionSize =
1472 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1473 uint32_t FirstSectionLink =
1474 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1475 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1477 for (unsigned i = 1; i < NumSections; ++i) {
1478 const MCSectionELF &Section = *Sections[i];
1479 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1480 uint32_t GroupSymbolIndex;
1481 if (Section.getType() != ELF::SHT_GROUP)
1482 GroupSymbolIndex = 0;
1484 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1486 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1487 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1488 SD.getAlignment(), Section);
1492 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1494 Triple::OSType OSType,
1496 bool IsLittleEndian,
1497 bool HasRelocationAddend) {
1498 return new ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1499 HasRelocationAddend, OSType);