1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELF.h"
24 #include "llvm/MC/MCELFSymbolFlags.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCFixupKindInfo.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
38 #define DEBUG_TYPE "reloc-info"
42 class FragmentWriter {
46 FragmentWriter(bool IsLittleEndian);
47 template <typename T> void write(MCDataFragment &F, T Val);
50 class ELFObjectWriter : public MCObjectWriter {
51 FragmentWriter FWriter;
55 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
56 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
57 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
58 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
59 bool Used, bool Renamed);
60 static bool isLocal(const MCSymbolData &Data, bool isSignature,
62 static bool IsELFMetaDataSection(const MCSectionData &SD);
63 static uint64_t DataSectionSize(const MCSectionData &SD);
64 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
65 const MCSectionData &SD);
66 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
67 const MCSectionData &SD);
69 void WriteDataSectionData(MCAssembler &Asm,
70 const MCAsmLayout &Layout,
71 const MCSectionELF &Section);
73 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
74 return Kind == X86::reloc_riprel_4byte ||
75 Kind == X86::reloc_riprel_4byte_movq_load;
78 /// ELFSymbolData - Helper struct for containing some precomputed
79 /// information on symbols.
80 struct ELFSymbolData {
81 MCSymbolData *SymbolData;
83 uint32_t SectionIndex;
85 // Support lexicographic sorting.
86 bool operator<(const ELFSymbolData &RHS) const {
87 return SymbolData->getSymbol().getName() <
88 RHS.SymbolData->getSymbol().getName();
92 /// The target specific ELF writer instance.
93 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
95 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
96 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
97 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
99 llvm::DenseMap<const MCSectionData*,
100 std::vector<ELFRelocationEntry> > Relocations;
101 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
104 /// @name Symbol Table Data
107 SmallString<256> StringTable;
108 std::vector<uint64_t> FileSymbolData;
109 std::vector<ELFSymbolData> LocalSymbolData;
110 std::vector<ELFSymbolData> ExternalSymbolData;
111 std::vector<ELFSymbolData> UndefinedSymbolData;
117 bool NeedsSymtabShndx;
119 // This holds the symbol table index of the last local symbol.
120 unsigned LastLocalSymbolIndex;
121 // This holds the .strtab section index.
122 unsigned StringTableIndex;
123 // This holds the .symtab section index.
124 unsigned SymbolTableIndex;
126 unsigned ShstrtabIndex;
129 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
130 const MCValue &Target,
132 const MCFixup &Fixup,
135 // TargetObjectWriter wrappers.
136 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
137 const MCValue &Target,
139 const MCFixup &Fixup,
140 bool IsPCRel) const {
141 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
143 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
144 const MCFixup &Fixup,
145 bool IsPCRel) const {
146 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
150 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
151 bool hasRelocationAddend() const {
152 return TargetObjectWriter->hasRelocationAddend();
154 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
155 bool IsPCRel, bool IsRelocWithSymbol,
156 int64_t Addend) const {
157 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
158 IsRelocWithSymbol, Addend);
162 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
164 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
165 TargetObjectWriter(MOTW), NeedsGOT(false), NeedsSymtabShndx(false) {}
167 virtual ~ELFObjectWriter();
169 void WriteWord(uint64_t W) {
176 template <typename T> void write(MCDataFragment &F, T Value) {
177 FWriter.write(F, Value);
180 void WriteHeader(const MCAssembler &Asm,
181 uint64_t SectionDataSize,
182 unsigned NumberOfSections);
184 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
185 uint32_t name, uint8_t info, uint64_t value,
186 uint64_t size, uint8_t other, uint32_t shndx,
189 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
191 const MCAsmLayout &Layout);
193 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
194 void WriteSymbolTable(MCDataFragment *SymtabF,
195 MCDataFragment *ShndxF,
196 const MCAssembler &Asm,
197 const MCAsmLayout &Layout,
198 const SectionIndexMapTy &SectionIndexMap);
200 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
201 const MCFragment *Fragment, const MCFixup &Fixup,
202 MCValue Target, uint64_t &FixedValue) override;
204 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
207 // Map from a group section to the signature symbol
208 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
209 // Map from a signature symbol to the group section
210 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
211 // Map from a section to the section with the relocations
212 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
213 // Map from a section to its offset
214 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
216 /// Compute the symbol table data
218 /// \param Asm - The assembler.
219 /// \param SectionIndexMap - Maps a section to its index.
220 /// \param RevGroupMap - Maps a signature symbol to the group section.
221 /// \param NumRegularSections - Number of non-relocation sections.
222 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
223 const SectionIndexMapTy &SectionIndexMap,
224 RevGroupMapTy RevGroupMap,
225 unsigned NumRegularSections);
227 void ComputeIndexMap(MCAssembler &Asm,
228 SectionIndexMapTy &SectionIndexMap,
229 const RelMapTy &RelMap);
231 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
234 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
235 const RelMapTy &RelMap);
237 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
238 SectionIndexMapTy &SectionIndexMap,
239 const RelMapTy &RelMap);
241 // Create the sections that show up in the symbol table. Currently
242 // those are the .note.GNU-stack section and the group sections.
243 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
244 GroupMapTy &GroupMap,
245 RevGroupMapTy &RevGroupMap,
246 SectionIndexMapTy &SectionIndexMap,
247 const RelMapTy &RelMap);
249 void ExecutePostLayoutBinding(MCAssembler &Asm,
250 const MCAsmLayout &Layout) override;
252 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
253 const MCAsmLayout &Layout,
254 const SectionIndexMapTy &SectionIndexMap,
255 const SectionOffsetMapTy &SectionOffsetMap);
257 void ComputeSectionOrder(MCAssembler &Asm,
258 std::vector<const MCSectionELF*> &Sections);
260 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
261 uint64_t Address, uint64_t Offset,
262 uint64_t Size, uint32_t Link, uint32_t Info,
263 uint64_t Alignment, uint64_t EntrySize);
265 void WriteRelocationsFragment(const MCAssembler &Asm,
267 const MCSectionData *SD);
270 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
271 const MCSymbolData &DataA,
272 const MCFragment &FB,
274 bool IsPCRel) const override;
276 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
277 void WriteSection(MCAssembler &Asm,
278 const SectionIndexMapTy &SectionIndexMap,
279 uint32_t GroupSymbolIndex,
280 uint64_t Offset, uint64_t Size, uint64_t Alignment,
281 const MCSectionELF &Section);
285 FragmentWriter::FragmentWriter(bool IsLittleEndian)
286 : IsLittleEndian(IsLittleEndian) {}
288 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
290 Val = support::endian::byte_swap<T, support::little>(Val);
292 Val = support::endian::byte_swap<T, support::big>(Val);
293 const char *Start = (const char *)&Val;
294 F.getContents().append(Start, Start + sizeof(T));
297 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
298 const MCFixupKindInfo &FKI =
299 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
301 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
304 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
308 case MCSymbolRefExpr::VK_GOT:
309 case MCSymbolRefExpr::VK_PLT:
310 case MCSymbolRefExpr::VK_GOTPCREL:
311 case MCSymbolRefExpr::VK_GOTOFF:
312 case MCSymbolRefExpr::VK_TPOFF:
313 case MCSymbolRefExpr::VK_TLSGD:
314 case MCSymbolRefExpr::VK_GOTTPOFF:
315 case MCSymbolRefExpr::VK_INDNTPOFF:
316 case MCSymbolRefExpr::VK_NTPOFF:
317 case MCSymbolRefExpr::VK_GOTNTPOFF:
318 case MCSymbolRefExpr::VK_TLSLDM:
319 case MCSymbolRefExpr::VK_DTPOFF:
320 case MCSymbolRefExpr::VK_TLSLD:
325 ELFObjectWriter::~ELFObjectWriter()
328 // Emit the ELF header.
329 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
330 uint64_t SectionDataSize,
331 unsigned NumberOfSections) {
337 // emitWord method behaves differently for ELF32 and ELF64, writing
338 // 4 bytes in the former and 8 in the latter.
340 Write8(0x7f); // e_ident[EI_MAG0]
341 Write8('E'); // e_ident[EI_MAG1]
342 Write8('L'); // e_ident[EI_MAG2]
343 Write8('F'); // e_ident[EI_MAG3]
345 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
348 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
350 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
352 Write8(TargetObjectWriter->getOSABI());
353 Write8(0); // e_ident[EI_ABIVERSION]
355 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
357 Write16(ELF::ET_REL); // e_type
359 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
361 Write32(ELF::EV_CURRENT); // e_version
362 WriteWord(0); // e_entry, no entry point in .o file
363 WriteWord(0); // e_phoff, no program header for .o
364 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
365 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
367 // e_flags = whatever the target wants
368 Write32(Asm.getELFHeaderEFlags());
370 // e_ehsize = ELF header size
371 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
373 Write16(0); // e_phentsize = prog header entry size
374 Write16(0); // e_phnum = # prog header entries = 0
376 // e_shentsize = Section header entry size
377 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
379 // e_shnum = # of section header ents
380 if (NumberOfSections >= ELF::SHN_LORESERVE)
381 Write16(ELF::SHN_UNDEF);
383 Write16(NumberOfSections);
385 // e_shstrndx = Section # of '.shstrtab'
386 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
387 Write16(ELF::SHN_XINDEX);
389 Write16(ShstrtabIndex);
392 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
393 MCDataFragment *ShndxF, uint32_t name,
394 uint8_t info, uint64_t value,
395 uint64_t size, uint8_t other,
396 uint32_t shndx, bool Reserved) {
398 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
399 write(*ShndxF, shndx);
401 write(*ShndxF, uint32_t(0));
404 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
405 uint16_t(ELF::SHN_XINDEX) : shndx;
408 write(*SymtabF, name); // st_name
409 write(*SymtabF, info); // st_info
410 write(*SymtabF, other); // st_other
411 write(*SymtabF, Index); // st_shndx
412 write(*SymtabF, value); // st_value
413 write(*SymtabF, size); // st_size
415 write(*SymtabF, name); // st_name
416 write(*SymtabF, uint32_t(value)); // st_value
417 write(*SymtabF, uint32_t(size)); // st_size
418 write(*SymtabF, info); // st_info
419 write(*SymtabF, other); // st_other
420 write(*SymtabF, Index); // st_shndx
424 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
425 const MCAsmLayout &Layout) {
426 MCSymbolData *Data = &OrigData;
427 if (Data->isCommon() && Data->isExternal())
428 return Data->getCommonAlignment();
430 const MCSymbol *Symbol = &Data->getSymbol();
431 bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
434 if (Symbol->isVariable()) {
435 const MCExpr *Expr = Symbol->getVariableValue();
437 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
438 llvm_unreachable("Invalid expression");
440 assert(!Value.getSymB());
442 Res = Value.getConstant();
444 if (const MCSymbolRefExpr *A = Value.getSymA()) {
445 Symbol = &A->getSymbol();
446 Data = &Layout.getAssembler().getSymbolData(*Symbol);
456 if (!Symbol || !Symbol->isInSection())
459 Res += Layout.getSymbolOffset(Data);
464 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
465 const MCAsmLayout &Layout) {
466 // The presence of symbol versions causes undefined symbols and
467 // versions declared with @@@ to be renamed.
469 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
470 ie = Asm.symbol_end(); it != ie; ++it) {
471 const MCSymbol &Alias = it->getSymbol();
472 const MCSymbol &Symbol = Alias.AliasedSymbol();
473 MCSymbolData &SD = Asm.getSymbolData(Symbol);
476 if (&Symbol == &Alias)
479 StringRef AliasName = Alias.getName();
480 size_t Pos = AliasName.find('@');
481 if (Pos == StringRef::npos)
484 // Aliases defined with .symvar copy the binding from the symbol they alias.
485 // This is the first place we are able to copy this information.
486 it->setExternal(SD.isExternal());
487 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
489 StringRef Rest = AliasName.substr(Pos);
490 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
493 // FIXME: produce a better error message.
494 if (Symbol.isUndefined() && Rest.startswith("@@") &&
495 !Rest.startswith("@@@"))
496 report_fatal_error("A @@ version cannot be undefined");
498 Renames.insert(std::make_pair(&Symbol, &Alias));
502 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
503 uint8_t Type = newType;
505 // Propagation rules:
506 // IFUNC > FUNC > OBJECT > NOTYPE
507 // TLS_OBJECT > OBJECT > NOTYPE
509 // dont let the new type degrade the old type
513 case ELF::STT_GNU_IFUNC:
514 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
515 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
516 Type = ELF::STT_GNU_IFUNC;
519 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
520 Type == ELF::STT_TLS)
521 Type = ELF::STT_FUNC;
523 case ELF::STT_OBJECT:
524 if (Type == ELF::STT_NOTYPE)
525 Type = ELF::STT_OBJECT;
528 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
529 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
537 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
538 const MCSymbol &Symbol) {
539 if (!Symbol.isVariable())
542 const MCExpr *Expr = Symbol.getVariableValue();
544 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
545 llvm_unreachable("Invalid Expression");
546 assert(!Value.getSymB());
547 const MCSymbolRefExpr *A = Value.getSymA();
550 return getBaseSymbol(Layout, A->getSymbol());
553 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
554 MCDataFragment *ShndxF,
556 const MCAsmLayout &Layout) {
557 MCSymbolData &OrigData = *MSD.SymbolData;
559 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
561 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
562 Data.getSymbol().isVariable();
564 // Binding and Type share the same byte as upper and lower nibbles
565 uint8_t Binding = MCELF::GetBinding(OrigData);
566 uint8_t Type = MCELF::GetType(OrigData);
567 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
569 MCSymbolData BaseSD = Layout.getAssembler().getSymbolData(*Base);
570 Type = mergeTypeForSet(Type, MCELF::GetType(BaseSD));
572 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
573 Type = ELF::STT_FUNC;
574 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
576 // Other and Visibility share the same byte with Visibility using the lower
578 uint8_t Visibility = MCELF::GetVisibility(OrigData);
579 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
582 uint64_t Value = SymbolValue(OrigData, Layout);
583 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
587 assert(!(Data.isCommon() && !Data.isExternal()));
589 const MCExpr *ESize = Data.getSize();
592 if (!ESize->EvaluateAsAbsolute(Res, Layout))
593 report_fatal_error("Size expression must be absolute.");
597 // Write out the symbol table entry
598 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
599 Size, Other, MSD.SectionIndex, IsReserved);
602 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
603 MCDataFragment *ShndxF,
604 const MCAssembler &Asm,
605 const MCAsmLayout &Layout,
606 const SectionIndexMapTy &SectionIndexMap) {
607 // The string table must be emitted first because we need the index
608 // into the string table for all the symbol names.
609 assert(StringTable.size() && "Missing string table");
611 // FIXME: Make sure the start of the symbol table is aligned.
613 // The first entry is the undefined symbol entry.
614 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
616 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
617 WriteSymbolEntry(SymtabF, ShndxF, FileSymbolData[i],
618 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
619 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
622 // Write the symbol table entries.
623 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
625 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
626 ELFSymbolData &MSD = LocalSymbolData[i];
627 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
630 // Write out a symbol table entry for each regular section.
631 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
633 const MCSectionELF &Section =
634 static_cast<const MCSectionELF&>(i->getSection());
635 if (Section.getType() == ELF::SHT_RELA ||
636 Section.getType() == ELF::SHT_REL ||
637 Section.getType() == ELF::SHT_STRTAB ||
638 Section.getType() == ELF::SHT_SYMTAB ||
639 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
641 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
642 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
644 LastLocalSymbolIndex++;
647 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
648 ELFSymbolData &MSD = ExternalSymbolData[i];
649 MCSymbolData &Data = *MSD.SymbolData;
650 assert(((Data.getFlags() & ELF_STB_Global) ||
651 (Data.getFlags() & ELF_STB_Weak)) &&
652 "External symbol requires STB_GLOBAL or STB_WEAK flag");
653 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
654 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
655 LastLocalSymbolIndex++;
658 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
659 ELFSymbolData &MSD = UndefinedSymbolData[i];
660 MCSymbolData &Data = *MSD.SymbolData;
661 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
662 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
663 LastLocalSymbolIndex++;
667 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
668 const MCValue &Target,
670 const MCFixup &Fixup,
671 bool IsPCRel) const {
672 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
673 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
674 const MCSymbol *Renamed = Renames.lookup(&Symbol);
675 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
677 if (ASymbol.isUndefined()) {
680 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
683 if (SD.isExternal()) {
689 const MCSectionELF &Section =
690 static_cast<const MCSectionELF&>(ASymbol.getSection());
691 const SectionKind secKind = Section.getKind();
694 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
696 if (secKind.isThreadLocal()) {
702 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
703 const MCSectionELF &Sec2 =
704 static_cast<const MCSectionELF&>(F.getParent()->getSection());
706 if (&Sec2 != &Section &&
707 (Kind == MCSymbolRefExpr::VK_PLT ||
708 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
709 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
715 if (Section.getFlags() & ELF::SHF_MERGE) {
716 if (Target.getConstant() == 0)
717 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
723 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
728 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
729 const MCAsmLayout &Layout,
730 const MCFragment *Fragment,
731 const MCFixup &Fixup,
733 uint64_t &FixedValue) {
736 int64_t Value = Target.getConstant();
737 const MCSymbol *RelocSymbol = NULL;
739 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
740 if (!Target.isAbsolute()) {
741 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
742 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
743 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
745 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
746 const MCSymbol &SymbolB = RefB->getSymbol();
747 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
750 if (!SDB.getFragment())
751 Asm.getContext().FatalError(
753 Twine("symbol '") + SymbolB.getName() +
754 "' can not be undefined in a subtraction expression");
756 // Offset of the symbol in the section
757 int64_t a = Layout.getSymbolOffset(&SDB);
759 // Offset of the relocation in the section
760 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
765 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
766 MCFragment *F = SD.getFragment();
769 Index = F->getParent()->getOrdinal() + 1;
770 // Offset of the symbol in the section
771 Value += Layout.getSymbolOffset(&SD);
776 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
777 WeakrefUsedInReloc.insert(RelocSymbol);
779 UsedInReloc.insert(RelocSymbol);
783 if (hasRelocationAddend())
788 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
789 (RelocSymbol != 0), Addend);
790 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
791 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
792 if (RelocNeedsGOT(Modifier))
795 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
798 if (!hasRelocationAddend())
802 assert(isInt<64>(Addend));
804 assert(isInt<32>(Addend));
806 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
807 Relocations[Fragment->getParent()].push_back(ERE);
812 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
814 MCSymbolData &SD = Asm.getSymbolData(*S);
815 return SD.getIndex();
818 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
819 const MCSymbolData &Data,
820 bool Used, bool Renamed) {
821 const MCSymbol &Symbol = Data.getSymbol();
822 if (Symbol.isVariable()) {
823 const MCExpr *Expr = Symbol.getVariableValue();
824 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
825 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
836 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
839 const MCSymbol &A = Symbol.AliasedSymbol();
840 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
843 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
844 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
847 if (Symbol.isTemporary())
853 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
854 bool isUsedInReloc) {
855 if (Data.isExternal())
858 const MCSymbol &Symbol = Data.getSymbol();
859 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
861 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
862 if (isSignature && !isUsedInReloc)
871 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
872 SectionIndexMapTy &SectionIndexMap,
873 const RelMapTy &RelMap) {
875 for (MCAssembler::iterator it = Asm.begin(),
876 ie = Asm.end(); it != ie; ++it) {
877 const MCSectionELF &Section =
878 static_cast<const MCSectionELF &>(it->getSection());
879 if (Section.getType() != ELF::SHT_GROUP)
881 SectionIndexMap[&Section] = Index++;
884 for (MCAssembler::iterator it = Asm.begin(),
885 ie = Asm.end(); it != ie; ++it) {
886 const MCSectionELF &Section =
887 static_cast<const MCSectionELF &>(it->getSection());
888 if (Section.getType() == ELF::SHT_GROUP ||
889 Section.getType() == ELF::SHT_REL ||
890 Section.getType() == ELF::SHT_RELA)
892 SectionIndexMap[&Section] = Index++;
893 const MCSectionELF *RelSection = RelMap.lookup(&Section);
895 SectionIndexMap[RelSection] = Index++;
900 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
901 const SectionIndexMapTy &SectionIndexMap,
902 RevGroupMapTy RevGroupMap,
903 unsigned NumRegularSections) {
904 // FIXME: Is this the correct place to do this?
905 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
907 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
908 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
909 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
910 Data.setExternal(true);
911 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
914 // Index 0 is always the empty string.
915 StringMap<uint64_t> StringIndexMap;
916 StringTable += '\x00';
918 // FIXME: We could optimize suffixes in strtab in the same way we
919 // optimize them in shstrtab.
921 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
922 ie = Asm.file_names_end();
925 StringRef Name = *it;
926 uint64_t &Entry = StringIndexMap[Name];
928 Entry = StringTable.size();
930 StringTable += '\x00';
932 FileSymbolData.push_back(Entry);
935 // Add the data for the symbols.
936 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
937 ie = Asm.symbol_end(); it != ie; ++it) {
938 const MCSymbol &Symbol = it->getSymbol();
940 bool Used = UsedInReloc.count(&Symbol);
941 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
942 bool isSignature = RevGroupMap.count(&Symbol);
944 if (!isInSymtab(Asm, *it,
945 Used || WeakrefUsed || isSignature,
946 Renames.count(&Symbol)))
951 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
953 // Undefined symbols are global, but this is the first place we
954 // are able to set it.
955 bool Local = isLocal(*it, isSignature, Used);
956 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
958 MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
959 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
960 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
964 MSD.SectionIndex = ELF::SHN_ABS;
965 } else if (it->isCommon()) {
967 MSD.SectionIndex = ELF::SHN_COMMON;
968 } else if (BaseSymbol->isUndefined()) {
969 if (isSignature && !Used)
970 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
972 MSD.SectionIndex = ELF::SHN_UNDEF;
973 if (!Used && WeakrefUsed)
974 MCELF::SetBinding(*it, ELF::STB_WEAK);
976 const MCSectionELF &Section =
977 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
978 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
979 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
980 NeedsSymtabShndx = true;
981 assert(MSD.SectionIndex && "Invalid section index!");
984 // The @@@ in symbol version is replaced with @ in undefined symbols and
985 // @@ in defined ones.
986 StringRef Name = Symbol.getName();
989 size_t Pos = Name.find("@@@");
990 if (Pos != StringRef::npos) {
991 Buf += Name.substr(0, Pos);
992 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
993 Buf += Name.substr(Pos + Skip);
997 uint64_t &Entry = StringIndexMap[Name];
999 Entry = StringTable.size();
1000 StringTable += Name;
1001 StringTable += '\x00';
1003 MSD.StringIndex = Entry;
1004 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1005 UndefinedSymbolData.push_back(MSD);
1007 LocalSymbolData.push_back(MSD);
1009 ExternalSymbolData.push_back(MSD);
1012 // Symbols are required to be in lexicographic order.
1013 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1014 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1015 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1017 // Set the symbol indices. Local symbols must come before all other
1018 // symbols with non-local bindings.
1019 unsigned Index = FileSymbolData.size() + 1;
1020 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1021 LocalSymbolData[i].SymbolData->setIndex(Index++);
1023 Index += NumRegularSections;
1025 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1026 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1027 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1028 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1030 if (Index >= ELF::SHN_LORESERVE)
1031 NeedsSymtabShndx = true;
1034 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1035 MCAsmLayout &Layout,
1037 for (MCAssembler::const_iterator it = Asm.begin(),
1038 ie = Asm.end(); it != ie; ++it) {
1039 const MCSectionData &SD = *it;
1040 if (Relocations[&SD].empty())
1043 MCContext &Ctx = Asm.getContext();
1044 const MCSectionELF &Section =
1045 static_cast<const MCSectionELF&>(SD.getSection());
1047 const StringRef SectionName = Section.getSectionName();
1048 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1049 RelaSectionName += SectionName;
1052 if (hasRelocationAddend())
1053 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1055 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1058 StringRef Group = "";
1059 if (Section.getFlags() & ELF::SHF_GROUP) {
1060 Flags = ELF::SHF_GROUP;
1061 Group = Section.getGroup()->getName();
1064 const MCSectionELF *RelaSection =
1065 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1066 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1067 SectionKind::getReadOnly(),
1069 RelMap[&Section] = RelaSection;
1070 Asm.getOrCreateSectionData(*RelaSection);
1074 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1075 const RelMapTy &RelMap) {
1076 for (MCAssembler::const_iterator it = Asm.begin(),
1077 ie = Asm.end(); it != ie; ++it) {
1078 const MCSectionData &SD = *it;
1079 const MCSectionELF &Section =
1080 static_cast<const MCSectionELF&>(SD.getSection());
1082 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1085 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1086 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1088 MCDataFragment *F = new MCDataFragment(&RelaSD);
1089 WriteRelocationsFragment(Asm, F, &*it);
1093 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1094 uint64_t Flags, uint64_t Address,
1095 uint64_t Offset, uint64_t Size,
1096 uint32_t Link, uint32_t Info,
1098 uint64_t EntrySize) {
1099 Write32(Name); // sh_name: index into string table
1100 Write32(Type); // sh_type
1101 WriteWord(Flags); // sh_flags
1102 WriteWord(Address); // sh_addr
1103 WriteWord(Offset); // sh_offset
1104 WriteWord(Size); // sh_size
1105 Write32(Link); // sh_link
1106 Write32(Info); // sh_info
1107 WriteWord(Alignment); // sh_addralign
1108 WriteWord(EntrySize); // sh_entsize
1111 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1113 const MCSectionData *SD) {
1114 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1116 // Sort the relocation entries. Most targets just sort by r_offset, but some
1117 // (e.g., MIPS) have additional constraints.
1118 TargetObjectWriter->sortRelocs(Asm, Relocs);
1120 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1121 ELFRelocationEntry entry = Relocs[e - i - 1];
1125 // FIXME: this is most likely a bug if index overflows.
1126 else if (entry.Index < 0)
1127 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1129 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1131 write(*F, entry.r_offset);
1132 if (TargetObjectWriter->isN64()) {
1133 write(*F, uint32_t(entry.Index));
1135 write(*F, TargetObjectWriter->getRSsym(entry.Type));
1136 write(*F, TargetObjectWriter->getRType3(entry.Type));
1137 write(*F, TargetObjectWriter->getRType2(entry.Type));
1138 write(*F, TargetObjectWriter->getRType(entry.Type));
1141 struct ELF::Elf64_Rela ERE64;
1142 ERE64.setSymbolAndType(entry.Index, entry.Type);
1143 write(*F, ERE64.r_info);
1145 if (hasRelocationAddend())
1146 write(*F, entry.r_addend);
1148 write(*F, uint32_t(entry.r_offset));
1150 struct ELF::Elf32_Rela ERE32;
1151 ERE32.setSymbolAndType(entry.Index, entry.Type);
1152 write(*F, ERE32.r_info);
1154 if (hasRelocationAddend())
1155 write(*F, uint32_t(entry.r_addend));
1160 static int compareBySuffix(const MCSectionELF *const *a,
1161 const MCSectionELF *const *b) {
1162 const StringRef &NameA = (*a)->getSectionName();
1163 const StringRef &NameB = (*b)->getSectionName();
1164 const unsigned sizeA = NameA.size();
1165 const unsigned sizeB = NameB.size();
1166 const unsigned len = std::min(sizeA, sizeB);
1167 for (unsigned int i = 0; i < len; ++i) {
1168 char ca = NameA[sizeA - i - 1];
1169 char cb = NameB[sizeB - i - 1];
1174 return sizeB - sizeA;
1177 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1178 MCAsmLayout &Layout,
1179 SectionIndexMapTy &SectionIndexMap,
1180 const RelMapTy &RelMap) {
1181 MCContext &Ctx = Asm.getContext();
1184 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1186 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1187 const MCSectionELF *ShstrtabSection =
1188 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1189 SectionKind::getReadOnly());
1190 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1191 ShstrtabSD.setAlignment(1);
1193 const MCSectionELF *SymtabSection =
1194 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1195 SectionKind::getReadOnly(),
1197 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1198 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1200 MCSectionData *SymtabShndxSD = NULL;
1202 if (NeedsSymtabShndx) {
1203 const MCSectionELF *SymtabShndxSection =
1204 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1205 SectionKind::getReadOnly(), 4, "");
1206 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1207 SymtabShndxSD->setAlignment(4);
1210 const MCSectionELF *StrtabSection;
1211 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1212 SectionKind::getReadOnly());
1213 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1214 StrtabSD.setAlignment(1);
1216 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1218 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1219 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1220 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1223 F = new MCDataFragment(&SymtabSD);
1224 MCDataFragment *ShndxF = NULL;
1225 if (NeedsSymtabShndx) {
1226 ShndxF = new MCDataFragment(SymtabShndxSD);
1228 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1230 F = new MCDataFragment(&StrtabSD);
1231 F->getContents().append(StringTable.begin(), StringTable.end());
1233 F = new MCDataFragment(&ShstrtabSD);
1235 std::vector<const MCSectionELF*> Sections;
1236 for (MCAssembler::const_iterator it = Asm.begin(),
1237 ie = Asm.end(); it != ie; ++it) {
1238 const MCSectionELF &Section =
1239 static_cast<const MCSectionELF&>(it->getSection());
1240 Sections.push_back(&Section);
1242 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1244 // Section header string table.
1246 // The first entry of a string table holds a null character so skip
1249 F->getContents().push_back('\x00');
1251 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1252 const MCSectionELF &Section = *Sections[I];
1254 StringRef Name = Section.getSectionName();
1256 StringRef PreviousName = Sections[I - 1]->getSectionName();
1257 if (PreviousName.endswith(Name)) {
1258 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1262 // Remember the index into the string table so we can write it
1263 // into the sh_name field of the section header table.
1264 SectionStringTableIndex[&Section] = Index;
1266 Index += Name.size() + 1;
1267 F->getContents().append(Name.begin(), Name.end());
1268 F->getContents().push_back('\x00');
1272 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1273 MCAsmLayout &Layout,
1274 GroupMapTy &GroupMap,
1275 RevGroupMapTy &RevGroupMap,
1276 SectionIndexMapTy &SectionIndexMap,
1277 const RelMapTy &RelMap) {
1278 // Create the .note.GNU-stack section if needed.
1279 MCContext &Ctx = Asm.getContext();
1280 if (Asm.getNoExecStack()) {
1281 const MCSectionELF *GnuStackSection =
1282 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1283 SectionKind::getReadOnly());
1284 Asm.getOrCreateSectionData(*GnuStackSection);
1288 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1290 const MCSectionELF &Section =
1291 static_cast<const MCSectionELF&>(it->getSection());
1292 if (!(Section.getFlags() & ELF::SHF_GROUP))
1295 const MCSymbol *SignatureSymbol = Section.getGroup();
1296 Asm.getOrCreateSymbolData(*SignatureSymbol);
1297 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1299 Group = Ctx.CreateELFGroupSection();
1300 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1301 Data.setAlignment(4);
1302 MCDataFragment *F = new MCDataFragment(&Data);
1303 write(*F, uint32_t(ELF::GRP_COMDAT));
1305 GroupMap[Group] = SignatureSymbol;
1308 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1310 // Add sections to the groups
1311 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1313 const MCSectionELF &Section =
1314 static_cast<const MCSectionELF&>(it->getSection());
1315 if (!(Section.getFlags() & ELF::SHF_GROUP))
1317 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1318 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1319 // FIXME: we could use the previous fragment
1320 MCDataFragment *F = new MCDataFragment(&Data);
1321 uint32_t Index = SectionIndexMap.lookup(&Section);
1326 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1327 const SectionIndexMapTy &SectionIndexMap,
1328 uint32_t GroupSymbolIndex,
1329 uint64_t Offset, uint64_t Size,
1331 const MCSectionELF &Section) {
1332 uint64_t sh_link = 0;
1333 uint64_t sh_info = 0;
1335 switch(Section.getType()) {
1336 case ELF::SHT_DYNAMIC:
1337 sh_link = SectionStringTableIndex[&Section];
1342 case ELF::SHT_RELA: {
1343 const MCSectionELF *SymtabSection;
1344 const MCSectionELF *InfoSection;
1345 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1347 SectionKind::getReadOnly());
1348 sh_link = SectionIndexMap.lookup(SymtabSection);
1349 assert(sh_link && ".symtab not found");
1351 // Remove ".rel" and ".rela" prefixes.
1352 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1353 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1354 StringRef GroupName =
1355 Section.getGroup() ? Section.getGroup()->getName() : "";
1357 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1358 0, SectionKind::getReadOnly(),
1360 sh_info = SectionIndexMap.lookup(InfoSection);
1364 case ELF::SHT_SYMTAB:
1365 case ELF::SHT_DYNSYM:
1366 sh_link = StringTableIndex;
1367 sh_info = LastLocalSymbolIndex;
1370 case ELF::SHT_SYMTAB_SHNDX:
1371 sh_link = SymbolTableIndex;
1374 case ELF::SHT_PROGBITS:
1375 case ELF::SHT_STRTAB:
1376 case ELF::SHT_NOBITS:
1379 case ELF::SHT_ARM_ATTRIBUTES:
1380 case ELF::SHT_INIT_ARRAY:
1381 case ELF::SHT_FINI_ARRAY:
1382 case ELF::SHT_PREINIT_ARRAY:
1383 case ELF::SHT_X86_64_UNWIND:
1384 case ELF::SHT_MIPS_REGINFO:
1385 case ELF::SHT_MIPS_OPTIONS:
1389 case ELF::SHT_GROUP:
1390 sh_link = SymbolTableIndex;
1391 sh_info = GroupSymbolIndex;
1395 assert(0 && "FIXME: sh_type value not supported!");
1399 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1400 Section.getType() == ELF::SHT_ARM_EXIDX) {
1401 StringRef SecName(Section.getSectionName());
1402 if (SecName == ".ARM.exidx") {
1403 sh_link = SectionIndexMap.lookup(
1404 Asm.getContext().getELFSection(".text",
1406 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1407 SectionKind::getText()));
1408 } else if (SecName.startswith(".ARM.exidx")) {
1409 StringRef GroupName =
1410 Section.getGroup() ? Section.getGroup()->getName() : "";
1411 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1412 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1413 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1418 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1419 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1420 Alignment, Section.getEntrySize());
1423 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1424 return SD.getOrdinal() == ~UINT32_C(0) &&
1425 !SD.getSection().isVirtualSection();
1428 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1430 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1432 const MCFragment &F = *i;
1433 assert(F.getKind() == MCFragment::FT_Data);
1434 Ret += cast<MCDataFragment>(F).getContents().size();
1439 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1440 const MCSectionData &SD) {
1441 if (IsELFMetaDataSection(SD))
1442 return DataSectionSize(SD);
1443 return Layout.getSectionFileSize(&SD);
1446 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1447 const MCSectionData &SD) {
1448 if (IsELFMetaDataSection(SD))
1449 return DataSectionSize(SD);
1450 return Layout.getSectionAddressSize(&SD);
1453 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1454 const MCAsmLayout &Layout,
1455 const MCSectionELF &Section) {
1456 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1458 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1459 WriteZeros(Padding);
1461 if (IsELFMetaDataSection(SD)) {
1462 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1464 const MCFragment &F = *i;
1465 assert(F.getKind() == MCFragment::FT_Data);
1466 WriteBytes(cast<MCDataFragment>(F).getContents());
1469 Asm.writeSectionData(&SD, Layout);
1473 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1474 const GroupMapTy &GroupMap,
1475 const MCAsmLayout &Layout,
1476 const SectionIndexMapTy &SectionIndexMap,
1477 const SectionOffsetMapTy &SectionOffsetMap) {
1478 const unsigned NumSections = Asm.size() + 1;
1480 std::vector<const MCSectionELF*> Sections;
1481 Sections.resize(NumSections - 1);
1483 for (SectionIndexMapTy::const_iterator i=
1484 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1485 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1486 Sections[p.second - 1] = p.first;
1489 // Null section first.
1490 uint64_t FirstSectionSize =
1491 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1492 uint32_t FirstSectionLink =
1493 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1494 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1496 for (unsigned i = 0; i < NumSections - 1; ++i) {
1497 const MCSectionELF &Section = *Sections[i];
1498 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1499 uint32_t GroupSymbolIndex;
1500 if (Section.getType() != ELF::SHT_GROUP)
1501 GroupSymbolIndex = 0;
1503 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1504 GroupMap.lookup(&Section));
1506 uint64_t Size = GetSectionAddressSize(Layout, SD);
1508 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1509 SectionOffsetMap.lookup(&Section), Size,
1510 SD.getAlignment(), Section);
1514 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1515 std::vector<const MCSectionELF*> &Sections) {
1516 for (MCAssembler::iterator it = Asm.begin(),
1517 ie = Asm.end(); it != ie; ++it) {
1518 const MCSectionELF &Section =
1519 static_cast<const MCSectionELF &>(it->getSection());
1520 if (Section.getType() == ELF::SHT_GROUP)
1521 Sections.push_back(&Section);
1524 for (MCAssembler::iterator it = Asm.begin(),
1525 ie = Asm.end(); it != ie; ++it) {
1526 const MCSectionELF &Section =
1527 static_cast<const MCSectionELF &>(it->getSection());
1528 if (Section.getType() != ELF::SHT_GROUP &&
1529 Section.getType() != ELF::SHT_REL &&
1530 Section.getType() != ELF::SHT_RELA)
1531 Sections.push_back(&Section);
1534 for (MCAssembler::iterator it = Asm.begin(),
1535 ie = Asm.end(); it != ie; ++it) {
1536 const MCSectionELF &Section =
1537 static_cast<const MCSectionELF &>(it->getSection());
1538 if (Section.getType() == ELF::SHT_REL ||
1539 Section.getType() == ELF::SHT_RELA)
1540 Sections.push_back(&Section);
1544 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1545 const MCAsmLayout &Layout) {
1546 GroupMapTy GroupMap;
1547 RevGroupMapTy RevGroupMap;
1548 SectionIndexMapTy SectionIndexMap;
1550 unsigned NumUserSections = Asm.size();
1552 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1553 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1555 const unsigned NumUserAndRelocSections = Asm.size();
1556 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1557 RevGroupMap, SectionIndexMap, RelMap);
1558 const unsigned AllSections = Asm.size();
1559 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1561 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1563 // Compute symbol table information.
1564 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1565 NumRegularSections);
1567 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1569 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1570 const_cast<MCAsmLayout&>(Layout),
1574 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1575 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1576 sizeof(ELF::Elf32_Ehdr);
1577 uint64_t FileOff = HeaderSize;
1579 std::vector<const MCSectionELF*> Sections;
1580 ComputeSectionOrder(Asm, Sections);
1581 unsigned NumSections = Sections.size();
1582 SectionOffsetMapTy SectionOffsetMap;
1583 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1584 const MCSectionELF &Section = *Sections[i];
1585 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1587 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1589 // Remember the offset into the file for this section.
1590 SectionOffsetMap[&Section] = FileOff;
1592 // Get the size of the section in the output file (including padding).
1593 FileOff += GetSectionFileSize(Layout, SD);
1596 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1598 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1600 uint64_t SectionHeaderEntrySize = is64Bit() ?
1601 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1602 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1604 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1605 const MCSectionELF &Section = *Sections[i];
1606 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1608 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1610 // Remember the offset into the file for this section.
1611 SectionOffsetMap[&Section] = FileOff;
1613 // Get the size of the section in the output file (including padding).
1614 FileOff += GetSectionFileSize(Layout, SD);
1617 // Write out the ELF header ...
1618 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1620 // ... then the regular sections ...
1621 // + because of .shstrtab
1622 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1623 WriteDataSectionData(Asm, Layout, *Sections[i]);
1625 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1626 WriteZeros(Padding);
1628 // ... then the section header table ...
1629 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1632 // ... and then the remaining sections ...
1633 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1634 WriteDataSectionData(Asm, Layout, *Sections[i]);
1638 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1639 const MCSymbolData &DataA,
1640 const MCFragment &FB,
1642 bool IsPCRel) const {
1643 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1645 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1646 Asm, DataA, FB,InSet, IsPCRel);
1649 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1651 bool IsLittleEndian) {
1652 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);