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 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/STLExtras.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/MCELFObjectWriter.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/ErrorHandling.h"
33 #include "llvm/Support/ELF.h"
39 #define DEBUG_TYPE "reloc-info"
42 class ELFObjectWriter : public MCObjectWriter {
45 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
46 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
47 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
48 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
49 bool Used, bool Renamed);
50 static bool isLocal(const MCSymbolData &Data, bool isSignature,
52 static bool IsELFMetaDataSection(const MCSectionData &SD);
53 static uint64_t DataSectionSize(const MCSectionData &SD);
54 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
55 const MCSectionData &SD);
56 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
57 const MCSectionData &SD);
59 void WriteDataSectionData(MCAssembler &Asm,
60 const MCAsmLayout &Layout,
61 const MCSectionELF &Section);
63 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
64 return Kind == X86::reloc_riprel_4byte ||
65 Kind == X86::reloc_riprel_4byte_movq_load;
68 /// ELFSymbolData - Helper struct for containing some precomputed
69 /// information on symbols.
70 struct ELFSymbolData {
71 MCSymbolData *SymbolData;
73 uint32_t SectionIndex;
75 // Support lexicographic sorting.
76 bool operator<(const ELFSymbolData &RHS) const {
77 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
79 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
81 return SymbolData->getSymbol().getName() <
82 RHS.SymbolData->getSymbol().getName();
86 /// The target specific ELF writer instance.
87 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
89 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
90 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
91 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
93 llvm::DenseMap<const MCSectionData*,
94 std::vector<ELFRelocationEntry> > Relocations;
95 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
98 /// @name Symbol Table Data
101 SmallString<256> StringTable;
102 std::vector<ELFSymbolData> LocalSymbolData;
103 std::vector<ELFSymbolData> ExternalSymbolData;
104 std::vector<ELFSymbolData> UndefinedSymbolData;
110 bool NeedsSymtabShndx;
112 // This holds the symbol table index of the last local symbol.
113 unsigned LastLocalSymbolIndex;
114 // This holds the .strtab section index.
115 unsigned StringTableIndex;
116 // This holds the .symtab section index.
117 unsigned SymbolTableIndex;
119 unsigned ShstrtabIndex;
122 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
123 const MCValue &Target,
125 const MCFixup &Fixup,
128 // TargetObjectWriter wrappers.
129 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
130 const MCValue &Target,
132 const MCFixup &Fixup,
133 bool IsPCRel) const {
134 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
136 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
137 const MCFixup &Fixup,
138 bool IsPCRel) const {
139 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup, IsPCRel);
142 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
143 bool hasRelocationAddend() const {
144 return TargetObjectWriter->hasRelocationAddend();
146 unsigned getEFlags() const {
147 return TargetObjectWriter->getEFlags();
149 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
150 bool IsPCRel, bool IsRelocWithSymbol,
151 int64_t Addend) const {
152 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
153 IsRelocWithSymbol, Addend);
158 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
159 raw_ostream &_OS, bool IsLittleEndian)
160 : MCObjectWriter(_OS, IsLittleEndian),
161 TargetObjectWriter(MOTW),
162 NeedsGOT(false), NeedsSymtabShndx(false){
165 virtual ~ELFObjectWriter();
167 void WriteWord(uint64_t W) {
174 void StringLE16(char *buf, uint16_t Value) {
175 buf[0] = char(Value >> 0);
176 buf[1] = char(Value >> 8);
179 void StringLE32(char *buf, uint32_t Value) {
180 StringLE16(buf, uint16_t(Value >> 0));
181 StringLE16(buf + 2, uint16_t(Value >> 16));
184 void StringLE64(char *buf, uint64_t Value) {
185 StringLE32(buf, uint32_t(Value >> 0));
186 StringLE32(buf + 4, uint32_t(Value >> 32));
189 void StringBE16(char *buf ,uint16_t Value) {
190 buf[0] = char(Value >> 8);
191 buf[1] = char(Value >> 0);
194 void StringBE32(char *buf, uint32_t Value) {
195 StringBE16(buf, uint16_t(Value >> 16));
196 StringBE16(buf + 2, uint16_t(Value >> 0));
199 void StringBE64(char *buf, uint64_t Value) {
200 StringBE32(buf, uint32_t(Value >> 32));
201 StringBE32(buf + 4, uint32_t(Value >> 0));
204 void String8(MCDataFragment &F, uint8_t Value) {
207 F.getContents() += StringRef(buf, 1);
210 void String16(MCDataFragment &F, uint16_t Value) {
212 if (isLittleEndian())
213 StringLE16(buf, Value);
215 StringBE16(buf, Value);
216 F.getContents() += StringRef(buf, 2);
219 void String32(MCDataFragment &F, uint32_t Value) {
221 if (isLittleEndian())
222 StringLE32(buf, Value);
224 StringBE32(buf, Value);
225 F.getContents() += StringRef(buf, 4);
228 void String64(MCDataFragment &F, uint64_t Value) {
230 if (isLittleEndian())
231 StringLE64(buf, Value);
233 StringBE64(buf, Value);
234 F.getContents() += StringRef(buf, 8);
237 void WriteHeader(uint64_t SectionDataSize,
238 unsigned NumberOfSections);
240 void WriteSymbolEntry(MCDataFragment *SymtabF,
241 MCDataFragment *ShndxF,
242 uint64_t name, uint8_t info,
243 uint64_t value, uint64_t size,
244 uint8_t other, uint32_t shndx,
247 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
249 const MCAsmLayout &Layout);
251 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
252 void WriteSymbolTable(MCDataFragment *SymtabF,
253 MCDataFragment *ShndxF,
254 const MCAssembler &Asm,
255 const MCAsmLayout &Layout,
256 const SectionIndexMapTy &SectionIndexMap);
258 virtual void RecordRelocation(const MCAssembler &Asm,
259 const MCAsmLayout &Layout,
260 const MCFragment *Fragment,
261 const MCFixup &Fixup,
262 MCValue Target, uint64_t &FixedValue);
264 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
267 // Map from a group section to the signature symbol
268 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
269 // Map from a signature symbol to the group section
270 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
271 // Map from a section to the section with the relocations
272 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
273 // Map from a section to its offset
274 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
276 /// ComputeSymbolTable - Compute the symbol table data
278 /// \param Asm - The assembler.
279 /// \param SectionIndexMap - Maps a section to its index.
280 /// \param RevGroupMap - Maps a signature symbol to the group section.
281 /// \param NumRegularSections - Number of non-relocation sections.
282 void ComputeSymbolTable(MCAssembler &Asm,
283 const SectionIndexMapTy &SectionIndexMap,
284 RevGroupMapTy RevGroupMap,
285 unsigned NumRegularSections);
287 void ComputeIndexMap(MCAssembler &Asm,
288 SectionIndexMapTy &SectionIndexMap,
289 const RelMapTy &RelMap);
291 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
294 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
295 const RelMapTy &RelMap);
297 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
298 SectionIndexMapTy &SectionIndexMap,
299 const RelMapTy &RelMap);
301 // Create the sections that show up in the symbol table. Currently
302 // those are the .note.GNU-stack section and the group sections.
303 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
304 GroupMapTy &GroupMap,
305 RevGroupMapTy &RevGroupMap,
306 SectionIndexMapTy &SectionIndexMap,
307 const RelMapTy &RelMap);
309 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
310 const MCAsmLayout &Layout);
312 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
313 const MCAsmLayout &Layout,
314 const SectionIndexMapTy &SectionIndexMap,
315 const SectionOffsetMapTy &SectionOffsetMap);
317 void ComputeSectionOrder(MCAssembler &Asm,
318 std::vector<const MCSectionELF*> &Sections);
320 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
321 uint64_t Address, uint64_t Offset,
322 uint64_t Size, uint32_t Link, uint32_t Info,
323 uint64_t Alignment, uint64_t EntrySize);
325 void WriteRelocationsFragment(const MCAssembler &Asm,
327 const MCSectionData *SD);
330 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
331 const MCSymbolData &DataA,
332 const MCFragment &FB,
336 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
337 void WriteSection(MCAssembler &Asm,
338 const SectionIndexMapTy &SectionIndexMap,
339 uint32_t GroupSymbolIndex,
340 uint64_t Offset, uint64_t Size, uint64_t Alignment,
341 const MCSectionELF &Section);
345 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
346 const MCFixupKindInfo &FKI =
347 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
349 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
352 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
356 case MCSymbolRefExpr::VK_GOT:
357 case MCSymbolRefExpr::VK_PLT:
358 case MCSymbolRefExpr::VK_GOTPCREL:
359 case MCSymbolRefExpr::VK_GOTOFF:
360 case MCSymbolRefExpr::VK_TPOFF:
361 case MCSymbolRefExpr::VK_TLSGD:
362 case MCSymbolRefExpr::VK_GOTTPOFF:
363 case MCSymbolRefExpr::VK_INDNTPOFF:
364 case MCSymbolRefExpr::VK_NTPOFF:
365 case MCSymbolRefExpr::VK_GOTNTPOFF:
366 case MCSymbolRefExpr::VK_TLSLDM:
367 case MCSymbolRefExpr::VK_DTPOFF:
368 case MCSymbolRefExpr::VK_TLSLD:
373 ELFObjectWriter::~ELFObjectWriter()
376 // Emit the ELF header.
377 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
378 unsigned NumberOfSections) {
384 // emitWord method behaves differently for ELF32 and ELF64, writing
385 // 4 bytes in the former and 8 in the latter.
387 Write8(0x7f); // e_ident[EI_MAG0]
388 Write8('E'); // e_ident[EI_MAG1]
389 Write8('L'); // e_ident[EI_MAG2]
390 Write8('F'); // e_ident[EI_MAG3]
392 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
395 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
397 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
399 Write8(TargetObjectWriter->getOSABI());
400 Write8(0); // e_ident[EI_ABIVERSION]
402 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
404 Write16(ELF::ET_REL); // e_type
406 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
408 Write32(ELF::EV_CURRENT); // e_version
409 WriteWord(0); // e_entry, no entry point in .o file
410 WriteWord(0); // e_phoff, no program header for .o
411 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
412 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
414 // e_flags = whatever the target wants
415 Write32(getEFlags());
417 // e_ehsize = ELF header size
418 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
420 Write16(0); // e_phentsize = prog header entry size
421 Write16(0); // e_phnum = # prog header entries = 0
423 // e_shentsize = Section header entry size
424 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
426 // e_shnum = # of section header ents
427 if (NumberOfSections >= ELF::SHN_LORESERVE)
428 Write16(ELF::SHN_UNDEF);
430 Write16(NumberOfSections);
432 // e_shstrndx = Section # of '.shstrtab'
433 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
434 Write16(ELF::SHN_XINDEX);
436 Write16(ShstrtabIndex);
439 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
440 MCDataFragment *ShndxF,
442 uint8_t info, uint64_t value,
443 uint64_t size, uint8_t other,
447 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
448 String32(*ShndxF, shndx);
450 String32(*ShndxF, 0);
453 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
454 uint16_t(ELF::SHN_XINDEX) : shndx;
457 String32(*SymtabF, name); // st_name
458 String8(*SymtabF, info); // st_info
459 String8(*SymtabF, other); // st_other
460 String16(*SymtabF, Index); // st_shndx
461 String64(*SymtabF, value); // st_value
462 String64(*SymtabF, size); // st_size
464 String32(*SymtabF, name); // st_name
465 String32(*SymtabF, value); // st_value
466 String32(*SymtabF, size); // st_size
467 String8(*SymtabF, info); // st_info
468 String8(*SymtabF, other); // st_other
469 String16(*SymtabF, Index); // st_shndx
473 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
474 const MCAsmLayout &Layout) {
475 if (Data.isCommon() && Data.isExternal())
476 return Data.getCommonAlignment();
478 const MCSymbol &Symbol = Data.getSymbol();
480 if (Symbol.isAbsolute() && Symbol.isVariable()) {
481 if (const MCExpr *Value = Symbol.getVariableValue()) {
483 if (Value->EvaluateAsAbsolute(IntValue, Layout))
484 return (uint64_t)IntValue;
488 if (!Symbol.isInSection())
492 if (Data.getFragment()) {
493 if (Data.getFlags() & ELF_Other_ThumbFunc)
494 return Layout.getSymbolOffset(&Data)+1;
496 return Layout.getSymbolOffset(&Data);
502 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
503 const MCAsmLayout &Layout) {
504 // The presence of symbol versions causes undefined symbols and
505 // versions declared with @@@ to be renamed.
507 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
508 ie = Asm.symbol_end(); it != ie; ++it) {
509 const MCSymbol &Alias = it->getSymbol();
510 const MCSymbol &Symbol = Alias.AliasedSymbol();
511 MCSymbolData &SD = Asm.getSymbolData(Symbol);
514 if (&Symbol == &Alias)
517 StringRef AliasName = Alias.getName();
518 size_t Pos = AliasName.find('@');
519 if (Pos == StringRef::npos)
522 // Aliases defined with .symvar copy the binding from the symbol they alias.
523 // This is the first place we are able to copy this information.
524 it->setExternal(SD.isExternal());
525 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
527 StringRef Rest = AliasName.substr(Pos);
528 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
531 // FIXME: produce a better error message.
532 if (Symbol.isUndefined() && Rest.startswith("@@") &&
533 !Rest.startswith("@@@"))
534 report_fatal_error("A @@ version cannot be undefined");
536 Renames.insert(std::make_pair(&Symbol, &Alias));
540 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
541 MCDataFragment *ShndxF,
543 const MCAsmLayout &Layout) {
544 MCSymbolData &OrigData = *MSD.SymbolData;
546 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
548 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
549 Data.getSymbol().isVariable();
551 uint8_t Binding = MCELF::GetBinding(OrigData);
552 uint8_t Visibility = MCELF::GetVisibility(OrigData);
553 uint8_t Type = MCELF::GetType(Data);
555 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
556 uint8_t Other = Visibility;
558 uint64_t Value = SymbolValue(Data, Layout);
561 assert(!(Data.isCommon() && !Data.isExternal()));
563 const MCExpr *ESize = Data.getSize();
566 if (!ESize->EvaluateAsAbsolute(Res, Layout))
567 report_fatal_error("Size expression must be absolute.");
571 // Write out the symbol table entry
572 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
573 Size, Other, MSD.SectionIndex, IsReserved);
576 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
577 MCDataFragment *ShndxF,
578 const MCAssembler &Asm,
579 const MCAsmLayout &Layout,
580 const SectionIndexMapTy &SectionIndexMap) {
581 // The string table must be emitted first because we need the index
582 // into the string table for all the symbol names.
583 assert(StringTable.size() && "Missing string table");
585 // FIXME: Make sure the start of the symbol table is aligned.
587 // The first entry is the undefined symbol entry.
588 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
590 // Write the symbol table entries.
591 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
592 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
593 ELFSymbolData &MSD = LocalSymbolData[i];
594 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
597 // Write out a symbol table entry for each regular section.
598 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
600 const MCSectionELF &Section =
601 static_cast<const MCSectionELF&>(i->getSection());
602 if (Section.getType() == ELF::SHT_RELA ||
603 Section.getType() == ELF::SHT_REL ||
604 Section.getType() == ELF::SHT_STRTAB ||
605 Section.getType() == ELF::SHT_SYMTAB ||
606 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
608 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
609 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
611 LastLocalSymbolIndex++;
614 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
615 ELFSymbolData &MSD = ExternalSymbolData[i];
616 MCSymbolData &Data = *MSD.SymbolData;
617 assert(((Data.getFlags() & ELF_STB_Global) ||
618 (Data.getFlags() & ELF_STB_Weak)) &&
619 "External symbol requires STB_GLOBAL or STB_WEAK flag");
620 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
621 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
622 LastLocalSymbolIndex++;
625 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
626 ELFSymbolData &MSD = UndefinedSymbolData[i];
627 MCSymbolData &Data = *MSD.SymbolData;
628 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
629 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
630 LastLocalSymbolIndex++;
634 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
635 const MCValue &Target,
637 const MCFixup &Fixup,
638 bool IsPCRel) const {
639 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
640 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
641 const MCSymbol *Renamed = Renames.lookup(&Symbol);
642 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
644 if (ASymbol.isUndefined()) {
647 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
650 if (SD.isExternal()) {
656 const MCSectionELF &Section =
657 static_cast<const MCSectionELF&>(ASymbol.getSection());
658 const SectionKind secKind = Section.getKind();
661 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
663 if (secKind.isThreadLocal()) {
669 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
670 const MCSectionELF &Sec2 =
671 static_cast<const MCSectionELF&>(F.getParent()->getSection());
673 if (&Sec2 != &Section &&
674 (Kind == MCSymbolRefExpr::VK_PLT ||
675 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
676 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
682 if (Section.getFlags() & ELF::SHF_MERGE) {
683 if (Target.getConstant() == 0)
684 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
690 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
695 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
696 const MCAsmLayout &Layout,
697 const MCFragment *Fragment,
698 const MCFixup &Fixup,
700 uint64_t &FixedValue) {
703 int64_t Value = Target.getConstant();
704 const MCSymbol *RelocSymbol = NULL;
706 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
707 if (!Target.isAbsolute()) {
708 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
709 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
710 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
712 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
713 const MCSymbol &SymbolB = RefB->getSymbol();
714 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
717 // Offset of the symbol in the section
718 int64_t a = Layout.getSymbolOffset(&SDB);
720 // Offset of the relocation in the section
721 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
726 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
727 MCFragment *F = SD.getFragment();
730 Index = F->getParent()->getOrdinal() + 1;
731 // Offset of the symbol in the section
732 Value += Layout.getSymbolOffset(&SD);
737 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
738 WeakrefUsedInReloc.insert(RelocSymbol);
740 UsedInReloc.insert(RelocSymbol);
744 if (hasRelocationAddend())
749 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
750 (RelocSymbol != 0), Addend);
751 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
752 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
753 if (RelocNeedsGOT(Modifier))
756 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
759 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
760 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
762 if (!hasRelocationAddend())
766 assert(isInt<64>(Addend));
768 assert(isInt<32>(Addend));
770 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
771 Relocations[Fragment->getParent()].push_back(ERE);
776 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
778 MCSymbolData &SD = Asm.getSymbolData(*S);
779 return SD.getIndex();
782 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
783 const MCSymbolData &Data,
784 bool Used, bool Renamed) {
785 if (Data.getFlags() & ELF_Other_Weakref)
794 const MCSymbol &Symbol = Data.getSymbol();
796 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
799 const MCSymbol &A = Symbol.AliasedSymbol();
800 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
803 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
804 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
807 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
810 if (Symbol.isTemporary())
816 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
817 bool isUsedInReloc) {
818 if (Data.isExternal())
821 const MCSymbol &Symbol = Data.getSymbol();
822 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
824 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
825 if (isSignature && !isUsedInReloc)
834 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
835 SectionIndexMapTy &SectionIndexMap,
836 const RelMapTy &RelMap) {
838 for (MCAssembler::iterator it = Asm.begin(),
839 ie = Asm.end(); it != ie; ++it) {
840 const MCSectionELF &Section =
841 static_cast<const MCSectionELF &>(it->getSection());
842 if (Section.getType() != ELF::SHT_GROUP)
844 SectionIndexMap[&Section] = Index++;
847 for (MCAssembler::iterator it = Asm.begin(),
848 ie = Asm.end(); it != ie; ++it) {
849 const MCSectionELF &Section =
850 static_cast<const MCSectionELF &>(it->getSection());
851 if (Section.getType() == ELF::SHT_GROUP ||
852 Section.getType() == ELF::SHT_REL ||
853 Section.getType() == ELF::SHT_RELA)
855 SectionIndexMap[&Section] = Index++;
856 const MCSectionELF *RelSection = RelMap.lookup(&Section);
858 SectionIndexMap[RelSection] = Index++;
862 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
863 const SectionIndexMapTy &SectionIndexMap,
864 RevGroupMapTy RevGroupMap,
865 unsigned NumRegularSections) {
866 // FIXME: Is this the correct place to do this?
867 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
869 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
870 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
871 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
872 Data.setExternal(true);
873 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
876 // Index 0 is always the empty string.
877 StringMap<uint64_t> StringIndexMap;
878 StringTable += '\x00';
880 // FIXME: We could optimize suffixes in strtab in the same way we
881 // optimize them in shstrtab.
883 // Add the data for the symbols.
884 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
885 ie = Asm.symbol_end(); it != ie; ++it) {
886 const MCSymbol &Symbol = it->getSymbol();
888 bool Used = UsedInReloc.count(&Symbol);
889 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
890 bool isSignature = RevGroupMap.count(&Symbol);
892 if (!isInSymtab(Asm, *it,
893 Used || WeakrefUsed || isSignature,
894 Renames.count(&Symbol)))
899 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
901 // Undefined symbols are global, but this is the first place we
902 // are able to set it.
903 bool Local = isLocal(*it, isSignature, Used);
904 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
905 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
906 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
907 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
910 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
911 MCELF::SetBinding(*it, ELF::STB_WEAK);
913 if (it->isCommon()) {
915 MSD.SectionIndex = ELF::SHN_COMMON;
916 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
917 MSD.SectionIndex = ELF::SHN_ABS;
918 } else if (RefSymbol.isUndefined()) {
919 if (isSignature && !Used)
920 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
922 MSD.SectionIndex = ELF::SHN_UNDEF;
924 const MCSectionELF &Section =
925 static_cast<const MCSectionELF&>(RefSymbol.getSection());
926 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
927 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
928 NeedsSymtabShndx = true;
929 assert(MSD.SectionIndex && "Invalid section index!");
932 // The @@@ in symbol version is replaced with @ in undefined symbols and
933 // @@ in defined ones.
934 StringRef Name = Symbol.getName();
937 size_t Pos = Name.find("@@@");
938 if (Pos != StringRef::npos) {
939 Buf += Name.substr(0, Pos);
940 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
941 Buf += Name.substr(Pos + Skip);
945 uint64_t &Entry = StringIndexMap[Name];
947 Entry = StringTable.size();
949 StringTable += '\x00';
951 MSD.StringIndex = Entry;
952 if (MSD.SectionIndex == ELF::SHN_UNDEF)
953 UndefinedSymbolData.push_back(MSD);
955 LocalSymbolData.push_back(MSD);
957 ExternalSymbolData.push_back(MSD);
960 // Symbols are required to be in lexicographic order.
961 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
962 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
963 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
965 // Set the symbol indices. Local symbols must come before all other
966 // symbols with non-local bindings.
968 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
969 LocalSymbolData[i].SymbolData->setIndex(Index++);
971 Index += NumRegularSections;
973 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
974 ExternalSymbolData[i].SymbolData->setIndex(Index++);
975 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
976 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
978 if (NumRegularSections > ELF::SHN_LORESERVE)
979 NeedsSymtabShndx = true;
982 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
985 for (MCAssembler::const_iterator it = Asm.begin(),
986 ie = Asm.end(); it != ie; ++it) {
987 const MCSectionData &SD = *it;
988 if (Relocations[&SD].empty())
991 MCContext &Ctx = Asm.getContext();
992 const MCSectionELF &Section =
993 static_cast<const MCSectionELF&>(SD.getSection());
995 const StringRef SectionName = Section.getSectionName();
996 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
997 RelaSectionName += SectionName;
1000 if (hasRelocationAddend())
1001 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1003 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1005 const MCSectionELF *RelaSection =
1006 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1007 ELF::SHT_RELA : ELF::SHT_REL, 0,
1008 SectionKind::getReadOnly(),
1010 RelMap[&Section] = RelaSection;
1011 Asm.getOrCreateSectionData(*RelaSection);
1015 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1016 const RelMapTy &RelMap) {
1017 for (MCAssembler::const_iterator it = Asm.begin(),
1018 ie = Asm.end(); it != ie; ++it) {
1019 const MCSectionData &SD = *it;
1020 const MCSectionELF &Section =
1021 static_cast<const MCSectionELF&>(SD.getSection());
1023 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1026 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1027 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1029 MCDataFragment *F = new MCDataFragment(&RelaSD);
1030 WriteRelocationsFragment(Asm, F, &*it);
1034 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1035 uint64_t Flags, uint64_t Address,
1036 uint64_t Offset, uint64_t Size,
1037 uint32_t Link, uint32_t Info,
1039 uint64_t EntrySize) {
1040 Write32(Name); // sh_name: index into string table
1041 Write32(Type); // sh_type
1042 WriteWord(Flags); // sh_flags
1043 WriteWord(Address); // sh_addr
1044 WriteWord(Offset); // sh_offset
1045 WriteWord(Size); // sh_size
1046 Write32(Link); // sh_link
1047 Write32(Info); // sh_info
1048 WriteWord(Alignment); // sh_addralign
1049 WriteWord(EntrySize); // sh_entsize
1052 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1054 const MCSectionData *SD) {
1055 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1057 // Sort the relocation entries. Most targets just sort by r_offset, but some
1058 // (e.g., MIPS) have additional constraints.
1059 TargetObjectWriter->sortRelocs(Asm, Relocs);
1061 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1062 ELFRelocationEntry entry = Relocs[e - i - 1];
1066 else if (entry.Index < 0)
1067 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1069 entry.Index += LocalSymbolData.size();
1071 String64(*F, entry.r_offset);
1072 if (TargetObjectWriter->isN64()) {
1073 String32(*F, entry.Index);
1075 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1076 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1077 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1078 String8(*F, TargetObjectWriter->getRType(entry.Type));
1081 struct ELF::Elf64_Rela ERE64;
1082 ERE64.setSymbolAndType(entry.Index, entry.Type);
1083 String64(*F, ERE64.r_info);
1085 if (hasRelocationAddend())
1086 String64(*F, entry.r_addend);
1088 String32(*F, entry.r_offset);
1090 struct ELF::Elf32_Rela ERE32;
1091 ERE32.setSymbolAndType(entry.Index, entry.Type);
1092 String32(*F, ERE32.r_info);
1094 if (hasRelocationAddend())
1095 String32(*F, entry.r_addend);
1100 static int compareBySuffix(const void *a, const void *b) {
1101 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1102 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1103 const StringRef &NameA = secA->getSectionName();
1104 const StringRef &NameB = secB->getSectionName();
1105 const unsigned sizeA = NameA.size();
1106 const unsigned sizeB = NameB.size();
1107 const unsigned len = std::min(sizeA, sizeB);
1108 for (unsigned int i = 0; i < len; ++i) {
1109 char ca = NameA[sizeA - i - 1];
1110 char cb = NameB[sizeB - i - 1];
1115 return sizeB - sizeA;
1118 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1119 MCAsmLayout &Layout,
1120 SectionIndexMapTy &SectionIndexMap,
1121 const RelMapTy &RelMap) {
1122 MCContext &Ctx = Asm.getContext();
1125 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1127 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1128 const MCSectionELF *ShstrtabSection =
1129 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1130 SectionKind::getReadOnly());
1131 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1132 ShstrtabSD.setAlignment(1);
1134 const MCSectionELF *SymtabSection =
1135 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1136 SectionKind::getReadOnly(),
1138 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1139 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1141 MCSectionData *SymtabShndxSD = NULL;
1143 if (NeedsSymtabShndx) {
1144 const MCSectionELF *SymtabShndxSection =
1145 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1146 SectionKind::getReadOnly(), 4, "");
1147 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1148 SymtabShndxSD->setAlignment(4);
1151 const MCSectionELF *StrtabSection;
1152 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1153 SectionKind::getReadOnly());
1154 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1155 StrtabSD.setAlignment(1);
1157 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1159 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1160 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1161 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1164 F = new MCDataFragment(&SymtabSD);
1165 MCDataFragment *ShndxF = NULL;
1166 if (NeedsSymtabShndx) {
1167 ShndxF = new MCDataFragment(SymtabShndxSD);
1169 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1171 F = new MCDataFragment(&StrtabSD);
1172 F->getContents().append(StringTable.begin(), StringTable.end());
1174 F = new MCDataFragment(&ShstrtabSD);
1176 std::vector<const MCSectionELF*> Sections;
1177 for (MCAssembler::const_iterator it = Asm.begin(),
1178 ie = Asm.end(); it != ie; ++it) {
1179 const MCSectionELF &Section =
1180 static_cast<const MCSectionELF&>(it->getSection());
1181 Sections.push_back(&Section);
1183 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1185 // Section header string table.
1187 // The first entry of a string table holds a null character so skip
1190 F->getContents() += '\x00';
1192 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1193 const MCSectionELF &Section = *Sections[I];
1195 StringRef Name = Section.getSectionName();
1197 StringRef PreviousName = Sections[I - 1]->getSectionName();
1198 if (PreviousName.endswith(Name)) {
1199 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1203 // Remember the index into the string table so we can write it
1204 // into the sh_name field of the section header table.
1205 SectionStringTableIndex[&Section] = Index;
1207 Index += Name.size() + 1;
1208 F->getContents() += Name;
1209 F->getContents() += '\x00';
1213 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1214 MCAsmLayout &Layout,
1215 GroupMapTy &GroupMap,
1216 RevGroupMapTy &RevGroupMap,
1217 SectionIndexMapTy &SectionIndexMap,
1218 const RelMapTy &RelMap) {
1219 // Create the .note.GNU-stack section if needed.
1220 MCContext &Ctx = Asm.getContext();
1221 if (Asm.getNoExecStack()) {
1222 const MCSectionELF *GnuStackSection =
1223 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1224 SectionKind::getReadOnly());
1225 Asm.getOrCreateSectionData(*GnuStackSection);
1229 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1231 const MCSectionELF &Section =
1232 static_cast<const MCSectionELF&>(it->getSection());
1233 if (!(Section.getFlags() & ELF::SHF_GROUP))
1236 const MCSymbol *SignatureSymbol = Section.getGroup();
1237 Asm.getOrCreateSymbolData(*SignatureSymbol);
1238 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1240 Group = Ctx.CreateELFGroupSection();
1241 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1242 Data.setAlignment(4);
1243 MCDataFragment *F = new MCDataFragment(&Data);
1244 String32(*F, ELF::GRP_COMDAT);
1246 GroupMap[Group] = SignatureSymbol;
1249 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1251 // Add sections to the groups
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))
1258 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1259 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1260 // FIXME: we could use the previous fragment
1261 MCDataFragment *F = new MCDataFragment(&Data);
1262 unsigned Index = SectionIndexMap.lookup(&Section);
1263 String32(*F, Index);
1267 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1268 const SectionIndexMapTy &SectionIndexMap,
1269 uint32_t GroupSymbolIndex,
1270 uint64_t Offset, uint64_t Size,
1272 const MCSectionELF &Section) {
1273 uint64_t sh_link = 0;
1274 uint64_t sh_info = 0;
1276 switch(Section.getType()) {
1277 case ELF::SHT_DYNAMIC:
1278 sh_link = SectionStringTableIndex[&Section];
1283 case ELF::SHT_RELA: {
1284 const MCSectionELF *SymtabSection;
1285 const MCSectionELF *InfoSection;
1286 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1288 SectionKind::getReadOnly());
1289 sh_link = SectionIndexMap.lookup(SymtabSection);
1290 assert(sh_link && ".symtab not found");
1292 // Remove ".rel" and ".rela" prefixes.
1293 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1294 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1296 InfoSection = Asm.getContext().getELFSection(SectionName,
1297 ELF::SHT_PROGBITS, 0,
1298 SectionKind::getReadOnly());
1299 sh_info = SectionIndexMap.lookup(InfoSection);
1303 case ELF::SHT_SYMTAB:
1304 case ELF::SHT_DYNSYM:
1305 sh_link = StringTableIndex;
1306 sh_info = LastLocalSymbolIndex;
1309 case ELF::SHT_SYMTAB_SHNDX:
1310 sh_link = SymbolTableIndex;
1313 case ELF::SHT_PROGBITS:
1314 case ELF::SHT_STRTAB:
1315 case ELF::SHT_NOBITS:
1318 case ELF::SHT_ARM_ATTRIBUTES:
1319 case ELF::SHT_INIT_ARRAY:
1320 case ELF::SHT_FINI_ARRAY:
1321 case ELF::SHT_PREINIT_ARRAY:
1322 case ELF::SHT_X86_64_UNWIND:
1326 case ELF::SHT_GROUP:
1327 sh_link = SymbolTableIndex;
1328 sh_info = GroupSymbolIndex;
1332 assert(0 && "FIXME: sh_type value not supported!");
1336 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1337 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1338 Alignment, Section.getEntrySize());
1341 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1342 return SD.getOrdinal() == ~UINT32_C(0) &&
1343 !SD.getSection().isVirtualSection();
1346 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1348 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1350 const MCFragment &F = *i;
1351 assert(F.getKind() == MCFragment::FT_Data);
1352 Ret += cast<MCDataFragment>(F).getContents().size();
1357 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1358 const MCSectionData &SD) {
1359 if (IsELFMetaDataSection(SD))
1360 return DataSectionSize(SD);
1361 return Layout.getSectionFileSize(&SD);
1364 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1365 const MCSectionData &SD) {
1366 if (IsELFMetaDataSection(SD))
1367 return DataSectionSize(SD);
1368 return Layout.getSectionAddressSize(&SD);
1371 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1372 const MCAsmLayout &Layout,
1373 const MCSectionELF &Section) {
1374 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1376 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1377 WriteZeros(Padding);
1379 if (IsELFMetaDataSection(SD)) {
1380 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1382 const MCFragment &F = *i;
1383 assert(F.getKind() == MCFragment::FT_Data);
1384 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1387 Asm.writeSectionData(&SD, Layout);
1391 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1392 const GroupMapTy &GroupMap,
1393 const MCAsmLayout &Layout,
1394 const SectionIndexMapTy &SectionIndexMap,
1395 const SectionOffsetMapTy &SectionOffsetMap) {
1396 const unsigned NumSections = Asm.size() + 1;
1398 std::vector<const MCSectionELF*> Sections;
1399 Sections.resize(NumSections - 1);
1401 for (SectionIndexMapTy::const_iterator i=
1402 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1403 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1404 Sections[p.second - 1] = p.first;
1407 // Null section first.
1408 uint64_t FirstSectionSize =
1409 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1410 uint32_t FirstSectionLink =
1411 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1412 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1414 for (unsigned i = 0; i < NumSections - 1; ++i) {
1415 const MCSectionELF &Section = *Sections[i];
1416 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1417 uint32_t GroupSymbolIndex;
1418 if (Section.getType() != ELF::SHT_GROUP)
1419 GroupSymbolIndex = 0;
1421 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1422 GroupMap.lookup(&Section));
1424 uint64_t Size = GetSectionAddressSize(Layout, SD);
1426 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1427 SectionOffsetMap.lookup(&Section), Size,
1428 SD.getAlignment(), Section);
1432 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1433 std::vector<const MCSectionELF*> &Sections) {
1434 for (MCAssembler::iterator it = Asm.begin(),
1435 ie = Asm.end(); it != ie; ++it) {
1436 const MCSectionELF &Section =
1437 static_cast<const MCSectionELF &>(it->getSection());
1438 if (Section.getType() == ELF::SHT_GROUP)
1439 Sections.push_back(&Section);
1442 for (MCAssembler::iterator it = Asm.begin(),
1443 ie = Asm.end(); it != ie; ++it) {
1444 const MCSectionELF &Section =
1445 static_cast<const MCSectionELF &>(it->getSection());
1446 if (Section.getType() != ELF::SHT_GROUP &&
1447 Section.getType() != ELF::SHT_REL &&
1448 Section.getType() != ELF::SHT_RELA)
1449 Sections.push_back(&Section);
1452 for (MCAssembler::iterator it = Asm.begin(),
1453 ie = Asm.end(); it != ie; ++it) {
1454 const MCSectionELF &Section =
1455 static_cast<const MCSectionELF &>(it->getSection());
1456 if (Section.getType() == ELF::SHT_REL ||
1457 Section.getType() == ELF::SHT_RELA)
1458 Sections.push_back(&Section);
1462 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1463 const MCAsmLayout &Layout) {
1464 GroupMapTy GroupMap;
1465 RevGroupMapTy RevGroupMap;
1466 SectionIndexMapTy SectionIndexMap;
1468 unsigned NumUserSections = Asm.size();
1470 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1471 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1473 const unsigned NumUserAndRelocSections = Asm.size();
1474 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1475 RevGroupMap, SectionIndexMap, RelMap);
1476 const unsigned AllSections = Asm.size();
1477 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1479 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1481 // Compute symbol table information.
1482 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1485 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1487 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1488 const_cast<MCAsmLayout&>(Layout),
1492 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1493 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1494 sizeof(ELF::Elf32_Ehdr);
1495 uint64_t FileOff = HeaderSize;
1497 std::vector<const MCSectionELF*> Sections;
1498 ComputeSectionOrder(Asm, Sections);
1499 unsigned NumSections = Sections.size();
1500 SectionOffsetMapTy SectionOffsetMap;
1501 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1502 const MCSectionELF &Section = *Sections[i];
1503 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1505 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1507 // Remember the offset into the file for this section.
1508 SectionOffsetMap[&Section] = FileOff;
1510 // Get the size of the section in the output file (including padding).
1511 FileOff += GetSectionFileSize(Layout, SD);
1514 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1516 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1518 uint64_t SectionHeaderEntrySize = is64Bit() ?
1519 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1520 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1522 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1523 const MCSectionELF &Section = *Sections[i];
1524 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1526 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1528 // Remember the offset into the file for this section.
1529 SectionOffsetMap[&Section] = FileOff;
1531 // Get the size of the section in the output file (including padding).
1532 FileOff += GetSectionFileSize(Layout, SD);
1535 // Write out the ELF header ...
1536 WriteHeader(SectionHeaderOffset, NumSections + 1);
1538 // ... then the regular sections ...
1539 // + because of .shstrtab
1540 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1541 WriteDataSectionData(Asm, Layout, *Sections[i]);
1543 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1544 WriteZeros(Padding);
1546 // ... then the section header table ...
1547 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1550 // ... and then the remaining sections ...
1551 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1552 WriteDataSectionData(Asm, Layout, *Sections[i]);
1556 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1557 const MCSymbolData &DataA,
1558 const MCFragment &FB,
1560 bool IsPCRel) const {
1561 if (DataA.getFlags() & ELF_STB_Weak)
1563 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1564 Asm, DataA, FB,InSet, IsPCRel);
1567 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1569 bool IsLittleEndian) {
1570 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);