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/OwningPtr.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELF.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
38 #define DEBUG_TYPE "reloc-info"
41 class ELFObjectWriter : public MCObjectWriter {
44 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
45 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
46 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
47 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
48 bool Used, bool Renamed);
49 static bool isLocal(const MCSymbolData &Data, bool isSignature,
51 static bool IsELFMetaDataSection(const MCSectionData &SD);
52 static uint64_t DataSectionSize(const MCSectionData &SD);
53 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
54 const MCSectionData &SD);
55 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
56 const MCSectionData &SD);
58 void WriteDataSectionData(MCAssembler &Asm,
59 const MCAsmLayout &Layout,
60 const MCSectionELF &Section);
62 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
63 return Kind == X86::reloc_riprel_4byte ||
64 Kind == X86::reloc_riprel_4byte_movq_load;
67 /// ELFSymbolData - Helper struct for containing some precomputed
68 /// information on symbols.
69 struct ELFSymbolData {
70 MCSymbolData *SymbolData;
72 uint32_t SectionIndex;
74 // Support lexicographic sorting.
75 bool operator<(const ELFSymbolData &RHS) const {
76 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
78 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
80 return SymbolData->getSymbol().getName() <
81 RHS.SymbolData->getSymbol().getName();
85 /// The target specific ELF writer instance.
86 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
88 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
89 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
90 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
92 llvm::DenseMap<const MCSectionData*,
93 std::vector<ELFRelocationEntry> > Relocations;
94 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
97 /// @name Symbol Table Data
100 SmallString<256> StringTable;
101 std::vector<ELFSymbolData> LocalSymbolData;
102 std::vector<ELFSymbolData> ExternalSymbolData;
103 std::vector<ELFSymbolData> UndefinedSymbolData;
109 bool NeedsSymtabShndx;
111 // This holds the symbol table index of the last local symbol.
112 unsigned LastLocalSymbolIndex;
113 // This holds the .strtab section index.
114 unsigned StringTableIndex;
115 // This holds the .symtab section index.
116 unsigned SymbolTableIndex;
118 unsigned ShstrtabIndex;
121 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
122 const MCValue &Target,
124 const MCFixup &Fixup,
127 // TargetObjectWriter wrappers.
128 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
129 const MCValue &Target,
131 const MCFixup &Fixup,
132 bool IsPCRel) const {
133 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
135 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
136 const MCFixup &Fixup,
137 bool IsPCRel) const {
138 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup, IsPCRel);
141 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
142 bool hasRelocationAddend() const {
143 return TargetObjectWriter->hasRelocationAddend();
145 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
146 bool IsPCRel, bool IsRelocWithSymbol,
147 int64_t Addend) const {
148 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
149 IsRelocWithSymbol, Addend);
153 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
154 raw_ostream &_OS, bool IsLittleEndian)
155 : MCObjectWriter(_OS, IsLittleEndian),
156 TargetObjectWriter(MOTW),
157 NeedsGOT(false), NeedsSymtabShndx(false){
160 virtual ~ELFObjectWriter();
162 void WriteWord(uint64_t W) {
169 void StringLE16(char *buf, uint16_t Value) {
170 buf[0] = char(Value >> 0);
171 buf[1] = char(Value >> 8);
174 void StringLE32(char *buf, uint32_t Value) {
175 StringLE16(buf, uint16_t(Value >> 0));
176 StringLE16(buf + 2, uint16_t(Value >> 16));
179 void StringLE64(char *buf, uint64_t Value) {
180 StringLE32(buf, uint32_t(Value >> 0));
181 StringLE32(buf + 4, uint32_t(Value >> 32));
184 void StringBE16(char *buf ,uint16_t Value) {
185 buf[0] = char(Value >> 8);
186 buf[1] = char(Value >> 0);
189 void StringBE32(char *buf, uint32_t Value) {
190 StringBE16(buf, uint16_t(Value >> 16));
191 StringBE16(buf + 2, uint16_t(Value >> 0));
194 void StringBE64(char *buf, uint64_t Value) {
195 StringBE32(buf, uint32_t(Value >> 32));
196 StringBE32(buf + 4, uint32_t(Value >> 0));
199 void String8(MCDataFragment &F, uint8_t Value) {
202 F.getContents().append(&buf[0], &buf[1]);
205 void String16(MCDataFragment &F, uint16_t Value) {
207 if (isLittleEndian())
208 StringLE16(buf, Value);
210 StringBE16(buf, Value);
211 F.getContents().append(&buf[0], &buf[2]);
214 void String32(MCDataFragment &F, uint32_t Value) {
216 if (isLittleEndian())
217 StringLE32(buf, Value);
219 StringBE32(buf, Value);
220 F.getContents().append(&buf[0], &buf[4]);
223 void String64(MCDataFragment &F, uint64_t Value) {
225 if (isLittleEndian())
226 StringLE64(buf, Value);
228 StringBE64(buf, Value);
229 F.getContents().append(&buf[0], &buf[8]);
232 void WriteHeader(const MCAssembler &Asm,
233 uint64_t SectionDataSize,
234 unsigned NumberOfSections);
236 void WriteSymbolEntry(MCDataFragment *SymtabF,
237 MCDataFragment *ShndxF,
238 uint64_t name, uint8_t info,
239 uint64_t value, uint64_t size,
240 uint8_t other, uint32_t shndx,
243 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
245 const MCAsmLayout &Layout);
247 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
248 void WriteSymbolTable(MCDataFragment *SymtabF,
249 MCDataFragment *ShndxF,
250 const MCAssembler &Asm,
251 const MCAsmLayout &Layout,
252 const SectionIndexMapTy &SectionIndexMap);
254 virtual void RecordRelocation(const MCAssembler &Asm,
255 const MCAsmLayout &Layout,
256 const MCFragment *Fragment,
257 const MCFixup &Fixup,
258 MCValue Target, uint64_t &FixedValue);
260 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
263 // Map from a group section to the signature symbol
264 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
265 // Map from a signature symbol to the group section
266 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
267 // Map from a section to the section with the relocations
268 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
269 // Map from a section to its offset
270 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
272 /// ComputeSymbolTable - Compute the symbol table data
274 /// \param Asm - The assembler.
275 /// \param SectionIndexMap - Maps a section to its index.
276 /// \param RevGroupMap - Maps a signature symbol to the group section.
277 /// \param NumRegularSections - Number of non-relocation sections.
278 void ComputeSymbolTable(MCAssembler &Asm,
279 const SectionIndexMapTy &SectionIndexMap,
280 RevGroupMapTy RevGroupMap,
281 unsigned NumRegularSections);
283 void ComputeIndexMap(MCAssembler &Asm,
284 SectionIndexMapTy &SectionIndexMap,
285 const RelMapTy &RelMap);
287 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
290 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
291 const RelMapTy &RelMap);
293 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
294 SectionIndexMapTy &SectionIndexMap,
295 const RelMapTy &RelMap);
297 // Create the sections that show up in the symbol table. Currently
298 // those are the .note.GNU-stack section and the group sections.
299 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
300 GroupMapTy &GroupMap,
301 RevGroupMapTy &RevGroupMap,
302 SectionIndexMapTy &SectionIndexMap,
303 const RelMapTy &RelMap);
305 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
306 const MCAsmLayout &Layout);
308 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
309 const MCAsmLayout &Layout,
310 const SectionIndexMapTy &SectionIndexMap,
311 const SectionOffsetMapTy &SectionOffsetMap);
313 void ComputeSectionOrder(MCAssembler &Asm,
314 std::vector<const MCSectionELF*> &Sections);
316 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
317 uint64_t Address, uint64_t Offset,
318 uint64_t Size, uint32_t Link, uint32_t Info,
319 uint64_t Alignment, uint64_t EntrySize);
321 void WriteRelocationsFragment(const MCAssembler &Asm,
323 const MCSectionData *SD);
326 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
327 const MCSymbolData &DataA,
328 const MCFragment &FB,
332 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
333 void WriteSection(MCAssembler &Asm,
334 const SectionIndexMapTy &SectionIndexMap,
335 uint32_t GroupSymbolIndex,
336 uint64_t Offset, uint64_t Size, uint64_t Alignment,
337 const MCSectionELF &Section);
341 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
342 const MCFixupKindInfo &FKI =
343 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
345 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
348 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
352 case MCSymbolRefExpr::VK_GOT:
353 case MCSymbolRefExpr::VK_PLT:
354 case MCSymbolRefExpr::VK_GOTPCREL:
355 case MCSymbolRefExpr::VK_GOTOFF:
356 case MCSymbolRefExpr::VK_TPOFF:
357 case MCSymbolRefExpr::VK_TLSGD:
358 case MCSymbolRefExpr::VK_GOTTPOFF:
359 case MCSymbolRefExpr::VK_INDNTPOFF:
360 case MCSymbolRefExpr::VK_NTPOFF:
361 case MCSymbolRefExpr::VK_GOTNTPOFF:
362 case MCSymbolRefExpr::VK_TLSLDM:
363 case MCSymbolRefExpr::VK_DTPOFF:
364 case MCSymbolRefExpr::VK_TLSLD:
369 ELFObjectWriter::~ELFObjectWriter()
372 // Emit the ELF header.
373 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
374 uint64_t SectionDataSize,
375 unsigned NumberOfSections) {
381 // emitWord method behaves differently for ELF32 and ELF64, writing
382 // 4 bytes in the former and 8 in the latter.
384 Write8(0x7f); // e_ident[EI_MAG0]
385 Write8('E'); // e_ident[EI_MAG1]
386 Write8('L'); // e_ident[EI_MAG2]
387 Write8('F'); // e_ident[EI_MAG3]
389 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
392 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
394 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
396 Write8(TargetObjectWriter->getOSABI());
397 Write8(0); // e_ident[EI_ABIVERSION]
399 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
401 Write16(ELF::ET_REL); // e_type
403 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
405 Write32(ELF::EV_CURRENT); // e_version
406 WriteWord(0); // e_entry, no entry point in .o file
407 WriteWord(0); // e_phoff, no program header for .o
408 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
409 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
411 // e_flags = whatever the target wants
412 Write32(Asm.getELFHeaderEFlags());
414 // e_ehsize = ELF header size
415 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
417 Write16(0); // e_phentsize = prog header entry size
418 Write16(0); // e_phnum = # prog header entries = 0
420 // e_shentsize = Section header entry size
421 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
423 // e_shnum = # of section header ents
424 if (NumberOfSections >= ELF::SHN_LORESERVE)
425 Write16(ELF::SHN_UNDEF);
427 Write16(NumberOfSections);
429 // e_shstrndx = Section # of '.shstrtab'
430 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
431 Write16(ELF::SHN_XINDEX);
433 Write16(ShstrtabIndex);
436 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
437 MCDataFragment *ShndxF,
439 uint8_t info, uint64_t value,
440 uint64_t size, uint8_t other,
444 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
445 String32(*ShndxF, shndx);
447 String32(*ShndxF, 0);
450 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
451 uint16_t(ELF::SHN_XINDEX) : shndx;
454 String32(*SymtabF, name); // st_name
455 String8(*SymtabF, info); // st_info
456 String8(*SymtabF, other); // st_other
457 String16(*SymtabF, Index); // st_shndx
458 String64(*SymtabF, value); // st_value
459 String64(*SymtabF, size); // st_size
461 String32(*SymtabF, name); // st_name
462 String32(*SymtabF, value); // st_value
463 String32(*SymtabF, size); // st_size
464 String8(*SymtabF, info); // st_info
465 String8(*SymtabF, other); // st_other
466 String16(*SymtabF, Index); // st_shndx
470 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
471 const MCAsmLayout &Layout) {
472 if (Data.isCommon() && Data.isExternal())
473 return Data.getCommonAlignment();
475 const MCSymbol &Symbol = Data.getSymbol();
477 if (Symbol.isAbsolute() && Symbol.isVariable()) {
478 if (const MCExpr *Value = Symbol.getVariableValue()) {
480 if (Value->EvaluateAsAbsolute(IntValue, Layout))
481 return (uint64_t)IntValue;
485 if (!Symbol.isInSection())
489 if (Data.getFragment()) {
490 if (Data.getFlags() & ELF_Other_ThumbFunc)
491 return Layout.getSymbolOffset(&Data)+1;
493 return Layout.getSymbolOffset(&Data);
499 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
500 const MCAsmLayout &Layout) {
501 // The presence of symbol versions causes undefined symbols and
502 // versions declared with @@@ to be renamed.
504 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
505 ie = Asm.symbol_end(); it != ie; ++it) {
506 const MCSymbol &Alias = it->getSymbol();
507 const MCSymbol &Symbol = Alias.AliasedSymbol();
508 MCSymbolData &SD = Asm.getSymbolData(Symbol);
511 if (&Symbol == &Alias)
514 StringRef AliasName = Alias.getName();
515 size_t Pos = AliasName.find('@');
516 if (Pos == StringRef::npos)
519 // Aliases defined with .symvar copy the binding from the symbol they alias.
520 // This is the first place we are able to copy this information.
521 it->setExternal(SD.isExternal());
522 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
524 StringRef Rest = AliasName.substr(Pos);
525 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
528 // FIXME: produce a better error message.
529 if (Symbol.isUndefined() && Rest.startswith("@@") &&
530 !Rest.startswith("@@@"))
531 report_fatal_error("A @@ version cannot be undefined");
533 Renames.insert(std::make_pair(&Symbol, &Alias));
537 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
538 MCDataFragment *ShndxF,
540 const MCAsmLayout &Layout) {
541 MCSymbolData &OrigData = *MSD.SymbolData;
543 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
545 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
546 Data.getSymbol().isVariable();
548 uint8_t Binding = MCELF::GetBinding(OrigData);
549 uint8_t Visibility = MCELF::GetVisibility(OrigData);
550 uint8_t Type = MCELF::GetType(Data);
552 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
553 uint8_t Other = Visibility;
555 uint64_t Value = SymbolValue(Data, Layout);
558 assert(!(Data.isCommon() && !Data.isExternal()));
560 const MCExpr *ESize = Data.getSize();
563 if (!ESize->EvaluateAsAbsolute(Res, Layout))
564 report_fatal_error("Size expression must be absolute.");
568 // Write out the symbol table entry
569 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
570 Size, Other, MSD.SectionIndex, IsReserved);
573 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
574 MCDataFragment *ShndxF,
575 const MCAssembler &Asm,
576 const MCAsmLayout &Layout,
577 const SectionIndexMapTy &SectionIndexMap) {
578 // The string table must be emitted first because we need the index
579 // into the string table for all the symbol names.
580 assert(StringTable.size() && "Missing string table");
582 // FIXME: Make sure the start of the symbol table is aligned.
584 // The first entry is the undefined symbol entry.
585 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
587 // Write the symbol table entries.
588 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
589 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
590 ELFSymbolData &MSD = LocalSymbolData[i];
591 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
594 // Write out a symbol table entry for each regular section.
595 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
597 const MCSectionELF &Section =
598 static_cast<const MCSectionELF&>(i->getSection());
599 if (Section.getType() == ELF::SHT_RELA ||
600 Section.getType() == ELF::SHT_REL ||
601 Section.getType() == ELF::SHT_STRTAB ||
602 Section.getType() == ELF::SHT_SYMTAB ||
603 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
605 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
606 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
608 LastLocalSymbolIndex++;
611 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
612 ELFSymbolData &MSD = ExternalSymbolData[i];
613 MCSymbolData &Data = *MSD.SymbolData;
614 assert(((Data.getFlags() & ELF_STB_Global) ||
615 (Data.getFlags() & ELF_STB_Weak)) &&
616 "External symbol requires STB_GLOBAL or STB_WEAK flag");
617 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
618 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
619 LastLocalSymbolIndex++;
622 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
623 ELFSymbolData &MSD = UndefinedSymbolData[i];
624 MCSymbolData &Data = *MSD.SymbolData;
625 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
626 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
627 LastLocalSymbolIndex++;
631 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
632 const MCValue &Target,
634 const MCFixup &Fixup,
635 bool IsPCRel) const {
636 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
637 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
638 const MCSymbol *Renamed = Renames.lookup(&Symbol);
639 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
641 if (ASymbol.isUndefined()) {
644 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
647 if (SD.isExternal()) {
653 const MCSectionELF &Section =
654 static_cast<const MCSectionELF&>(ASymbol.getSection());
655 const SectionKind secKind = Section.getKind();
658 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
660 if (secKind.isThreadLocal()) {
666 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
667 const MCSectionELF &Sec2 =
668 static_cast<const MCSectionELF&>(F.getParent()->getSection());
670 if (&Sec2 != &Section &&
671 (Kind == MCSymbolRefExpr::VK_PLT ||
672 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
673 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
679 if (Section.getFlags() & ELF::SHF_MERGE) {
680 if (Target.getConstant() == 0)
681 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
687 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
692 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
693 const MCAsmLayout &Layout,
694 const MCFragment *Fragment,
695 const MCFixup &Fixup,
697 uint64_t &FixedValue) {
700 int64_t Value = Target.getConstant();
701 const MCSymbol *RelocSymbol = NULL;
703 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
704 if (!Target.isAbsolute()) {
705 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
706 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
707 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
709 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
710 const MCSymbol &SymbolB = RefB->getSymbol();
711 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
714 // Offset of the symbol in the section
715 int64_t a = Layout.getSymbolOffset(&SDB);
717 // Offset of the relocation in the section
718 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
723 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
724 MCFragment *F = SD.getFragment();
727 Index = F->getParent()->getOrdinal() + 1;
728 // Offset of the symbol in the section
729 Value += Layout.getSymbolOffset(&SD);
734 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
735 WeakrefUsedInReloc.insert(RelocSymbol);
737 UsedInReloc.insert(RelocSymbol);
741 if (hasRelocationAddend())
746 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
747 (RelocSymbol != 0), Addend);
748 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
749 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
750 if (RelocNeedsGOT(Modifier))
753 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
756 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
757 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
759 if (!hasRelocationAddend())
763 assert(isInt<64>(Addend));
765 assert(isInt<32>(Addend));
767 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
768 Relocations[Fragment->getParent()].push_back(ERE);
773 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
775 MCSymbolData &SD = Asm.getSymbolData(*S);
776 return SD.getIndex();
779 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
780 const MCSymbolData &Data,
781 bool Used, bool Renamed) {
782 if (Data.getFlags() & ELF_Other_Weakref)
791 const MCSymbol &Symbol = Data.getSymbol();
793 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
796 const MCSymbol &A = Symbol.AliasedSymbol();
797 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
800 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
801 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
804 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
807 if (Symbol.isTemporary())
813 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
814 bool isUsedInReloc) {
815 if (Data.isExternal())
818 const MCSymbol &Symbol = Data.getSymbol();
819 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
821 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
822 if (isSignature && !isUsedInReloc)
831 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
832 SectionIndexMapTy &SectionIndexMap,
833 const RelMapTy &RelMap) {
835 for (MCAssembler::iterator it = Asm.begin(),
836 ie = Asm.end(); it != ie; ++it) {
837 const MCSectionELF &Section =
838 static_cast<const MCSectionELF &>(it->getSection());
839 if (Section.getType() != ELF::SHT_GROUP)
841 SectionIndexMap[&Section] = Index++;
844 for (MCAssembler::iterator it = Asm.begin(),
845 ie = Asm.end(); it != ie; ++it) {
846 const MCSectionELF &Section =
847 static_cast<const MCSectionELF &>(it->getSection());
848 if (Section.getType() == ELF::SHT_GROUP ||
849 Section.getType() == ELF::SHT_REL ||
850 Section.getType() == ELF::SHT_RELA)
852 SectionIndexMap[&Section] = Index++;
853 const MCSectionELF *RelSection = RelMap.lookup(&Section);
855 SectionIndexMap[RelSection] = Index++;
859 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
860 const SectionIndexMapTy &SectionIndexMap,
861 RevGroupMapTy RevGroupMap,
862 unsigned NumRegularSections) {
863 // FIXME: Is this the correct place to do this?
864 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
866 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
867 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
868 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
869 Data.setExternal(true);
870 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
873 // Index 0 is always the empty string.
874 StringMap<uint64_t> StringIndexMap;
875 StringTable += '\x00';
877 // FIXME: We could optimize suffixes in strtab in the same way we
878 // optimize them in shstrtab.
880 // Add the data for the symbols.
881 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
882 ie = Asm.symbol_end(); it != ie; ++it) {
883 const MCSymbol &Symbol = it->getSymbol();
885 bool Used = UsedInReloc.count(&Symbol);
886 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
887 bool isSignature = RevGroupMap.count(&Symbol);
889 if (!isInSymtab(Asm, *it,
890 Used || WeakrefUsed || isSignature,
891 Renames.count(&Symbol)))
896 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
898 // Undefined symbols are global, but this is the first place we
899 // are able to set it.
900 bool Local = isLocal(*it, isSignature, Used);
901 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
902 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
903 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
904 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
907 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
908 MCELF::SetBinding(*it, ELF::STB_WEAK);
910 if (it->isCommon()) {
912 MSD.SectionIndex = ELF::SHN_COMMON;
913 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
914 MSD.SectionIndex = ELF::SHN_ABS;
915 } else if (RefSymbol.isUndefined()) {
916 if (isSignature && !Used)
917 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
919 MSD.SectionIndex = ELF::SHN_UNDEF;
921 const MCSectionELF &Section =
922 static_cast<const MCSectionELF&>(RefSymbol.getSection());
923 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
924 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
925 NeedsSymtabShndx = true;
926 assert(MSD.SectionIndex && "Invalid section index!");
929 // The @@@ in symbol version is replaced with @ in undefined symbols and
930 // @@ in defined ones.
931 StringRef Name = Symbol.getName();
934 size_t Pos = Name.find("@@@");
935 if (Pos != StringRef::npos) {
936 Buf += Name.substr(0, Pos);
937 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
938 Buf += Name.substr(Pos + Skip);
942 uint64_t &Entry = StringIndexMap[Name];
944 Entry = StringTable.size();
946 StringTable += '\x00';
948 MSD.StringIndex = Entry;
949 if (MSD.SectionIndex == ELF::SHN_UNDEF)
950 UndefinedSymbolData.push_back(MSD);
952 LocalSymbolData.push_back(MSD);
954 ExternalSymbolData.push_back(MSD);
957 // Symbols are required to be in lexicographic order.
958 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
959 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
960 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
962 // Set the symbol indices. Local symbols must come before all other
963 // symbols with non-local bindings.
965 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
966 LocalSymbolData[i].SymbolData->setIndex(Index++);
968 Index += NumRegularSections;
970 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
971 ExternalSymbolData[i].SymbolData->setIndex(Index++);
972 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
973 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
975 if (NumRegularSections > ELF::SHN_LORESERVE)
976 NeedsSymtabShndx = true;
979 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
982 for (MCAssembler::const_iterator it = Asm.begin(),
983 ie = Asm.end(); it != ie; ++it) {
984 const MCSectionData &SD = *it;
985 if (Relocations[&SD].empty())
988 MCContext &Ctx = Asm.getContext();
989 const MCSectionELF &Section =
990 static_cast<const MCSectionELF&>(SD.getSection());
992 const StringRef SectionName = Section.getSectionName();
993 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
994 RelaSectionName += SectionName;
997 if (hasRelocationAddend())
998 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1000 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1002 const MCSectionELF *RelaSection =
1003 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1004 ELF::SHT_RELA : ELF::SHT_REL, 0,
1005 SectionKind::getReadOnly(),
1007 RelMap[&Section] = RelaSection;
1008 Asm.getOrCreateSectionData(*RelaSection);
1012 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1013 const RelMapTy &RelMap) {
1014 for (MCAssembler::const_iterator it = Asm.begin(),
1015 ie = Asm.end(); it != ie; ++it) {
1016 const MCSectionData &SD = *it;
1017 const MCSectionELF &Section =
1018 static_cast<const MCSectionELF&>(SD.getSection());
1020 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1023 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1024 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1026 MCDataFragment *F = new MCDataFragment(&RelaSD);
1027 WriteRelocationsFragment(Asm, F, &*it);
1031 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1032 uint64_t Flags, uint64_t Address,
1033 uint64_t Offset, uint64_t Size,
1034 uint32_t Link, uint32_t Info,
1036 uint64_t EntrySize) {
1037 Write32(Name); // sh_name: index into string table
1038 Write32(Type); // sh_type
1039 WriteWord(Flags); // sh_flags
1040 WriteWord(Address); // sh_addr
1041 WriteWord(Offset); // sh_offset
1042 WriteWord(Size); // sh_size
1043 Write32(Link); // sh_link
1044 Write32(Info); // sh_info
1045 WriteWord(Alignment); // sh_addralign
1046 WriteWord(EntrySize); // sh_entsize
1049 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1051 const MCSectionData *SD) {
1052 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1054 // Sort the relocation entries. Most targets just sort by r_offset, but some
1055 // (e.g., MIPS) have additional constraints.
1056 TargetObjectWriter->sortRelocs(Asm, Relocs);
1058 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1059 ELFRelocationEntry entry = Relocs[e - i - 1];
1063 else if (entry.Index < 0)
1064 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1066 entry.Index += LocalSymbolData.size();
1068 String64(*F, entry.r_offset);
1069 if (TargetObjectWriter->isN64()) {
1070 String32(*F, entry.Index);
1072 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1073 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1074 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1075 String8(*F, TargetObjectWriter->getRType(entry.Type));
1078 struct ELF::Elf64_Rela ERE64;
1079 ERE64.setSymbolAndType(entry.Index, entry.Type);
1080 String64(*F, ERE64.r_info);
1082 if (hasRelocationAddend())
1083 String64(*F, entry.r_addend);
1085 String32(*F, entry.r_offset);
1087 struct ELF::Elf32_Rela ERE32;
1088 ERE32.setSymbolAndType(entry.Index, entry.Type);
1089 String32(*F, ERE32.r_info);
1091 if (hasRelocationAddend())
1092 String32(*F, entry.r_addend);
1097 static int compareBySuffix(const void *a, const void *b) {
1098 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1099 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1100 const StringRef &NameA = secA->getSectionName();
1101 const StringRef &NameB = secB->getSectionName();
1102 const unsigned sizeA = NameA.size();
1103 const unsigned sizeB = NameB.size();
1104 const unsigned len = std::min(sizeA, sizeB);
1105 for (unsigned int i = 0; i < len; ++i) {
1106 char ca = NameA[sizeA - i - 1];
1107 char cb = NameB[sizeB - i - 1];
1112 return sizeB - sizeA;
1115 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1116 MCAsmLayout &Layout,
1117 SectionIndexMapTy &SectionIndexMap,
1118 const RelMapTy &RelMap) {
1119 MCContext &Ctx = Asm.getContext();
1122 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1124 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1125 const MCSectionELF *ShstrtabSection =
1126 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1127 SectionKind::getReadOnly());
1128 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1129 ShstrtabSD.setAlignment(1);
1131 const MCSectionELF *SymtabSection =
1132 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1133 SectionKind::getReadOnly(),
1135 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1136 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1138 MCSectionData *SymtabShndxSD = NULL;
1140 if (NeedsSymtabShndx) {
1141 const MCSectionELF *SymtabShndxSection =
1142 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1143 SectionKind::getReadOnly(), 4, "");
1144 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1145 SymtabShndxSD->setAlignment(4);
1148 const MCSectionELF *StrtabSection;
1149 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1150 SectionKind::getReadOnly());
1151 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1152 StrtabSD.setAlignment(1);
1154 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1156 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1157 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1158 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1161 F = new MCDataFragment(&SymtabSD);
1162 MCDataFragment *ShndxF = NULL;
1163 if (NeedsSymtabShndx) {
1164 ShndxF = new MCDataFragment(SymtabShndxSD);
1166 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1168 F = new MCDataFragment(&StrtabSD);
1169 F->getContents().append(StringTable.begin(), StringTable.end());
1171 F = new MCDataFragment(&ShstrtabSD);
1173 std::vector<const MCSectionELF*> Sections;
1174 for (MCAssembler::const_iterator it = Asm.begin(),
1175 ie = Asm.end(); it != ie; ++it) {
1176 const MCSectionELF &Section =
1177 static_cast<const MCSectionELF&>(it->getSection());
1178 Sections.push_back(&Section);
1180 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1182 // Section header string table.
1184 // The first entry of a string table holds a null character so skip
1187 F->getContents().push_back('\x00');
1189 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1190 const MCSectionELF &Section = *Sections[I];
1192 StringRef Name = Section.getSectionName();
1194 StringRef PreviousName = Sections[I - 1]->getSectionName();
1195 if (PreviousName.endswith(Name)) {
1196 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1200 // Remember the index into the string table so we can write it
1201 // into the sh_name field of the section header table.
1202 SectionStringTableIndex[&Section] = Index;
1204 Index += Name.size() + 1;
1205 F->getContents().append(Name.begin(), Name.end());
1206 F->getContents().push_back('\x00');
1210 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1211 MCAsmLayout &Layout,
1212 GroupMapTy &GroupMap,
1213 RevGroupMapTy &RevGroupMap,
1214 SectionIndexMapTy &SectionIndexMap,
1215 const RelMapTy &RelMap) {
1216 // Create the .note.GNU-stack section if needed.
1217 MCContext &Ctx = Asm.getContext();
1218 if (Asm.getNoExecStack()) {
1219 const MCSectionELF *GnuStackSection =
1220 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1221 SectionKind::getReadOnly());
1222 Asm.getOrCreateSectionData(*GnuStackSection);
1226 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1228 const MCSectionELF &Section =
1229 static_cast<const MCSectionELF&>(it->getSection());
1230 if (!(Section.getFlags() & ELF::SHF_GROUP))
1233 const MCSymbol *SignatureSymbol = Section.getGroup();
1234 Asm.getOrCreateSymbolData(*SignatureSymbol);
1235 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1237 Group = Ctx.CreateELFGroupSection();
1238 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1239 Data.setAlignment(4);
1240 MCDataFragment *F = new MCDataFragment(&Data);
1241 String32(*F, ELF::GRP_COMDAT);
1243 GroupMap[Group] = SignatureSymbol;
1246 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1248 // Add sections to the groups
1249 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1251 const MCSectionELF &Section =
1252 static_cast<const MCSectionELF&>(it->getSection());
1253 if (!(Section.getFlags() & ELF::SHF_GROUP))
1255 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1256 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1257 // FIXME: we could use the previous fragment
1258 MCDataFragment *F = new MCDataFragment(&Data);
1259 unsigned Index = SectionIndexMap.lookup(&Section);
1260 String32(*F, Index);
1264 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1265 const SectionIndexMapTy &SectionIndexMap,
1266 uint32_t GroupSymbolIndex,
1267 uint64_t Offset, uint64_t Size,
1269 const MCSectionELF &Section) {
1270 uint64_t sh_link = 0;
1271 uint64_t sh_info = 0;
1273 switch(Section.getType()) {
1274 case ELF::SHT_DYNAMIC:
1275 sh_link = SectionStringTableIndex[&Section];
1280 case ELF::SHT_RELA: {
1281 const MCSectionELF *SymtabSection;
1282 const MCSectionELF *InfoSection;
1283 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1285 SectionKind::getReadOnly());
1286 sh_link = SectionIndexMap.lookup(SymtabSection);
1287 assert(sh_link && ".symtab not found");
1289 // Remove ".rel" and ".rela" prefixes.
1290 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1291 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1293 InfoSection = Asm.getContext().getELFSection(SectionName,
1294 ELF::SHT_PROGBITS, 0,
1295 SectionKind::getReadOnly());
1296 sh_info = SectionIndexMap.lookup(InfoSection);
1300 case ELF::SHT_SYMTAB:
1301 case ELF::SHT_DYNSYM:
1302 sh_link = StringTableIndex;
1303 sh_info = LastLocalSymbolIndex;
1306 case ELF::SHT_SYMTAB_SHNDX:
1307 sh_link = SymbolTableIndex;
1310 case ELF::SHT_PROGBITS:
1311 case ELF::SHT_STRTAB:
1312 case ELF::SHT_NOBITS:
1315 case ELF::SHT_ARM_ATTRIBUTES:
1316 case ELF::SHT_INIT_ARRAY:
1317 case ELF::SHT_FINI_ARRAY:
1318 case ELF::SHT_PREINIT_ARRAY:
1319 case ELF::SHT_X86_64_UNWIND:
1320 case ELF::SHT_MIPS_REGINFO:
1321 case ELF::SHT_MIPS_OPTIONS:
1325 case ELF::SHT_GROUP:
1326 sh_link = SymbolTableIndex;
1327 sh_info = GroupSymbolIndex;
1331 assert(0 && "FIXME: sh_type value not supported!");
1335 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1336 Section.getType() == ELF::SHT_ARM_EXIDX) {
1337 StringRef SecName(Section.getSectionName());
1338 if (SecName == ".ARM.exidx") {
1339 sh_link = SectionIndexMap.lookup(
1340 Asm.getContext().getELFSection(".text",
1342 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1343 SectionKind::getText()));
1344 } else if (SecName.startswith(".ARM.exidx")) {
1345 sh_link = SectionIndexMap.lookup(
1346 Asm.getContext().getELFSection(SecName.substr(sizeof(".ARM.exidx") - 1),
1348 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1349 SectionKind::getText()));
1353 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1354 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1355 Alignment, Section.getEntrySize());
1358 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1359 return SD.getOrdinal() == ~UINT32_C(0) &&
1360 !SD.getSection().isVirtualSection();
1363 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1365 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1367 const MCFragment &F = *i;
1368 assert(F.getKind() == MCFragment::FT_Data);
1369 Ret += cast<MCDataFragment>(F).getContents().size();
1374 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1375 const MCSectionData &SD) {
1376 if (IsELFMetaDataSection(SD))
1377 return DataSectionSize(SD);
1378 return Layout.getSectionFileSize(&SD);
1381 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1382 const MCSectionData &SD) {
1383 if (IsELFMetaDataSection(SD))
1384 return DataSectionSize(SD);
1385 return Layout.getSectionAddressSize(&SD);
1388 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1389 const MCAsmLayout &Layout,
1390 const MCSectionELF &Section) {
1391 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1393 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1394 WriteZeros(Padding);
1396 if (IsELFMetaDataSection(SD)) {
1397 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1399 const MCFragment &F = *i;
1400 assert(F.getKind() == MCFragment::FT_Data);
1401 WriteBytes(cast<MCDataFragment>(F).getContents());
1404 Asm.writeSectionData(&SD, Layout);
1408 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1409 const GroupMapTy &GroupMap,
1410 const MCAsmLayout &Layout,
1411 const SectionIndexMapTy &SectionIndexMap,
1412 const SectionOffsetMapTy &SectionOffsetMap) {
1413 const unsigned NumSections = Asm.size() + 1;
1415 std::vector<const MCSectionELF*> Sections;
1416 Sections.resize(NumSections - 1);
1418 for (SectionIndexMapTy::const_iterator i=
1419 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1420 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1421 Sections[p.second - 1] = p.first;
1424 // Null section first.
1425 uint64_t FirstSectionSize =
1426 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1427 uint32_t FirstSectionLink =
1428 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1429 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1431 for (unsigned i = 0; i < NumSections - 1; ++i) {
1432 const MCSectionELF &Section = *Sections[i];
1433 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1434 uint32_t GroupSymbolIndex;
1435 if (Section.getType() != ELF::SHT_GROUP)
1436 GroupSymbolIndex = 0;
1438 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1439 GroupMap.lookup(&Section));
1441 uint64_t Size = GetSectionAddressSize(Layout, SD);
1443 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1444 SectionOffsetMap.lookup(&Section), Size,
1445 SD.getAlignment(), Section);
1449 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1450 std::vector<const MCSectionELF*> &Sections) {
1451 for (MCAssembler::iterator it = Asm.begin(),
1452 ie = Asm.end(); it != ie; ++it) {
1453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF &>(it->getSection());
1455 if (Section.getType() == ELF::SHT_GROUP)
1456 Sections.push_back(&Section);
1459 for (MCAssembler::iterator it = Asm.begin(),
1460 ie = Asm.end(); it != ie; ++it) {
1461 const MCSectionELF &Section =
1462 static_cast<const MCSectionELF &>(it->getSection());
1463 if (Section.getType() != ELF::SHT_GROUP &&
1464 Section.getType() != ELF::SHT_REL &&
1465 Section.getType() != ELF::SHT_RELA)
1466 Sections.push_back(&Section);
1469 for (MCAssembler::iterator it = Asm.begin(),
1470 ie = Asm.end(); it != ie; ++it) {
1471 const MCSectionELF &Section =
1472 static_cast<const MCSectionELF &>(it->getSection());
1473 if (Section.getType() == ELF::SHT_REL ||
1474 Section.getType() == ELF::SHT_RELA)
1475 Sections.push_back(&Section);
1479 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1480 const MCAsmLayout &Layout) {
1481 GroupMapTy GroupMap;
1482 RevGroupMapTy RevGroupMap;
1483 SectionIndexMapTy SectionIndexMap;
1485 unsigned NumUserSections = Asm.size();
1487 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1488 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1490 const unsigned NumUserAndRelocSections = Asm.size();
1491 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1492 RevGroupMap, SectionIndexMap, RelMap);
1493 const unsigned AllSections = Asm.size();
1494 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1496 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1498 // Compute symbol table information.
1499 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1502 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1504 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1505 const_cast<MCAsmLayout&>(Layout),
1509 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1510 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1511 sizeof(ELF::Elf32_Ehdr);
1512 uint64_t FileOff = HeaderSize;
1514 std::vector<const MCSectionELF*> Sections;
1515 ComputeSectionOrder(Asm, Sections);
1516 unsigned NumSections = Sections.size();
1517 SectionOffsetMapTy SectionOffsetMap;
1518 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1519 const MCSectionELF &Section = *Sections[i];
1520 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1522 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1524 // Remember the offset into the file for this section.
1525 SectionOffsetMap[&Section] = FileOff;
1527 // Get the size of the section in the output file (including padding).
1528 FileOff += GetSectionFileSize(Layout, SD);
1531 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1533 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1535 uint64_t SectionHeaderEntrySize = is64Bit() ?
1536 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1537 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1539 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1540 const MCSectionELF &Section = *Sections[i];
1541 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1543 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1545 // Remember the offset into the file for this section.
1546 SectionOffsetMap[&Section] = FileOff;
1548 // Get the size of the section in the output file (including padding).
1549 FileOff += GetSectionFileSize(Layout, SD);
1552 // Write out the ELF header ...
1553 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1555 // ... then the regular sections ...
1556 // + because of .shstrtab
1557 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1558 WriteDataSectionData(Asm, Layout, *Sections[i]);
1560 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1561 WriteZeros(Padding);
1563 // ... then the section header table ...
1564 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1567 // ... and then the remaining sections ...
1568 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1569 WriteDataSectionData(Asm, Layout, *Sections[i]);
1573 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1574 const MCSymbolData &DataA,
1575 const MCFragment &FB,
1577 bool IsPCRel) const {
1578 if (DataA.getFlags() & ELF_STB_Weak)
1580 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1581 Asm, DataA, FB,InSet, IsPCRel);
1584 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1586 bool IsLittleEndian) {
1587 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);