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 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
185 const MCValue &Target,
186 const MCFragment &F) const;
189 ELFObjectWriter(raw_ostream &_OS, bool _Is64Bit, bool IsLittleEndian,
190 uint16_t _EMachine, bool _HasRelAddend,
191 Triple::OSType _OSType)
192 : MCObjectWriter(_OS, IsLittleEndian),
193 NeedsGOT(false), NeedsSymtabShndx(false),
194 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
195 OSType(_OSType), EMachine(_EMachine) {
198 void WriteWord(uint64_t W) {
205 void StringLE16(char *buf, uint16_t Value) {
206 buf[0] = char(Value >> 0);
207 buf[1] = char(Value >> 8);
210 void StringLE32(char *buf, uint32_t Value) {
211 StringLE16(buf, uint16_t(Value >> 0));
212 StringLE16(buf + 2, uint16_t(Value >> 16));
215 void StringLE64(char *buf, uint64_t Value) {
216 StringLE32(buf, uint32_t(Value >> 0));
217 StringLE32(buf + 4, uint32_t(Value >> 32));
220 void StringBE16(char *buf ,uint16_t Value) {
221 buf[0] = char(Value >> 8);
222 buf[1] = char(Value >> 0);
225 void StringBE32(char *buf, uint32_t Value) {
226 StringBE16(buf, uint16_t(Value >> 16));
227 StringBE16(buf + 2, uint16_t(Value >> 0));
230 void StringBE64(char *buf, uint64_t Value) {
231 StringBE32(buf, uint32_t(Value >> 32));
232 StringBE32(buf + 4, uint32_t(Value >> 0));
235 void String8(MCDataFragment &F, uint8_t Value) {
238 F.getContents() += StringRef(buf, 1);
241 void String16(MCDataFragment &F, uint16_t Value) {
243 if (isLittleEndian())
244 StringLE16(buf, Value);
246 StringBE16(buf, Value);
247 F.getContents() += StringRef(buf, 2);
250 void String32(MCDataFragment &F, uint32_t Value) {
252 if (isLittleEndian())
253 StringLE32(buf, Value);
255 StringBE32(buf, Value);
256 F.getContents() += StringRef(buf, 4);
259 void String64(MCDataFragment &F, uint64_t Value) {
261 if (isLittleEndian())
262 StringLE64(buf, Value);
264 StringBE64(buf, Value);
265 F.getContents() += StringRef(buf, 8);
268 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
270 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
271 uint64_t name, uint8_t info,
272 uint64_t value, uint64_t size,
273 uint8_t other, uint32_t shndx,
276 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
278 const MCAsmLayout &Layout);
280 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
281 void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
282 const MCAssembler &Asm,
283 const MCAsmLayout &Layout,
284 const SectionIndexMapTy &SectionIndexMap);
286 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
287 const MCFragment *Fragment, const MCFixup &Fixup,
288 MCValue Target, uint64_t &FixedValue);
290 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
293 // Map from a group section to the signature symbol
294 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
295 // Map from a signature symbol to the group section
296 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
298 /// ComputeSymbolTable - Compute the symbol table data
300 /// \param StringTable [out] - The string table data.
301 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
303 void ComputeSymbolTable(MCAssembler &Asm,
304 const SectionIndexMapTy &SectionIndexMap,
305 RevGroupMapTy RevGroupMap);
307 void ComputeIndexMap(MCAssembler &Asm,
308 SectionIndexMapTy &SectionIndexMap);
310 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
311 const MCSectionData &SD);
313 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
314 for (MCAssembler::const_iterator it = Asm.begin(),
315 ie = Asm.end(); it != ie; ++it) {
316 WriteRelocation(Asm, Layout, *it);
320 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
321 const SectionIndexMapTy &SectionIndexMap);
323 void CreateGroupSections(MCAssembler &Asm, MCAsmLayout &Layout,
324 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap);
326 void ExecutePostLayoutBinding(MCAssembler &Asm);
328 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
329 uint64_t Address, uint64_t Offset,
330 uint64_t Size, uint32_t Link, uint32_t Info,
331 uint64_t Alignment, uint64_t EntrySize);
333 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
334 const MCSectionData *SD);
336 bool IsFixupFullyResolved(const MCAssembler &Asm,
337 const MCValue Target,
339 const MCFragment *DF) const;
341 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
342 void WriteSection(MCAssembler &Asm,
343 const SectionIndexMapTy &SectionIndexMap,
344 uint32_t GroupSymbolIndex,
345 uint64_t Offset, uint64_t Size, uint64_t Alignment,
346 const MCSectionELF &Section);
351 // Emit the ELF header.
352 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
353 unsigned NumberOfSections) {
359 // emitWord method behaves differently for ELF32 and ELF64, writing
360 // 4 bytes in the former and 8 in the latter.
362 Write8(0x7f); // e_ident[EI_MAG0]
363 Write8('E'); // e_ident[EI_MAG1]
364 Write8('L'); // e_ident[EI_MAG2]
365 Write8('F'); // e_ident[EI_MAG3]
367 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
370 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
372 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
375 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
376 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
377 default: Write8(ELF::ELFOSABI_NONE); break;
379 Write8(0); // e_ident[EI_ABIVERSION]
381 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
383 Write16(ELF::ET_REL); // e_type
385 Write16(EMachine); // e_machine = target
387 Write32(ELF::EV_CURRENT); // e_version
388 WriteWord(0); // e_entry, no entry point in .o file
389 WriteWord(0); // e_phoff, no program header for .o
390 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
391 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
393 // FIXME: Make this configurable.
394 Write32(0); // e_flags = whatever the target wants
396 // e_ehsize = ELF header size
397 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
399 Write16(0); // e_phentsize = prog header entry size
400 Write16(0); // e_phnum = # prog header entries = 0
402 // e_shentsize = Section header entry size
403 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
405 // e_shnum = # of section header ents
406 if (NumberOfSections >= ELF::SHN_LORESERVE)
409 Write16(NumberOfSections);
411 // e_shstrndx = Section # of '.shstrtab'
412 if (NumberOfSections >= ELF::SHN_LORESERVE)
413 Write16(ELF::SHN_XINDEX);
415 Write16(ShstrtabIndex);
418 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
419 MCDataFragment *ShndxF,
421 uint8_t info, uint64_t value,
422 uint64_t size, uint8_t other,
426 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
427 String32(*ShndxF, shndx);
429 String32(*ShndxF, 0);
432 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
433 uint16_t(ELF::SHN_XINDEX) : shndx;
436 String32(*SymtabF, name); // st_name
437 String8(*SymtabF, info); // st_info
438 String8(*SymtabF, other); // st_other
439 String16(*SymtabF, Index); // st_shndx
440 String64(*SymtabF, value); // st_value
441 String64(*SymtabF, size); // st_size
443 String32(*SymtabF, name); // st_name
444 String32(*SymtabF, value); // st_value
445 String32(*SymtabF, size); // st_size
446 String8(*SymtabF, info); // st_info
447 String8(*SymtabF, other); // st_other
448 String16(*SymtabF, Index); // st_shndx
452 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
453 if (Data.isCommon() && Data.isExternal())
454 return Data.getCommonAlignment();
456 const MCSymbol &Symbol = Data.getSymbol();
457 if (!Symbol.isInSection())
460 if (MCFragment *FF = Data.getFragment())
461 return Layout.getSymbolAddress(&Data) -
462 Layout.getSectionAddress(FF->getParent());
467 static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
468 const MCSymbol *S = &Symbol;
469 while (S->isVariable()) {
470 const MCExpr *Value = S->getVariableValue();
471 MCExpr::ExprKind Kind = Value->getKind();
473 case MCExpr::SymbolRef: {
474 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
475 S = &Ref->getSymbol();
478 case MCExpr::Target: {
479 const MCTargetExpr *TExp = static_cast<const MCTargetExpr*>(Value);
481 TExp->EvaluateAsRelocatableImpl(Res, NULL);
482 S = &Res.getSymA()->getSymbol();
492 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
493 // The presence of symbol versions causes undefined symbols and
494 // versions declared with @@@ to be renamed.
496 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
497 ie = Asm.symbol_end(); it != ie; ++it) {
498 const MCSymbol &Alias = it->getSymbol();
499 const MCSymbol &Symbol = AliasedSymbol(Alias);
500 MCSymbolData &SD = Asm.getSymbolData(Symbol);
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 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
633 const MCValue &Target,
634 const MCFragment &F) const {
635 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
636 const MCSymbol &ASymbol = AliasedSymbol(Symbol);
637 const MCSymbol *RenamedP = Renames.lookup(&Symbol);
640 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_None ||
641 Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
646 const MCSymbol &Renamed = *RenamedP;
648 MCSymbolData &SD = Asm.getSymbolData(Symbol);
650 if (Symbol.isUndefined())
656 const MCSectionELF &Section =
657 static_cast<const MCSectionELF&>(Symbol.getSection());
659 if (Section.getKind().isBSS())
662 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
663 const MCSectionELF &Sec2 =
664 static_cast<const MCSectionELF&>(F.getParent()->getSection());
666 if (&Sec2 != &Section &&
667 (Kind == MCSymbolRefExpr::VK_PLT ||
668 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
669 Kind == MCSymbolRefExpr::VK_GOTOFF))
672 if (Section.getFlags() & MCSectionELF::SHF_MERGE) {
673 if (Target.getConstant() != 0)
681 // FIXME: this is currently X86/X86_64 only
682 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
683 const MCAsmLayout &Layout,
684 const MCFragment *Fragment,
685 const MCFixup &Fixup,
687 uint64_t &FixedValue) {
690 int64_t Value = Target.getConstant();
691 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
692 const MCSymbol *RelocSymbol = SymbolToReloc(Asm, Target, *Fragment);
694 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
695 if (!Target.isAbsolute()) {
696 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
697 const MCSymbol &SymbolB = RefB->getSymbol();
698 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
700 MCSectionData *Sec = Fragment->getParent();
702 // Offset of the symbol in the section
703 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
705 // Ofeset of the relocation in the section
706 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
711 MCSymbolData &SD = Asm.getSymbolData(Symbol);
712 MCFragment *F = SD.getFragment();
714 Index = F->getParent()->getOrdinal();
716 MCSectionData *FSD = F->getParent();
717 // Offset of the symbol in the section
718 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
720 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
721 WeakrefUsedInReloc.insert(RelocSymbol);
723 UsedInReloc.insert(RelocSymbol);
727 // Compensate for the addend on i386.
734 // determine the type of the relocation
736 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
742 llvm_unreachable("Unimplemented");
743 case MCSymbolRefExpr::VK_None:
744 Type = ELF::R_X86_64_PC32;
746 case MCSymbolRefExpr::VK_PLT:
747 Type = ELF::R_X86_64_PLT32;
749 case MCSymbolRefExpr::VK_GOTPCREL:
750 Type = ELF::R_X86_64_GOTPCREL;
752 case MCSymbolRefExpr::VK_GOTTPOFF:
753 Type = ELF::R_X86_64_GOTTPOFF;
755 case MCSymbolRefExpr::VK_TLSGD:
756 Type = ELF::R_X86_64_TLSGD;
758 case MCSymbolRefExpr::VK_TLSLD:
759 Type = ELF::R_X86_64_TLSLD;
763 switch ((unsigned)Fixup.getKind()) {
764 default: llvm_unreachable("invalid fixup kind!");
765 case FK_Data_8: Type = ELF::R_X86_64_64; break;
766 case X86::reloc_signed_4byte:
767 case X86::reloc_pcrel_4byte:
768 assert(isInt<32>(Target.getConstant()));
771 llvm_unreachable("Unimplemented");
772 case MCSymbolRefExpr::VK_None:
773 Type = ELF::R_X86_64_32S;
775 case MCSymbolRefExpr::VK_GOT:
776 Type = ELF::R_X86_64_GOT32;
778 case MCSymbolRefExpr::VK_GOTPCREL:
779 Type = ELF::R_X86_64_GOTPCREL;
781 case MCSymbolRefExpr::VK_TPOFF:
782 Type = ELF::R_X86_64_TPOFF32;
784 case MCSymbolRefExpr::VK_DTPOFF:
785 Type = ELF::R_X86_64_DTPOFF32;
790 Type = ELF::R_X86_64_32;
792 case FK_Data_2: Type = ELF::R_X86_64_16; break;
793 case X86::reloc_pcrel_1byte:
794 case FK_Data_1: Type = ELF::R_X86_64_8; break;
801 llvm_unreachable("Unimplemented");
802 case MCSymbolRefExpr::VK_None:
803 Type = ELF::R_386_PC32;
805 case MCSymbolRefExpr::VK_PLT:
806 Type = ELF::R_386_PLT32;
810 switch ((unsigned)Fixup.getKind()) {
811 default: llvm_unreachable("invalid fixup kind!");
813 case X86::reloc_global_offset_table:
814 Type = ELF::R_386_GOTPC;
817 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
819 case X86::reloc_signed_4byte:
820 case X86::reloc_pcrel_4byte:
824 llvm_unreachable("Unimplemented");
825 case MCSymbolRefExpr::VK_None:
826 Type = ELF::R_386_32;
828 case MCSymbolRefExpr::VK_GOT:
829 Type = ELF::R_386_GOT32;
831 case MCSymbolRefExpr::VK_GOTOFF:
832 Type = ELF::R_386_GOTOFF;
834 case MCSymbolRefExpr::VK_TLSGD:
835 Type = ELF::R_386_TLS_GD;
837 case MCSymbolRefExpr::VK_TPOFF:
838 Type = ELF::R_386_TLS_LE_32;
840 case MCSymbolRefExpr::VK_INDNTPOFF:
841 Type = ELF::R_386_TLS_IE;
843 case MCSymbolRefExpr::VK_NTPOFF:
844 Type = ELF::R_386_TLS_LE;
846 case MCSymbolRefExpr::VK_GOTNTPOFF:
847 Type = ELF::R_386_TLS_GOTIE;
849 case MCSymbolRefExpr::VK_TLSLDM:
850 Type = ELF::R_386_TLS_LDM;
852 case MCSymbolRefExpr::VK_DTPOFF:
853 Type = ELF::R_386_TLS_LDO_32;
857 case FK_Data_2: Type = ELF::R_386_16; break;
858 case X86::reloc_pcrel_1byte:
859 case FK_Data_1: Type = ELF::R_386_8; break;
864 if (RelocNeedsGOT(Modifier))
867 ELFRelocationEntry ERE;
871 ERE.Symbol = RelocSymbol;
873 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
875 if (HasRelocationAddend)
876 ERE.r_addend = Addend;
878 ERE.r_addend = 0; // Silence compiler warning.
880 Relocations[Fragment->getParent()].push_back(ERE);
884 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
886 MCSymbolData &SD = Asm.getSymbolData(*S);
887 return SD.getIndex();
890 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
891 bool Used, bool Renamed) {
892 if (Data.getFlags() & ELF_Other_Weakref)
901 const MCSymbol &Symbol = Data.getSymbol();
903 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
906 const MCSymbol &A = AliasedSymbol(Symbol);
907 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
910 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
913 if (Symbol.isTemporary())
919 static bool isLocal(const MCSymbolData &Data, bool isSignature,
920 bool isUsedInReloc) {
921 if (Data.isExternal())
924 const MCSymbol &Symbol = Data.getSymbol();
925 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
927 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
928 if (isSignature && !isUsedInReloc)
937 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
938 SectionIndexMapTy &SectionIndexMap) {
940 for (MCAssembler::iterator it = Asm.begin(),
941 ie = Asm.end(); it != ie; ++it) {
942 const MCSectionELF &Section =
943 static_cast<const MCSectionELF &>(it->getSection());
944 if (Section.getType() != ELF::SHT_GROUP)
946 SectionIndexMap[&Section] = Index++;
949 for (MCAssembler::iterator it = Asm.begin(),
950 ie = Asm.end(); it != ie; ++it) {
951 const MCSectionELF &Section =
952 static_cast<const MCSectionELF &>(it->getSection());
953 if (Section.getType() == ELF::SHT_GROUP)
955 SectionIndexMap[&Section] = Index++;
959 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
960 const SectionIndexMapTy &SectionIndexMap,
961 RevGroupMapTy RevGroupMap) {
962 // FIXME: Is this the correct place to do this?
964 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
965 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
966 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
967 Data.setExternal(true);
968 SetBinding(Data, ELF::STB_GLOBAL);
971 // Build section lookup table.
972 int NumRegularSections = Asm.size();
974 // Index 0 is always the empty string.
975 StringMap<uint64_t> StringIndexMap;
976 StringTable += '\x00';
978 // Add the data for the symbols.
979 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
980 ie = Asm.symbol_end(); it != ie; ++it) {
981 const MCSymbol &Symbol = it->getSymbol();
983 bool Used = UsedInReloc.count(&Symbol);
984 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
985 bool isSignature = RevGroupMap.count(&Symbol);
987 if (!isInSymtab(Asm, *it,
988 Used || WeakrefUsed || isSignature,
989 Renames.count(&Symbol)))
994 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
996 // Undefined symbols are global, but this is the first place we
997 // are able to set it.
998 bool Local = isLocal(*it, isSignature, Used);
999 if (!Local && GetBinding(*it) == ELF::STB_LOCAL) {
1000 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
1001 SetBinding(*it, ELF::STB_GLOBAL);
1002 SetBinding(SD, ELF::STB_GLOBAL);
1005 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
1006 SetBinding(*it, ELF::STB_WEAK);
1008 if (it->isCommon()) {
1010 MSD.SectionIndex = ELF::SHN_COMMON;
1011 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
1012 MSD.SectionIndex = ELF::SHN_ABS;
1013 } else if (RefSymbol.isUndefined()) {
1014 if (isSignature && !Used)
1015 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1017 MSD.SectionIndex = ELF::SHN_UNDEF;
1019 const MCSectionELF &Section =
1020 static_cast<const MCSectionELF&>(RefSymbol.getSection());
1021 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1022 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
1023 NeedsSymtabShndx = true;
1024 assert(MSD.SectionIndex && "Invalid section index!");
1027 // The @@@ in symbol version is replaced with @ in undefined symbols and
1028 // @@ in defined ones.
1029 StringRef Name = Symbol.getName();
1030 SmallString<32> Buf;
1032 size_t Pos = Name.find("@@@");
1033 if (Pos != StringRef::npos) {
1034 Buf += Name.substr(0, Pos);
1035 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1036 Buf += Name.substr(Pos + Skip);
1040 uint64_t &Entry = StringIndexMap[Name];
1042 Entry = StringTable.size();
1043 StringTable += Name;
1044 StringTable += '\x00';
1046 MSD.StringIndex = Entry;
1047 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1048 UndefinedSymbolData.push_back(MSD);
1050 LocalSymbolData.push_back(MSD);
1052 ExternalSymbolData.push_back(MSD);
1055 // Symbols are required to be in lexicographic order.
1056 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1057 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1058 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1060 // Set the symbol indices. Local symbols must come before all other
1061 // symbols with non-local bindings.
1063 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1064 LocalSymbolData[i].SymbolData->setIndex(Index++);
1066 Index += NumRegularSections;
1068 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1069 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1070 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1071 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1074 void ELFObjectWriter::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1075 const MCSectionData &SD) {
1076 if (!Relocations[&SD].empty()) {
1077 MCContext &Ctx = Asm.getContext();
1078 const MCSectionELF *RelaSection;
1079 const MCSectionELF &Section =
1080 static_cast<const MCSectionELF&>(SD.getSection());
1082 const StringRef SectionName = Section.getSectionName();
1083 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
1084 RelaSectionName += SectionName;
1087 if (HasRelocationAddend)
1088 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1090 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1092 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1093 ELF::SHT_RELA : ELF::SHT_REL, 0,
1094 SectionKind::getReadOnly(),
1097 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1098 RelaSD.setAlignment(Is64Bit ? 8 : 4);
1100 MCDataFragment *F = new MCDataFragment(&RelaSD);
1102 WriteRelocationsFragment(Asm, F, &SD);
1104 Asm.AddSectionToTheEnd(*this, RelaSD, Layout);
1108 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1109 uint64_t Flags, uint64_t Address,
1110 uint64_t Offset, uint64_t Size,
1111 uint32_t Link, uint32_t Info,
1113 uint64_t EntrySize) {
1114 Write32(Name); // sh_name: index into string table
1115 Write32(Type); // sh_type
1116 WriteWord(Flags); // sh_flags
1117 WriteWord(Address); // sh_addr
1118 WriteWord(Offset); // sh_offset
1119 WriteWord(Size); // sh_size
1120 Write32(Link); // sh_link
1121 Write32(Info); // sh_info
1122 WriteWord(Alignment); // sh_addralign
1123 WriteWord(EntrySize); // sh_entsize
1126 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1128 const MCSectionData *SD) {
1129 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1130 // sort by the r_offset just like gnu as does
1131 array_pod_sort(Relocs.begin(), Relocs.end());
1133 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1134 ELFRelocationEntry entry = Relocs[e - i - 1];
1136 if (entry.Index < 0)
1137 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1139 entry.Index += LocalSymbolData.size() + 1;
1141 String64(*F, entry.r_offset);
1143 struct ELF::Elf64_Rela ERE64;
1144 ERE64.setSymbolAndType(entry.Index, entry.Type);
1145 String64(*F, ERE64.r_info);
1147 if (HasRelocationAddend)
1148 String64(*F, entry.r_addend);
1150 String32(*F, entry.r_offset);
1152 struct ELF::Elf32_Rela ERE32;
1153 ERE32.setSymbolAndType(entry.Index, entry.Type);
1154 String32(*F, ERE32.r_info);
1156 if (HasRelocationAddend)
1157 String32(*F, entry.r_addend);
1162 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1163 MCAsmLayout &Layout,
1164 const SectionIndexMapTy &SectionIndexMap) {
1165 MCContext &Ctx = Asm.getContext();
1168 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1170 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1171 const MCSectionELF *ShstrtabSection =
1172 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1173 SectionKind::getReadOnly());
1174 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1175 ShstrtabSD.setAlignment(1);
1176 ShstrtabIndex = Asm.size();
1178 const MCSectionELF *SymtabSection =
1179 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1180 SectionKind::getReadOnly(),
1182 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1183 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
1184 SymbolTableIndex = Asm.size();
1186 MCSectionData *SymtabShndxSD = NULL;
1188 if (NeedsSymtabShndx) {
1189 const MCSectionELF *SymtabShndxSection =
1190 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1191 SectionKind::getReadOnly(), 4, "");
1192 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1193 SymtabShndxSD->setAlignment(4);
1196 const MCSection *StrtabSection;
1197 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1198 SectionKind::getReadOnly());
1199 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1200 StrtabSD.setAlignment(1);
1201 StringTableIndex = Asm.size();
1203 WriteRelocations(Asm, Layout);
1206 F = new MCDataFragment(&SymtabSD);
1207 MCDataFragment *ShndxF = NULL;
1208 if (NeedsSymtabShndx) {
1209 ShndxF = new MCDataFragment(SymtabShndxSD);
1210 Asm.AddSectionToTheEnd(*this, *SymtabShndxSD, Layout);
1212 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1213 Asm.AddSectionToTheEnd(*this, SymtabSD, Layout);
1215 F = new MCDataFragment(&StrtabSD);
1216 F->getContents().append(StringTable.begin(), StringTable.end());
1217 Asm.AddSectionToTheEnd(*this, StrtabSD, Layout);
1219 F = new MCDataFragment(&ShstrtabSD);
1221 // Section header string table.
1223 // The first entry of a string table holds a null character so skip
1226 F->getContents() += '\x00';
1228 StringMap<uint64_t> SecStringMap;
1229 for (MCAssembler::const_iterator it = Asm.begin(),
1230 ie = Asm.end(); it != ie; ++it) {
1231 const MCSectionELF &Section =
1232 static_cast<const MCSectionELF&>(it->getSection());
1233 // FIXME: We could merge suffixes like in .text and .rela.text.
1235 StringRef Name = Section.getSectionName();
1236 if (SecStringMap.count(Name)) {
1237 SectionStringTableIndex[&Section] = SecStringMap[Name];
1240 // Remember the index into the string table so we can write it
1241 // into the sh_name field of the section header table.
1242 SectionStringTableIndex[&Section] = Index;
1243 SecStringMap[Name] = Index;
1245 Index += Name.size() + 1;
1246 F->getContents() += Name;
1247 F->getContents() += '\x00';
1250 Asm.AddSectionToTheEnd(*this, ShstrtabSD, Layout);
1253 bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1254 const MCValue Target,
1256 const MCFragment *DF) const {
1257 // If this is a PCrel relocation, find the section this fixup value is
1259 const MCSection *BaseSection = 0;
1261 BaseSection = &DF->getParent()->getSection();
1262 assert(BaseSection);
1265 const MCSection *SectionA = 0;
1266 const MCSymbol *SymbolA = 0;
1267 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1268 SymbolA = &A->getSymbol();
1269 SectionA = &SymbolA->getSection();
1272 const MCSection *SectionB = 0;
1273 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1274 SectionB = &B->getSymbol().getSection();
1278 return SectionA == SectionB;
1280 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1281 if (DataA.isExternal())
1284 return !SectionB && BaseSection == SectionA;
1287 void ELFObjectWriter::CreateGroupSections(MCAssembler &Asm,
1288 MCAsmLayout &Layout,
1289 GroupMapTy &GroupMap,
1290 RevGroupMapTy &RevGroupMap) {
1292 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1294 const MCSectionELF &Section =
1295 static_cast<const MCSectionELF&>(it->getSection());
1296 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1299 const MCSymbol *SignatureSymbol = Section.getGroup();
1300 Asm.getOrCreateSymbolData(*SignatureSymbol);
1301 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1303 Group = Asm.getContext().CreateELFGroupSection();
1304 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1305 Data.setAlignment(4);
1306 MCDataFragment *F = new MCDataFragment(&Data);
1307 String32(*F, ELF::GRP_COMDAT);
1309 GroupMap[Group] = SignatureSymbol;
1312 // Add sections to the groups
1314 unsigned NumGroups = RevGroupMap.size();
1315 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1316 it != ie; ++it, ++Index) {
1317 const MCSectionELF &Section =
1318 static_cast<const MCSectionELF&>(it->getSection());
1319 if (!(Section.getFlags() & MCSectionELF::SHF_GROUP))
1321 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1322 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1323 // FIXME: we could use the previous fragment
1324 MCDataFragment *F = new MCDataFragment(&Data);
1325 String32(*F, NumGroups + Index);
1328 for (RevGroupMapTy::const_iterator i = RevGroupMap.begin(),
1329 e = RevGroupMap.end(); i != e; ++i) {
1330 const MCSectionELF *Group = i->second;
1331 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1332 Asm.AddSectionToTheEnd(*this, Data, Layout);
1336 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1337 const SectionIndexMapTy &SectionIndexMap,
1338 uint32_t GroupSymbolIndex,
1339 uint64_t Offset, uint64_t Size,
1341 const MCSectionELF &Section) {
1342 uint64_t sh_link = 0;
1343 uint64_t sh_info = 0;
1345 switch(Section.getType()) {
1346 case ELF::SHT_DYNAMIC:
1347 sh_link = SectionStringTableIndex[&Section];
1352 case ELF::SHT_RELA: {
1353 const MCSectionELF *SymtabSection;
1354 const MCSectionELF *InfoSection;
1355 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1357 SectionKind::getReadOnly());
1358 sh_link = SectionIndexMap.lookup(SymtabSection);
1359 assert(sh_link && ".symtab not found");
1361 // Remove ".rel" and ".rela" prefixes.
1362 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1363 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1365 InfoSection = Asm.getContext().getELFSection(SectionName,
1366 ELF::SHT_PROGBITS, 0,
1367 SectionKind::getReadOnly());
1368 sh_info = SectionIndexMap.lookup(InfoSection);
1372 case ELF::SHT_SYMTAB:
1373 case ELF::SHT_DYNSYM:
1374 sh_link = StringTableIndex;
1375 sh_info = LastLocalSymbolIndex;
1378 case ELF::SHT_SYMTAB_SHNDX:
1379 sh_link = SymbolTableIndex;
1382 case ELF::SHT_PROGBITS:
1383 case ELF::SHT_STRTAB:
1384 case ELF::SHT_NOBITS:
1386 case ELF::SHT_ARM_ATTRIBUTES:
1390 case ELF::SHT_GROUP: {
1391 sh_link = SymbolTableIndex;
1392 sh_info = GroupSymbolIndex;
1397 assert(0 && "FIXME: sh_type value not supported!");
1401 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1402 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1403 Alignment, Section.getEntrySize());
1406 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1407 const MCAsmLayout &Layout) {
1408 GroupMapTy GroupMap;
1409 RevGroupMapTy RevGroupMap;
1410 CreateGroupSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1413 SectionIndexMapTy SectionIndexMap;
1415 ComputeIndexMap(Asm, SectionIndexMap);
1417 // Compute symbol table information.
1418 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap);
1420 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1421 const_cast<MCAsmLayout&>(Layout),
1424 // Update to include the metadata sections.
1425 ComputeIndexMap(Asm, SectionIndexMap);
1427 // Add 1 for the null section.
1428 unsigned NumSections = Asm.size() + 1;
1429 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1430 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1431 uint64_t FileOff = HeaderSize;
1433 std::vector<const MCSectionELF*> Sections;
1434 Sections.resize(NumSections);
1436 for (SectionIndexMapTy::const_iterator i=
1437 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1438 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1439 Sections[p.second] = p.first;
1442 for (unsigned i = 1; i < NumSections; ++i) {
1443 const MCSectionELF &Section = *Sections[i];
1444 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1446 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1448 // Get the size of the section in the output file (including padding).
1449 uint64_t Size = Layout.getSectionFileSize(&SD);
1454 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1456 // Write out the ELF header ...
1457 WriteHeader(FileOff - HeaderSize, NumSections);
1459 FileOff = HeaderSize;
1461 // ... then all of the sections ...
1462 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1464 for (unsigned i = 1; i < NumSections; ++i) {
1465 const MCSectionELF &Section = *Sections[i];
1466 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1468 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1469 WriteZeros(Padding);
1472 // Remember the offset into the file for this section.
1473 SectionOffsetMap[&Section] = FileOff;
1475 FileOff += Layout.getSectionFileSize(&SD);
1477 Asm.WriteSectionData(&SD, Layout, this);
1480 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1481 WriteZeros(Padding);
1484 // ... and then the section header table.
1485 // Should we align the section header table?
1487 // Null section first.
1488 uint64_t FirstSectionSize =
1489 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1490 uint32_t FirstSectionLink =
1491 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1492 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1494 for (unsigned i = 1; i < NumSections; ++i) {
1495 const MCSectionELF &Section = *Sections[i];
1496 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1497 uint32_t GroupSymbolIndex;
1498 if (Section.getType() != ELF::SHT_GROUP)
1499 GroupSymbolIndex = 0;
1501 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, GroupMap[&Section]);
1503 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1504 SectionOffsetMap[&Section], Layout.getSectionSize(&SD),
1505 SD.getAlignment(), Section);
1509 MCObjectWriter *llvm::createELFObjectWriter(raw_ostream &OS,
1511 Triple::OSType OSType,
1513 bool IsLittleEndian,
1514 bool HasRelocationAddend) {
1515 return new ELFObjectWriter(OS, Is64Bit, IsLittleEndian, EMachine,
1516 HasRelocationAddend, OSType);