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/ADT/Twine.h"
21 #include "llvm/MC/MCAsmBackend.h"
22 #include "llvm/MC/MCAsmLayout.h"
23 #include "llvm/MC/MCAssembler.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCELFObjectWriter.h"
26 #include "llvm/MC/MCELFSymbolFlags.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/ADT/StringSwitch.h"
40 #define DEBUG_TYPE "reloc-info"
43 class ELFObjectWriter : public MCObjectWriter {
46 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
47 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
48 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
49 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
50 bool Used, bool Renamed);
51 static bool isLocal(const MCSymbolData &Data, bool isSignature,
53 static bool IsELFMetaDataSection(const MCSectionData &SD);
54 static uint64_t DataSectionSize(const MCSectionData &SD);
55 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
56 const MCSectionData &SD);
57 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
58 const MCSectionData &SD);
60 void WriteDataSectionData(MCAssembler &Asm,
61 const MCAsmLayout &Layout,
62 const MCSectionELF &Section);
64 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
65 return Kind == X86::reloc_riprel_4byte ||
66 Kind == X86::reloc_riprel_4byte_movq_load;
69 /// ELFSymbolData - Helper struct for containing some precomputed
70 /// information on symbols.
71 struct ELFSymbolData {
72 MCSymbolData *SymbolData;
74 uint32_t SectionIndex;
76 // Support lexicographic sorting.
77 bool operator<(const ELFSymbolData &RHS) const {
78 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
80 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
82 return SymbolData->getSymbol().getName() <
83 RHS.SymbolData->getSymbol().getName();
87 /// @name Relocation Data
90 struct ELFRelocationEntry {
91 // Make these big enough for both 32-bit and 64-bit
95 const MCSymbol *Symbol;
99 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
101 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
102 unsigned RelType, const MCSymbol *Sym,
104 : r_offset(RelocOffset), Index(Idx), Type(RelType),
105 Symbol(Sym), r_addend(Addend) {}
107 // Support lexicographic sorting.
108 bool operator<(const ELFRelocationEntry &RE) const {
109 return RE.r_offset < r_offset;
113 /// The target specific ELF writer instance.
114 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
116 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
117 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
118 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
120 llvm::DenseMap<const MCSectionData*,
121 std::vector<ELFRelocationEntry> > Relocations;
122 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
125 /// @name Symbol Table Data
128 SmallString<256> StringTable;
129 std::vector<ELFSymbolData> LocalSymbolData;
130 std::vector<ELFSymbolData> ExternalSymbolData;
131 std::vector<ELFSymbolData> UndefinedSymbolData;
137 bool NeedsSymtabShndx;
139 // This holds the symbol table index of the last local symbol.
140 unsigned LastLocalSymbolIndex;
141 // This holds the .strtab section index.
142 unsigned StringTableIndex;
143 // This holds the .symtab section index.
144 unsigned SymbolTableIndex;
146 unsigned ShstrtabIndex;
149 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
150 const MCValue &Target,
152 const MCFixup &Fixup,
155 // TargetObjectWriter wrappers.
156 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
157 const MCValue &Target,
159 const MCFixup &Fixup,
160 bool IsPCRel) const {
161 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
164 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
165 bool hasRelocationAddend() const {
166 return TargetObjectWriter->hasRelocationAddend();
168 unsigned getEFlags() const {
169 return TargetObjectWriter->getEFlags();
171 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
172 bool IsPCRel, bool IsRelocWithSymbol,
173 int64_t Addend) const {
174 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
175 IsRelocWithSymbol, Addend);
180 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
181 raw_ostream &_OS, bool IsLittleEndian)
182 : MCObjectWriter(_OS, IsLittleEndian),
183 TargetObjectWriter(MOTW),
184 NeedsGOT(false), NeedsSymtabShndx(false){
187 virtual ~ELFObjectWriter();
189 void WriteWord(uint64_t W) {
196 void StringLE16(char *buf, uint16_t Value) {
197 buf[0] = char(Value >> 0);
198 buf[1] = char(Value >> 8);
201 void StringLE32(char *buf, uint32_t Value) {
202 StringLE16(buf, uint16_t(Value >> 0));
203 StringLE16(buf + 2, uint16_t(Value >> 16));
206 void StringLE64(char *buf, uint64_t Value) {
207 StringLE32(buf, uint32_t(Value >> 0));
208 StringLE32(buf + 4, uint32_t(Value >> 32));
211 void StringBE16(char *buf ,uint16_t Value) {
212 buf[0] = char(Value >> 8);
213 buf[1] = char(Value >> 0);
216 void StringBE32(char *buf, uint32_t Value) {
217 StringBE16(buf, uint16_t(Value >> 16));
218 StringBE16(buf + 2, uint16_t(Value >> 0));
221 void StringBE64(char *buf, uint64_t Value) {
222 StringBE32(buf, uint32_t(Value >> 32));
223 StringBE32(buf + 4, uint32_t(Value >> 0));
226 void String8(MCDataFragment &F, uint8_t Value) {
229 F.getContents() += StringRef(buf, 1);
232 void String16(MCDataFragment &F, uint16_t Value) {
234 if (isLittleEndian())
235 StringLE16(buf, Value);
237 StringBE16(buf, Value);
238 F.getContents() += StringRef(buf, 2);
241 void String32(MCDataFragment &F, uint32_t Value) {
243 if (isLittleEndian())
244 StringLE32(buf, Value);
246 StringBE32(buf, Value);
247 F.getContents() += StringRef(buf, 4);
250 void String64(MCDataFragment &F, uint64_t Value) {
252 if (isLittleEndian())
253 StringLE64(buf, Value);
255 StringBE64(buf, Value);
256 F.getContents() += StringRef(buf, 8);
259 void WriteHeader(uint64_t SectionDataSize,
260 unsigned NumberOfSections);
262 void WriteSymbolEntry(MCDataFragment *SymtabF,
263 MCDataFragment *ShndxF,
264 uint64_t name, uint8_t info,
265 uint64_t value, uint64_t size,
266 uint8_t other, uint32_t shndx,
269 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
271 const MCAsmLayout &Layout);
273 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
274 void WriteSymbolTable(MCDataFragment *SymtabF,
275 MCDataFragment *ShndxF,
276 const MCAssembler &Asm,
277 const MCAsmLayout &Layout,
278 const SectionIndexMapTy &SectionIndexMap);
280 virtual void RecordRelocation(const MCAssembler &Asm,
281 const MCAsmLayout &Layout,
282 const MCFragment *Fragment,
283 const MCFixup &Fixup,
284 MCValue Target, uint64_t &FixedValue);
286 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
289 // Map from a group section to the signature symbol
290 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
291 // Map from a signature symbol to the group section
292 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
293 // Map from a section to the section with the relocations
294 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
295 // Map from a section to its offset
296 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
298 /// ComputeSymbolTable - Compute the symbol table data
300 /// \param StringTable [out] - The string table data.
301 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
303 void ComputeSymbolTable(MCAssembler &Asm,
304 const SectionIndexMapTy &SectionIndexMap,
305 RevGroupMapTy RevGroupMap,
306 unsigned NumRegularSections);
308 void ComputeIndexMap(MCAssembler &Asm,
309 SectionIndexMapTy &SectionIndexMap,
310 const RelMapTy &RelMap);
312 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
315 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
316 const RelMapTy &RelMap);
318 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
319 SectionIndexMapTy &SectionIndexMap,
320 const RelMapTy &RelMap);
322 // Create the sections that show up in the symbol table. Currently
323 // those are the .note.GNU-stack section and the group sections.
324 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
325 GroupMapTy &GroupMap,
326 RevGroupMapTy &RevGroupMap,
327 SectionIndexMapTy &SectionIndexMap,
328 const RelMapTy &RelMap);
330 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
331 const MCAsmLayout &Layout);
333 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
334 const MCAsmLayout &Layout,
335 const SectionIndexMapTy &SectionIndexMap,
336 const SectionOffsetMapTy &SectionOffsetMap);
338 void ComputeSectionOrder(MCAssembler &Asm,
339 std::vector<const MCSectionELF*> &Sections);
341 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
342 uint64_t Address, uint64_t Offset,
343 uint64_t Size, uint32_t Link, uint32_t Info,
344 uint64_t Alignment, uint64_t EntrySize);
346 void WriteRelocationsFragment(const MCAssembler &Asm,
348 const MCSectionData *SD);
351 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
352 const MCSymbolData &DataA,
353 const MCFragment &FB,
357 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
358 void WriteSection(MCAssembler &Asm,
359 const SectionIndexMapTy &SectionIndexMap,
360 uint32_t GroupSymbolIndex,
361 uint64_t Offset, uint64_t Size, uint64_t Alignment,
362 const MCSectionELF &Section);
366 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
367 const MCFixupKindInfo &FKI =
368 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
370 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
373 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
377 case MCSymbolRefExpr::VK_GOT:
378 case MCSymbolRefExpr::VK_PLT:
379 case MCSymbolRefExpr::VK_GOTPCREL:
380 case MCSymbolRefExpr::VK_GOTOFF:
381 case MCSymbolRefExpr::VK_TPOFF:
382 case MCSymbolRefExpr::VK_TLSGD:
383 case MCSymbolRefExpr::VK_GOTTPOFF:
384 case MCSymbolRefExpr::VK_INDNTPOFF:
385 case MCSymbolRefExpr::VK_NTPOFF:
386 case MCSymbolRefExpr::VK_GOTNTPOFF:
387 case MCSymbolRefExpr::VK_TLSLDM:
388 case MCSymbolRefExpr::VK_DTPOFF:
389 case MCSymbolRefExpr::VK_TLSLD:
394 ELFObjectWriter::~ELFObjectWriter()
397 // Emit the ELF header.
398 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
399 unsigned NumberOfSections) {
405 // emitWord method behaves differently for ELF32 and ELF64, writing
406 // 4 bytes in the former and 8 in the latter.
408 Write8(0x7f); // e_ident[EI_MAG0]
409 Write8('E'); // e_ident[EI_MAG1]
410 Write8('L'); // e_ident[EI_MAG2]
411 Write8('F'); // e_ident[EI_MAG3]
413 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
416 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
418 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
420 Write8(TargetObjectWriter->getOSABI());
421 Write8(0); // e_ident[EI_ABIVERSION]
423 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
425 Write16(ELF::ET_REL); // e_type
427 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
429 Write32(ELF::EV_CURRENT); // e_version
430 WriteWord(0); // e_entry, no entry point in .o file
431 WriteWord(0); // e_phoff, no program header for .o
432 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
433 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
435 // e_flags = whatever the target wants
436 Write32(getEFlags());
438 // e_ehsize = ELF header size
439 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
441 Write16(0); // e_phentsize = prog header entry size
442 Write16(0); // e_phnum = # prog header entries = 0
444 // e_shentsize = Section header entry size
445 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
447 // e_shnum = # of section header ents
448 if (NumberOfSections >= ELF::SHN_LORESERVE)
449 Write16(ELF::SHN_UNDEF);
451 Write16(NumberOfSections);
453 // e_shstrndx = Section # of '.shstrtab'
454 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
455 Write16(ELF::SHN_XINDEX);
457 Write16(ShstrtabIndex);
460 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
461 MCDataFragment *ShndxF,
463 uint8_t info, uint64_t value,
464 uint64_t size, uint8_t other,
468 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
469 String32(*ShndxF, shndx);
471 String32(*ShndxF, 0);
474 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
475 uint16_t(ELF::SHN_XINDEX) : shndx;
478 String32(*SymtabF, name); // st_name
479 String8(*SymtabF, info); // st_info
480 String8(*SymtabF, other); // st_other
481 String16(*SymtabF, Index); // st_shndx
482 String64(*SymtabF, value); // st_value
483 String64(*SymtabF, size); // st_size
485 String32(*SymtabF, name); // st_name
486 String32(*SymtabF, value); // st_value
487 String32(*SymtabF, size); // st_size
488 String8(*SymtabF, info); // st_info
489 String8(*SymtabF, other); // st_other
490 String16(*SymtabF, Index); // st_shndx
494 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
495 const MCAsmLayout &Layout) {
496 if (Data.isCommon() && Data.isExternal())
497 return Data.getCommonAlignment();
499 const MCSymbol &Symbol = Data.getSymbol();
501 if (Symbol.isAbsolute() && Symbol.isVariable()) {
502 if (const MCExpr *Value = Symbol.getVariableValue()) {
504 if (Value->EvaluateAsAbsolute(IntValue, Layout))
505 return (uint64_t)IntValue;
509 if (!Symbol.isInSection())
513 if (Data.getFragment()) {
514 if (Data.getFlags() & ELF_Other_ThumbFunc)
515 return Layout.getSymbolOffset(&Data)+1;
517 return Layout.getSymbolOffset(&Data);
523 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
524 const MCAsmLayout &Layout) {
525 // The presence of symbol versions causes undefined symbols and
526 // versions declared with @@@ to be renamed.
528 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
529 ie = Asm.symbol_end(); it != ie; ++it) {
530 const MCSymbol &Alias = it->getSymbol();
531 const MCSymbol &Symbol = Alias.AliasedSymbol();
532 MCSymbolData &SD = Asm.getSymbolData(Symbol);
535 if (&Symbol == &Alias)
538 StringRef AliasName = Alias.getName();
539 size_t Pos = AliasName.find('@');
540 if (Pos == StringRef::npos)
543 // Aliases defined with .symvar copy the binding from the symbol they alias.
544 // This is the first place we are able to copy this information.
545 it->setExternal(SD.isExternal());
546 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
548 StringRef Rest = AliasName.substr(Pos);
549 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
552 // FIXME: produce a better error message.
553 if (Symbol.isUndefined() && Rest.startswith("@@") &&
554 !Rest.startswith("@@@"))
555 report_fatal_error("A @@ version cannot be undefined");
557 Renames.insert(std::make_pair(&Symbol, &Alias));
561 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
562 MCDataFragment *ShndxF,
564 const MCAsmLayout &Layout) {
565 MCSymbolData &OrigData = *MSD.SymbolData;
567 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
569 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
570 Data.getSymbol().isVariable();
572 uint8_t Binding = MCELF::GetBinding(OrigData);
573 uint8_t Visibility = MCELF::GetVisibility(OrigData);
574 uint8_t Type = MCELF::GetType(Data);
576 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
577 uint8_t Other = Visibility;
579 uint64_t Value = SymbolValue(Data, Layout);
582 assert(!(Data.isCommon() && !Data.isExternal()));
584 const MCExpr *ESize = Data.getSize();
587 if (!ESize->EvaluateAsAbsolute(Res, Layout))
588 report_fatal_error("Size expression must be absolute.");
592 // Write out the symbol table entry
593 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
594 Size, Other, MSD.SectionIndex, IsReserved);
597 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
598 MCDataFragment *ShndxF,
599 const MCAssembler &Asm,
600 const MCAsmLayout &Layout,
601 const SectionIndexMapTy &SectionIndexMap) {
602 // The string table must be emitted first because we need the index
603 // into the string table for all the symbol names.
604 assert(StringTable.size() && "Missing string table");
606 // FIXME: Make sure the start of the symbol table is aligned.
608 // The first entry is the undefined symbol entry.
609 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
611 // Write the symbol table entries.
612 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
613 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
614 ELFSymbolData &MSD = LocalSymbolData[i];
615 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
618 // Write out a symbol table entry for each regular section.
619 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
621 const MCSectionELF &Section =
622 static_cast<const MCSectionELF&>(i->getSection());
623 if (Section.getType() == ELF::SHT_RELA ||
624 Section.getType() == ELF::SHT_REL ||
625 Section.getType() == ELF::SHT_STRTAB ||
626 Section.getType() == ELF::SHT_SYMTAB ||
627 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
629 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
630 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
632 LastLocalSymbolIndex++;
635 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
636 ELFSymbolData &MSD = ExternalSymbolData[i];
637 MCSymbolData &Data = *MSD.SymbolData;
638 assert(((Data.getFlags() & ELF_STB_Global) ||
639 (Data.getFlags() & ELF_STB_Weak)) &&
640 "External symbol requires STB_GLOBAL or STB_WEAK flag");
641 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
642 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
643 LastLocalSymbolIndex++;
646 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
647 ELFSymbolData &MSD = UndefinedSymbolData[i];
648 MCSymbolData &Data = *MSD.SymbolData;
649 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
650 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
651 LastLocalSymbolIndex++;
655 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
656 const MCValue &Target,
658 const MCFixup &Fixup,
659 bool IsPCRel) const {
660 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
661 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
662 const MCSymbol *Renamed = Renames.lookup(&Symbol);
663 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
665 if (ASymbol.isUndefined()) {
671 if (SD.isExternal()) {
677 const MCSectionELF &Section =
678 static_cast<const MCSectionELF&>(ASymbol.getSection());
679 const SectionKind secKind = Section.getKind();
682 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
684 if (secKind.isThreadLocal()) {
690 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
691 const MCSectionELF &Sec2 =
692 static_cast<const MCSectionELF&>(F.getParent()->getSection());
694 if (&Sec2 != &Section &&
695 (Kind == MCSymbolRefExpr::VK_PLT ||
696 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
697 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
703 if (Section.getFlags() & ELF::SHF_MERGE) {
704 if (Target.getConstant() == 0)
705 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
711 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
716 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
717 const MCAsmLayout &Layout,
718 const MCFragment *Fragment,
719 const MCFixup &Fixup,
721 uint64_t &FixedValue) {
724 int64_t Value = Target.getConstant();
725 const MCSymbol *RelocSymbol = NULL;
727 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
728 if (!Target.isAbsolute()) {
729 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
730 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
731 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
733 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
734 const MCSymbol &SymbolB = RefB->getSymbol();
735 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
738 // Offset of the symbol in the section
739 int64_t a = Layout.getSymbolOffset(&SDB);
741 // Offset of the relocation in the section
742 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
747 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
748 MCFragment *F = SD.getFragment();
750 Index = F->getParent()->getOrdinal() + 1;
752 // Offset of the symbol in the section
753 Value += Layout.getSymbolOffset(&SD);
755 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
756 WeakrefUsedInReloc.insert(RelocSymbol);
758 UsedInReloc.insert(RelocSymbol);
762 // Compensate for the addend on i386.
768 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
769 (RelocSymbol != 0), Addend);
770 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
771 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
772 if (RelocNeedsGOT(Modifier))
775 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
778 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
779 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
781 if (!hasRelocationAddend())
785 assert(isInt<64>(Addend));
787 assert(isInt<32>(Addend));
789 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
790 Relocations[Fragment->getParent()].push_back(ERE);
795 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
797 MCSymbolData &SD = Asm.getSymbolData(*S);
798 return SD.getIndex();
801 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
802 const MCSymbolData &Data,
803 bool Used, bool Renamed) {
804 if (Data.getFlags() & ELF_Other_Weakref)
813 const MCSymbol &Symbol = Data.getSymbol();
815 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
818 const MCSymbol &A = Symbol.AliasedSymbol();
819 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
822 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
823 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
826 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
829 if (Symbol.isTemporary())
835 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
836 bool isUsedInReloc) {
837 if (Data.isExternal())
840 const MCSymbol &Symbol = Data.getSymbol();
841 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
843 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
844 if (isSignature && !isUsedInReloc)
853 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
854 SectionIndexMapTy &SectionIndexMap,
855 const RelMapTy &RelMap) {
857 for (MCAssembler::iterator it = Asm.begin(),
858 ie = Asm.end(); it != ie; ++it) {
859 const MCSectionELF &Section =
860 static_cast<const MCSectionELF &>(it->getSection());
861 if (Section.getType() != ELF::SHT_GROUP)
863 SectionIndexMap[&Section] = Index++;
866 for (MCAssembler::iterator it = Asm.begin(),
867 ie = Asm.end(); it != ie; ++it) {
868 const MCSectionELF &Section =
869 static_cast<const MCSectionELF &>(it->getSection());
870 if (Section.getType() == ELF::SHT_GROUP ||
871 Section.getType() == ELF::SHT_REL ||
872 Section.getType() == ELF::SHT_RELA)
874 SectionIndexMap[&Section] = Index++;
875 const MCSectionELF *RelSection = RelMap.lookup(&Section);
877 SectionIndexMap[RelSection] = Index++;
881 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
882 const SectionIndexMapTy &SectionIndexMap,
883 RevGroupMapTy RevGroupMap,
884 unsigned NumRegularSections) {
885 // FIXME: Is this the correct place to do this?
886 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
888 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
889 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
890 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
891 Data.setExternal(true);
892 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
895 // Index 0 is always the empty string.
896 StringMap<uint64_t> StringIndexMap;
897 StringTable += '\x00';
899 // FIXME: We could optimize suffixes in strtab in the same way we
900 // optimize them in shstrtab.
902 // Add the data for the symbols.
903 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
904 ie = Asm.symbol_end(); it != ie; ++it) {
905 const MCSymbol &Symbol = it->getSymbol();
907 bool Used = UsedInReloc.count(&Symbol);
908 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
909 bool isSignature = RevGroupMap.count(&Symbol);
911 if (!isInSymtab(Asm, *it,
912 Used || WeakrefUsed || isSignature,
913 Renames.count(&Symbol)))
918 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
920 // Undefined symbols are global, but this is the first place we
921 // are able to set it.
922 bool Local = isLocal(*it, isSignature, Used);
923 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
924 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
925 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
926 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
929 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
930 MCELF::SetBinding(*it, ELF::STB_WEAK);
932 if (it->isCommon()) {
934 MSD.SectionIndex = ELF::SHN_COMMON;
935 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
936 MSD.SectionIndex = ELF::SHN_ABS;
937 } else if (RefSymbol.isUndefined()) {
938 if (isSignature && !Used)
939 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
941 MSD.SectionIndex = ELF::SHN_UNDEF;
943 const MCSectionELF &Section =
944 static_cast<const MCSectionELF&>(RefSymbol.getSection());
945 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
946 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
947 NeedsSymtabShndx = true;
948 assert(MSD.SectionIndex && "Invalid section index!");
951 // The @@@ in symbol version is replaced with @ in undefined symbols and
952 // @@ in defined ones.
953 StringRef Name = Symbol.getName();
956 size_t Pos = Name.find("@@@");
957 if (Pos != StringRef::npos) {
958 Buf += Name.substr(0, Pos);
959 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
960 Buf += Name.substr(Pos + Skip);
964 uint64_t &Entry = StringIndexMap[Name];
966 Entry = StringTable.size();
968 StringTable += '\x00';
970 MSD.StringIndex = Entry;
971 if (MSD.SectionIndex == ELF::SHN_UNDEF)
972 UndefinedSymbolData.push_back(MSD);
974 LocalSymbolData.push_back(MSD);
976 ExternalSymbolData.push_back(MSD);
979 // Symbols are required to be in lexicographic order.
980 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
981 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
982 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
984 // Set the symbol indices. Local symbols must come before all other
985 // symbols with non-local bindings.
987 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
988 LocalSymbolData[i].SymbolData->setIndex(Index++);
990 Index += NumRegularSections;
992 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
993 ExternalSymbolData[i].SymbolData->setIndex(Index++);
994 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
995 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
997 if (NumRegularSections > ELF::SHN_LORESERVE)
998 NeedsSymtabShndx = true;
1001 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1002 MCAsmLayout &Layout,
1004 for (MCAssembler::const_iterator it = Asm.begin(),
1005 ie = Asm.end(); it != ie; ++it) {
1006 const MCSectionData &SD = *it;
1007 if (Relocations[&SD].empty())
1010 MCContext &Ctx = Asm.getContext();
1011 const MCSectionELF &Section =
1012 static_cast<const MCSectionELF&>(SD.getSection());
1014 const StringRef SectionName = Section.getSectionName();
1015 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1016 RelaSectionName += SectionName;
1019 if (hasRelocationAddend())
1020 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1022 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1024 const MCSectionELF *RelaSection =
1025 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1026 ELF::SHT_RELA : ELF::SHT_REL, 0,
1027 SectionKind::getReadOnly(),
1029 RelMap[&Section] = RelaSection;
1030 Asm.getOrCreateSectionData(*RelaSection);
1034 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1035 const RelMapTy &RelMap) {
1036 for (MCAssembler::const_iterator it = Asm.begin(),
1037 ie = Asm.end(); it != ie; ++it) {
1038 const MCSectionData &SD = *it;
1039 const MCSectionELF &Section =
1040 static_cast<const MCSectionELF&>(SD.getSection());
1042 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1045 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1046 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1048 MCDataFragment *F = new MCDataFragment(&RelaSD);
1049 WriteRelocationsFragment(Asm, F, &*it);
1053 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1054 uint64_t Flags, uint64_t Address,
1055 uint64_t Offset, uint64_t Size,
1056 uint32_t Link, uint32_t Info,
1058 uint64_t EntrySize) {
1059 Write32(Name); // sh_name: index into string table
1060 Write32(Type); // sh_type
1061 WriteWord(Flags); // sh_flags
1062 WriteWord(Address); // sh_addr
1063 WriteWord(Offset); // sh_offset
1064 WriteWord(Size); // sh_size
1065 Write32(Link); // sh_link
1066 Write32(Info); // sh_info
1067 WriteWord(Alignment); // sh_addralign
1068 WriteWord(EntrySize); // sh_entsize
1071 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1073 const MCSectionData *SD) {
1074 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1075 // sort by the r_offset just like gnu as does
1076 array_pod_sort(Relocs.begin(), Relocs.end());
1078 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1079 ELFRelocationEntry entry = Relocs[e - i - 1];
1083 else if (entry.Index < 0)
1084 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1086 entry.Index += LocalSymbolData.size();
1088 String64(*F, entry.r_offset);
1090 struct ELF::Elf64_Rela ERE64;
1091 ERE64.setSymbolAndType(entry.Index, entry.Type);
1092 String64(*F, ERE64.r_info);
1094 if (hasRelocationAddend())
1095 String64(*F, entry.r_addend);
1097 String32(*F, entry.r_offset);
1099 struct ELF::Elf32_Rela ERE32;
1100 ERE32.setSymbolAndType(entry.Index, entry.Type);
1101 String32(*F, ERE32.r_info);
1103 if (hasRelocationAddend())
1104 String32(*F, entry.r_addend);
1109 static int compareBySuffix(const void *a, const void *b) {
1110 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1111 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1112 const StringRef &NameA = secA->getSectionName();
1113 const StringRef &NameB = secB->getSectionName();
1114 const unsigned sizeA = NameA.size();
1115 const unsigned sizeB = NameB.size();
1116 const unsigned len = std::min(sizeA, sizeB);
1117 for (unsigned int i = 0; i < len; ++i) {
1118 char ca = NameA[sizeA - i - 1];
1119 char cb = NameB[sizeB - i - 1];
1124 return sizeB - sizeA;
1127 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1128 MCAsmLayout &Layout,
1129 SectionIndexMapTy &SectionIndexMap,
1130 const RelMapTy &RelMap) {
1131 MCContext &Ctx = Asm.getContext();
1134 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1136 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1137 const MCSectionELF *ShstrtabSection =
1138 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1139 SectionKind::getReadOnly());
1140 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1141 ShstrtabSD.setAlignment(1);
1143 const MCSectionELF *SymtabSection =
1144 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1145 SectionKind::getReadOnly(),
1147 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1148 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1150 MCSectionData *SymtabShndxSD = NULL;
1152 if (NeedsSymtabShndx) {
1153 const MCSectionELF *SymtabShndxSection =
1154 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1155 SectionKind::getReadOnly(), 4, "");
1156 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1157 SymtabShndxSD->setAlignment(4);
1160 const MCSectionELF *StrtabSection;
1161 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1162 SectionKind::getReadOnly());
1163 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1164 StrtabSD.setAlignment(1);
1166 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1168 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1169 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1170 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1173 F = new MCDataFragment(&SymtabSD);
1174 MCDataFragment *ShndxF = NULL;
1175 if (NeedsSymtabShndx) {
1176 ShndxF = new MCDataFragment(SymtabShndxSD);
1178 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1180 F = new MCDataFragment(&StrtabSD);
1181 F->getContents().append(StringTable.begin(), StringTable.end());
1183 F = new MCDataFragment(&ShstrtabSD);
1185 std::vector<const MCSectionELF*> Sections;
1186 for (MCAssembler::const_iterator it = Asm.begin(),
1187 ie = Asm.end(); it != ie; ++it) {
1188 const MCSectionELF &Section =
1189 static_cast<const MCSectionELF&>(it->getSection());
1190 Sections.push_back(&Section);
1192 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1194 // Section header string table.
1196 // The first entry of a string table holds a null character so skip
1199 F->getContents() += '\x00';
1201 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1202 const MCSectionELF &Section = *Sections[I];
1204 StringRef Name = Section.getSectionName();
1206 StringRef PreviousName = Sections[I - 1]->getSectionName();
1207 if (PreviousName.endswith(Name)) {
1208 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1212 // Remember the index into the string table so we can write it
1213 // into the sh_name field of the section header table.
1214 SectionStringTableIndex[&Section] = Index;
1216 Index += Name.size() + 1;
1217 F->getContents() += Name;
1218 F->getContents() += '\x00';
1222 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1223 MCAsmLayout &Layout,
1224 GroupMapTy &GroupMap,
1225 RevGroupMapTy &RevGroupMap,
1226 SectionIndexMapTy &SectionIndexMap,
1227 const RelMapTy &RelMap) {
1228 // Create the .note.GNU-stack section if needed.
1229 MCContext &Ctx = Asm.getContext();
1230 if (Asm.getNoExecStack()) {
1231 const MCSectionELF *GnuStackSection =
1232 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1233 SectionKind::getReadOnly());
1234 Asm.getOrCreateSectionData(*GnuStackSection);
1238 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1240 const MCSectionELF &Section =
1241 static_cast<const MCSectionELF&>(it->getSection());
1242 if (!(Section.getFlags() & ELF::SHF_GROUP))
1245 const MCSymbol *SignatureSymbol = Section.getGroup();
1246 Asm.getOrCreateSymbolData(*SignatureSymbol);
1247 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1249 Group = Ctx.CreateELFGroupSection();
1250 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1251 Data.setAlignment(4);
1252 MCDataFragment *F = new MCDataFragment(&Data);
1253 String32(*F, ELF::GRP_COMDAT);
1255 GroupMap[Group] = SignatureSymbol;
1258 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1260 // Add sections to the groups
1261 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1263 const MCSectionELF &Section =
1264 static_cast<const MCSectionELF&>(it->getSection());
1265 if (!(Section.getFlags() & ELF::SHF_GROUP))
1267 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1268 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1269 // FIXME: we could use the previous fragment
1270 MCDataFragment *F = new MCDataFragment(&Data);
1271 unsigned Index = SectionIndexMap.lookup(&Section);
1272 String32(*F, Index);
1276 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1277 const SectionIndexMapTy &SectionIndexMap,
1278 uint32_t GroupSymbolIndex,
1279 uint64_t Offset, uint64_t Size,
1281 const MCSectionELF &Section) {
1282 uint64_t sh_link = 0;
1283 uint64_t sh_info = 0;
1285 switch(Section.getType()) {
1286 case ELF::SHT_DYNAMIC:
1287 sh_link = SectionStringTableIndex[&Section];
1292 case ELF::SHT_RELA: {
1293 const MCSectionELF *SymtabSection;
1294 const MCSectionELF *InfoSection;
1295 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1297 SectionKind::getReadOnly());
1298 sh_link = SectionIndexMap.lookup(SymtabSection);
1299 assert(sh_link && ".symtab not found");
1301 // Remove ".rel" and ".rela" prefixes.
1302 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1303 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1305 InfoSection = Asm.getContext().getELFSection(SectionName,
1306 ELF::SHT_PROGBITS, 0,
1307 SectionKind::getReadOnly());
1308 sh_info = SectionIndexMap.lookup(InfoSection);
1312 case ELF::SHT_SYMTAB:
1313 case ELF::SHT_DYNSYM:
1314 sh_link = StringTableIndex;
1315 sh_info = LastLocalSymbolIndex;
1318 case ELF::SHT_SYMTAB_SHNDX:
1319 sh_link = SymbolTableIndex;
1322 case ELF::SHT_PROGBITS:
1323 case ELF::SHT_STRTAB:
1324 case ELF::SHT_NOBITS:
1327 case ELF::SHT_ARM_ATTRIBUTES:
1328 case ELF::SHT_INIT_ARRAY:
1329 case ELF::SHT_FINI_ARRAY:
1330 case ELF::SHT_PREINIT_ARRAY:
1331 case ELF::SHT_X86_64_UNWIND:
1335 case ELF::SHT_GROUP:
1336 sh_link = SymbolTableIndex;
1337 sh_info = GroupSymbolIndex;
1341 assert(0 && "FIXME: sh_type value not supported!");
1345 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1346 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1347 Alignment, Section.getEntrySize());
1350 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1351 return SD.getOrdinal() == ~UINT32_C(0) &&
1352 !SD.getSection().isVirtualSection();
1355 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1357 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1359 const MCFragment &F = *i;
1360 assert(F.getKind() == MCFragment::FT_Data);
1361 Ret += cast<MCDataFragment>(F).getContents().size();
1366 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1367 const MCSectionData &SD) {
1368 if (IsELFMetaDataSection(SD))
1369 return DataSectionSize(SD);
1370 return Layout.getSectionFileSize(&SD);
1373 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1374 const MCSectionData &SD) {
1375 if (IsELFMetaDataSection(SD))
1376 return DataSectionSize(SD);
1377 return Layout.getSectionAddressSize(&SD);
1380 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1381 const MCAsmLayout &Layout,
1382 const MCSectionELF &Section) {
1383 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1385 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1386 WriteZeros(Padding);
1388 if (IsELFMetaDataSection(SD)) {
1389 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1391 const MCFragment &F = *i;
1392 assert(F.getKind() == MCFragment::FT_Data);
1393 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1396 Asm.writeSectionData(&SD, Layout);
1400 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1401 const GroupMapTy &GroupMap,
1402 const MCAsmLayout &Layout,
1403 const SectionIndexMapTy &SectionIndexMap,
1404 const SectionOffsetMapTy &SectionOffsetMap) {
1405 const unsigned NumSections = Asm.size() + 1;
1407 std::vector<const MCSectionELF*> Sections;
1408 Sections.resize(NumSections - 1);
1410 for (SectionIndexMapTy::const_iterator i=
1411 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1412 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1413 Sections[p.second - 1] = p.first;
1416 // Null section first.
1417 uint64_t FirstSectionSize =
1418 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1419 uint32_t FirstSectionLink =
1420 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1421 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1423 for (unsigned i = 0; i < NumSections - 1; ++i) {
1424 const MCSectionELF &Section = *Sections[i];
1425 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1426 uint32_t GroupSymbolIndex;
1427 if (Section.getType() != ELF::SHT_GROUP)
1428 GroupSymbolIndex = 0;
1430 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1431 GroupMap.lookup(&Section));
1433 uint64_t Size = GetSectionAddressSize(Layout, SD);
1435 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1436 SectionOffsetMap.lookup(&Section), Size,
1437 SD.getAlignment(), Section);
1441 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1442 std::vector<const MCSectionELF*> &Sections) {
1443 for (MCAssembler::iterator it = Asm.begin(),
1444 ie = Asm.end(); it != ie; ++it) {
1445 const MCSectionELF &Section =
1446 static_cast<const MCSectionELF &>(it->getSection());
1447 if (Section.getType() == ELF::SHT_GROUP)
1448 Sections.push_back(&Section);
1451 for (MCAssembler::iterator it = Asm.begin(),
1452 ie = Asm.end(); it != ie; ++it) {
1453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF &>(it->getSection());
1455 if (Section.getType() != ELF::SHT_GROUP &&
1456 Section.getType() != ELF::SHT_REL &&
1457 Section.getType() != ELF::SHT_RELA)
1458 Sections.push_back(&Section);
1461 for (MCAssembler::iterator it = Asm.begin(),
1462 ie = Asm.end(); it != ie; ++it) {
1463 const MCSectionELF &Section =
1464 static_cast<const MCSectionELF &>(it->getSection());
1465 if (Section.getType() == ELF::SHT_REL ||
1466 Section.getType() == ELF::SHT_RELA)
1467 Sections.push_back(&Section);
1471 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1472 const MCAsmLayout &Layout) {
1473 GroupMapTy GroupMap;
1474 RevGroupMapTy RevGroupMap;
1475 SectionIndexMapTy SectionIndexMap;
1477 unsigned NumUserSections = Asm.size();
1479 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1480 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1482 const unsigned NumUserAndRelocSections = Asm.size();
1483 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1484 RevGroupMap, SectionIndexMap, RelMap);
1485 const unsigned AllSections = Asm.size();
1486 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1488 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1490 // Compute symbol table information.
1491 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1494 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1496 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1497 const_cast<MCAsmLayout&>(Layout),
1501 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1502 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1503 sizeof(ELF::Elf32_Ehdr);
1504 uint64_t FileOff = HeaderSize;
1506 std::vector<const MCSectionELF*> Sections;
1507 ComputeSectionOrder(Asm, Sections);
1508 unsigned NumSections = Sections.size();
1509 SectionOffsetMapTy SectionOffsetMap;
1510 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1511 const MCSectionELF &Section = *Sections[i];
1512 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1514 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1516 // Remember the offset into the file for this section.
1517 SectionOffsetMap[&Section] = FileOff;
1519 // Get the size of the section in the output file (including padding).
1520 FileOff += GetSectionFileSize(Layout, SD);
1523 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1525 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1527 uint64_t SectionHeaderEntrySize = is64Bit() ?
1528 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1529 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1531 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1532 const MCSectionELF &Section = *Sections[i];
1533 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1535 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1537 // Remember the offset into the file for this section.
1538 SectionOffsetMap[&Section] = FileOff;
1540 // Get the size of the section in the output file (including padding).
1541 FileOff += GetSectionFileSize(Layout, SD);
1544 // Write out the ELF header ...
1545 WriteHeader(SectionHeaderOffset, NumSections + 1);
1547 // ... then the regular sections ...
1548 // + because of .shstrtab
1549 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1550 WriteDataSectionData(Asm, Layout, *Sections[i]);
1552 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1553 WriteZeros(Padding);
1555 // ... then the section header table ...
1556 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1559 // ... and then the remaining sections ...
1560 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1561 WriteDataSectionData(Asm, Layout, *Sections[i]);
1565 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1566 const MCSymbolData &DataA,
1567 const MCFragment &FB,
1569 bool IsPCRel) const {
1570 if (DataA.getFlags() & ELF_STB_Weak)
1572 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1573 Asm, DataA, FB,InSet, IsPCRel);
1576 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1578 bool IsLittleEndian) {
1579 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);