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/ELF.h"
32 #include "llvm/Support/ErrorHandling.h"
37 #define DEBUG_TYPE "reloc-info"
40 class ELFObjectWriter : public MCObjectWriter {
43 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
44 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
45 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
46 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
47 bool Used, bool Renamed);
48 static bool isLocal(const MCSymbolData &Data, bool isSignature,
50 static bool IsELFMetaDataSection(const MCSectionData &SD);
51 static uint64_t DataSectionSize(const MCSectionData &SD);
52 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
53 const MCSectionData &SD);
54 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
55 const MCSectionData &SD);
57 void WriteDataSectionData(MCAssembler &Asm,
58 const MCAsmLayout &Layout,
59 const MCSectionELF &Section);
61 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
62 return Kind == X86::reloc_riprel_4byte ||
63 Kind == X86::reloc_riprel_4byte_movq_load;
66 /// ELFSymbolData - Helper struct for containing some precomputed
67 /// information on symbols.
68 struct ELFSymbolData {
69 MCSymbolData *SymbolData;
71 uint32_t SectionIndex;
73 // Support lexicographic sorting.
74 bool operator<(const ELFSymbolData &RHS) const {
75 return SymbolData->getSymbol().getName() <
76 RHS.SymbolData->getSymbol().getName();
80 /// The target specific ELF writer instance.
81 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
83 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
84 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
85 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
87 llvm::DenseMap<const MCSectionData*,
88 std::vector<ELFRelocationEntry> > Relocations;
89 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
92 /// @name Symbol Table Data
95 SmallString<256> StringTable;
96 std::vector<uint64_t> FileSymbolData;
97 std::vector<ELFSymbolData> LocalSymbolData;
98 std::vector<ELFSymbolData> ExternalSymbolData;
99 std::vector<ELFSymbolData> UndefinedSymbolData;
105 bool NeedsSymtabShndx;
107 // This holds the symbol table index of the last local symbol.
108 unsigned LastLocalSymbolIndex;
109 // This holds the .strtab section index.
110 unsigned StringTableIndex;
111 // This holds the .symtab section index.
112 unsigned SymbolTableIndex;
114 unsigned ShstrtabIndex;
117 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
118 const MCValue &Target,
120 const MCFixup &Fixup,
123 // TargetObjectWriter wrappers.
124 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
125 const MCValue &Target,
127 const MCFixup &Fixup,
128 bool IsPCRel) const {
129 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
131 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
132 const MCFixup &Fixup,
133 bool IsPCRel) const {
134 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
138 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
139 bool hasRelocationAddend() const {
140 return TargetObjectWriter->hasRelocationAddend();
142 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
143 bool IsPCRel, bool IsRelocWithSymbol,
144 int64_t Addend) const {
145 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
146 IsRelocWithSymbol, Addend);
150 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
151 raw_ostream &_OS, bool IsLittleEndian)
152 : MCObjectWriter(_OS, IsLittleEndian),
153 TargetObjectWriter(MOTW),
154 NeedsGOT(false), NeedsSymtabShndx(false) {
157 virtual ~ELFObjectWriter();
159 void WriteWord(uint64_t W) {
166 void StringLE16(char *buf, uint16_t Value) {
167 buf[0] = char(Value >> 0);
168 buf[1] = char(Value >> 8);
171 void StringLE32(char *buf, uint32_t Value) {
172 StringLE16(buf, uint16_t(Value >> 0));
173 StringLE16(buf + 2, uint16_t(Value >> 16));
176 void StringLE64(char *buf, uint64_t Value) {
177 StringLE32(buf, uint32_t(Value >> 0));
178 StringLE32(buf + 4, uint32_t(Value >> 32));
181 void StringBE16(char *buf ,uint16_t Value) {
182 buf[0] = char(Value >> 8);
183 buf[1] = char(Value >> 0);
186 void StringBE32(char *buf, uint32_t Value) {
187 StringBE16(buf, uint16_t(Value >> 16));
188 StringBE16(buf + 2, uint16_t(Value >> 0));
191 void StringBE64(char *buf, uint64_t Value) {
192 StringBE32(buf, uint32_t(Value >> 32));
193 StringBE32(buf + 4, uint32_t(Value >> 0));
196 void String8(MCDataFragment &F, uint8_t Value) {
199 F.getContents().append(&buf[0], &buf[1]);
202 void String16(MCDataFragment &F, uint16_t Value) {
204 if (isLittleEndian())
205 StringLE16(buf, Value);
207 StringBE16(buf, Value);
208 F.getContents().append(&buf[0], &buf[2]);
211 void String32(MCDataFragment &F, uint32_t Value) {
213 if (isLittleEndian())
214 StringLE32(buf, Value);
216 StringBE32(buf, Value);
217 F.getContents().append(&buf[0], &buf[4]);
220 void String64(MCDataFragment &F, uint64_t Value) {
222 if (isLittleEndian())
223 StringLE64(buf, Value);
225 StringBE64(buf, Value);
226 F.getContents().append(&buf[0], &buf[8]);
229 void WriteHeader(const MCAssembler &Asm,
230 uint64_t SectionDataSize,
231 unsigned NumberOfSections);
233 void WriteSymbolEntry(MCDataFragment *SymtabF,
234 MCDataFragment *ShndxF,
235 uint64_t name, uint8_t info,
236 uint64_t value, uint64_t size,
237 uint8_t other, uint32_t shndx,
240 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
242 const MCAsmLayout &Layout);
244 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
245 void WriteSymbolTable(MCDataFragment *SymtabF,
246 MCDataFragment *ShndxF,
247 const MCAssembler &Asm,
248 const MCAsmLayout &Layout,
249 const SectionIndexMapTy &SectionIndexMap);
251 virtual void RecordRelocation(const MCAssembler &Asm,
252 const MCAsmLayout &Layout,
253 const MCFragment *Fragment,
254 const MCFixup &Fixup,
255 MCValue Target, uint64_t &FixedValue);
257 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
260 // Map from a group section to the signature symbol
261 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
262 // Map from a signature symbol to the group section
263 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
264 // Map from a section to the section with the relocations
265 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
266 // Map from a section to its offset
267 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
269 /// ComputeSymbolTable - Compute the symbol table data
271 /// \param Asm - The assembler.
272 /// \param SectionIndexMap - Maps a section to its index.
273 /// \param RevGroupMap - Maps a signature symbol to the group section.
274 /// \param NumRegularSections - Number of non-relocation sections.
275 void ComputeSymbolTable(MCAssembler &Asm,
276 const SectionIndexMapTy &SectionIndexMap,
277 RevGroupMapTy RevGroupMap,
278 unsigned NumRegularSections);
280 void ComputeIndexMap(MCAssembler &Asm,
281 SectionIndexMapTy &SectionIndexMap,
282 const RelMapTy &RelMap);
284 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
287 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
288 const RelMapTy &RelMap);
290 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
291 SectionIndexMapTy &SectionIndexMap,
292 const RelMapTy &RelMap);
294 // Create the sections that show up in the symbol table. Currently
295 // those are the .note.GNU-stack section and the group sections.
296 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
297 GroupMapTy &GroupMap,
298 RevGroupMapTy &RevGroupMap,
299 SectionIndexMapTy &SectionIndexMap,
300 const RelMapTy &RelMap);
302 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
303 const MCAsmLayout &Layout);
305 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
306 const MCAsmLayout &Layout,
307 const SectionIndexMapTy &SectionIndexMap,
308 const SectionOffsetMapTy &SectionOffsetMap);
310 void ComputeSectionOrder(MCAssembler &Asm,
311 std::vector<const MCSectionELF*> &Sections);
313 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
314 uint64_t Address, uint64_t Offset,
315 uint64_t Size, uint32_t Link, uint32_t Info,
316 uint64_t Alignment, uint64_t EntrySize);
318 void WriteRelocationsFragment(const MCAssembler &Asm,
320 const MCSectionData *SD);
323 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
324 const MCSymbolData &DataA,
325 const MCFragment &FB,
329 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
330 void WriteSection(MCAssembler &Asm,
331 const SectionIndexMapTy &SectionIndexMap,
332 uint32_t GroupSymbolIndex,
333 uint64_t Offset, uint64_t Size, uint64_t Alignment,
334 const MCSectionELF &Section);
338 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
339 const MCFixupKindInfo &FKI =
340 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
342 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
345 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
349 case MCSymbolRefExpr::VK_GOT:
350 case MCSymbolRefExpr::VK_PLT:
351 case MCSymbolRefExpr::VK_GOTPCREL:
352 case MCSymbolRefExpr::VK_GOTOFF:
353 case MCSymbolRefExpr::VK_TPOFF:
354 case MCSymbolRefExpr::VK_TLSGD:
355 case MCSymbolRefExpr::VK_GOTTPOFF:
356 case MCSymbolRefExpr::VK_INDNTPOFF:
357 case MCSymbolRefExpr::VK_NTPOFF:
358 case MCSymbolRefExpr::VK_GOTNTPOFF:
359 case MCSymbolRefExpr::VK_TLSLDM:
360 case MCSymbolRefExpr::VK_DTPOFF:
361 case MCSymbolRefExpr::VK_TLSLD:
366 ELFObjectWriter::~ELFObjectWriter()
369 // Emit the ELF header.
370 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
371 uint64_t SectionDataSize,
372 unsigned NumberOfSections) {
378 // emitWord method behaves differently for ELF32 and ELF64, writing
379 // 4 bytes in the former and 8 in the latter.
381 Write8(0x7f); // e_ident[EI_MAG0]
382 Write8('E'); // e_ident[EI_MAG1]
383 Write8('L'); // e_ident[EI_MAG2]
384 Write8('F'); // e_ident[EI_MAG3]
386 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
389 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
391 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
393 Write8(TargetObjectWriter->getOSABI());
394 Write8(0); // e_ident[EI_ABIVERSION]
396 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
398 Write16(ELF::ET_REL); // e_type
400 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
402 Write32(ELF::EV_CURRENT); // e_version
403 WriteWord(0); // e_entry, no entry point in .o file
404 WriteWord(0); // e_phoff, no program header for .o
405 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
406 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
408 // e_flags = whatever the target wants
409 Write32(Asm.getELFHeaderEFlags());
411 // e_ehsize = ELF header size
412 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
414 Write16(0); // e_phentsize = prog header entry size
415 Write16(0); // e_phnum = # prog header entries = 0
417 // e_shentsize = Section header entry size
418 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
420 // e_shnum = # of section header ents
421 if (NumberOfSections >= ELF::SHN_LORESERVE)
422 Write16(ELF::SHN_UNDEF);
424 Write16(NumberOfSections);
426 // e_shstrndx = Section # of '.shstrtab'
427 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
428 Write16(ELF::SHN_XINDEX);
430 Write16(ShstrtabIndex);
433 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
434 MCDataFragment *ShndxF,
436 uint8_t info, uint64_t value,
437 uint64_t size, uint8_t other,
441 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
442 String32(*ShndxF, shndx);
444 String32(*ShndxF, 0);
447 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
448 uint16_t(ELF::SHN_XINDEX) : shndx;
451 String32(*SymtabF, name); // st_name
452 String8(*SymtabF, info); // st_info
453 String8(*SymtabF, other); // st_other
454 String16(*SymtabF, Index); // st_shndx
455 String64(*SymtabF, value); // st_value
456 String64(*SymtabF, size); // st_size
458 String32(*SymtabF, name); // st_name
459 String32(*SymtabF, value); // st_value
460 String32(*SymtabF, size); // st_size
461 String8(*SymtabF, info); // st_info
462 String8(*SymtabF, other); // st_other
463 String16(*SymtabF, Index); // st_shndx
467 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
468 const MCAsmLayout &Layout) {
469 if (Data.isCommon() && Data.isExternal())
470 return Data.getCommonAlignment();
472 const MCSymbol &Symbol = Data.getSymbol();
474 if (Symbol.isAbsolute() && Symbol.isVariable()) {
475 if (const MCExpr *Value = Symbol.getVariableValue()) {
477 if (Value->EvaluateAsAbsolute(IntValue, Layout))
478 return (uint64_t)IntValue;
482 if (!Symbol.isInSection())
486 if (Data.getFragment()) {
487 if (Data.getFlags() & ELF_Other_ThumbFunc)
488 return Layout.getSymbolOffset(&Data)+1;
490 return Layout.getSymbolOffset(&Data);
496 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
497 const MCAsmLayout &Layout) {
498 // The presence of symbol versions causes undefined symbols and
499 // versions declared with @@@ to be renamed.
501 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
502 ie = Asm.symbol_end(); it != ie; ++it) {
503 const MCSymbol &Alias = it->getSymbol();
504 const MCSymbol &Symbol = Alias.AliasedSymbol();
505 MCSymbolData &SD = Asm.getSymbolData(Symbol);
508 if (&Symbol == &Alias)
511 StringRef AliasName = Alias.getName();
512 size_t Pos = AliasName.find('@');
513 if (Pos == StringRef::npos)
516 // Aliases defined with .symvar copy the binding from the symbol they alias.
517 // This is the first place we are able to copy this information.
518 it->setExternal(SD.isExternal());
519 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
521 StringRef Rest = AliasName.substr(Pos);
522 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
525 // FIXME: produce a better error message.
526 if (Symbol.isUndefined() && Rest.startswith("@@") &&
527 !Rest.startswith("@@@"))
528 report_fatal_error("A @@ version cannot be undefined");
530 Renames.insert(std::make_pair(&Symbol, &Alias));
534 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
535 uint8_t Type = newType;
537 // Propagation rules:
538 // IFUNC > FUNC > OBJECT > NOTYPE
539 // TLS_OBJECT > OBJECT > NOTYPE
541 // dont let the new type degrade the old type
545 case ELF::STT_GNU_IFUNC:
546 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
547 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
548 Type = ELF::STT_GNU_IFUNC;
551 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
552 Type == ELF::STT_TLS)
553 Type = ELF::STT_FUNC;
555 case ELF::STT_OBJECT:
556 if (Type == ELF::STT_NOTYPE)
557 Type = ELF::STT_OBJECT;
560 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
561 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
569 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
570 MCDataFragment *ShndxF,
572 const MCAsmLayout &Layout) {
573 MCSymbolData &OrigData = *MSD.SymbolData;
575 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
577 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
578 Data.getSymbol().isVariable();
580 // Binding and Type share the same byte as upper and lower nibbles
581 uint8_t Binding = MCELF::GetBinding(OrigData);
582 uint8_t Type = mergeTypeForSet(MCELF::GetType(OrigData), MCELF::GetType(Data));
583 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
585 // Other and Visibility share the same byte with Visibility using the lower
587 uint8_t Visibility = MCELF::GetVisibility(OrigData);
588 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
591 uint64_t Value = SymbolValue(Data, Layout);
594 assert(!(Data.isCommon() && !Data.isExternal()));
596 const MCExpr *ESize = Data.getSize();
599 if (!ESize->EvaluateAsAbsolute(Res, Layout))
600 report_fatal_error("Size expression must be absolute.");
604 // Write out the symbol table entry
605 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
606 Size, Other, MSD.SectionIndex, IsReserved);
609 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
610 MCDataFragment *ShndxF,
611 const MCAssembler &Asm,
612 const MCAsmLayout &Layout,
613 const SectionIndexMapTy &SectionIndexMap) {
614 // The string table must be emitted first because we need the index
615 // into the string table for all the symbol names.
616 assert(StringTable.size() && "Missing string table");
618 // FIXME: Make sure the start of the symbol table is aligned.
620 // The first entry is the undefined symbol entry.
621 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
623 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
624 WriteSymbolEntry(SymtabF, ShndxF, FileSymbolData[i],
625 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
626 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
629 // Write the symbol table entries.
630 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
632 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
633 ELFSymbolData &MSD = LocalSymbolData[i];
634 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
637 // Write out a symbol table entry for each regular section.
638 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
640 const MCSectionELF &Section =
641 static_cast<const MCSectionELF&>(i->getSection());
642 if (Section.getType() == ELF::SHT_RELA ||
643 Section.getType() == ELF::SHT_REL ||
644 Section.getType() == ELF::SHT_STRTAB ||
645 Section.getType() == ELF::SHT_SYMTAB ||
646 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
648 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
649 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
651 LastLocalSymbolIndex++;
654 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
655 ELFSymbolData &MSD = ExternalSymbolData[i];
656 MCSymbolData &Data = *MSD.SymbolData;
657 assert(((Data.getFlags() & ELF_STB_Global) ||
658 (Data.getFlags() & ELF_STB_Weak)) &&
659 "External symbol requires STB_GLOBAL or STB_WEAK flag");
660 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
661 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
662 LastLocalSymbolIndex++;
665 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
666 ELFSymbolData &MSD = UndefinedSymbolData[i];
667 MCSymbolData &Data = *MSD.SymbolData;
668 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
669 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
670 LastLocalSymbolIndex++;
674 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
675 const MCValue &Target,
677 const MCFixup &Fixup,
678 bool IsPCRel) const {
679 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
680 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
681 const MCSymbol *Renamed = Renames.lookup(&Symbol);
682 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
684 if (ASymbol.isUndefined()) {
687 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
690 if (SD.isExternal()) {
696 const MCSectionELF &Section =
697 static_cast<const MCSectionELF&>(ASymbol.getSection());
698 const SectionKind secKind = Section.getKind();
701 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
703 if (secKind.isThreadLocal()) {
709 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
710 const MCSectionELF &Sec2 =
711 static_cast<const MCSectionELF&>(F.getParent()->getSection());
713 if (&Sec2 != &Section &&
714 (Kind == MCSymbolRefExpr::VK_PLT ||
715 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
716 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
722 if (Section.getFlags() & ELF::SHF_MERGE) {
723 if (Target.getConstant() == 0)
724 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
730 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
735 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
736 const MCAsmLayout &Layout,
737 const MCFragment *Fragment,
738 const MCFixup &Fixup,
740 uint64_t &FixedValue) {
743 int64_t Value = Target.getConstant();
744 const MCSymbol *RelocSymbol = NULL;
746 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
747 if (!Target.isAbsolute()) {
748 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
749 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
750 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
752 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
753 const MCSymbol &SymbolB = RefB->getSymbol();
754 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
757 if (!SDB.getFragment())
758 Asm.getContext().FatalError(
760 Twine("symbol '") + SymbolB.getName() +
761 "' can not be undefined in a subtraction expression");
763 // Offset of the symbol in the section
764 int64_t a = Layout.getSymbolOffset(&SDB);
766 // Offset of the relocation in the section
767 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
772 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
773 MCFragment *F = SD.getFragment();
776 Index = F->getParent()->getOrdinal() + 1;
777 // Offset of the symbol in the section
778 Value += Layout.getSymbolOffset(&SD);
783 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
784 WeakrefUsedInReloc.insert(RelocSymbol);
786 UsedInReloc.insert(RelocSymbol);
790 if (hasRelocationAddend())
795 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
796 (RelocSymbol != 0), Addend);
797 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
798 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
799 if (RelocNeedsGOT(Modifier))
802 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
805 if (!hasRelocationAddend())
809 assert(isInt<64>(Addend));
811 assert(isInt<32>(Addend));
813 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
814 Relocations[Fragment->getParent()].push_back(ERE);
819 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
821 MCSymbolData &SD = Asm.getSymbolData(*S);
822 return SD.getIndex();
825 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
826 const MCSymbolData &Data,
827 bool Used, bool Renamed) {
828 if (Data.getFlags() & ELF_Other_Weakref)
837 const MCSymbol &Symbol = Data.getSymbol();
839 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
842 const MCSymbol &A = Symbol.AliasedSymbol();
843 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
846 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
847 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
850 if (Symbol.isTemporary())
856 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
857 bool isUsedInReloc) {
858 if (Data.isExternal())
861 const MCSymbol &Symbol = Data.getSymbol();
862 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
864 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
865 if (isSignature && !isUsedInReloc)
874 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
875 SectionIndexMapTy &SectionIndexMap,
876 const RelMapTy &RelMap) {
878 for (MCAssembler::iterator it = Asm.begin(),
879 ie = Asm.end(); it != ie; ++it) {
880 const MCSectionELF &Section =
881 static_cast<const MCSectionELF &>(it->getSection());
882 if (Section.getType() != ELF::SHT_GROUP)
884 SectionIndexMap[&Section] = Index++;
887 for (MCAssembler::iterator it = Asm.begin(),
888 ie = Asm.end(); it != ie; ++it) {
889 const MCSectionELF &Section =
890 static_cast<const MCSectionELF &>(it->getSection());
891 if (Section.getType() == ELF::SHT_GROUP ||
892 Section.getType() == ELF::SHT_REL ||
893 Section.getType() == ELF::SHT_RELA)
895 SectionIndexMap[&Section] = Index++;
896 const MCSectionELF *RelSection = RelMap.lookup(&Section);
898 SectionIndexMap[RelSection] = Index++;
902 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
903 const SectionIndexMapTy &SectionIndexMap,
904 RevGroupMapTy RevGroupMap,
905 unsigned NumRegularSections) {
906 // FIXME: Is this the correct place to do this?
907 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
909 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
910 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
911 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
912 Data.setExternal(true);
913 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
916 // Index 0 is always the empty string.
917 StringMap<uint64_t> StringIndexMap;
918 StringTable += '\x00';
920 // FIXME: We could optimize suffixes in strtab in the same way we
921 // optimize them in shstrtab.
923 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
924 ie = Asm.file_names_end();
927 StringRef Name = *it;
928 uint64_t &Entry = StringIndexMap[Name];
930 Entry = StringTable.size();
932 StringTable += '\x00';
934 FileSymbolData.push_back(Entry);
937 // Add the data for the symbols.
938 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
939 ie = Asm.symbol_end(); it != ie; ++it) {
940 const MCSymbol &Symbol = it->getSymbol();
942 bool Used = UsedInReloc.count(&Symbol);
943 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
944 bool isSignature = RevGroupMap.count(&Symbol);
946 if (!isInSymtab(Asm, *it,
947 Used || WeakrefUsed || isSignature,
948 Renames.count(&Symbol)))
953 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
955 // Undefined symbols are global, but this is the first place we
956 // are able to set it.
957 bool Local = isLocal(*it, isSignature, Used);
958 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
959 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
960 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
961 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
964 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
965 MCELF::SetBinding(*it, ELF::STB_WEAK);
967 if (it->isCommon()) {
969 MSD.SectionIndex = ELF::SHN_COMMON;
970 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
971 MSD.SectionIndex = ELF::SHN_ABS;
972 } else if (RefSymbol.isUndefined()) {
973 if (isSignature && !Used)
974 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
976 MSD.SectionIndex = ELF::SHN_UNDEF;
978 const MCSectionELF &Section =
979 static_cast<const MCSectionELF&>(RefSymbol.getSection());
980 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
981 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
982 NeedsSymtabShndx = true;
983 assert(MSD.SectionIndex && "Invalid section index!");
986 // The @@@ in symbol version is replaced with @ in undefined symbols and
987 // @@ in defined ones.
988 StringRef Name = Symbol.getName();
991 size_t Pos = Name.find("@@@");
992 if (Pos != StringRef::npos) {
993 Buf += Name.substr(0, Pos);
994 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
995 Buf += Name.substr(Pos + Skip);
999 uint64_t &Entry = StringIndexMap[Name];
1001 Entry = StringTable.size();
1002 StringTable += Name;
1003 StringTable += '\x00';
1005 MSD.StringIndex = Entry;
1006 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1007 UndefinedSymbolData.push_back(MSD);
1009 LocalSymbolData.push_back(MSD);
1011 ExternalSymbolData.push_back(MSD);
1014 // Symbols are required to be in lexicographic order.
1015 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1016 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1017 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1019 // Set the symbol indices. Local symbols must come before all other
1020 // symbols with non-local bindings.
1021 unsigned Index = FileSymbolData.size() + 1;
1022 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1023 LocalSymbolData[i].SymbolData->setIndex(Index++);
1025 Index += NumRegularSections;
1027 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1028 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1029 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1030 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1032 if (Index >= ELF::SHN_LORESERVE)
1033 NeedsSymtabShndx = true;
1036 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1037 MCAsmLayout &Layout,
1039 for (MCAssembler::const_iterator it = Asm.begin(),
1040 ie = Asm.end(); it != ie; ++it) {
1041 const MCSectionData &SD = *it;
1042 if (Relocations[&SD].empty())
1045 MCContext &Ctx = Asm.getContext();
1046 const MCSectionELF &Section =
1047 static_cast<const MCSectionELF&>(SD.getSection());
1049 const StringRef SectionName = Section.getSectionName();
1050 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1051 RelaSectionName += SectionName;
1054 if (hasRelocationAddend())
1055 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1057 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1060 StringRef Group = "";
1061 if (Section.getFlags() & ELF::SHF_GROUP) {
1062 Flags = ELF::SHF_GROUP;
1063 Group = Section.getGroup()->getName();
1066 const MCSectionELF *RelaSection =
1067 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1068 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1069 SectionKind::getReadOnly(),
1071 RelMap[&Section] = RelaSection;
1072 Asm.getOrCreateSectionData(*RelaSection);
1076 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1077 const RelMapTy &RelMap) {
1078 for (MCAssembler::const_iterator it = Asm.begin(),
1079 ie = Asm.end(); it != ie; ++it) {
1080 const MCSectionData &SD = *it;
1081 const MCSectionELF &Section =
1082 static_cast<const MCSectionELF&>(SD.getSection());
1084 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1087 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1088 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1090 MCDataFragment *F = new MCDataFragment(&RelaSD);
1091 WriteRelocationsFragment(Asm, F, &*it);
1095 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1096 uint64_t Flags, uint64_t Address,
1097 uint64_t Offset, uint64_t Size,
1098 uint32_t Link, uint32_t Info,
1100 uint64_t EntrySize) {
1101 Write32(Name); // sh_name: index into string table
1102 Write32(Type); // sh_type
1103 WriteWord(Flags); // sh_flags
1104 WriteWord(Address); // sh_addr
1105 WriteWord(Offset); // sh_offset
1106 WriteWord(Size); // sh_size
1107 Write32(Link); // sh_link
1108 Write32(Info); // sh_info
1109 WriteWord(Alignment); // sh_addralign
1110 WriteWord(EntrySize); // sh_entsize
1113 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1115 const MCSectionData *SD) {
1116 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1118 // Sort the relocation entries. Most targets just sort by r_offset, but some
1119 // (e.g., MIPS) have additional constraints.
1120 TargetObjectWriter->sortRelocs(Asm, Relocs);
1122 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1123 ELFRelocationEntry entry = Relocs[e - i - 1];
1127 else if (entry.Index < 0)
1128 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1130 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1132 String64(*F, entry.r_offset);
1133 if (TargetObjectWriter->isN64()) {
1134 String32(*F, entry.Index);
1136 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1137 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1138 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1139 String8(*F, TargetObjectWriter->getRType(entry.Type));
1142 struct ELF::Elf64_Rela ERE64;
1143 ERE64.setSymbolAndType(entry.Index, entry.Type);
1144 String64(*F, ERE64.r_info);
1146 if (hasRelocationAddend())
1147 String64(*F, entry.r_addend);
1149 String32(*F, entry.r_offset);
1151 struct ELF::Elf32_Rela ERE32;
1152 ERE32.setSymbolAndType(entry.Index, entry.Type);
1153 String32(*F, ERE32.r_info);
1155 if (hasRelocationAddend())
1156 String32(*F, entry.r_addend);
1161 static int compareBySuffix(const MCSectionELF *const *a,
1162 const MCSectionELF *const *b) {
1163 const StringRef &NameA = (*a)->getSectionName();
1164 const StringRef &NameB = (*b)->getSectionName();
1165 const unsigned sizeA = NameA.size();
1166 const unsigned sizeB = NameB.size();
1167 const unsigned len = std::min(sizeA, sizeB);
1168 for (unsigned int i = 0; i < len; ++i) {
1169 char ca = NameA[sizeA - i - 1];
1170 char cb = NameB[sizeB - i - 1];
1175 return sizeB - sizeA;
1178 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1179 MCAsmLayout &Layout,
1180 SectionIndexMapTy &SectionIndexMap,
1181 const RelMapTy &RelMap) {
1182 MCContext &Ctx = Asm.getContext();
1185 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1187 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1188 const MCSectionELF *ShstrtabSection =
1189 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1190 SectionKind::getReadOnly());
1191 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1192 ShstrtabSD.setAlignment(1);
1194 const MCSectionELF *SymtabSection =
1195 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1196 SectionKind::getReadOnly(),
1198 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1199 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1201 MCSectionData *SymtabShndxSD = NULL;
1203 if (NeedsSymtabShndx) {
1204 const MCSectionELF *SymtabShndxSection =
1205 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1206 SectionKind::getReadOnly(), 4, "");
1207 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1208 SymtabShndxSD->setAlignment(4);
1211 const MCSectionELF *StrtabSection;
1212 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1213 SectionKind::getReadOnly());
1214 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1215 StrtabSD.setAlignment(1);
1217 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1219 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1220 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1221 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1224 F = new MCDataFragment(&SymtabSD);
1225 MCDataFragment *ShndxF = NULL;
1226 if (NeedsSymtabShndx) {
1227 ShndxF = new MCDataFragment(SymtabShndxSD);
1229 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1231 F = new MCDataFragment(&StrtabSD);
1232 F->getContents().append(StringTable.begin(), StringTable.end());
1234 F = new MCDataFragment(&ShstrtabSD);
1236 std::vector<const MCSectionELF*> Sections;
1237 for (MCAssembler::const_iterator it = Asm.begin(),
1238 ie = Asm.end(); it != ie; ++it) {
1239 const MCSectionELF &Section =
1240 static_cast<const MCSectionELF&>(it->getSection());
1241 Sections.push_back(&Section);
1243 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1245 // Section header string table.
1247 // The first entry of a string table holds a null character so skip
1250 F->getContents().push_back('\x00');
1252 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1253 const MCSectionELF &Section = *Sections[I];
1255 StringRef Name = Section.getSectionName();
1257 StringRef PreviousName = Sections[I - 1]->getSectionName();
1258 if (PreviousName.endswith(Name)) {
1259 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1263 // Remember the index into the string table so we can write it
1264 // into the sh_name field of the section header table.
1265 SectionStringTableIndex[&Section] = Index;
1267 Index += Name.size() + 1;
1268 F->getContents().append(Name.begin(), Name.end());
1269 F->getContents().push_back('\x00');
1273 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1274 MCAsmLayout &Layout,
1275 GroupMapTy &GroupMap,
1276 RevGroupMapTy &RevGroupMap,
1277 SectionIndexMapTy &SectionIndexMap,
1278 const RelMapTy &RelMap) {
1279 // Create the .note.GNU-stack section if needed.
1280 MCContext &Ctx = Asm.getContext();
1281 if (Asm.getNoExecStack()) {
1282 const MCSectionELF *GnuStackSection =
1283 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1284 SectionKind::getReadOnly());
1285 Asm.getOrCreateSectionData(*GnuStackSection);
1289 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1291 const MCSectionELF &Section =
1292 static_cast<const MCSectionELF&>(it->getSection());
1293 if (!(Section.getFlags() & ELF::SHF_GROUP))
1296 const MCSymbol *SignatureSymbol = Section.getGroup();
1297 Asm.getOrCreateSymbolData(*SignatureSymbol);
1298 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1300 Group = Ctx.CreateELFGroupSection();
1301 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1302 Data.setAlignment(4);
1303 MCDataFragment *F = new MCDataFragment(&Data);
1304 String32(*F, ELF::GRP_COMDAT);
1306 GroupMap[Group] = SignatureSymbol;
1309 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1311 // Add sections to the groups
1312 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1314 const MCSectionELF &Section =
1315 static_cast<const MCSectionELF&>(it->getSection());
1316 if (!(Section.getFlags() & ELF::SHF_GROUP))
1318 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1319 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1320 // FIXME: we could use the previous fragment
1321 MCDataFragment *F = new MCDataFragment(&Data);
1322 unsigned Index = SectionIndexMap.lookup(&Section);
1323 String32(*F, Index);
1327 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1328 const SectionIndexMapTy &SectionIndexMap,
1329 uint32_t GroupSymbolIndex,
1330 uint64_t Offset, uint64_t Size,
1332 const MCSectionELF &Section) {
1333 uint64_t sh_link = 0;
1334 uint64_t sh_info = 0;
1336 switch(Section.getType()) {
1337 case ELF::SHT_DYNAMIC:
1338 sh_link = SectionStringTableIndex[&Section];
1343 case ELF::SHT_RELA: {
1344 const MCSectionELF *SymtabSection;
1345 const MCSectionELF *InfoSection;
1346 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1348 SectionKind::getReadOnly());
1349 sh_link = SectionIndexMap.lookup(SymtabSection);
1350 assert(sh_link && ".symtab not found");
1352 // Remove ".rel" and ".rela" prefixes.
1353 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1354 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1355 StringRef GroupName =
1356 Section.getGroup() ? Section.getGroup()->getName() : "";
1358 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1359 0, SectionKind::getReadOnly(),
1361 sh_info = SectionIndexMap.lookup(InfoSection);
1365 case ELF::SHT_SYMTAB:
1366 case ELF::SHT_DYNSYM:
1367 sh_link = StringTableIndex;
1368 sh_info = LastLocalSymbolIndex;
1371 case ELF::SHT_SYMTAB_SHNDX:
1372 sh_link = SymbolTableIndex;
1375 case ELF::SHT_PROGBITS:
1376 case ELF::SHT_STRTAB:
1377 case ELF::SHT_NOBITS:
1380 case ELF::SHT_ARM_ATTRIBUTES:
1381 case ELF::SHT_INIT_ARRAY:
1382 case ELF::SHT_FINI_ARRAY:
1383 case ELF::SHT_PREINIT_ARRAY:
1384 case ELF::SHT_X86_64_UNWIND:
1385 case ELF::SHT_MIPS_REGINFO:
1386 case ELF::SHT_MIPS_OPTIONS:
1390 case ELF::SHT_GROUP:
1391 sh_link = SymbolTableIndex;
1392 sh_info = GroupSymbolIndex;
1396 assert(0 && "FIXME: sh_type value not supported!");
1400 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1401 Section.getType() == ELF::SHT_ARM_EXIDX) {
1402 StringRef SecName(Section.getSectionName());
1403 if (SecName == ".ARM.exidx") {
1404 sh_link = SectionIndexMap.lookup(
1405 Asm.getContext().getELFSection(".text",
1407 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1408 SectionKind::getText()));
1409 } else if (SecName.startswith(".ARM.exidx")) {
1410 StringRef GroupName =
1411 Section.getGroup() ? Section.getGroup()->getName() : "";
1412 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1413 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1414 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1419 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1420 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1421 Alignment, Section.getEntrySize());
1424 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1425 return SD.getOrdinal() == ~UINT32_C(0) &&
1426 !SD.getSection().isVirtualSection();
1429 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1431 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1433 const MCFragment &F = *i;
1434 assert(F.getKind() == MCFragment::FT_Data);
1435 Ret += cast<MCDataFragment>(F).getContents().size();
1440 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1441 const MCSectionData &SD) {
1442 if (IsELFMetaDataSection(SD))
1443 return DataSectionSize(SD);
1444 return Layout.getSectionFileSize(&SD);
1447 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1448 const MCSectionData &SD) {
1449 if (IsELFMetaDataSection(SD))
1450 return DataSectionSize(SD);
1451 return Layout.getSectionAddressSize(&SD);
1454 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1455 const MCAsmLayout &Layout,
1456 const MCSectionELF &Section) {
1457 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1459 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1460 WriteZeros(Padding);
1462 if (IsELFMetaDataSection(SD)) {
1463 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1465 const MCFragment &F = *i;
1466 assert(F.getKind() == MCFragment::FT_Data);
1467 WriteBytes(cast<MCDataFragment>(F).getContents());
1470 Asm.writeSectionData(&SD, Layout);
1474 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1475 const GroupMapTy &GroupMap,
1476 const MCAsmLayout &Layout,
1477 const SectionIndexMapTy &SectionIndexMap,
1478 const SectionOffsetMapTy &SectionOffsetMap) {
1479 const unsigned NumSections = Asm.size() + 1;
1481 std::vector<const MCSectionELF*> Sections;
1482 Sections.resize(NumSections - 1);
1484 for (SectionIndexMapTy::const_iterator i=
1485 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1486 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1487 Sections[p.second - 1] = p.first;
1490 // Null section first.
1491 uint64_t FirstSectionSize =
1492 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1493 uint32_t FirstSectionLink =
1494 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1495 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1497 for (unsigned i = 0; i < NumSections - 1; ++i) {
1498 const MCSectionELF &Section = *Sections[i];
1499 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1500 uint32_t GroupSymbolIndex;
1501 if (Section.getType() != ELF::SHT_GROUP)
1502 GroupSymbolIndex = 0;
1504 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1505 GroupMap.lookup(&Section));
1507 uint64_t Size = GetSectionAddressSize(Layout, SD);
1509 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1510 SectionOffsetMap.lookup(&Section), Size,
1511 SD.getAlignment(), Section);
1515 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1516 std::vector<const MCSectionELF*> &Sections) {
1517 for (MCAssembler::iterator it = Asm.begin(),
1518 ie = Asm.end(); it != ie; ++it) {
1519 const MCSectionELF &Section =
1520 static_cast<const MCSectionELF &>(it->getSection());
1521 if (Section.getType() == ELF::SHT_GROUP)
1522 Sections.push_back(&Section);
1525 for (MCAssembler::iterator it = Asm.begin(),
1526 ie = Asm.end(); it != ie; ++it) {
1527 const MCSectionELF &Section =
1528 static_cast<const MCSectionELF &>(it->getSection());
1529 if (Section.getType() != ELF::SHT_GROUP &&
1530 Section.getType() != ELF::SHT_REL &&
1531 Section.getType() != ELF::SHT_RELA)
1532 Sections.push_back(&Section);
1535 for (MCAssembler::iterator it = Asm.begin(),
1536 ie = Asm.end(); it != ie; ++it) {
1537 const MCSectionELF &Section =
1538 static_cast<const MCSectionELF &>(it->getSection());
1539 if (Section.getType() == ELF::SHT_REL ||
1540 Section.getType() == ELF::SHT_RELA)
1541 Sections.push_back(&Section);
1545 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1546 const MCAsmLayout &Layout) {
1547 GroupMapTy GroupMap;
1548 RevGroupMapTy RevGroupMap;
1549 SectionIndexMapTy SectionIndexMap;
1551 unsigned NumUserSections = Asm.size();
1553 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1554 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1556 const unsigned NumUserAndRelocSections = Asm.size();
1557 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1558 RevGroupMap, SectionIndexMap, RelMap);
1559 const unsigned AllSections = Asm.size();
1560 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1562 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1564 // Compute symbol table information.
1565 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1568 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1570 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1571 const_cast<MCAsmLayout&>(Layout),
1575 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1576 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1577 sizeof(ELF::Elf32_Ehdr);
1578 uint64_t FileOff = HeaderSize;
1580 std::vector<const MCSectionELF*> Sections;
1581 ComputeSectionOrder(Asm, Sections);
1582 unsigned NumSections = Sections.size();
1583 SectionOffsetMapTy SectionOffsetMap;
1584 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1585 const MCSectionELF &Section = *Sections[i];
1586 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1588 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1590 // Remember the offset into the file for this section.
1591 SectionOffsetMap[&Section] = FileOff;
1593 // Get the size of the section in the output file (including padding).
1594 FileOff += GetSectionFileSize(Layout, SD);
1597 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1599 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1601 uint64_t SectionHeaderEntrySize = is64Bit() ?
1602 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1603 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1605 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1606 const MCSectionELF &Section = *Sections[i];
1607 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1609 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1611 // Remember the offset into the file for this section.
1612 SectionOffsetMap[&Section] = FileOff;
1614 // Get the size of the section in the output file (including padding).
1615 FileOff += GetSectionFileSize(Layout, SD);
1618 // Write out the ELF header ...
1619 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1621 // ... then the regular sections ...
1622 // + because of .shstrtab
1623 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1624 WriteDataSectionData(Asm, Layout, *Sections[i]);
1626 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1627 WriteZeros(Padding);
1629 // ... then the section header table ...
1630 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1633 // ... and then the remaining sections ...
1634 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1635 WriteDataSectionData(Asm, Layout, *Sections[i]);
1639 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1640 const MCSymbolData &DataA,
1641 const MCFragment &FB,
1643 bool IsPCRel) const {
1644 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1646 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1647 Asm, DataA, FB,InSet, IsPCRel);
1650 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1652 bool IsLittleEndian) {
1653 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);