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 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
252 const MCFragment *Fragment, const MCFixup &Fixup,
253 MCValue Target, uint64_t &FixedValue) override;
255 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
258 // Map from a group section to the signature symbol
259 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
260 // Map from a signature symbol to the group section
261 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
262 // Map from a section to the section with the relocations
263 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
264 // Map from a section to its offset
265 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
267 /// ComputeSymbolTable - Compute the symbol table data
269 /// \param Asm - The assembler.
270 /// \param SectionIndexMap - Maps a section to its index.
271 /// \param RevGroupMap - Maps a signature symbol to the group section.
272 /// \param NumRegularSections - Number of non-relocation sections.
273 void ComputeSymbolTable(MCAssembler &Asm,
274 const SectionIndexMapTy &SectionIndexMap,
275 RevGroupMapTy RevGroupMap,
276 unsigned NumRegularSections);
278 void ComputeIndexMap(MCAssembler &Asm,
279 SectionIndexMapTy &SectionIndexMap,
280 const RelMapTy &RelMap);
282 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
285 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
286 const RelMapTy &RelMap);
288 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
289 SectionIndexMapTy &SectionIndexMap,
290 const RelMapTy &RelMap);
292 // Create the sections that show up in the symbol table. Currently
293 // those are the .note.GNU-stack section and the group sections.
294 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
295 GroupMapTy &GroupMap,
296 RevGroupMapTy &RevGroupMap,
297 SectionIndexMapTy &SectionIndexMap,
298 const RelMapTy &RelMap);
300 void ExecutePostLayoutBinding(MCAssembler &Asm,
301 const MCAsmLayout &Layout) override;
303 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
304 const MCAsmLayout &Layout,
305 const SectionIndexMapTy &SectionIndexMap,
306 const SectionOffsetMapTy &SectionOffsetMap);
308 void ComputeSectionOrder(MCAssembler &Asm,
309 std::vector<const MCSectionELF*> &Sections);
311 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
312 uint64_t Address, uint64_t Offset,
313 uint64_t Size, uint32_t Link, uint32_t Info,
314 uint64_t Alignment, uint64_t EntrySize);
316 void WriteRelocationsFragment(const MCAssembler &Asm,
318 const MCSectionData *SD);
321 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
322 const MCSymbolData &DataA,
323 const MCFragment &FB,
325 bool IsPCRel) const override;
327 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
328 void WriteSection(MCAssembler &Asm,
329 const SectionIndexMapTy &SectionIndexMap,
330 uint32_t GroupSymbolIndex,
331 uint64_t Offset, uint64_t Size, uint64_t Alignment,
332 const MCSectionELF &Section);
336 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
337 const MCFixupKindInfo &FKI =
338 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
340 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
343 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
347 case MCSymbolRefExpr::VK_GOT:
348 case MCSymbolRefExpr::VK_PLT:
349 case MCSymbolRefExpr::VK_GOTPCREL:
350 case MCSymbolRefExpr::VK_GOTOFF:
351 case MCSymbolRefExpr::VK_TPOFF:
352 case MCSymbolRefExpr::VK_TLSGD:
353 case MCSymbolRefExpr::VK_GOTTPOFF:
354 case MCSymbolRefExpr::VK_INDNTPOFF:
355 case MCSymbolRefExpr::VK_NTPOFF:
356 case MCSymbolRefExpr::VK_GOTNTPOFF:
357 case MCSymbolRefExpr::VK_TLSLDM:
358 case MCSymbolRefExpr::VK_DTPOFF:
359 case MCSymbolRefExpr::VK_TLSLD:
364 ELFObjectWriter::~ELFObjectWriter()
367 // Emit the ELF header.
368 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
369 uint64_t SectionDataSize,
370 unsigned NumberOfSections) {
376 // emitWord method behaves differently for ELF32 and ELF64, writing
377 // 4 bytes in the former and 8 in the latter.
379 Write8(0x7f); // e_ident[EI_MAG0]
380 Write8('E'); // e_ident[EI_MAG1]
381 Write8('L'); // e_ident[EI_MAG2]
382 Write8('F'); // e_ident[EI_MAG3]
384 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
387 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
389 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
391 Write8(TargetObjectWriter->getOSABI());
392 Write8(0); // e_ident[EI_ABIVERSION]
394 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
396 Write16(ELF::ET_REL); // e_type
398 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
400 Write32(ELF::EV_CURRENT); // e_version
401 WriteWord(0); // e_entry, no entry point in .o file
402 WriteWord(0); // e_phoff, no program header for .o
403 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
404 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
406 // e_flags = whatever the target wants
407 Write32(Asm.getELFHeaderEFlags());
409 // e_ehsize = ELF header size
410 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
412 Write16(0); // e_phentsize = prog header entry size
413 Write16(0); // e_phnum = # prog header entries = 0
415 // e_shentsize = Section header entry size
416 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
418 // e_shnum = # of section header ents
419 if (NumberOfSections >= ELF::SHN_LORESERVE)
420 Write16(ELF::SHN_UNDEF);
422 Write16(NumberOfSections);
424 // e_shstrndx = Section # of '.shstrtab'
425 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
426 Write16(ELF::SHN_XINDEX);
428 Write16(ShstrtabIndex);
431 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
432 MCDataFragment *ShndxF,
434 uint8_t info, uint64_t value,
435 uint64_t size, uint8_t other,
439 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
440 String32(*ShndxF, shndx);
442 String32(*ShndxF, 0);
445 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
446 uint16_t(ELF::SHN_XINDEX) : shndx;
449 String32(*SymtabF, name); // st_name
450 String8(*SymtabF, info); // st_info
451 String8(*SymtabF, other); // st_other
452 String16(*SymtabF, Index); // st_shndx
453 String64(*SymtabF, value); // st_value
454 String64(*SymtabF, size); // st_size
456 String32(*SymtabF, name); // st_name
457 String32(*SymtabF, value); // st_value
458 String32(*SymtabF, size); // st_size
459 String8(*SymtabF, info); // st_info
460 String8(*SymtabF, other); // st_other
461 String16(*SymtabF, Index); // st_shndx
465 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
466 const MCAsmLayout &Layout) {
467 if (Data.isCommon() && Data.isExternal())
468 return Data.getCommonAlignment();
470 const MCSymbol &Symbol = Data.getSymbol();
472 if (Symbol.isAbsolute() && Symbol.isVariable()) {
473 if (const MCExpr *Value = Symbol.getVariableValue()) {
475 if (Value->EvaluateAsAbsolute(IntValue, Layout)) {
476 if (Data.getFlags() & ELF_Other_ThumbFunc)
477 return static_cast<uint64_t>(IntValue | 1);
479 return static_cast<uint64_t>(IntValue);
484 if (!Symbol.isInSection())
487 if (Data.getFragment()) {
488 if (Data.getFlags() & ELF_Other_ThumbFunc)
489 return Layout.getSymbolOffset(&Data) | 1;
491 return Layout.getSymbolOffset(&Data);
497 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
498 const MCAsmLayout &Layout) {
499 // The presence of symbol versions causes undefined symbols and
500 // versions declared with @@@ to be renamed.
502 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
503 ie = Asm.symbol_end(); it != ie; ++it) {
504 const MCSymbol &Alias = it->getSymbol();
505 const MCSymbol &Symbol = Alias.AliasedSymbol();
506 MCSymbolData &SD = Asm.getSymbolData(Symbol);
509 if (&Symbol == &Alias)
512 StringRef AliasName = Alias.getName();
513 size_t Pos = AliasName.find('@');
514 if (Pos == StringRef::npos)
517 // Aliases defined with .symvar copy the binding from the symbol they alias.
518 // This is the first place we are able to copy this information.
519 it->setExternal(SD.isExternal());
520 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
522 StringRef Rest = AliasName.substr(Pos);
523 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
526 // FIXME: produce a better error message.
527 if (Symbol.isUndefined() && Rest.startswith("@@") &&
528 !Rest.startswith("@@@"))
529 report_fatal_error("A @@ version cannot be undefined");
531 Renames.insert(std::make_pair(&Symbol, &Alias));
535 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
536 uint8_t Type = newType;
538 // Propagation rules:
539 // IFUNC > FUNC > OBJECT > NOTYPE
540 // TLS_OBJECT > OBJECT > NOTYPE
542 // dont let the new type degrade the old type
546 case ELF::STT_GNU_IFUNC:
547 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
548 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
549 Type = ELF::STT_GNU_IFUNC;
552 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
553 Type == ELF::STT_TLS)
554 Type = ELF::STT_FUNC;
556 case ELF::STT_OBJECT:
557 if (Type == ELF::STT_NOTYPE)
558 Type = ELF::STT_OBJECT;
561 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
562 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
570 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
571 MCDataFragment *ShndxF,
573 const MCAsmLayout &Layout) {
574 MCSymbolData &OrigData = *MSD.SymbolData;
576 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
578 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
579 Data.getSymbol().isVariable();
581 // Binding and Type share the same byte as upper and lower nibbles
582 uint8_t Binding = MCELF::GetBinding(OrigData);
583 uint8_t Type = mergeTypeForSet(MCELF::GetType(OrigData), MCELF::GetType(Data));
584 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
585 Type = ELF::STT_FUNC;
586 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
588 // Other and Visibility share the same byte with Visibility using the lower
590 uint8_t Visibility = MCELF::GetVisibility(OrigData);
591 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
594 uint64_t Value = SymbolValue(Data, Layout);
595 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
599 assert(!(Data.isCommon() && !Data.isExternal()));
601 const MCExpr *ESize = Data.getSize();
604 if (!ESize->EvaluateAsAbsolute(Res, Layout))
605 report_fatal_error("Size expression must be absolute.");
609 // Write out the symbol table entry
610 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
611 Size, Other, MSD.SectionIndex, IsReserved);
614 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
615 MCDataFragment *ShndxF,
616 const MCAssembler &Asm,
617 const MCAsmLayout &Layout,
618 const SectionIndexMapTy &SectionIndexMap) {
619 // The string table must be emitted first because we need the index
620 // into the string table for all the symbol names.
621 assert(StringTable.size() && "Missing string table");
623 // FIXME: Make sure the start of the symbol table is aligned.
625 // The first entry is the undefined symbol entry.
626 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
628 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
629 WriteSymbolEntry(SymtabF, ShndxF, FileSymbolData[i],
630 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
631 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
634 // Write the symbol table entries.
635 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
637 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
638 ELFSymbolData &MSD = LocalSymbolData[i];
639 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
642 // Write out a symbol table entry for each regular section.
643 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
645 const MCSectionELF &Section =
646 static_cast<const MCSectionELF&>(i->getSection());
647 if (Section.getType() == ELF::SHT_RELA ||
648 Section.getType() == ELF::SHT_REL ||
649 Section.getType() == ELF::SHT_STRTAB ||
650 Section.getType() == ELF::SHT_SYMTAB ||
651 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
653 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
654 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
656 LastLocalSymbolIndex++;
659 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
660 ELFSymbolData &MSD = ExternalSymbolData[i];
661 MCSymbolData &Data = *MSD.SymbolData;
662 assert(((Data.getFlags() & ELF_STB_Global) ||
663 (Data.getFlags() & ELF_STB_Weak)) &&
664 "External symbol requires STB_GLOBAL or STB_WEAK flag");
665 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
666 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
667 LastLocalSymbolIndex++;
670 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
671 ELFSymbolData &MSD = UndefinedSymbolData[i];
672 MCSymbolData &Data = *MSD.SymbolData;
673 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
674 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
675 LastLocalSymbolIndex++;
679 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
680 const MCValue &Target,
682 const MCFixup &Fixup,
683 bool IsPCRel) const {
684 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
685 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
686 const MCSymbol *Renamed = Renames.lookup(&Symbol);
687 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
689 if (ASymbol.isUndefined()) {
692 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
695 if (SD.isExternal()) {
701 const MCSectionELF &Section =
702 static_cast<const MCSectionELF&>(ASymbol.getSection());
703 const SectionKind secKind = Section.getKind();
706 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
708 if (secKind.isThreadLocal()) {
714 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
715 const MCSectionELF &Sec2 =
716 static_cast<const MCSectionELF&>(F.getParent()->getSection());
718 if (&Sec2 != &Section &&
719 (Kind == MCSymbolRefExpr::VK_PLT ||
720 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
721 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
727 if (Section.getFlags() & ELF::SHF_MERGE) {
728 if (Target.getConstant() == 0)
729 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
735 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
740 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
741 const MCAsmLayout &Layout,
742 const MCFragment *Fragment,
743 const MCFixup &Fixup,
745 uint64_t &FixedValue) {
748 int64_t Value = Target.getConstant();
749 const MCSymbol *RelocSymbol = NULL;
751 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
752 if (!Target.isAbsolute()) {
753 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
754 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
755 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
757 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
758 const MCSymbol &SymbolB = RefB->getSymbol();
759 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
762 if (!SDB.getFragment())
763 Asm.getContext().FatalError(
765 Twine("symbol '") + SymbolB.getName() +
766 "' can not be undefined in a subtraction expression");
768 // Offset of the symbol in the section
769 int64_t a = Layout.getSymbolOffset(&SDB);
771 // Offset of the relocation in the section
772 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
777 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
778 MCFragment *F = SD.getFragment();
781 Index = F->getParent()->getOrdinal() + 1;
782 // Offset of the symbol in the section
783 Value += Layout.getSymbolOffset(&SD);
788 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
789 WeakrefUsedInReloc.insert(RelocSymbol);
791 UsedInReloc.insert(RelocSymbol);
795 if (hasRelocationAddend())
800 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
801 (RelocSymbol != 0), Addend);
802 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
803 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
804 if (RelocNeedsGOT(Modifier))
807 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
810 if (!hasRelocationAddend())
814 assert(isInt<64>(Addend));
816 assert(isInt<32>(Addend));
818 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
819 Relocations[Fragment->getParent()].push_back(ERE);
824 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
826 MCSymbolData &SD = Asm.getSymbolData(*S);
827 return SD.getIndex();
830 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
831 const MCSymbolData &Data,
832 bool Used, bool Renamed) {
833 const MCSymbol &Symbol = Data.getSymbol();
834 if (Symbol.isVariable()) {
835 const MCExpr *Expr = Symbol.getVariableValue();
836 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
837 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
848 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
851 const MCSymbol &A = Symbol.AliasedSymbol();
852 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
855 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
856 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
859 if (Symbol.isTemporary())
865 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
866 bool isUsedInReloc) {
867 if (Data.isExternal())
870 const MCSymbol &Symbol = Data.getSymbol();
871 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
873 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
874 if (isSignature && !isUsedInReloc)
883 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
884 SectionIndexMapTy &SectionIndexMap,
885 const RelMapTy &RelMap) {
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)
893 SectionIndexMap[&Section] = Index++;
896 for (MCAssembler::iterator it = Asm.begin(),
897 ie = Asm.end(); it != ie; ++it) {
898 const MCSectionELF &Section =
899 static_cast<const MCSectionELF &>(it->getSection());
900 if (Section.getType() == ELF::SHT_GROUP ||
901 Section.getType() == ELF::SHT_REL ||
902 Section.getType() == ELF::SHT_RELA)
904 SectionIndexMap[&Section] = Index++;
905 const MCSectionELF *RelSection = RelMap.lookup(&Section);
907 SectionIndexMap[RelSection] = Index++;
911 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
912 const SectionIndexMapTy &SectionIndexMap,
913 RevGroupMapTy RevGroupMap,
914 unsigned NumRegularSections) {
915 // FIXME: Is this the correct place to do this?
916 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
918 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
919 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
920 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
921 Data.setExternal(true);
922 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
925 // Index 0 is always the empty string.
926 StringMap<uint64_t> StringIndexMap;
927 StringTable += '\x00';
929 // FIXME: We could optimize suffixes in strtab in the same way we
930 // optimize them in shstrtab.
932 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
933 ie = Asm.file_names_end();
936 StringRef Name = *it;
937 uint64_t &Entry = StringIndexMap[Name];
939 Entry = StringTable.size();
941 StringTable += '\x00';
943 FileSymbolData.push_back(Entry);
946 // Add the data for the symbols.
947 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
948 ie = Asm.symbol_end(); it != ie; ++it) {
949 const MCSymbol &Symbol = it->getSymbol();
951 bool Used = UsedInReloc.count(&Symbol);
952 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
953 bool isSignature = RevGroupMap.count(&Symbol);
955 if (!isInSymtab(Asm, *it,
956 Used || WeakrefUsed || isSignature,
957 Renames.count(&Symbol)))
962 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
964 // Undefined symbols are global, but this is the first place we
965 // are able to set it.
966 bool Local = isLocal(*it, isSignature, Used);
967 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
968 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
969 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
970 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
973 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
974 MCELF::SetBinding(*it, ELF::STB_WEAK);
976 if (it->isCommon()) {
978 MSD.SectionIndex = ELF::SHN_COMMON;
979 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
980 MSD.SectionIndex = ELF::SHN_ABS;
981 } else if (RefSymbol.isUndefined()) {
982 if (isSignature && !Used)
983 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
985 MSD.SectionIndex = ELF::SHN_UNDEF;
987 const MCSectionELF &Section =
988 static_cast<const MCSectionELF&>(RefSymbol.getSection());
989 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
990 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
991 NeedsSymtabShndx = true;
992 assert(MSD.SectionIndex && "Invalid section index!");
995 // The @@@ in symbol version is replaced with @ in undefined symbols and
996 // @@ in defined ones.
997 StringRef Name = Symbol.getName();
1000 size_t Pos = Name.find("@@@");
1001 if (Pos != StringRef::npos) {
1002 Buf += Name.substr(0, Pos);
1003 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1004 Buf += Name.substr(Pos + Skip);
1008 uint64_t &Entry = StringIndexMap[Name];
1010 Entry = StringTable.size();
1011 StringTable += Name;
1012 StringTable += '\x00';
1014 MSD.StringIndex = Entry;
1015 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1016 UndefinedSymbolData.push_back(MSD);
1018 LocalSymbolData.push_back(MSD);
1020 ExternalSymbolData.push_back(MSD);
1023 // Symbols are required to be in lexicographic order.
1024 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1025 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1026 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1028 // Set the symbol indices. Local symbols must come before all other
1029 // symbols with non-local bindings.
1030 unsigned Index = FileSymbolData.size() + 1;
1031 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1032 LocalSymbolData[i].SymbolData->setIndex(Index++);
1034 Index += NumRegularSections;
1036 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1037 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1038 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1039 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1041 if (Index >= ELF::SHN_LORESERVE)
1042 NeedsSymtabShndx = true;
1045 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1046 MCAsmLayout &Layout,
1048 for (MCAssembler::const_iterator it = Asm.begin(),
1049 ie = Asm.end(); it != ie; ++it) {
1050 const MCSectionData &SD = *it;
1051 if (Relocations[&SD].empty())
1054 MCContext &Ctx = Asm.getContext();
1055 const MCSectionELF &Section =
1056 static_cast<const MCSectionELF&>(SD.getSection());
1058 const StringRef SectionName = Section.getSectionName();
1059 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1060 RelaSectionName += SectionName;
1063 if (hasRelocationAddend())
1064 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1066 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1069 StringRef Group = "";
1070 if (Section.getFlags() & ELF::SHF_GROUP) {
1071 Flags = ELF::SHF_GROUP;
1072 Group = Section.getGroup()->getName();
1075 const MCSectionELF *RelaSection =
1076 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1077 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1078 SectionKind::getReadOnly(),
1080 RelMap[&Section] = RelaSection;
1081 Asm.getOrCreateSectionData(*RelaSection);
1085 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1086 const RelMapTy &RelMap) {
1087 for (MCAssembler::const_iterator it = Asm.begin(),
1088 ie = Asm.end(); it != ie; ++it) {
1089 const MCSectionData &SD = *it;
1090 const MCSectionELF &Section =
1091 static_cast<const MCSectionELF&>(SD.getSection());
1093 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1096 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1097 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1099 MCDataFragment *F = new MCDataFragment(&RelaSD);
1100 WriteRelocationsFragment(Asm, F, &*it);
1104 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1105 uint64_t Flags, uint64_t Address,
1106 uint64_t Offset, uint64_t Size,
1107 uint32_t Link, uint32_t Info,
1109 uint64_t EntrySize) {
1110 Write32(Name); // sh_name: index into string table
1111 Write32(Type); // sh_type
1112 WriteWord(Flags); // sh_flags
1113 WriteWord(Address); // sh_addr
1114 WriteWord(Offset); // sh_offset
1115 WriteWord(Size); // sh_size
1116 Write32(Link); // sh_link
1117 Write32(Info); // sh_info
1118 WriteWord(Alignment); // sh_addralign
1119 WriteWord(EntrySize); // sh_entsize
1122 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1124 const MCSectionData *SD) {
1125 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1127 // Sort the relocation entries. Most targets just sort by r_offset, but some
1128 // (e.g., MIPS) have additional constraints.
1129 TargetObjectWriter->sortRelocs(Asm, Relocs);
1131 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1132 ELFRelocationEntry entry = Relocs[e - i - 1];
1136 else if (entry.Index < 0)
1137 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1139 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1141 String64(*F, entry.r_offset);
1142 if (TargetObjectWriter->isN64()) {
1143 String32(*F, entry.Index);
1145 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1146 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1147 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1148 String8(*F, TargetObjectWriter->getRType(entry.Type));
1151 struct ELF::Elf64_Rela ERE64;
1152 ERE64.setSymbolAndType(entry.Index, entry.Type);
1153 String64(*F, ERE64.r_info);
1155 if (hasRelocationAddend())
1156 String64(*F, entry.r_addend);
1158 String32(*F, entry.r_offset);
1160 struct ELF::Elf32_Rela ERE32;
1161 ERE32.setSymbolAndType(entry.Index, entry.Type);
1162 String32(*F, ERE32.r_info);
1164 if (hasRelocationAddend())
1165 String32(*F, entry.r_addend);
1170 static int compareBySuffix(const MCSectionELF *const *a,
1171 const MCSectionELF *const *b) {
1172 const StringRef &NameA = (*a)->getSectionName();
1173 const StringRef &NameB = (*b)->getSectionName();
1174 const unsigned sizeA = NameA.size();
1175 const unsigned sizeB = NameB.size();
1176 const unsigned len = std::min(sizeA, sizeB);
1177 for (unsigned int i = 0; i < len; ++i) {
1178 char ca = NameA[sizeA - i - 1];
1179 char cb = NameB[sizeB - i - 1];
1184 return sizeB - sizeA;
1187 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1188 MCAsmLayout &Layout,
1189 SectionIndexMapTy &SectionIndexMap,
1190 const RelMapTy &RelMap) {
1191 MCContext &Ctx = Asm.getContext();
1194 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1196 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1197 const MCSectionELF *ShstrtabSection =
1198 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1199 SectionKind::getReadOnly());
1200 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1201 ShstrtabSD.setAlignment(1);
1203 const MCSectionELF *SymtabSection =
1204 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1205 SectionKind::getReadOnly(),
1207 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1208 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1210 MCSectionData *SymtabShndxSD = NULL;
1212 if (NeedsSymtabShndx) {
1213 const MCSectionELF *SymtabShndxSection =
1214 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1215 SectionKind::getReadOnly(), 4, "");
1216 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1217 SymtabShndxSD->setAlignment(4);
1220 const MCSectionELF *StrtabSection;
1221 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1222 SectionKind::getReadOnly());
1223 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1224 StrtabSD.setAlignment(1);
1226 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1228 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1229 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1230 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1233 F = new MCDataFragment(&SymtabSD);
1234 MCDataFragment *ShndxF = NULL;
1235 if (NeedsSymtabShndx) {
1236 ShndxF = new MCDataFragment(SymtabShndxSD);
1238 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1240 F = new MCDataFragment(&StrtabSD);
1241 F->getContents().append(StringTable.begin(), StringTable.end());
1243 F = new MCDataFragment(&ShstrtabSD);
1245 std::vector<const MCSectionELF*> Sections;
1246 for (MCAssembler::const_iterator it = Asm.begin(),
1247 ie = Asm.end(); it != ie; ++it) {
1248 const MCSectionELF &Section =
1249 static_cast<const MCSectionELF&>(it->getSection());
1250 Sections.push_back(&Section);
1252 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1254 // Section header string table.
1256 // The first entry of a string table holds a null character so skip
1259 F->getContents().push_back('\x00');
1261 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1262 const MCSectionELF &Section = *Sections[I];
1264 StringRef Name = Section.getSectionName();
1266 StringRef PreviousName = Sections[I - 1]->getSectionName();
1267 if (PreviousName.endswith(Name)) {
1268 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1272 // Remember the index into the string table so we can write it
1273 // into the sh_name field of the section header table.
1274 SectionStringTableIndex[&Section] = Index;
1276 Index += Name.size() + 1;
1277 F->getContents().append(Name.begin(), Name.end());
1278 F->getContents().push_back('\x00');
1282 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1283 MCAsmLayout &Layout,
1284 GroupMapTy &GroupMap,
1285 RevGroupMapTy &RevGroupMap,
1286 SectionIndexMapTy &SectionIndexMap,
1287 const RelMapTy &RelMap) {
1288 // Create the .note.GNU-stack section if needed.
1289 MCContext &Ctx = Asm.getContext();
1290 if (Asm.getNoExecStack()) {
1291 const MCSectionELF *GnuStackSection =
1292 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1293 SectionKind::getReadOnly());
1294 Asm.getOrCreateSectionData(*GnuStackSection);
1298 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1300 const MCSectionELF &Section =
1301 static_cast<const MCSectionELF&>(it->getSection());
1302 if (!(Section.getFlags() & ELF::SHF_GROUP))
1305 const MCSymbol *SignatureSymbol = Section.getGroup();
1306 Asm.getOrCreateSymbolData(*SignatureSymbol);
1307 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1309 Group = Ctx.CreateELFGroupSection();
1310 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1311 Data.setAlignment(4);
1312 MCDataFragment *F = new MCDataFragment(&Data);
1313 String32(*F, ELF::GRP_COMDAT);
1315 GroupMap[Group] = SignatureSymbol;
1318 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1320 // Add sections to the groups
1321 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1323 const MCSectionELF &Section =
1324 static_cast<const MCSectionELF&>(it->getSection());
1325 if (!(Section.getFlags() & ELF::SHF_GROUP))
1327 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1328 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1329 // FIXME: we could use the previous fragment
1330 MCDataFragment *F = new MCDataFragment(&Data);
1331 unsigned Index = SectionIndexMap.lookup(&Section);
1332 String32(*F, Index);
1336 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1337 const SectionIndexMapTy &SectionIndexMap,
1338 uint32_t GroupSymbolIndex,
1339 uint64_t Offset, uint64_t Size,
1341 const MCSectionELF &Section) {
1342 uint64_t sh_link = 0;
1343 uint64_t sh_info = 0;
1345 switch(Section.getType()) {
1346 case ELF::SHT_DYNAMIC:
1347 sh_link = SectionStringTableIndex[&Section];
1352 case ELF::SHT_RELA: {
1353 const MCSectionELF *SymtabSection;
1354 const MCSectionELF *InfoSection;
1355 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1357 SectionKind::getReadOnly());
1358 sh_link = SectionIndexMap.lookup(SymtabSection);
1359 assert(sh_link && ".symtab not found");
1361 // Remove ".rel" and ".rela" prefixes.
1362 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1363 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1364 StringRef GroupName =
1365 Section.getGroup() ? Section.getGroup()->getName() : "";
1367 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1368 0, SectionKind::getReadOnly(),
1370 sh_info = SectionIndexMap.lookup(InfoSection);
1374 case ELF::SHT_SYMTAB:
1375 case ELF::SHT_DYNSYM:
1376 sh_link = StringTableIndex;
1377 sh_info = LastLocalSymbolIndex;
1380 case ELF::SHT_SYMTAB_SHNDX:
1381 sh_link = SymbolTableIndex;
1384 case ELF::SHT_PROGBITS:
1385 case ELF::SHT_STRTAB:
1386 case ELF::SHT_NOBITS:
1389 case ELF::SHT_ARM_ATTRIBUTES:
1390 case ELF::SHT_INIT_ARRAY:
1391 case ELF::SHT_FINI_ARRAY:
1392 case ELF::SHT_PREINIT_ARRAY:
1393 case ELF::SHT_X86_64_UNWIND:
1394 case ELF::SHT_MIPS_REGINFO:
1395 case ELF::SHT_MIPS_OPTIONS:
1399 case ELF::SHT_GROUP:
1400 sh_link = SymbolTableIndex;
1401 sh_info = GroupSymbolIndex;
1405 assert(0 && "FIXME: sh_type value not supported!");
1409 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1410 Section.getType() == ELF::SHT_ARM_EXIDX) {
1411 StringRef SecName(Section.getSectionName());
1412 if (SecName == ".ARM.exidx") {
1413 sh_link = SectionIndexMap.lookup(
1414 Asm.getContext().getELFSection(".text",
1416 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1417 SectionKind::getText()));
1418 } else if (SecName.startswith(".ARM.exidx")) {
1419 StringRef GroupName =
1420 Section.getGroup() ? Section.getGroup()->getName() : "";
1421 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1422 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1423 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1428 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1429 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1430 Alignment, Section.getEntrySize());
1433 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1434 return SD.getOrdinal() == ~UINT32_C(0) &&
1435 !SD.getSection().isVirtualSection();
1438 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1440 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1442 const MCFragment &F = *i;
1443 assert(F.getKind() == MCFragment::FT_Data);
1444 Ret += cast<MCDataFragment>(F).getContents().size();
1449 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1450 const MCSectionData &SD) {
1451 if (IsELFMetaDataSection(SD))
1452 return DataSectionSize(SD);
1453 return Layout.getSectionFileSize(&SD);
1456 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1457 const MCSectionData &SD) {
1458 if (IsELFMetaDataSection(SD))
1459 return DataSectionSize(SD);
1460 return Layout.getSectionAddressSize(&SD);
1463 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1464 const MCAsmLayout &Layout,
1465 const MCSectionELF &Section) {
1466 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1468 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1469 WriteZeros(Padding);
1471 if (IsELFMetaDataSection(SD)) {
1472 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1474 const MCFragment &F = *i;
1475 assert(F.getKind() == MCFragment::FT_Data);
1476 WriteBytes(cast<MCDataFragment>(F).getContents());
1479 Asm.writeSectionData(&SD, Layout);
1483 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1484 const GroupMapTy &GroupMap,
1485 const MCAsmLayout &Layout,
1486 const SectionIndexMapTy &SectionIndexMap,
1487 const SectionOffsetMapTy &SectionOffsetMap) {
1488 const unsigned NumSections = Asm.size() + 1;
1490 std::vector<const MCSectionELF*> Sections;
1491 Sections.resize(NumSections - 1);
1493 for (SectionIndexMapTy::const_iterator i=
1494 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1495 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1496 Sections[p.second - 1] = p.first;
1499 // Null section first.
1500 uint64_t FirstSectionSize =
1501 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1502 uint32_t FirstSectionLink =
1503 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1504 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1506 for (unsigned i = 0; i < NumSections - 1; ++i) {
1507 const MCSectionELF &Section = *Sections[i];
1508 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1509 uint32_t GroupSymbolIndex;
1510 if (Section.getType() != ELF::SHT_GROUP)
1511 GroupSymbolIndex = 0;
1513 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1514 GroupMap.lookup(&Section));
1516 uint64_t Size = GetSectionAddressSize(Layout, SD);
1518 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1519 SectionOffsetMap.lookup(&Section), Size,
1520 SD.getAlignment(), Section);
1524 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1525 std::vector<const MCSectionELF*> &Sections) {
1526 for (MCAssembler::iterator it = Asm.begin(),
1527 ie = Asm.end(); it != ie; ++it) {
1528 const MCSectionELF &Section =
1529 static_cast<const MCSectionELF &>(it->getSection());
1530 if (Section.getType() == ELF::SHT_GROUP)
1531 Sections.push_back(&Section);
1534 for (MCAssembler::iterator it = Asm.begin(),
1535 ie = Asm.end(); it != ie; ++it) {
1536 const MCSectionELF &Section =
1537 static_cast<const MCSectionELF &>(it->getSection());
1538 if (Section.getType() != ELF::SHT_GROUP &&
1539 Section.getType() != ELF::SHT_REL &&
1540 Section.getType() != ELF::SHT_RELA)
1541 Sections.push_back(&Section);
1544 for (MCAssembler::iterator it = Asm.begin(),
1545 ie = Asm.end(); it != ie; ++it) {
1546 const MCSectionELF &Section =
1547 static_cast<const MCSectionELF &>(it->getSection());
1548 if (Section.getType() == ELF::SHT_REL ||
1549 Section.getType() == ELF::SHT_RELA)
1550 Sections.push_back(&Section);
1554 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1555 const MCAsmLayout &Layout) {
1556 GroupMapTy GroupMap;
1557 RevGroupMapTy RevGroupMap;
1558 SectionIndexMapTy SectionIndexMap;
1560 unsigned NumUserSections = Asm.size();
1562 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1563 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1565 const unsigned NumUserAndRelocSections = Asm.size();
1566 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1567 RevGroupMap, SectionIndexMap, RelMap);
1568 const unsigned AllSections = Asm.size();
1569 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1571 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1573 // Compute symbol table information.
1574 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1577 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1579 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1580 const_cast<MCAsmLayout&>(Layout),
1584 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1585 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1586 sizeof(ELF::Elf32_Ehdr);
1587 uint64_t FileOff = HeaderSize;
1589 std::vector<const MCSectionELF*> Sections;
1590 ComputeSectionOrder(Asm, Sections);
1591 unsigned NumSections = Sections.size();
1592 SectionOffsetMapTy SectionOffsetMap;
1593 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1594 const MCSectionELF &Section = *Sections[i];
1595 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1597 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1599 // Remember the offset into the file for this section.
1600 SectionOffsetMap[&Section] = FileOff;
1602 // Get the size of the section in the output file (including padding).
1603 FileOff += GetSectionFileSize(Layout, SD);
1606 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1608 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1610 uint64_t SectionHeaderEntrySize = is64Bit() ?
1611 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1612 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1614 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1615 const MCSectionELF &Section = *Sections[i];
1616 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1618 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1620 // Remember the offset into the file for this section.
1621 SectionOffsetMap[&Section] = FileOff;
1623 // Get the size of the section in the output file (including padding).
1624 FileOff += GetSectionFileSize(Layout, SD);
1627 // Write out the ELF header ...
1628 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1630 // ... then the regular sections ...
1631 // + because of .shstrtab
1632 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1633 WriteDataSectionData(Asm, Layout, *Sections[i]);
1635 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1636 WriteZeros(Padding);
1638 // ... then the section header table ...
1639 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1642 // ... and then the remaining sections ...
1643 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1644 WriteDataSectionData(Asm, Layout, *Sections[i]);
1648 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1649 const MCSymbolData &DataA,
1650 const MCFragment &FB,
1652 bool IsPCRel) const {
1653 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
1655 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1656 Asm, DataA, FB,InSet, IsPCRel);
1659 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1661 bool IsLittleEndian) {
1662 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);