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"
41 class FragmentWriter {
45 FragmentWriter(bool IsLittleEndian);
46 template <typename T> void write(MCDataFragment &F, T Val);
49 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
51 class SymbolTableWriter {
53 FragmentWriter &FWriter;
55 SectionIndexMapTy &SectionIndexMap;
57 // The symbol .symtab fragment we are writting to.
58 MCDataFragment *SymtabF;
60 // .symtab_shndx fragment we are writting to.
61 MCDataFragment *ShndxF;
63 // The numbel of symbols written so far.
66 void createSymtabShndx();
68 template <typename T> void write(MCDataFragment &F, T Value);
71 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
72 SectionIndexMapTy &SectionIndexMap,
73 MCDataFragment *SymtabF);
75 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
76 uint8_t other, uint32_t shndx, bool Reserved);
79 class ELFObjectWriter : public MCObjectWriter {
80 FragmentWriter FWriter;
84 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
85 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
86 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
87 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
88 bool Used, bool Renamed);
89 static bool isLocal(const MCSymbolData &Data, bool isSignature,
91 static bool IsELFMetaDataSection(const MCSectionData &SD);
92 static uint64_t DataSectionSize(const MCSectionData &SD);
93 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
94 const MCSectionData &SD);
95 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
98 void WriteDataSectionData(MCAssembler &Asm,
99 const MCAsmLayout &Layout,
100 const MCSectionELF &Section);
102 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
103 return Kind == X86::reloc_riprel_4byte ||
104 Kind == X86::reloc_riprel_4byte_movq_load;
107 /// ELFSymbolData - Helper struct for containing some precomputed
108 /// information on symbols.
109 struct ELFSymbolData {
110 MCSymbolData *SymbolData;
111 uint64_t StringIndex;
112 uint32_t SectionIndex;
114 // Support lexicographic sorting.
115 bool operator<(const ELFSymbolData &RHS) const {
116 return SymbolData->getSymbol().getName() <
117 RHS.SymbolData->getSymbol().getName();
121 /// The target specific ELF writer instance.
122 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
124 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
125 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
126 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
128 llvm::DenseMap<const MCSectionData*,
129 std::vector<ELFRelocationEntry> > Relocations;
130 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
133 /// @name Symbol Table Data
136 SmallString<256> StringTable;
137 std::vector<uint64_t> FileSymbolData;
138 std::vector<ELFSymbolData> LocalSymbolData;
139 std::vector<ELFSymbolData> ExternalSymbolData;
140 std::vector<ELFSymbolData> UndefinedSymbolData;
146 // This holds the symbol table index of the last local symbol.
147 unsigned LastLocalSymbolIndex;
148 // This holds the .strtab section index.
149 unsigned StringTableIndex;
150 // This holds the .symtab section index.
151 unsigned SymbolTableIndex;
153 unsigned ShstrtabIndex;
156 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
157 const MCValue &Target,
159 const MCFixup &Fixup,
162 // TargetObjectWriter wrappers.
163 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
164 const MCValue &Target,
166 const MCFixup &Fixup,
167 bool IsPCRel) const {
168 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
170 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
171 const MCFixup &Fixup,
172 bool IsPCRel) const {
173 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
177 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
178 bool hasRelocationAddend() const {
179 return TargetObjectWriter->hasRelocationAddend();
181 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
182 bool IsPCRel) const {
183 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
187 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
189 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
190 TargetObjectWriter(MOTW), NeedsGOT(false) {}
192 virtual ~ELFObjectWriter();
194 void WriteWord(uint64_t W) {
201 template <typename T> void write(MCDataFragment &F, T Value) {
202 FWriter.write(F, Value);
205 void WriteHeader(const MCAssembler &Asm,
206 uint64_t SectionDataSize,
207 unsigned NumberOfSections);
209 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
210 const MCAsmLayout &Layout);
212 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
213 const MCAsmLayout &Layout,
214 SectionIndexMapTy &SectionIndexMap);
216 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
217 const MCFragment *Fragment, const MCFixup &Fixup,
218 MCValue Target, uint64_t &FixedValue) override;
220 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
223 // Map from a group section to the signature symbol
224 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
225 // Map from a signature symbol to the group section
226 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
227 // Map from a section to the section with the relocations
228 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
229 // Map from a section to its offset
230 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
232 /// Compute the symbol table data
234 /// \param Asm - The assembler.
235 /// \param SectionIndexMap - Maps a section to its index.
236 /// \param RevGroupMap - Maps a signature symbol to the group section.
237 /// \param NumRegularSections - Number of non-relocation sections.
238 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
239 const SectionIndexMapTy &SectionIndexMap,
240 RevGroupMapTy RevGroupMap,
241 unsigned NumRegularSections);
243 void ComputeIndexMap(MCAssembler &Asm,
244 SectionIndexMapTy &SectionIndexMap,
245 const RelMapTy &RelMap);
247 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
250 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
251 const RelMapTy &RelMap);
253 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
254 SectionIndexMapTy &SectionIndexMap,
255 const RelMapTy &RelMap);
257 // Create the sections that show up in the symbol table. Currently
258 // those are the .note.GNU-stack section and the group sections.
259 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
260 GroupMapTy &GroupMap,
261 RevGroupMapTy &RevGroupMap,
262 SectionIndexMapTy &SectionIndexMap,
263 const RelMapTy &RelMap);
265 void ExecutePostLayoutBinding(MCAssembler &Asm,
266 const MCAsmLayout &Layout) override;
268 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
269 const MCAsmLayout &Layout,
270 const SectionIndexMapTy &SectionIndexMap,
271 const SectionOffsetMapTy &SectionOffsetMap);
273 void ComputeSectionOrder(MCAssembler &Asm,
274 std::vector<const MCSectionELF*> &Sections);
276 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
277 uint64_t Address, uint64_t Offset,
278 uint64_t Size, uint32_t Link, uint32_t Info,
279 uint64_t Alignment, uint64_t EntrySize);
281 void WriteRelocationsFragment(const MCAssembler &Asm,
283 const MCSectionData *SD);
286 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
287 const MCSymbolData &DataA,
288 const MCFragment &FB,
290 bool IsPCRel) const override;
292 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
293 void WriteSection(MCAssembler &Asm,
294 const SectionIndexMapTy &SectionIndexMap,
295 uint32_t GroupSymbolIndex,
296 uint64_t Offset, uint64_t Size, uint64_t Alignment,
297 const MCSectionELF &Section);
301 FragmentWriter::FragmentWriter(bool IsLittleEndian)
302 : IsLittleEndian(IsLittleEndian) {}
304 template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
306 Val = support::endian::byte_swap<T, support::little>(Val);
308 Val = support::endian::byte_swap<T, support::big>(Val);
309 const char *Start = (const char *)&Val;
310 F.getContents().append(Start, Start + sizeof(T));
313 void SymbolTableWriter::createSymtabShndx() {
317 MCContext &Ctx = Asm.getContext();
318 const MCSectionELF *SymtabShndxSection =
319 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
320 SectionKind::getReadOnly(), 4, "");
321 MCSectionData *SymtabShndxSD =
322 &Asm.getOrCreateSectionData(*SymtabShndxSection);
323 SymtabShndxSD->setAlignment(4);
324 ShndxF = new MCDataFragment(SymtabShndxSD);
325 unsigned Index = SectionIndexMap.size() + 1;
326 SectionIndexMap[SymtabShndxSection] = Index;
328 for (unsigned I = 0; I < NumWritten; ++I)
329 write(*ShndxF, uint32_t(0));
332 template <typename T>
333 void SymbolTableWriter::write(MCDataFragment &F, T Value) {
334 FWriter.write(F, Value);
337 SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
339 SectionIndexMapTy &SectionIndexMap,
340 MCDataFragment *SymtabF)
341 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
342 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
345 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
346 uint64_t size, uint8_t other,
347 uint32_t shndx, bool Reserved) {
348 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
355 write(*ShndxF, shndx);
357 write(*ShndxF, uint32_t(0));
360 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
362 raw_svector_ostream OS(SymtabF->getContents());
365 write(*SymtabF, name); // st_name
366 write(*SymtabF, info); // st_info
367 write(*SymtabF, other); // st_other
368 write(*SymtabF, Index); // st_shndx
369 write(*SymtabF, value); // st_value
370 write(*SymtabF, size); // st_size
372 write(*SymtabF, name); // st_name
373 write(*SymtabF, uint32_t(value)); // st_value
374 write(*SymtabF, uint32_t(size)); // st_size
375 write(*SymtabF, info); // st_info
376 write(*SymtabF, other); // st_other
377 write(*SymtabF, Index); // st_shndx
383 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
384 const MCFixupKindInfo &FKI =
385 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
387 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
390 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
394 case MCSymbolRefExpr::VK_GOT:
395 case MCSymbolRefExpr::VK_PLT:
396 case MCSymbolRefExpr::VK_GOTPCREL:
397 case MCSymbolRefExpr::VK_GOTOFF:
398 case MCSymbolRefExpr::VK_TPOFF:
399 case MCSymbolRefExpr::VK_TLSGD:
400 case MCSymbolRefExpr::VK_GOTTPOFF:
401 case MCSymbolRefExpr::VK_INDNTPOFF:
402 case MCSymbolRefExpr::VK_NTPOFF:
403 case MCSymbolRefExpr::VK_GOTNTPOFF:
404 case MCSymbolRefExpr::VK_TLSLDM:
405 case MCSymbolRefExpr::VK_DTPOFF:
406 case MCSymbolRefExpr::VK_TLSLD:
411 ELFObjectWriter::~ELFObjectWriter()
414 // Emit the ELF header.
415 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
416 uint64_t SectionDataSize,
417 unsigned NumberOfSections) {
423 // emitWord method behaves differently for ELF32 and ELF64, writing
424 // 4 bytes in the former and 8 in the latter.
426 Write8(0x7f); // e_ident[EI_MAG0]
427 Write8('E'); // e_ident[EI_MAG1]
428 Write8('L'); // e_ident[EI_MAG2]
429 Write8('F'); // e_ident[EI_MAG3]
431 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
434 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
436 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
438 Write8(TargetObjectWriter->getOSABI());
439 Write8(0); // e_ident[EI_ABIVERSION]
441 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
443 Write16(ELF::ET_REL); // e_type
445 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
447 Write32(ELF::EV_CURRENT); // e_version
448 WriteWord(0); // e_entry, no entry point in .o file
449 WriteWord(0); // e_phoff, no program header for .o
450 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
451 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
453 // e_flags = whatever the target wants
454 Write32(Asm.getELFHeaderEFlags());
456 // e_ehsize = ELF header size
457 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
459 Write16(0); // e_phentsize = prog header entry size
460 Write16(0); // e_phnum = # prog header entries = 0
462 // e_shentsize = Section header entry size
463 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
465 // e_shnum = # of section header ents
466 if (NumberOfSections >= ELF::SHN_LORESERVE)
467 Write16(ELF::SHN_UNDEF);
469 Write16(NumberOfSections);
471 // e_shstrndx = Section # of '.shstrtab'
472 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
473 Write16(ELF::SHN_XINDEX);
475 Write16(ShstrtabIndex);
478 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
479 const MCAsmLayout &Layout) {
480 MCSymbolData *Data = &OrigData;
481 if (Data->isCommon() && Data->isExternal())
482 return Data->getCommonAlignment();
484 const MCSymbol *Symbol = &Data->getSymbol();
485 bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
488 if (Symbol->isVariable()) {
489 const MCExpr *Expr = Symbol->getVariableValue();
491 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
492 llvm_unreachable("Invalid expression");
494 assert(!Value.getSymB());
496 Res = Value.getConstant();
498 if (const MCSymbolRefExpr *A = Value.getSymA()) {
499 Symbol = &A->getSymbol();
500 Data = &Layout.getAssembler().getSymbolData(*Symbol);
510 if (!Symbol || !Symbol->isInSection())
513 Res += Layout.getSymbolOffset(Data);
518 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
519 const MCAsmLayout &Layout) {
520 // The presence of symbol versions causes undefined symbols and
521 // versions declared with @@@ to be renamed.
523 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
524 ie = Asm.symbol_end(); it != ie; ++it) {
525 const MCSymbol &Alias = it->getSymbol();
526 const MCSymbol &Symbol = Alias.AliasedSymbol();
527 MCSymbolData &SD = Asm.getSymbolData(Symbol);
530 if (&Symbol == &Alias)
533 StringRef AliasName = Alias.getName();
534 size_t Pos = AliasName.find('@');
535 if (Pos == StringRef::npos)
538 // Aliases defined with .symvar copy the binding from the symbol they alias.
539 // This is the first place we are able to copy this information.
540 it->setExternal(SD.isExternal());
541 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
543 StringRef Rest = AliasName.substr(Pos);
544 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
547 // FIXME: produce a better error message.
548 if (Symbol.isUndefined() && Rest.startswith("@@") &&
549 !Rest.startswith("@@@"))
550 report_fatal_error("A @@ version cannot be undefined");
552 Renames.insert(std::make_pair(&Symbol, &Alias));
556 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
557 uint8_t Type = newType;
559 // Propagation rules:
560 // IFUNC > FUNC > OBJECT > NOTYPE
561 // TLS_OBJECT > OBJECT > NOTYPE
563 // dont let the new type degrade the old type
567 case ELF::STT_GNU_IFUNC:
568 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
569 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
570 Type = ELF::STT_GNU_IFUNC;
573 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
574 Type == ELF::STT_TLS)
575 Type = ELF::STT_FUNC;
577 case ELF::STT_OBJECT:
578 if (Type == ELF::STT_NOTYPE)
579 Type = ELF::STT_OBJECT;
582 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
583 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
591 static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
592 const MCSymbol &Symbol) {
593 if (!Symbol.isVariable())
596 const MCExpr *Expr = Symbol.getVariableValue();
598 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
599 llvm_unreachable("Invalid Expression");
600 assert(!Value.getSymB());
601 const MCSymbolRefExpr *A = Value.getSymA();
604 return getBaseSymbol(Layout, A->getSymbol());
607 void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
608 const MCAsmLayout &Layout) {
609 MCSymbolData &OrigData = *MSD.SymbolData;
610 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
612 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
614 bool IsReserved = !Base || OrigData.isCommon();
616 // Binding and Type share the same byte as upper and lower nibbles
617 uint8_t Binding = MCELF::GetBinding(OrigData);
618 uint8_t Type = MCELF::GetType(OrigData);
619 MCSymbolData *BaseSD = nullptr;
621 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
622 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
624 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
625 Type = ELF::STT_FUNC;
626 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
628 // Other and Visibility share the same byte with Visibility using the lower
630 uint8_t Visibility = MCELF::GetVisibility(OrigData);
631 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
634 uint64_t Value = SymbolValue(OrigData, Layout);
635 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
639 const MCExpr *ESize = OrigData.getSize();
641 ESize = BaseSD->getSize();
645 if (!ESize->EvaluateAsAbsolute(Res, Layout))
646 report_fatal_error("Size expression must be absolute.");
650 // Write out the symbol table entry
651 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
652 MSD.SectionIndex, IsReserved);
655 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
657 const MCAsmLayout &Layout,
658 SectionIndexMapTy &SectionIndexMap) {
659 // The string table must be emitted first because we need the index
660 // into the string table for all the symbol names.
661 assert(StringTable.size() && "Missing string table");
663 // FIXME: Make sure the start of the symbol table is aligned.
665 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
667 // The first entry is the undefined symbol entry.
668 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
670 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
671 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
672 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
675 // Write the symbol table entries.
676 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
678 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
679 ELFSymbolData &MSD = LocalSymbolData[i];
680 WriteSymbol(Writer, MSD, Layout);
683 // Write out a symbol table entry for each regular section.
684 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
686 const MCSectionELF &Section =
687 static_cast<const MCSectionELF&>(i->getSection());
688 if (Section.getType() == ELF::SHT_RELA ||
689 Section.getType() == ELF::SHT_REL ||
690 Section.getType() == ELF::SHT_STRTAB ||
691 Section.getType() == ELF::SHT_SYMTAB ||
692 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
694 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
695 SectionIndexMap.lookup(&Section), false);
696 LastLocalSymbolIndex++;
699 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
700 ELFSymbolData &MSD = ExternalSymbolData[i];
701 MCSymbolData &Data = *MSD.SymbolData;
702 assert(((Data.getFlags() & ELF_STB_Global) ||
703 (Data.getFlags() & ELF_STB_Weak)) &&
704 "External symbol requires STB_GLOBAL or STB_WEAK flag");
705 WriteSymbol(Writer, MSD, Layout);
706 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
707 LastLocalSymbolIndex++;
710 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
711 ELFSymbolData &MSD = UndefinedSymbolData[i];
712 MCSymbolData &Data = *MSD.SymbolData;
713 WriteSymbol(Writer, MSD, Layout);
714 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
715 LastLocalSymbolIndex++;
719 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
720 const MCValue &Target,
722 const MCFixup &Fixup,
723 bool IsPCRel) const {
724 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
725 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
726 const MCSymbol *Renamed = Renames.lookup(&Symbol);
727 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
729 if (ASymbol.isUndefined()) {
732 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
735 if (SD.isExternal()) {
741 const MCSectionELF &Section =
742 static_cast<const MCSectionELF&>(ASymbol.getSection());
743 const SectionKind secKind = Section.getKind();
746 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
748 if (secKind.isThreadLocal()) {
754 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
755 const MCSectionELF &Sec2 =
756 static_cast<const MCSectionELF&>(F.getParent()->getSection());
758 if (&Sec2 != &Section &&
759 (Kind == MCSymbolRefExpr::VK_PLT ||
760 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
761 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
767 if (Section.getFlags() & ELF::SHF_MERGE) {
768 if (Target.getConstant() == 0)
769 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
775 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
780 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
781 const MCAsmLayout &Layout,
782 const MCFragment *Fragment,
783 const MCFixup &Fixup,
785 uint64_t &FixedValue) {
788 int64_t Value = Target.getConstant();
789 const MCSymbol *RelocSymbol = NULL;
791 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
792 if (!Target.isAbsolute()) {
793 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
794 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
795 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
797 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
798 const MCSymbol &SymbolB = RefB->getSymbol();
799 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
802 if (!SDB.getFragment())
803 Asm.getContext().FatalError(
805 Twine("symbol '") + SymbolB.getName() +
806 "' can not be undefined in a subtraction expression");
808 // Offset of the symbol in the section
809 int64_t a = Layout.getSymbolOffset(&SDB);
811 // Offset of the relocation in the section
812 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
817 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
818 MCFragment *F = SD.getFragment();
821 Index = F->getParent()->getOrdinal() + 1;
822 // Offset of the symbol in the section
823 Value += Layout.getSymbolOffset(&SD);
828 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
829 WeakrefUsedInReloc.insert(RelocSymbol);
831 UsedInReloc.insert(RelocSymbol);
835 if (hasRelocationAddend())
840 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
841 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
842 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
843 if (RelocNeedsGOT(Modifier))
846 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
849 if (!hasRelocationAddend())
853 assert(isInt<64>(Addend));
855 assert(isInt<32>(Addend));
857 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
858 Relocations[Fragment->getParent()].push_back(ERE);
863 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
865 MCSymbolData &SD = Asm.getSymbolData(*S);
866 return SD.getIndex();
869 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
870 const MCSymbolData &Data,
871 bool Used, bool Renamed) {
872 const MCSymbol &Symbol = Data.getSymbol();
873 if (Symbol.isVariable()) {
874 const MCExpr *Expr = Symbol.getVariableValue();
875 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
876 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
887 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
890 const MCSymbol &A = Symbol.AliasedSymbol();
891 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
894 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
895 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
898 if (Symbol.isTemporary())
904 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
905 bool isUsedInReloc) {
906 if (Data.isExternal())
909 const MCSymbol &Symbol = Data.getSymbol();
910 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
912 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
913 if (isSignature && !isUsedInReloc)
922 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
923 SectionIndexMapTy &SectionIndexMap,
924 const RelMapTy &RelMap) {
926 for (MCAssembler::iterator it = Asm.begin(),
927 ie = Asm.end(); it != ie; ++it) {
928 const MCSectionELF &Section =
929 static_cast<const MCSectionELF &>(it->getSection());
930 if (Section.getType() != ELF::SHT_GROUP)
932 SectionIndexMap[&Section] = Index++;
935 for (MCAssembler::iterator it = Asm.begin(),
936 ie = Asm.end(); it != ie; ++it) {
937 const MCSectionELF &Section =
938 static_cast<const MCSectionELF &>(it->getSection());
939 if (Section.getType() == ELF::SHT_GROUP ||
940 Section.getType() == ELF::SHT_REL ||
941 Section.getType() == ELF::SHT_RELA)
943 SectionIndexMap[&Section] = Index++;
944 const MCSectionELF *RelSection = RelMap.lookup(&Section);
946 SectionIndexMap[RelSection] = Index++;
951 ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
952 const SectionIndexMapTy &SectionIndexMap,
953 RevGroupMapTy RevGroupMap,
954 unsigned NumRegularSections) {
955 // FIXME: Is this the correct place to do this?
956 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
958 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
959 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
960 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
961 Data.setExternal(true);
962 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
965 // Index 0 is always the empty string.
966 StringMap<uint64_t> StringIndexMap;
967 StringTable += '\x00';
969 // FIXME: We could optimize suffixes in strtab in the same way we
970 // optimize them in shstrtab.
972 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
973 ie = Asm.file_names_end();
976 StringRef Name = *it;
977 uint64_t &Entry = StringIndexMap[Name];
979 Entry = StringTable.size();
981 StringTable += '\x00';
983 FileSymbolData.push_back(Entry);
986 // Add the data for the symbols.
987 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
988 ie = Asm.symbol_end(); it != ie; ++it) {
989 const MCSymbol &Symbol = it->getSymbol();
991 bool Used = UsedInReloc.count(&Symbol);
992 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
993 bool isSignature = RevGroupMap.count(&Symbol);
995 if (!isInSymtab(Asm, *it,
996 Used || WeakrefUsed || isSignature,
997 Renames.count(&Symbol)))
1001 MSD.SymbolData = it;
1002 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
1004 // Undefined symbols are global, but this is the first place we
1005 // are able to set it.
1006 bool Local = isLocal(*it, isSignature, Used);
1007 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
1009 MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
1010 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
1011 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
1015 MSD.SectionIndex = ELF::SHN_ABS;
1016 } else if (it->isCommon()) {
1018 MSD.SectionIndex = ELF::SHN_COMMON;
1019 } else if (BaseSymbol->isUndefined()) {
1020 if (isSignature && !Used)
1021 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1023 MSD.SectionIndex = ELF::SHN_UNDEF;
1024 if (!Used && WeakrefUsed)
1025 MCELF::SetBinding(*it, ELF::STB_WEAK);
1027 const MCSectionELF &Section =
1028 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
1029 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
1030 assert(MSD.SectionIndex && "Invalid section index!");
1033 // The @@@ in symbol version is replaced with @ in undefined symbols and
1034 // @@ in defined ones.
1035 StringRef Name = Symbol.getName();
1036 SmallString<32> Buf;
1038 size_t Pos = Name.find("@@@");
1039 if (Pos != StringRef::npos) {
1040 Buf += Name.substr(0, Pos);
1041 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1042 Buf += Name.substr(Pos + Skip);
1046 uint64_t &Entry = StringIndexMap[Name];
1048 Entry = StringTable.size();
1049 StringTable += Name;
1050 StringTable += '\x00';
1052 MSD.StringIndex = Entry;
1053 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1054 UndefinedSymbolData.push_back(MSD);
1056 LocalSymbolData.push_back(MSD);
1058 ExternalSymbolData.push_back(MSD);
1061 // Symbols are required to be in lexicographic order.
1062 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1063 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1064 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1066 // Set the symbol indices. Local symbols must come before all other
1067 // symbols with non-local bindings.
1068 unsigned Index = FileSymbolData.size() + 1;
1069 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1070 LocalSymbolData[i].SymbolData->setIndex(Index++);
1072 Index += NumRegularSections;
1074 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1075 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1076 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1077 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1080 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1081 MCAsmLayout &Layout,
1083 for (MCAssembler::const_iterator it = Asm.begin(),
1084 ie = Asm.end(); it != ie; ++it) {
1085 const MCSectionData &SD = *it;
1086 if (Relocations[&SD].empty())
1089 MCContext &Ctx = Asm.getContext();
1090 const MCSectionELF &Section =
1091 static_cast<const MCSectionELF&>(SD.getSection());
1093 const StringRef SectionName = Section.getSectionName();
1094 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1095 RelaSectionName += SectionName;
1098 if (hasRelocationAddend())
1099 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1101 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1104 StringRef Group = "";
1105 if (Section.getFlags() & ELF::SHF_GROUP) {
1106 Flags = ELF::SHF_GROUP;
1107 Group = Section.getGroup()->getName();
1110 const MCSectionELF *RelaSection =
1111 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1112 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1113 SectionKind::getReadOnly(),
1115 RelMap[&Section] = RelaSection;
1116 Asm.getOrCreateSectionData(*RelaSection);
1120 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1121 const RelMapTy &RelMap) {
1122 for (MCAssembler::const_iterator it = Asm.begin(),
1123 ie = Asm.end(); it != ie; ++it) {
1124 const MCSectionData &SD = *it;
1125 const MCSectionELF &Section =
1126 static_cast<const MCSectionELF&>(SD.getSection());
1128 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1131 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1132 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1134 MCDataFragment *F = new MCDataFragment(&RelaSD);
1135 WriteRelocationsFragment(Asm, F, &*it);
1139 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1140 uint64_t Flags, uint64_t Address,
1141 uint64_t Offset, uint64_t Size,
1142 uint32_t Link, uint32_t Info,
1144 uint64_t EntrySize) {
1145 Write32(Name); // sh_name: index into string table
1146 Write32(Type); // sh_type
1147 WriteWord(Flags); // sh_flags
1148 WriteWord(Address); // sh_addr
1149 WriteWord(Offset); // sh_offset
1150 WriteWord(Size); // sh_size
1151 Write32(Link); // sh_link
1152 Write32(Info); // sh_info
1153 WriteWord(Alignment); // sh_addralign
1154 WriteWord(EntrySize); // sh_entsize
1157 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1159 const MCSectionData *SD) {
1160 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1162 // Sort the relocation entries. Most targets just sort by r_offset, but some
1163 // (e.g., MIPS) have additional constraints.
1164 TargetObjectWriter->sortRelocs(Asm, Relocs);
1166 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1167 ELFRelocationEntry entry = Relocs[e - i - 1];
1171 // FIXME: this is most likely a bug if index overflows.
1172 else if (entry.Index < 0)
1173 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1175 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1177 write(*F, entry.r_offset);
1178 if (TargetObjectWriter->isN64()) {
1179 write(*F, uint32_t(entry.Index));
1181 write(*F, TargetObjectWriter->getRSsym(entry.Type));
1182 write(*F, TargetObjectWriter->getRType3(entry.Type));
1183 write(*F, TargetObjectWriter->getRType2(entry.Type));
1184 write(*F, TargetObjectWriter->getRType(entry.Type));
1187 struct ELF::Elf64_Rela ERE64;
1188 ERE64.setSymbolAndType(entry.Index, entry.Type);
1189 write(*F, ERE64.r_info);
1191 if (hasRelocationAddend())
1192 write(*F, entry.r_addend);
1194 write(*F, uint32_t(entry.r_offset));
1196 struct ELF::Elf32_Rela ERE32;
1197 ERE32.setSymbolAndType(entry.Index, entry.Type);
1198 write(*F, ERE32.r_info);
1200 if (hasRelocationAddend())
1201 write(*F, uint32_t(entry.r_addend));
1206 static int compareBySuffix(const MCSectionELF *const *a,
1207 const MCSectionELF *const *b) {
1208 const StringRef &NameA = (*a)->getSectionName();
1209 const StringRef &NameB = (*b)->getSectionName();
1210 const unsigned sizeA = NameA.size();
1211 const unsigned sizeB = NameB.size();
1212 const unsigned len = std::min(sizeA, sizeB);
1213 for (unsigned int i = 0; i < len; ++i) {
1214 char ca = NameA[sizeA - i - 1];
1215 char cb = NameB[sizeB - i - 1];
1220 return sizeB - sizeA;
1223 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1224 MCAsmLayout &Layout,
1225 SectionIndexMapTy &SectionIndexMap,
1226 const RelMapTy &RelMap) {
1227 MCContext &Ctx = Asm.getContext();
1230 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1232 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1233 const MCSectionELF *ShstrtabSection =
1234 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1235 SectionKind::getReadOnly());
1236 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1237 ShstrtabSD.setAlignment(1);
1239 const MCSectionELF *SymtabSection =
1240 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1241 SectionKind::getReadOnly(),
1243 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1244 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1246 const MCSectionELF *StrtabSection;
1247 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1248 SectionKind::getReadOnly());
1249 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1250 StrtabSD.setAlignment(1);
1252 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1254 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1255 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1256 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1259 F = new MCDataFragment(&SymtabSD);
1260 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
1262 F = new MCDataFragment(&StrtabSD);
1263 F->getContents().append(StringTable.begin(), StringTable.end());
1265 F = new MCDataFragment(&ShstrtabSD);
1267 std::vector<const MCSectionELF*> Sections;
1268 for (MCAssembler::const_iterator it = Asm.begin(),
1269 ie = Asm.end(); it != ie; ++it) {
1270 const MCSectionELF &Section =
1271 static_cast<const MCSectionELF&>(it->getSection());
1272 Sections.push_back(&Section);
1274 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1276 // Section header string table.
1278 // The first entry of a string table holds a null character so skip
1281 F->getContents().push_back('\x00');
1283 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1284 const MCSectionELF &Section = *Sections[I];
1286 StringRef Name = Section.getSectionName();
1288 StringRef PreviousName = Sections[I - 1]->getSectionName();
1289 if (PreviousName.endswith(Name)) {
1290 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1294 // Remember the index into the string table so we can write it
1295 // into the sh_name field of the section header table.
1296 SectionStringTableIndex[&Section] = Index;
1298 Index += Name.size() + 1;
1299 F->getContents().append(Name.begin(), Name.end());
1300 F->getContents().push_back('\x00');
1304 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1305 MCAsmLayout &Layout,
1306 GroupMapTy &GroupMap,
1307 RevGroupMapTy &RevGroupMap,
1308 SectionIndexMapTy &SectionIndexMap,
1309 const RelMapTy &RelMap) {
1310 // Create the .note.GNU-stack section if needed.
1311 MCContext &Ctx = Asm.getContext();
1312 if (Asm.getNoExecStack()) {
1313 const MCSectionELF *GnuStackSection =
1314 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1315 SectionKind::getReadOnly());
1316 Asm.getOrCreateSectionData(*GnuStackSection);
1320 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1322 const MCSectionELF &Section =
1323 static_cast<const MCSectionELF&>(it->getSection());
1324 if (!(Section.getFlags() & ELF::SHF_GROUP))
1327 const MCSymbol *SignatureSymbol = Section.getGroup();
1328 Asm.getOrCreateSymbolData(*SignatureSymbol);
1329 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1331 Group = Ctx.CreateELFGroupSection();
1332 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1333 Data.setAlignment(4);
1334 MCDataFragment *F = new MCDataFragment(&Data);
1335 write(*F, uint32_t(ELF::GRP_COMDAT));
1337 GroupMap[Group] = SignatureSymbol;
1340 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1342 // Add sections to the groups
1343 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1345 const MCSectionELF &Section =
1346 static_cast<const MCSectionELF&>(it->getSection());
1347 if (!(Section.getFlags() & ELF::SHF_GROUP))
1349 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1350 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1351 // FIXME: we could use the previous fragment
1352 MCDataFragment *F = new MCDataFragment(&Data);
1353 uint32_t Index = SectionIndexMap.lookup(&Section);
1358 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1359 const SectionIndexMapTy &SectionIndexMap,
1360 uint32_t GroupSymbolIndex,
1361 uint64_t Offset, uint64_t Size,
1363 const MCSectionELF &Section) {
1364 uint64_t sh_link = 0;
1365 uint64_t sh_info = 0;
1367 switch(Section.getType()) {
1368 case ELF::SHT_DYNAMIC:
1369 sh_link = SectionStringTableIndex[&Section];
1374 case ELF::SHT_RELA: {
1375 const MCSectionELF *SymtabSection;
1376 const MCSectionELF *InfoSection;
1377 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1379 SectionKind::getReadOnly());
1380 sh_link = SectionIndexMap.lookup(SymtabSection);
1381 assert(sh_link && ".symtab not found");
1383 // Remove ".rel" and ".rela" prefixes.
1384 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1385 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1386 StringRef GroupName =
1387 Section.getGroup() ? Section.getGroup()->getName() : "";
1389 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1390 0, SectionKind::getReadOnly(),
1392 sh_info = SectionIndexMap.lookup(InfoSection);
1396 case ELF::SHT_SYMTAB:
1397 case ELF::SHT_DYNSYM:
1398 sh_link = StringTableIndex;
1399 sh_info = LastLocalSymbolIndex;
1402 case ELF::SHT_SYMTAB_SHNDX:
1403 sh_link = SymbolTableIndex;
1406 case ELF::SHT_PROGBITS:
1407 case ELF::SHT_STRTAB:
1408 case ELF::SHT_NOBITS:
1411 case ELF::SHT_ARM_ATTRIBUTES:
1412 case ELF::SHT_INIT_ARRAY:
1413 case ELF::SHT_FINI_ARRAY:
1414 case ELF::SHT_PREINIT_ARRAY:
1415 case ELF::SHT_X86_64_UNWIND:
1416 case ELF::SHT_MIPS_REGINFO:
1417 case ELF::SHT_MIPS_OPTIONS:
1421 case ELF::SHT_GROUP:
1422 sh_link = SymbolTableIndex;
1423 sh_info = GroupSymbolIndex;
1427 assert(0 && "FIXME: sh_type value not supported!");
1431 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1432 Section.getType() == ELF::SHT_ARM_EXIDX) {
1433 StringRef SecName(Section.getSectionName());
1434 if (SecName == ".ARM.exidx") {
1435 sh_link = SectionIndexMap.lookup(
1436 Asm.getContext().getELFSection(".text",
1438 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1439 SectionKind::getText()));
1440 } else if (SecName.startswith(".ARM.exidx")) {
1441 StringRef GroupName =
1442 Section.getGroup() ? Section.getGroup()->getName() : "";
1443 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1444 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1445 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1450 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1451 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1452 Alignment, Section.getEntrySize());
1455 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1456 return SD.getOrdinal() == ~UINT32_C(0) &&
1457 !SD.getSection().isVirtualSection();
1460 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &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 Ret += cast<MCDataFragment>(F).getContents().size();
1471 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1472 const MCSectionData &SD) {
1473 if (IsELFMetaDataSection(SD))
1474 return DataSectionSize(SD);
1475 return Layout.getSectionFileSize(&SD);
1478 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1479 const MCSectionData &SD) {
1480 if (IsELFMetaDataSection(SD))
1481 return DataSectionSize(SD);
1482 return Layout.getSectionAddressSize(&SD);
1485 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1486 const MCAsmLayout &Layout,
1487 const MCSectionELF &Section) {
1488 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1490 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1491 WriteZeros(Padding);
1493 if (IsELFMetaDataSection(SD)) {
1494 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1496 const MCFragment &F = *i;
1497 assert(F.getKind() == MCFragment::FT_Data);
1498 WriteBytes(cast<MCDataFragment>(F).getContents());
1501 Asm.writeSectionData(&SD, Layout);
1505 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1506 const GroupMapTy &GroupMap,
1507 const MCAsmLayout &Layout,
1508 const SectionIndexMapTy &SectionIndexMap,
1509 const SectionOffsetMapTy &SectionOffsetMap) {
1510 const unsigned NumSections = Asm.size() + 1;
1512 std::vector<const MCSectionELF*> Sections;
1513 Sections.resize(NumSections - 1);
1515 for (SectionIndexMapTy::const_iterator i=
1516 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1517 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1518 Sections[p.second - 1] = p.first;
1521 // Null section first.
1522 uint64_t FirstSectionSize =
1523 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1524 uint32_t FirstSectionLink =
1525 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1526 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1528 for (unsigned i = 0; i < NumSections - 1; ++i) {
1529 const MCSectionELF &Section = *Sections[i];
1530 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1531 uint32_t GroupSymbolIndex;
1532 if (Section.getType() != ELF::SHT_GROUP)
1533 GroupSymbolIndex = 0;
1535 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1536 GroupMap.lookup(&Section));
1538 uint64_t Size = GetSectionAddressSize(Layout, SD);
1540 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1541 SectionOffsetMap.lookup(&Section), Size,
1542 SD.getAlignment(), Section);
1546 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1547 std::vector<const MCSectionELF*> &Sections) {
1548 for (MCAssembler::iterator it = Asm.begin(),
1549 ie = Asm.end(); it != ie; ++it) {
1550 const MCSectionELF &Section =
1551 static_cast<const MCSectionELF &>(it->getSection());
1552 if (Section.getType() == ELF::SHT_GROUP)
1553 Sections.push_back(&Section);
1556 for (MCAssembler::iterator it = Asm.begin(),
1557 ie = Asm.end(); it != ie; ++it) {
1558 const MCSectionELF &Section =
1559 static_cast<const MCSectionELF &>(it->getSection());
1560 if (Section.getType() != ELF::SHT_GROUP &&
1561 Section.getType() != ELF::SHT_REL &&
1562 Section.getType() != ELF::SHT_RELA)
1563 Sections.push_back(&Section);
1566 for (MCAssembler::iterator it = Asm.begin(),
1567 ie = Asm.end(); it != ie; ++it) {
1568 const MCSectionELF &Section =
1569 static_cast<const MCSectionELF &>(it->getSection());
1570 if (Section.getType() == ELF::SHT_REL ||
1571 Section.getType() == ELF::SHT_RELA)
1572 Sections.push_back(&Section);
1576 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1577 const MCAsmLayout &Layout) {
1578 GroupMapTy GroupMap;
1579 RevGroupMapTy RevGroupMap;
1580 SectionIndexMapTy SectionIndexMap;
1582 unsigned NumUserSections = Asm.size();
1584 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1585 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1587 const unsigned NumUserAndRelocSections = Asm.size();
1588 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1589 RevGroupMap, SectionIndexMap, RelMap);
1590 const unsigned AllSections = Asm.size();
1591 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1593 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1595 // Compute symbol table information.
1596 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1597 NumRegularSections);
1599 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1601 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1602 const_cast<MCAsmLayout&>(Layout),
1606 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1607 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1608 sizeof(ELF::Elf32_Ehdr);
1609 uint64_t FileOff = HeaderSize;
1611 std::vector<const MCSectionELF*> Sections;
1612 ComputeSectionOrder(Asm, Sections);
1613 unsigned NumSections = Sections.size();
1614 SectionOffsetMapTy SectionOffsetMap;
1615 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1616 const MCSectionELF &Section = *Sections[i];
1617 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1619 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1621 // Remember the offset into the file for this section.
1622 SectionOffsetMap[&Section] = FileOff;
1624 // Get the size of the section in the output file (including padding).
1625 FileOff += GetSectionFileSize(Layout, SD);
1628 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1630 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1632 uint64_t SectionHeaderEntrySize = is64Bit() ?
1633 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1634 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1636 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1637 const MCSectionELF &Section = *Sections[i];
1638 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1640 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1642 // Remember the offset into the file for this section.
1643 SectionOffsetMap[&Section] = FileOff;
1645 // Get the size of the section in the output file (including padding).
1646 FileOff += GetSectionFileSize(Layout, SD);
1649 // Write out the ELF header ...
1650 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1652 // ... then the regular sections ...
1653 // + because of .shstrtab
1654 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1655 WriteDataSectionData(Asm, Layout, *Sections[i]);
1657 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1658 WriteZeros(Padding);
1660 // ... then the section header table ...
1661 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1664 // ... and then the remaining sections ...
1665 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1666 WriteDataSectionData(Asm, Layout, *Sections[i]);
1670 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1671 const MCSymbolData &DataA,
1672 const MCFragment &FB,
1674 bool IsPCRel) const {
1675 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1677 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1678 Asm, DataA, FB,InSet, IsPCRel);
1681 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1683 bool IsLittleEndian) {
1684 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);