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 return SymbolData->getSymbol().getName() <
77 RHS.SymbolData->getSymbol().getName();
81 /// The target specific ELF writer instance.
82 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
84 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
85 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
86 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
88 llvm::DenseMap<const MCSectionData*,
89 std::vector<ELFRelocationEntry> > Relocations;
90 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
93 /// @name Symbol Table Data
96 SmallString<256> StringTable;
97 std::vector<uint64_t> FileSymbolData;
98 std::vector<ELFSymbolData> LocalSymbolData;
99 std::vector<ELFSymbolData> ExternalSymbolData;
100 std::vector<ELFSymbolData> UndefinedSymbolData;
106 bool NeedsSymtabShndx;
108 // This holds the symbol table index of the last local symbol.
109 unsigned LastLocalSymbolIndex;
110 // This holds the .strtab section index.
111 unsigned StringTableIndex;
112 // This holds the .symtab section index.
113 unsigned SymbolTableIndex;
115 unsigned ShstrtabIndex;
118 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
119 const MCValue &Target,
121 const MCFixup &Fixup,
124 // TargetObjectWriter wrappers.
125 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
126 const MCValue &Target,
128 const MCFixup &Fixup,
129 bool IsPCRel) const {
130 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
132 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
133 const MCFixup &Fixup,
134 bool IsPCRel) const {
135 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
139 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
140 bool hasRelocationAddend() const {
141 return TargetObjectWriter->hasRelocationAddend();
143 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
144 bool IsPCRel, bool IsRelocWithSymbol,
145 int64_t Addend) const {
146 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
147 IsRelocWithSymbol, Addend);
151 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
152 raw_ostream &_OS, bool IsLittleEndian)
153 : MCObjectWriter(_OS, IsLittleEndian),
154 TargetObjectWriter(MOTW),
155 NeedsGOT(false), NeedsSymtabShndx(false) {
158 virtual ~ELFObjectWriter();
160 void WriteWord(uint64_t W) {
167 void StringLE16(char *buf, uint16_t Value) {
168 buf[0] = char(Value >> 0);
169 buf[1] = char(Value >> 8);
172 void StringLE32(char *buf, uint32_t Value) {
173 StringLE16(buf, uint16_t(Value >> 0));
174 StringLE16(buf + 2, uint16_t(Value >> 16));
177 void StringLE64(char *buf, uint64_t Value) {
178 StringLE32(buf, uint32_t(Value >> 0));
179 StringLE32(buf + 4, uint32_t(Value >> 32));
182 void StringBE16(char *buf ,uint16_t Value) {
183 buf[0] = char(Value >> 8);
184 buf[1] = char(Value >> 0);
187 void StringBE32(char *buf, uint32_t Value) {
188 StringBE16(buf, uint16_t(Value >> 16));
189 StringBE16(buf + 2, uint16_t(Value >> 0));
192 void StringBE64(char *buf, uint64_t Value) {
193 StringBE32(buf, uint32_t(Value >> 32));
194 StringBE32(buf + 4, uint32_t(Value >> 0));
197 void String8(MCDataFragment &F, uint8_t Value) {
200 F.getContents().append(&buf[0], &buf[1]);
203 void String16(MCDataFragment &F, uint16_t Value) {
205 if (isLittleEndian())
206 StringLE16(buf, Value);
208 StringBE16(buf, Value);
209 F.getContents().append(&buf[0], &buf[2]);
212 void String32(MCDataFragment &F, uint32_t Value) {
214 if (isLittleEndian())
215 StringLE32(buf, Value);
217 StringBE32(buf, Value);
218 F.getContents().append(&buf[0], &buf[4]);
221 void String64(MCDataFragment &F, uint64_t Value) {
223 if (isLittleEndian())
224 StringLE64(buf, Value);
226 StringBE64(buf, Value);
227 F.getContents().append(&buf[0], &buf[8]);
230 void WriteHeader(const MCAssembler &Asm,
231 uint64_t SectionDataSize,
232 unsigned NumberOfSections);
234 void WriteSymbolEntry(MCDataFragment *SymtabF,
235 MCDataFragment *ShndxF,
236 uint64_t name, uint8_t info,
237 uint64_t value, uint64_t size,
238 uint8_t other, uint32_t shndx,
241 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
243 const MCAsmLayout &Layout);
245 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
246 void WriteSymbolTable(MCDataFragment *SymtabF,
247 MCDataFragment *ShndxF,
248 const MCAssembler &Asm,
249 const MCAsmLayout &Layout,
250 const SectionIndexMapTy &SectionIndexMap);
252 virtual void RecordRelocation(const MCAssembler &Asm,
253 const MCAsmLayout &Layout,
254 const MCFragment *Fragment,
255 const MCFixup &Fixup,
256 MCValue Target, uint64_t &FixedValue);
258 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
261 // Map from a group section to the signature symbol
262 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
263 // Map from a signature symbol to the group section
264 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
265 // Map from a section to the section with the relocations
266 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
267 // Map from a section to its offset
268 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
270 /// ComputeSymbolTable - Compute the symbol table data
272 /// \param Asm - The assembler.
273 /// \param SectionIndexMap - Maps a section to its index.
274 /// \param RevGroupMap - Maps a signature symbol to the group section.
275 /// \param NumRegularSections - Number of non-relocation sections.
276 void ComputeSymbolTable(MCAssembler &Asm,
277 const SectionIndexMapTy &SectionIndexMap,
278 RevGroupMapTy RevGroupMap,
279 unsigned NumRegularSections);
281 void ComputeIndexMap(MCAssembler &Asm,
282 SectionIndexMapTy &SectionIndexMap,
283 const RelMapTy &RelMap);
285 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
288 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
289 const RelMapTy &RelMap);
291 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
292 SectionIndexMapTy &SectionIndexMap,
293 const RelMapTy &RelMap);
295 // Create the sections that show up in the symbol table. Currently
296 // those are the .note.GNU-stack section and the group sections.
297 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
298 GroupMapTy &GroupMap,
299 RevGroupMapTy &RevGroupMap,
300 SectionIndexMapTy &SectionIndexMap,
301 const RelMapTy &RelMap);
303 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
304 const MCAsmLayout &Layout);
306 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
307 const MCAsmLayout &Layout,
308 const SectionIndexMapTy &SectionIndexMap,
309 const SectionOffsetMapTy &SectionOffsetMap);
311 void ComputeSectionOrder(MCAssembler &Asm,
312 std::vector<const MCSectionELF*> &Sections);
314 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
315 uint64_t Address, uint64_t Offset,
316 uint64_t Size, uint32_t Link, uint32_t Info,
317 uint64_t Alignment, uint64_t EntrySize);
319 void WriteRelocationsFragment(const MCAssembler &Asm,
321 const MCSectionData *SD);
324 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
325 const MCSymbolData &DataA,
326 const MCFragment &FB,
330 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
331 void WriteSection(MCAssembler &Asm,
332 const SectionIndexMapTy &SectionIndexMap,
333 uint32_t GroupSymbolIndex,
334 uint64_t Offset, uint64_t Size, uint64_t Alignment,
335 const MCSectionELF &Section);
339 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
340 const MCFixupKindInfo &FKI =
341 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
343 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
346 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
350 case MCSymbolRefExpr::VK_GOT:
351 case MCSymbolRefExpr::VK_PLT:
352 case MCSymbolRefExpr::VK_GOTPCREL:
353 case MCSymbolRefExpr::VK_GOTOFF:
354 case MCSymbolRefExpr::VK_TPOFF:
355 case MCSymbolRefExpr::VK_TLSGD:
356 case MCSymbolRefExpr::VK_GOTTPOFF:
357 case MCSymbolRefExpr::VK_INDNTPOFF:
358 case MCSymbolRefExpr::VK_NTPOFF:
359 case MCSymbolRefExpr::VK_GOTNTPOFF:
360 case MCSymbolRefExpr::VK_TLSLDM:
361 case MCSymbolRefExpr::VK_DTPOFF:
362 case MCSymbolRefExpr::VK_TLSLD:
367 ELFObjectWriter::~ELFObjectWriter()
370 // Emit the ELF header.
371 void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
372 uint64_t SectionDataSize,
373 unsigned NumberOfSections) {
379 // emitWord method behaves differently for ELF32 and ELF64, writing
380 // 4 bytes in the former and 8 in the latter.
382 Write8(0x7f); // e_ident[EI_MAG0]
383 Write8('E'); // e_ident[EI_MAG1]
384 Write8('L'); // e_ident[EI_MAG2]
385 Write8('F'); // e_ident[EI_MAG3]
387 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
390 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
392 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
394 Write8(TargetObjectWriter->getOSABI());
395 Write8(0); // e_ident[EI_ABIVERSION]
397 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
399 Write16(ELF::ET_REL); // e_type
401 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
403 Write32(ELF::EV_CURRENT); // e_version
404 WriteWord(0); // e_entry, no entry point in .o file
405 WriteWord(0); // e_phoff, no program header for .o
406 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
407 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
409 // e_flags = whatever the target wants
410 Write32(Asm.getELFHeaderEFlags());
412 // e_ehsize = ELF header size
413 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
415 Write16(0); // e_phentsize = prog header entry size
416 Write16(0); // e_phnum = # prog header entries = 0
418 // e_shentsize = Section header entry size
419 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
421 // e_shnum = # of section header ents
422 if (NumberOfSections >= ELF::SHN_LORESERVE)
423 Write16(ELF::SHN_UNDEF);
425 Write16(NumberOfSections);
427 // e_shstrndx = Section # of '.shstrtab'
428 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
429 Write16(ELF::SHN_XINDEX);
431 Write16(ShstrtabIndex);
434 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
435 MCDataFragment *ShndxF,
437 uint8_t info, uint64_t value,
438 uint64_t size, uint8_t other,
442 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
443 String32(*ShndxF, shndx);
445 String32(*ShndxF, 0);
448 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
449 uint16_t(ELF::SHN_XINDEX) : shndx;
452 String32(*SymtabF, name); // st_name
453 String8(*SymtabF, info); // st_info
454 String8(*SymtabF, other); // st_other
455 String16(*SymtabF, Index); // st_shndx
456 String64(*SymtabF, value); // st_value
457 String64(*SymtabF, size); // st_size
459 String32(*SymtabF, name); // st_name
460 String32(*SymtabF, value); // st_value
461 String32(*SymtabF, size); // st_size
462 String8(*SymtabF, info); // st_info
463 String8(*SymtabF, other); // st_other
464 String16(*SymtabF, Index); // st_shndx
468 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
469 const MCAsmLayout &Layout) {
470 if (Data.isCommon() && Data.isExternal())
471 return Data.getCommonAlignment();
473 const MCSymbol &Symbol = Data.getSymbol();
475 if (Symbol.isAbsolute() && Symbol.isVariable()) {
476 if (const MCExpr *Value = Symbol.getVariableValue()) {
478 if (Value->EvaluateAsAbsolute(IntValue, Layout))
479 return (uint64_t)IntValue;
483 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 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
536 MCDataFragment *ShndxF,
538 const MCAsmLayout &Layout) {
539 MCSymbolData &OrigData = *MSD.SymbolData;
541 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
543 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
544 Data.getSymbol().isVariable();
546 // Binding and Type share the same byte as upper and lower nibbles
547 uint8_t Binding = MCELF::GetBinding(OrigData);
548 uint8_t Type = MCELF::GetType(Data);
549 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
551 // Other and Visibility share the same byte with Visibility using the lower
553 uint8_t Visibility = MCELF::GetVisibility(OrigData);
554 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
557 uint64_t Value = SymbolValue(Data, Layout);
560 assert(!(Data.isCommon() && !Data.isExternal()));
562 const MCExpr *ESize = Data.getSize();
565 if (!ESize->EvaluateAsAbsolute(Res, Layout))
566 report_fatal_error("Size expression must be absolute.");
570 // Write out the symbol table entry
571 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
572 Size, Other, MSD.SectionIndex, IsReserved);
575 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
576 MCDataFragment *ShndxF,
577 const MCAssembler &Asm,
578 const MCAsmLayout &Layout,
579 const SectionIndexMapTy &SectionIndexMap) {
580 // The string table must be emitted first because we need the index
581 // into the string table for all the symbol names.
582 assert(StringTable.size() && "Missing string table");
584 // FIXME: Make sure the start of the symbol table is aligned.
586 // The first entry is the undefined symbol entry.
587 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
589 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
590 WriteSymbolEntry(SymtabF, ShndxF, FileSymbolData[i],
591 ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
592 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
595 // Write the symbol table entries.
596 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
598 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
599 ELFSymbolData &MSD = LocalSymbolData[i];
600 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
603 // Write out a symbol table entry for each regular section.
604 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
606 const MCSectionELF &Section =
607 static_cast<const MCSectionELF&>(i->getSection());
608 if (Section.getType() == ELF::SHT_RELA ||
609 Section.getType() == ELF::SHT_REL ||
610 Section.getType() == ELF::SHT_STRTAB ||
611 Section.getType() == ELF::SHT_SYMTAB ||
612 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
614 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
615 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
617 LastLocalSymbolIndex++;
620 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
621 ELFSymbolData &MSD = ExternalSymbolData[i];
622 MCSymbolData &Data = *MSD.SymbolData;
623 assert(((Data.getFlags() & ELF_STB_Global) ||
624 (Data.getFlags() & ELF_STB_Weak)) &&
625 "External symbol requires STB_GLOBAL or STB_WEAK flag");
626 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
627 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
628 LastLocalSymbolIndex++;
631 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
632 ELFSymbolData &MSD = UndefinedSymbolData[i];
633 MCSymbolData &Data = *MSD.SymbolData;
634 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
635 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
636 LastLocalSymbolIndex++;
640 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
641 const MCValue &Target,
643 const MCFixup &Fixup,
644 bool IsPCRel) const {
645 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
646 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
647 const MCSymbol *Renamed = Renames.lookup(&Symbol);
648 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
650 if (ASymbol.isUndefined()) {
653 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
656 if (SD.isExternal()) {
662 const MCSectionELF &Section =
663 static_cast<const MCSectionELF&>(ASymbol.getSection());
664 const SectionKind secKind = Section.getKind();
667 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
669 if (secKind.isThreadLocal()) {
675 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
676 const MCSectionELF &Sec2 =
677 static_cast<const MCSectionELF&>(F.getParent()->getSection());
679 if (&Sec2 != &Section &&
680 (Kind == MCSymbolRefExpr::VK_PLT ||
681 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
682 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
688 if (Section.getFlags() & ELF::SHF_MERGE) {
689 if (Target.getConstant() == 0)
690 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
696 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
701 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
702 const MCAsmLayout &Layout,
703 const MCFragment *Fragment,
704 const MCFixup &Fixup,
706 uint64_t &FixedValue) {
709 int64_t Value = Target.getConstant();
710 const MCSymbol *RelocSymbol = NULL;
712 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
713 if (!Target.isAbsolute()) {
714 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
715 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
716 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
718 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
719 const MCSymbol &SymbolB = RefB->getSymbol();
720 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
723 // Offset of the symbol in the section
724 int64_t a = Layout.getSymbolOffset(&SDB);
726 // Offset of the relocation in the section
727 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
732 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
733 MCFragment *F = SD.getFragment();
736 Index = F->getParent()->getOrdinal() + 1;
737 // Offset of the symbol in the section
738 Value += Layout.getSymbolOffset(&SD);
743 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
744 WeakrefUsedInReloc.insert(RelocSymbol);
746 UsedInReloc.insert(RelocSymbol);
750 if (hasRelocationAddend())
755 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
756 (RelocSymbol != 0), Addend);
757 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
758 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
759 if (RelocNeedsGOT(Modifier))
762 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
765 if (!hasRelocationAddend())
769 assert(isInt<64>(Addend));
771 assert(isInt<32>(Addend));
773 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
774 Relocations[Fragment->getParent()].push_back(ERE);
779 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
781 MCSymbolData &SD = Asm.getSymbolData(*S);
782 return SD.getIndex();
785 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
786 const MCSymbolData &Data,
787 bool Used, bool Renamed) {
788 if (Data.getFlags() & ELF_Other_Weakref)
797 const MCSymbol &Symbol = Data.getSymbol();
799 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
802 const MCSymbol &A = Symbol.AliasedSymbol();
803 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
806 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
807 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
810 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
813 if (Symbol.isTemporary())
819 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
820 bool isUsedInReloc) {
821 if (Data.isExternal())
824 const MCSymbol &Symbol = Data.getSymbol();
825 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
827 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
828 if (isSignature && !isUsedInReloc)
837 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
838 SectionIndexMapTy &SectionIndexMap,
839 const RelMapTy &RelMap) {
841 for (MCAssembler::iterator it = Asm.begin(),
842 ie = Asm.end(); it != ie; ++it) {
843 const MCSectionELF &Section =
844 static_cast<const MCSectionELF &>(it->getSection());
845 if (Section.getType() != ELF::SHT_GROUP)
847 SectionIndexMap[&Section] = Index++;
850 for (MCAssembler::iterator it = Asm.begin(),
851 ie = Asm.end(); it != ie; ++it) {
852 const MCSectionELF &Section =
853 static_cast<const MCSectionELF &>(it->getSection());
854 if (Section.getType() == ELF::SHT_GROUP ||
855 Section.getType() == ELF::SHT_REL ||
856 Section.getType() == ELF::SHT_RELA)
858 SectionIndexMap[&Section] = Index++;
859 const MCSectionELF *RelSection = RelMap.lookup(&Section);
861 SectionIndexMap[RelSection] = Index++;
865 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
866 const SectionIndexMapTy &SectionIndexMap,
867 RevGroupMapTy RevGroupMap,
868 unsigned NumRegularSections) {
869 // FIXME: Is this the correct place to do this?
870 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
872 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
873 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
874 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
875 Data.setExternal(true);
876 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
879 // Index 0 is always the empty string.
880 StringMap<uint64_t> StringIndexMap;
881 StringTable += '\x00';
883 // FIXME: We could optimize suffixes in strtab in the same way we
884 // optimize them in shstrtab.
886 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
887 ie = Asm.file_names_end();
890 StringRef Name = *it;
891 uint64_t &Entry = StringIndexMap[Name];
893 Entry = StringTable.size();
895 StringTable += '\x00';
897 FileSymbolData.push_back(Entry);
900 // Add the data for the symbols.
901 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
902 ie = Asm.symbol_end(); it != ie; ++it) {
903 const MCSymbol &Symbol = it->getSymbol();
905 bool Used = UsedInReloc.count(&Symbol);
906 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
907 bool isSignature = RevGroupMap.count(&Symbol);
909 if (!isInSymtab(Asm, *it,
910 Used || WeakrefUsed || isSignature,
911 Renames.count(&Symbol)))
916 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
918 // Undefined symbols are global, but this is the first place we
919 // are able to set it.
920 bool Local = isLocal(*it, isSignature, Used);
921 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
922 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
923 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
924 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
927 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
928 MCELF::SetBinding(*it, ELF::STB_WEAK);
930 if (it->isCommon()) {
932 MSD.SectionIndex = ELF::SHN_COMMON;
933 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
934 MSD.SectionIndex = ELF::SHN_ABS;
935 } else if (RefSymbol.isUndefined()) {
936 if (isSignature && !Used)
937 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
939 MSD.SectionIndex = ELF::SHN_UNDEF;
941 const MCSectionELF &Section =
942 static_cast<const MCSectionELF&>(RefSymbol.getSection());
943 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
944 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
945 NeedsSymtabShndx = true;
946 assert(MSD.SectionIndex && "Invalid section index!");
949 // The @@@ in symbol version is replaced with @ in undefined symbols and
950 // @@ in defined ones.
951 StringRef Name = Symbol.getName();
954 size_t Pos = Name.find("@@@");
955 if (Pos != StringRef::npos) {
956 Buf += Name.substr(0, Pos);
957 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
958 Buf += Name.substr(Pos + Skip);
962 uint64_t &Entry = StringIndexMap[Name];
964 Entry = StringTable.size();
966 StringTable += '\x00';
968 MSD.StringIndex = Entry;
969 if (MSD.SectionIndex == ELF::SHN_UNDEF)
970 UndefinedSymbolData.push_back(MSD);
972 LocalSymbolData.push_back(MSD);
974 ExternalSymbolData.push_back(MSD);
977 // Symbols are required to be in lexicographic order.
978 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
979 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
980 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
982 // Set the symbol indices. Local symbols must come before all other
983 // symbols with non-local bindings.
984 unsigned Index = FileSymbolData.size() + 1;
985 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
986 LocalSymbolData[i].SymbolData->setIndex(Index++);
988 Index += NumRegularSections;
990 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
991 ExternalSymbolData[i].SymbolData->setIndex(Index++);
992 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
993 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
995 if (Index >= ELF::SHN_LORESERVE)
996 NeedsSymtabShndx = true;
999 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1000 MCAsmLayout &Layout,
1002 for (MCAssembler::const_iterator it = Asm.begin(),
1003 ie = Asm.end(); it != ie; ++it) {
1004 const MCSectionData &SD = *it;
1005 if (Relocations[&SD].empty())
1008 MCContext &Ctx = Asm.getContext();
1009 const MCSectionELF &Section =
1010 static_cast<const MCSectionELF&>(SD.getSection());
1012 const StringRef SectionName = Section.getSectionName();
1013 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1014 RelaSectionName += SectionName;
1017 if (hasRelocationAddend())
1018 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1020 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1023 StringRef Group = "";
1024 if (Section.getFlags() & ELF::SHF_GROUP) {
1025 Flags = ELF::SHF_GROUP;
1026 Group = Section.getGroup()->getName();
1029 const MCSectionELF *RelaSection =
1030 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1031 ELF::SHT_RELA : ELF::SHT_REL, Flags,
1032 SectionKind::getReadOnly(),
1034 RelMap[&Section] = RelaSection;
1035 Asm.getOrCreateSectionData(*RelaSection);
1039 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1040 const RelMapTy &RelMap) {
1041 for (MCAssembler::const_iterator it = Asm.begin(),
1042 ie = Asm.end(); it != ie; ++it) {
1043 const MCSectionData &SD = *it;
1044 const MCSectionELF &Section =
1045 static_cast<const MCSectionELF&>(SD.getSection());
1047 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1050 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1051 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1053 MCDataFragment *F = new MCDataFragment(&RelaSD);
1054 WriteRelocationsFragment(Asm, F, &*it);
1058 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1059 uint64_t Flags, uint64_t Address,
1060 uint64_t Offset, uint64_t Size,
1061 uint32_t Link, uint32_t Info,
1063 uint64_t EntrySize) {
1064 Write32(Name); // sh_name: index into string table
1065 Write32(Type); // sh_type
1066 WriteWord(Flags); // sh_flags
1067 WriteWord(Address); // sh_addr
1068 WriteWord(Offset); // sh_offset
1069 WriteWord(Size); // sh_size
1070 Write32(Link); // sh_link
1071 Write32(Info); // sh_info
1072 WriteWord(Alignment); // sh_addralign
1073 WriteWord(EntrySize); // sh_entsize
1076 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1078 const MCSectionData *SD) {
1079 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1081 // Sort the relocation entries. Most targets just sort by r_offset, but some
1082 // (e.g., MIPS) have additional constraints.
1083 TargetObjectWriter->sortRelocs(Asm, Relocs);
1085 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1086 ELFRelocationEntry entry = Relocs[e - i - 1];
1090 else if (entry.Index < 0)
1091 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1093 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
1095 String64(*F, entry.r_offset);
1096 if (TargetObjectWriter->isN64()) {
1097 String32(*F, entry.Index);
1099 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1100 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1101 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1102 String8(*F, TargetObjectWriter->getRType(entry.Type));
1105 struct ELF::Elf64_Rela ERE64;
1106 ERE64.setSymbolAndType(entry.Index, entry.Type);
1107 String64(*F, ERE64.r_info);
1109 if (hasRelocationAddend())
1110 String64(*F, entry.r_addend);
1112 String32(*F, entry.r_offset);
1114 struct ELF::Elf32_Rela ERE32;
1115 ERE32.setSymbolAndType(entry.Index, entry.Type);
1116 String32(*F, ERE32.r_info);
1118 if (hasRelocationAddend())
1119 String32(*F, entry.r_addend);
1124 static int compareBySuffix(const MCSectionELF *const *a,
1125 const MCSectionELF *const *b) {
1126 const StringRef &NameA = (*a)->getSectionName();
1127 const StringRef &NameB = (*b)->getSectionName();
1128 const unsigned sizeA = NameA.size();
1129 const unsigned sizeB = NameB.size();
1130 const unsigned len = std::min(sizeA, sizeB);
1131 for (unsigned int i = 0; i < len; ++i) {
1132 char ca = NameA[sizeA - i - 1];
1133 char cb = NameB[sizeB - i - 1];
1138 return sizeB - sizeA;
1141 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1142 MCAsmLayout &Layout,
1143 SectionIndexMapTy &SectionIndexMap,
1144 const RelMapTy &RelMap) {
1145 MCContext &Ctx = Asm.getContext();
1148 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1150 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1151 const MCSectionELF *ShstrtabSection =
1152 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1153 SectionKind::getReadOnly());
1154 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1155 ShstrtabSD.setAlignment(1);
1157 const MCSectionELF *SymtabSection =
1158 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1159 SectionKind::getReadOnly(),
1161 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1162 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1164 MCSectionData *SymtabShndxSD = NULL;
1166 if (NeedsSymtabShndx) {
1167 const MCSectionELF *SymtabShndxSection =
1168 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1169 SectionKind::getReadOnly(), 4, "");
1170 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1171 SymtabShndxSD->setAlignment(4);
1174 const MCSectionELF *StrtabSection;
1175 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1176 SectionKind::getReadOnly());
1177 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1178 StrtabSD.setAlignment(1);
1180 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1182 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1183 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1184 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1187 F = new MCDataFragment(&SymtabSD);
1188 MCDataFragment *ShndxF = NULL;
1189 if (NeedsSymtabShndx) {
1190 ShndxF = new MCDataFragment(SymtabShndxSD);
1192 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1194 F = new MCDataFragment(&StrtabSD);
1195 F->getContents().append(StringTable.begin(), StringTable.end());
1197 F = new MCDataFragment(&ShstrtabSD);
1199 std::vector<const MCSectionELF*> Sections;
1200 for (MCAssembler::const_iterator it = Asm.begin(),
1201 ie = Asm.end(); it != ie; ++it) {
1202 const MCSectionELF &Section =
1203 static_cast<const MCSectionELF&>(it->getSection());
1204 Sections.push_back(&Section);
1206 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1208 // Section header string table.
1210 // The first entry of a string table holds a null character so skip
1213 F->getContents().push_back('\x00');
1215 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1216 const MCSectionELF &Section = *Sections[I];
1218 StringRef Name = Section.getSectionName();
1220 StringRef PreviousName = Sections[I - 1]->getSectionName();
1221 if (PreviousName.endswith(Name)) {
1222 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1226 // Remember the index into the string table so we can write it
1227 // into the sh_name field of the section header table.
1228 SectionStringTableIndex[&Section] = Index;
1230 Index += Name.size() + 1;
1231 F->getContents().append(Name.begin(), Name.end());
1232 F->getContents().push_back('\x00');
1236 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1237 MCAsmLayout &Layout,
1238 GroupMapTy &GroupMap,
1239 RevGroupMapTy &RevGroupMap,
1240 SectionIndexMapTy &SectionIndexMap,
1241 const RelMapTy &RelMap) {
1242 // Create the .note.GNU-stack section if needed.
1243 MCContext &Ctx = Asm.getContext();
1244 if (Asm.getNoExecStack()) {
1245 const MCSectionELF *GnuStackSection =
1246 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1247 SectionKind::getReadOnly());
1248 Asm.getOrCreateSectionData(*GnuStackSection);
1252 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1254 const MCSectionELF &Section =
1255 static_cast<const MCSectionELF&>(it->getSection());
1256 if (!(Section.getFlags() & ELF::SHF_GROUP))
1259 const MCSymbol *SignatureSymbol = Section.getGroup();
1260 Asm.getOrCreateSymbolData(*SignatureSymbol);
1261 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1263 Group = Ctx.CreateELFGroupSection();
1264 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1265 Data.setAlignment(4);
1266 MCDataFragment *F = new MCDataFragment(&Data);
1267 String32(*F, ELF::GRP_COMDAT);
1269 GroupMap[Group] = SignatureSymbol;
1272 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1274 // Add sections to the groups
1275 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1277 const MCSectionELF &Section =
1278 static_cast<const MCSectionELF&>(it->getSection());
1279 if (!(Section.getFlags() & ELF::SHF_GROUP))
1281 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1282 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1283 // FIXME: we could use the previous fragment
1284 MCDataFragment *F = new MCDataFragment(&Data);
1285 unsigned Index = SectionIndexMap.lookup(&Section);
1286 String32(*F, Index);
1290 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1291 const SectionIndexMapTy &SectionIndexMap,
1292 uint32_t GroupSymbolIndex,
1293 uint64_t Offset, uint64_t Size,
1295 const MCSectionELF &Section) {
1296 uint64_t sh_link = 0;
1297 uint64_t sh_info = 0;
1299 switch(Section.getType()) {
1300 case ELF::SHT_DYNAMIC:
1301 sh_link = SectionStringTableIndex[&Section];
1306 case ELF::SHT_RELA: {
1307 const MCSectionELF *SymtabSection;
1308 const MCSectionELF *InfoSection;
1309 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1311 SectionKind::getReadOnly());
1312 sh_link = SectionIndexMap.lookup(SymtabSection);
1313 assert(sh_link && ".symtab not found");
1315 // Remove ".rel" and ".rela" prefixes.
1316 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1317 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1318 StringRef GroupName =
1319 Section.getGroup() ? Section.getGroup()->getName() : "";
1321 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1322 0, SectionKind::getReadOnly(),
1324 sh_info = SectionIndexMap.lookup(InfoSection);
1328 case ELF::SHT_SYMTAB:
1329 case ELF::SHT_DYNSYM:
1330 sh_link = StringTableIndex;
1331 sh_info = LastLocalSymbolIndex;
1334 case ELF::SHT_SYMTAB_SHNDX:
1335 sh_link = SymbolTableIndex;
1338 case ELF::SHT_PROGBITS:
1339 case ELF::SHT_STRTAB:
1340 case ELF::SHT_NOBITS:
1343 case ELF::SHT_ARM_ATTRIBUTES:
1344 case ELF::SHT_INIT_ARRAY:
1345 case ELF::SHT_FINI_ARRAY:
1346 case ELF::SHT_PREINIT_ARRAY:
1347 case ELF::SHT_X86_64_UNWIND:
1348 case ELF::SHT_MIPS_REGINFO:
1349 case ELF::SHT_MIPS_OPTIONS:
1353 case ELF::SHT_GROUP:
1354 sh_link = SymbolTableIndex;
1355 sh_info = GroupSymbolIndex;
1359 assert(0 && "FIXME: sh_type value not supported!");
1363 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1364 Section.getType() == ELF::SHT_ARM_EXIDX) {
1365 StringRef SecName(Section.getSectionName());
1366 if (SecName == ".ARM.exidx") {
1367 sh_link = SectionIndexMap.lookup(
1368 Asm.getContext().getELFSection(".text",
1370 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1371 SectionKind::getText()));
1372 } else if (SecName.startswith(".ARM.exidx")) {
1373 StringRef GroupName =
1374 Section.getGroup() ? Section.getGroup()->getName() : "";
1375 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1376 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1377 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1382 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1383 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1384 Alignment, Section.getEntrySize());
1387 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1388 return SD.getOrdinal() == ~UINT32_C(0) &&
1389 !SD.getSection().isVirtualSection();
1392 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1394 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1396 const MCFragment &F = *i;
1397 assert(F.getKind() == MCFragment::FT_Data);
1398 Ret += cast<MCDataFragment>(F).getContents().size();
1403 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1404 const MCSectionData &SD) {
1405 if (IsELFMetaDataSection(SD))
1406 return DataSectionSize(SD);
1407 return Layout.getSectionFileSize(&SD);
1410 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1411 const MCSectionData &SD) {
1412 if (IsELFMetaDataSection(SD))
1413 return DataSectionSize(SD);
1414 return Layout.getSectionAddressSize(&SD);
1417 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1418 const MCAsmLayout &Layout,
1419 const MCSectionELF &Section) {
1420 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1422 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1423 WriteZeros(Padding);
1425 if (IsELFMetaDataSection(SD)) {
1426 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1428 const MCFragment &F = *i;
1429 assert(F.getKind() == MCFragment::FT_Data);
1430 WriteBytes(cast<MCDataFragment>(F).getContents());
1433 Asm.writeSectionData(&SD, Layout);
1437 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1438 const GroupMapTy &GroupMap,
1439 const MCAsmLayout &Layout,
1440 const SectionIndexMapTy &SectionIndexMap,
1441 const SectionOffsetMapTy &SectionOffsetMap) {
1442 const unsigned NumSections = Asm.size() + 1;
1444 std::vector<const MCSectionELF*> Sections;
1445 Sections.resize(NumSections - 1);
1447 for (SectionIndexMapTy::const_iterator i=
1448 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1449 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1450 Sections[p.second - 1] = p.first;
1453 // Null section first.
1454 uint64_t FirstSectionSize =
1455 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1456 uint32_t FirstSectionLink =
1457 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1458 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1460 for (unsigned i = 0; i < NumSections - 1; ++i) {
1461 const MCSectionELF &Section = *Sections[i];
1462 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1463 uint32_t GroupSymbolIndex;
1464 if (Section.getType() != ELF::SHT_GROUP)
1465 GroupSymbolIndex = 0;
1467 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1468 GroupMap.lookup(&Section));
1470 uint64_t Size = GetSectionAddressSize(Layout, SD);
1472 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1473 SectionOffsetMap.lookup(&Section), Size,
1474 SD.getAlignment(), Section);
1478 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1479 std::vector<const MCSectionELF*> &Sections) {
1480 for (MCAssembler::iterator it = Asm.begin(),
1481 ie = Asm.end(); it != ie; ++it) {
1482 const MCSectionELF &Section =
1483 static_cast<const MCSectionELF &>(it->getSection());
1484 if (Section.getType() == ELF::SHT_GROUP)
1485 Sections.push_back(&Section);
1488 for (MCAssembler::iterator it = Asm.begin(),
1489 ie = Asm.end(); it != ie; ++it) {
1490 const MCSectionELF &Section =
1491 static_cast<const MCSectionELF &>(it->getSection());
1492 if (Section.getType() != ELF::SHT_GROUP &&
1493 Section.getType() != ELF::SHT_REL &&
1494 Section.getType() != ELF::SHT_RELA)
1495 Sections.push_back(&Section);
1498 for (MCAssembler::iterator it = Asm.begin(),
1499 ie = Asm.end(); it != ie; ++it) {
1500 const MCSectionELF &Section =
1501 static_cast<const MCSectionELF &>(it->getSection());
1502 if (Section.getType() == ELF::SHT_REL ||
1503 Section.getType() == ELF::SHT_RELA)
1504 Sections.push_back(&Section);
1508 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1509 const MCAsmLayout &Layout) {
1510 GroupMapTy GroupMap;
1511 RevGroupMapTy RevGroupMap;
1512 SectionIndexMapTy SectionIndexMap;
1514 unsigned NumUserSections = Asm.size();
1516 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1517 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1519 const unsigned NumUserAndRelocSections = Asm.size();
1520 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1521 RevGroupMap, SectionIndexMap, RelMap);
1522 const unsigned AllSections = Asm.size();
1523 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1525 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1527 // Compute symbol table information.
1528 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1531 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1533 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1534 const_cast<MCAsmLayout&>(Layout),
1538 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1539 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1540 sizeof(ELF::Elf32_Ehdr);
1541 uint64_t FileOff = HeaderSize;
1543 std::vector<const MCSectionELF*> Sections;
1544 ComputeSectionOrder(Asm, Sections);
1545 unsigned NumSections = Sections.size();
1546 SectionOffsetMapTy SectionOffsetMap;
1547 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1548 const MCSectionELF &Section = *Sections[i];
1549 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1551 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1553 // Remember the offset into the file for this section.
1554 SectionOffsetMap[&Section] = FileOff;
1556 // Get the size of the section in the output file (including padding).
1557 FileOff += GetSectionFileSize(Layout, SD);
1560 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1562 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1564 uint64_t SectionHeaderEntrySize = is64Bit() ?
1565 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1566 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1568 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1569 const MCSectionELF &Section = *Sections[i];
1570 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1572 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1574 // Remember the offset into the file for this section.
1575 SectionOffsetMap[&Section] = FileOff;
1577 // Get the size of the section in the output file (including padding).
1578 FileOff += GetSectionFileSize(Layout, SD);
1581 // Write out the ELF header ...
1582 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
1584 // ... then the regular sections ...
1585 // + because of .shstrtab
1586 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1587 WriteDataSectionData(Asm, Layout, *Sections[i]);
1589 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1590 WriteZeros(Padding);
1592 // ... then the section header table ...
1593 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1596 // ... and then the remaining sections ...
1597 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1598 WriteDataSectionData(Asm, Layout, *Sections[i]);
1602 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1603 const MCSymbolData &DataA,
1604 const MCFragment &FB,
1606 bool IsPCRel) const {
1607 if (DataA.getFlags() & ELF_STB_Weak)
1609 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1610 Asm, DataA, FB,InSet, IsPCRel);
1613 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1615 bool IsLittleEndian) {
1616 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);