1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCELFObjectWriter.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringMap.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/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
38 #define DEBUG_TYPE "reloc-info"
41 class ELFObjectWriter : public MCObjectWriter {
44 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
45 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
46 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
47 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
48 bool Used, bool Renamed);
49 static bool isLocal(const MCSymbolData &Data, bool isSignature,
51 static bool IsELFMetaDataSection(const MCSectionData &SD);
52 static uint64_t DataSectionSize(const MCSectionData &SD);
53 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
54 const MCSectionData &SD);
55 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
56 const MCSectionData &SD);
58 void WriteDataSectionData(MCAssembler &Asm,
59 const MCAsmLayout &Layout,
60 const MCSectionELF &Section);
62 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
63 return Kind == X86::reloc_riprel_4byte ||
64 Kind == X86::reloc_riprel_4byte_movq_load;
67 /// ELFSymbolData - Helper struct for containing some precomputed
68 /// information on symbols.
69 struct ELFSymbolData {
70 MCSymbolData *SymbolData;
72 uint32_t SectionIndex;
74 // Support lexicographic sorting.
75 bool operator<(const ELFSymbolData &RHS) const {
76 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
78 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
80 return SymbolData->getSymbol().getName() <
81 RHS.SymbolData->getSymbol().getName();
85 /// The target specific ELF writer instance.
86 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
88 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
89 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
90 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
92 llvm::DenseMap<const MCSectionData*,
93 std::vector<ELFRelocationEntry> > Relocations;
94 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
97 /// @name Symbol Table Data
100 SmallString<256> StringTable;
101 std::vector<ELFSymbolData> LocalSymbolData;
102 std::vector<ELFSymbolData> ExternalSymbolData;
103 std::vector<ELFSymbolData> UndefinedSymbolData;
109 bool NeedsSymtabShndx;
111 // This holds the symbol table index of the last local symbol.
112 unsigned LastLocalSymbolIndex;
113 // This holds the .strtab section index.
114 unsigned StringTableIndex;
115 // This holds the .symtab section index.
116 unsigned SymbolTableIndex;
118 unsigned ShstrtabIndex;
121 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
122 const MCValue &Target,
124 const MCFixup &Fixup,
127 // TargetObjectWriter wrappers.
128 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
129 const MCValue &Target,
131 const MCFixup &Fixup,
132 bool IsPCRel) const {
133 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
135 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
136 const MCFixup &Fixup,
137 bool IsPCRel) const {
138 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup, IsPCRel);
141 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
142 bool hasRelocationAddend() const {
143 return TargetObjectWriter->hasRelocationAddend();
145 unsigned getEFlags() const {
146 return TargetObjectWriter->getEFlags();
148 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
149 bool IsPCRel, bool IsRelocWithSymbol,
150 int64_t Addend) const {
151 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
152 IsRelocWithSymbol, Addend);
157 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
158 raw_ostream &_OS, bool IsLittleEndian)
159 : MCObjectWriter(_OS, IsLittleEndian),
160 TargetObjectWriter(MOTW),
161 NeedsGOT(false), NeedsSymtabShndx(false){
164 virtual ~ELFObjectWriter();
166 void WriteWord(uint64_t W) {
173 void StringLE16(char *buf, uint16_t Value) {
174 buf[0] = char(Value >> 0);
175 buf[1] = char(Value >> 8);
178 void StringLE32(char *buf, uint32_t Value) {
179 StringLE16(buf, uint16_t(Value >> 0));
180 StringLE16(buf + 2, uint16_t(Value >> 16));
183 void StringLE64(char *buf, uint64_t Value) {
184 StringLE32(buf, uint32_t(Value >> 0));
185 StringLE32(buf + 4, uint32_t(Value >> 32));
188 void StringBE16(char *buf ,uint16_t Value) {
189 buf[0] = char(Value >> 8);
190 buf[1] = char(Value >> 0);
193 void StringBE32(char *buf, uint32_t Value) {
194 StringBE16(buf, uint16_t(Value >> 16));
195 StringBE16(buf + 2, uint16_t(Value >> 0));
198 void StringBE64(char *buf, uint64_t Value) {
199 StringBE32(buf, uint32_t(Value >> 32));
200 StringBE32(buf + 4, uint32_t(Value >> 0));
203 void String8(MCDataFragment &F, uint8_t Value) {
206 F.getContents() += StringRef(buf, 1);
209 void String16(MCDataFragment &F, uint16_t Value) {
211 if (isLittleEndian())
212 StringLE16(buf, Value);
214 StringBE16(buf, Value);
215 F.getContents() += StringRef(buf, 2);
218 void String32(MCDataFragment &F, uint32_t Value) {
220 if (isLittleEndian())
221 StringLE32(buf, Value);
223 StringBE32(buf, Value);
224 F.getContents() += StringRef(buf, 4);
227 void String64(MCDataFragment &F, uint64_t Value) {
229 if (isLittleEndian())
230 StringLE64(buf, Value);
232 StringBE64(buf, Value);
233 F.getContents() += StringRef(buf, 8);
236 void WriteHeader(uint64_t SectionDataSize,
237 unsigned NumberOfSections);
239 void WriteSymbolEntry(MCDataFragment *SymtabF,
240 MCDataFragment *ShndxF,
241 uint64_t name, uint8_t info,
242 uint64_t value, uint64_t size,
243 uint8_t other, uint32_t shndx,
246 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
248 const MCAsmLayout &Layout);
250 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
251 void WriteSymbolTable(MCDataFragment *SymtabF,
252 MCDataFragment *ShndxF,
253 const MCAssembler &Asm,
254 const MCAsmLayout &Layout,
255 const SectionIndexMapTy &SectionIndexMap);
257 virtual void RecordRelocation(const MCAssembler &Asm,
258 const MCAsmLayout &Layout,
259 const MCFragment *Fragment,
260 const MCFixup &Fixup,
261 MCValue Target, uint64_t &FixedValue);
263 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
266 // Map from a group section to the signature symbol
267 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
268 // Map from a signature symbol to the group section
269 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
270 // Map from a section to the section with the relocations
271 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
272 // Map from a section to its offset
273 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
275 /// ComputeSymbolTable - Compute the symbol table data
277 /// \param Asm - The assembler.
278 /// \param SectionIndexMap - Maps a section to its index.
279 /// \param RevGroupMap - Maps a signature symbol to the group section.
280 /// \param NumRegularSections - Number of non-relocation sections.
281 void ComputeSymbolTable(MCAssembler &Asm,
282 const SectionIndexMapTy &SectionIndexMap,
283 RevGroupMapTy RevGroupMap,
284 unsigned NumRegularSections);
286 void ComputeIndexMap(MCAssembler &Asm,
287 SectionIndexMapTy &SectionIndexMap,
288 const RelMapTy &RelMap);
290 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
293 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
294 const RelMapTy &RelMap);
296 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
297 SectionIndexMapTy &SectionIndexMap,
298 const RelMapTy &RelMap);
300 // Create the sections that show up in the symbol table. Currently
301 // those are the .note.GNU-stack section and the group sections.
302 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
303 GroupMapTy &GroupMap,
304 RevGroupMapTy &RevGroupMap,
305 SectionIndexMapTy &SectionIndexMap,
306 const RelMapTy &RelMap);
308 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
309 const MCAsmLayout &Layout);
311 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
312 const MCAsmLayout &Layout,
313 const SectionIndexMapTy &SectionIndexMap,
314 const SectionOffsetMapTy &SectionOffsetMap);
316 void ComputeSectionOrder(MCAssembler &Asm,
317 std::vector<const MCSectionELF*> &Sections);
319 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
320 uint64_t Address, uint64_t Offset,
321 uint64_t Size, uint32_t Link, uint32_t Info,
322 uint64_t Alignment, uint64_t EntrySize);
324 void WriteRelocationsFragment(const MCAssembler &Asm,
326 const MCSectionData *SD);
329 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
330 const MCSymbolData &DataA,
331 const MCFragment &FB,
335 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
336 void WriteSection(MCAssembler &Asm,
337 const SectionIndexMapTy &SectionIndexMap,
338 uint32_t GroupSymbolIndex,
339 uint64_t Offset, uint64_t Size, uint64_t Alignment,
340 const MCSectionELF &Section);
344 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
345 const MCFixupKindInfo &FKI =
346 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
348 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
351 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
355 case MCSymbolRefExpr::VK_GOT:
356 case MCSymbolRefExpr::VK_PLT:
357 case MCSymbolRefExpr::VK_GOTPCREL:
358 case MCSymbolRefExpr::VK_GOTOFF:
359 case MCSymbolRefExpr::VK_TPOFF:
360 case MCSymbolRefExpr::VK_TLSGD:
361 case MCSymbolRefExpr::VK_GOTTPOFF:
362 case MCSymbolRefExpr::VK_INDNTPOFF:
363 case MCSymbolRefExpr::VK_NTPOFF:
364 case MCSymbolRefExpr::VK_GOTNTPOFF:
365 case MCSymbolRefExpr::VK_TLSLDM:
366 case MCSymbolRefExpr::VK_DTPOFF:
367 case MCSymbolRefExpr::VK_TLSLD:
372 ELFObjectWriter::~ELFObjectWriter()
375 // Emit the ELF header.
376 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
377 unsigned NumberOfSections) {
383 // emitWord method behaves differently for ELF32 and ELF64, writing
384 // 4 bytes in the former and 8 in the latter.
386 Write8(0x7f); // e_ident[EI_MAG0]
387 Write8('E'); // e_ident[EI_MAG1]
388 Write8('L'); // e_ident[EI_MAG2]
389 Write8('F'); // e_ident[EI_MAG3]
391 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
394 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
396 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
398 Write8(TargetObjectWriter->getOSABI());
399 Write8(0); // e_ident[EI_ABIVERSION]
401 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
403 Write16(ELF::ET_REL); // e_type
405 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
407 Write32(ELF::EV_CURRENT); // e_version
408 WriteWord(0); // e_entry, no entry point in .o file
409 WriteWord(0); // e_phoff, no program header for .o
410 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
411 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
413 // e_flags = whatever the target wants
414 Write32(getEFlags());
416 // e_ehsize = ELF header size
417 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
419 Write16(0); // e_phentsize = prog header entry size
420 Write16(0); // e_phnum = # prog header entries = 0
422 // e_shentsize = Section header entry size
423 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
425 // e_shnum = # of section header ents
426 if (NumberOfSections >= ELF::SHN_LORESERVE)
427 Write16(ELF::SHN_UNDEF);
429 Write16(NumberOfSections);
431 // e_shstrndx = Section # of '.shstrtab'
432 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
433 Write16(ELF::SHN_XINDEX);
435 Write16(ShstrtabIndex);
438 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
439 MCDataFragment *ShndxF,
441 uint8_t info, uint64_t value,
442 uint64_t size, uint8_t other,
446 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
447 String32(*ShndxF, shndx);
449 String32(*ShndxF, 0);
452 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
453 uint16_t(ELF::SHN_XINDEX) : shndx;
456 String32(*SymtabF, name); // st_name
457 String8(*SymtabF, info); // st_info
458 String8(*SymtabF, other); // st_other
459 String16(*SymtabF, Index); // st_shndx
460 String64(*SymtabF, value); // st_value
461 String64(*SymtabF, size); // st_size
463 String32(*SymtabF, name); // st_name
464 String32(*SymtabF, value); // st_value
465 String32(*SymtabF, size); // st_size
466 String8(*SymtabF, info); // st_info
467 String8(*SymtabF, other); // st_other
468 String16(*SymtabF, Index); // st_shndx
472 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
473 const MCAsmLayout &Layout) {
474 if (Data.isCommon() && Data.isExternal())
475 return Data.getCommonAlignment();
477 const MCSymbol &Symbol = Data.getSymbol();
479 if (Symbol.isAbsolute() && Symbol.isVariable()) {
480 if (const MCExpr *Value = Symbol.getVariableValue()) {
482 if (Value->EvaluateAsAbsolute(IntValue, Layout))
483 return (uint64_t)IntValue;
487 if (!Symbol.isInSection())
491 if (Data.getFragment()) {
492 if (Data.getFlags() & ELF_Other_ThumbFunc)
493 return Layout.getSymbolOffset(&Data)+1;
495 return Layout.getSymbolOffset(&Data);
501 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
502 const MCAsmLayout &Layout) {
503 // The presence of symbol versions causes undefined symbols and
504 // versions declared with @@@ to be renamed.
506 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
507 ie = Asm.symbol_end(); it != ie; ++it) {
508 const MCSymbol &Alias = it->getSymbol();
509 const MCSymbol &Symbol = Alias.AliasedSymbol();
510 MCSymbolData &SD = Asm.getSymbolData(Symbol);
513 if (&Symbol == &Alias)
516 StringRef AliasName = Alias.getName();
517 size_t Pos = AliasName.find('@');
518 if (Pos == StringRef::npos)
521 // Aliases defined with .symvar copy the binding from the symbol they alias.
522 // This is the first place we are able to copy this information.
523 it->setExternal(SD.isExternal());
524 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
526 StringRef Rest = AliasName.substr(Pos);
527 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
530 // FIXME: produce a better error message.
531 if (Symbol.isUndefined() && Rest.startswith("@@") &&
532 !Rest.startswith("@@@"))
533 report_fatal_error("A @@ version cannot be undefined");
535 Renames.insert(std::make_pair(&Symbol, &Alias));
539 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
540 MCDataFragment *ShndxF,
542 const MCAsmLayout &Layout) {
543 MCSymbolData &OrigData = *MSD.SymbolData;
545 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
547 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
548 Data.getSymbol().isVariable();
550 uint8_t Binding = MCELF::GetBinding(OrigData);
551 uint8_t Visibility = MCELF::GetVisibility(OrigData);
552 uint8_t Type = MCELF::GetType(Data);
554 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
555 uint8_t Other = Visibility;
557 uint64_t Value = SymbolValue(Data, Layout);
560 assert(!(Data.isCommon() && !Data.isExternal()));
562 const MCExpr *ESize = Data.getSize();
565 if (!ESize->EvaluateAsAbsolute(Res, Layout))
566 report_fatal_error("Size expression must be absolute.");
570 // Write out the symbol table entry
571 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
572 Size, Other, MSD.SectionIndex, IsReserved);
575 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
576 MCDataFragment *ShndxF,
577 const MCAssembler &Asm,
578 const MCAsmLayout &Layout,
579 const SectionIndexMapTy &SectionIndexMap) {
580 // The string table must be emitted first because we need the index
581 // into the string table for all the symbol names.
582 assert(StringTable.size() && "Missing string table");
584 // FIXME: Make sure the start of the symbol table is aligned.
586 // The first entry is the undefined symbol entry.
587 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
589 // Write the symbol table entries.
590 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
591 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
592 ELFSymbolData &MSD = LocalSymbolData[i];
593 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
596 // Write out a symbol table entry for each regular section.
597 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
599 const MCSectionELF &Section =
600 static_cast<const MCSectionELF&>(i->getSection());
601 if (Section.getType() == ELF::SHT_RELA ||
602 Section.getType() == ELF::SHT_REL ||
603 Section.getType() == ELF::SHT_STRTAB ||
604 Section.getType() == ELF::SHT_SYMTAB ||
605 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
607 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
608 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
610 LastLocalSymbolIndex++;
613 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
614 ELFSymbolData &MSD = ExternalSymbolData[i];
615 MCSymbolData &Data = *MSD.SymbolData;
616 assert(((Data.getFlags() & ELF_STB_Global) ||
617 (Data.getFlags() & ELF_STB_Weak)) &&
618 "External symbol requires STB_GLOBAL or STB_WEAK flag");
619 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
620 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
621 LastLocalSymbolIndex++;
624 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
625 ELFSymbolData &MSD = UndefinedSymbolData[i];
626 MCSymbolData &Data = *MSD.SymbolData;
627 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
628 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
629 LastLocalSymbolIndex++;
633 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
634 const MCValue &Target,
636 const MCFixup &Fixup,
637 bool IsPCRel) const {
638 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
639 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
640 const MCSymbol *Renamed = Renames.lookup(&Symbol);
641 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
643 if (ASymbol.isUndefined()) {
646 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
649 if (SD.isExternal()) {
655 const MCSectionELF &Section =
656 static_cast<const MCSectionELF&>(ASymbol.getSection());
657 const SectionKind secKind = Section.getKind();
660 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
662 if (secKind.isThreadLocal()) {
668 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
669 const MCSectionELF &Sec2 =
670 static_cast<const MCSectionELF&>(F.getParent()->getSection());
672 if (&Sec2 != &Section &&
673 (Kind == MCSymbolRefExpr::VK_PLT ||
674 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
675 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
681 if (Section.getFlags() & ELF::SHF_MERGE) {
682 if (Target.getConstant() == 0)
683 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
689 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
694 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
695 const MCAsmLayout &Layout,
696 const MCFragment *Fragment,
697 const MCFixup &Fixup,
699 uint64_t &FixedValue) {
702 int64_t Value = Target.getConstant();
703 const MCSymbol *RelocSymbol = NULL;
705 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
706 if (!Target.isAbsolute()) {
707 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
708 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
709 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
711 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
712 const MCSymbol &SymbolB = RefB->getSymbol();
713 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
716 // Offset of the symbol in the section
717 int64_t a = Layout.getSymbolOffset(&SDB);
719 // Offset of the relocation in the section
720 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
725 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
726 MCFragment *F = SD.getFragment();
729 Index = F->getParent()->getOrdinal() + 1;
730 // Offset of the symbol in the section
731 Value += Layout.getSymbolOffset(&SD);
736 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
737 WeakrefUsedInReloc.insert(RelocSymbol);
739 UsedInReloc.insert(RelocSymbol);
743 if (hasRelocationAddend())
748 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
749 (RelocSymbol != 0), Addend);
750 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
751 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
752 if (RelocNeedsGOT(Modifier))
755 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
758 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
759 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
761 if (!hasRelocationAddend())
765 assert(isInt<64>(Addend));
767 assert(isInt<32>(Addend));
769 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
770 Relocations[Fragment->getParent()].push_back(ERE);
775 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
777 MCSymbolData &SD = Asm.getSymbolData(*S);
778 return SD.getIndex();
781 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
782 const MCSymbolData &Data,
783 bool Used, bool Renamed) {
784 if (Data.getFlags() & ELF_Other_Weakref)
793 const MCSymbol &Symbol = Data.getSymbol();
795 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
798 const MCSymbol &A = Symbol.AliasedSymbol();
799 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
802 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
803 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
806 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
809 if (Symbol.isTemporary())
815 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
816 bool isUsedInReloc) {
817 if (Data.isExternal())
820 const MCSymbol &Symbol = Data.getSymbol();
821 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
823 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
824 if (isSignature && !isUsedInReloc)
833 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
834 SectionIndexMapTy &SectionIndexMap,
835 const RelMapTy &RelMap) {
837 for (MCAssembler::iterator it = Asm.begin(),
838 ie = Asm.end(); it != ie; ++it) {
839 const MCSectionELF &Section =
840 static_cast<const MCSectionELF &>(it->getSection());
841 if (Section.getType() != ELF::SHT_GROUP)
843 SectionIndexMap[&Section] = Index++;
846 for (MCAssembler::iterator it = Asm.begin(),
847 ie = Asm.end(); it != ie; ++it) {
848 const MCSectionELF &Section =
849 static_cast<const MCSectionELF &>(it->getSection());
850 if (Section.getType() == ELF::SHT_GROUP ||
851 Section.getType() == ELF::SHT_REL ||
852 Section.getType() == ELF::SHT_RELA)
854 SectionIndexMap[&Section] = Index++;
855 const MCSectionELF *RelSection = RelMap.lookup(&Section);
857 SectionIndexMap[RelSection] = Index++;
861 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
862 const SectionIndexMapTy &SectionIndexMap,
863 RevGroupMapTy RevGroupMap,
864 unsigned NumRegularSections) {
865 // FIXME: Is this the correct place to do this?
866 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
868 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
869 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
870 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
871 Data.setExternal(true);
872 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
875 // Index 0 is always the empty string.
876 StringMap<uint64_t> StringIndexMap;
877 StringTable += '\x00';
879 // FIXME: We could optimize suffixes in strtab in the same way we
880 // optimize them in shstrtab.
882 // Add the data for the symbols.
883 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
884 ie = Asm.symbol_end(); it != ie; ++it) {
885 const MCSymbol &Symbol = it->getSymbol();
887 bool Used = UsedInReloc.count(&Symbol);
888 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
889 bool isSignature = RevGroupMap.count(&Symbol);
891 if (!isInSymtab(Asm, *it,
892 Used || WeakrefUsed || isSignature,
893 Renames.count(&Symbol)))
898 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
900 // Undefined symbols are global, but this is the first place we
901 // are able to set it.
902 bool Local = isLocal(*it, isSignature, Used);
903 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
904 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
905 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
906 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
909 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
910 MCELF::SetBinding(*it, ELF::STB_WEAK);
912 if (it->isCommon()) {
914 MSD.SectionIndex = ELF::SHN_COMMON;
915 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
916 MSD.SectionIndex = ELF::SHN_ABS;
917 } else if (RefSymbol.isUndefined()) {
918 if (isSignature && !Used)
919 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
921 MSD.SectionIndex = ELF::SHN_UNDEF;
923 const MCSectionELF &Section =
924 static_cast<const MCSectionELF&>(RefSymbol.getSection());
925 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
926 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
927 NeedsSymtabShndx = true;
928 assert(MSD.SectionIndex && "Invalid section index!");
931 // The @@@ in symbol version is replaced with @ in undefined symbols and
932 // @@ in defined ones.
933 StringRef Name = Symbol.getName();
936 size_t Pos = Name.find("@@@");
937 if (Pos != StringRef::npos) {
938 Buf += Name.substr(0, Pos);
939 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
940 Buf += Name.substr(Pos + Skip);
944 uint64_t &Entry = StringIndexMap[Name];
946 Entry = StringTable.size();
948 StringTable += '\x00';
950 MSD.StringIndex = Entry;
951 if (MSD.SectionIndex == ELF::SHN_UNDEF)
952 UndefinedSymbolData.push_back(MSD);
954 LocalSymbolData.push_back(MSD);
956 ExternalSymbolData.push_back(MSD);
959 // Symbols are required to be in lexicographic order.
960 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
961 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
962 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
964 // Set the symbol indices. Local symbols must come before all other
965 // symbols with non-local bindings.
967 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
968 LocalSymbolData[i].SymbolData->setIndex(Index++);
970 Index += NumRegularSections;
972 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
973 ExternalSymbolData[i].SymbolData->setIndex(Index++);
974 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
975 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
977 if (NumRegularSections > ELF::SHN_LORESERVE)
978 NeedsSymtabShndx = true;
981 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
984 for (MCAssembler::const_iterator it = Asm.begin(),
985 ie = Asm.end(); it != ie; ++it) {
986 const MCSectionData &SD = *it;
987 if (Relocations[&SD].empty())
990 MCContext &Ctx = Asm.getContext();
991 const MCSectionELF &Section =
992 static_cast<const MCSectionELF&>(SD.getSection());
994 const StringRef SectionName = Section.getSectionName();
995 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
996 RelaSectionName += SectionName;
999 if (hasRelocationAddend())
1000 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1002 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
1004 const MCSectionELF *RelaSection =
1005 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1006 ELF::SHT_RELA : ELF::SHT_REL, 0,
1007 SectionKind::getReadOnly(),
1009 RelMap[&Section] = RelaSection;
1010 Asm.getOrCreateSectionData(*RelaSection);
1014 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1015 const RelMapTy &RelMap) {
1016 for (MCAssembler::const_iterator it = Asm.begin(),
1017 ie = Asm.end(); it != ie; ++it) {
1018 const MCSectionData &SD = *it;
1019 const MCSectionELF &Section =
1020 static_cast<const MCSectionELF&>(SD.getSection());
1022 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1025 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1026 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1028 MCDataFragment *F = new MCDataFragment(&RelaSD);
1029 WriteRelocationsFragment(Asm, F, &*it);
1033 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1034 uint64_t Flags, uint64_t Address,
1035 uint64_t Offset, uint64_t Size,
1036 uint32_t Link, uint32_t Info,
1038 uint64_t EntrySize) {
1039 Write32(Name); // sh_name: index into string table
1040 Write32(Type); // sh_type
1041 WriteWord(Flags); // sh_flags
1042 WriteWord(Address); // sh_addr
1043 WriteWord(Offset); // sh_offset
1044 WriteWord(Size); // sh_size
1045 Write32(Link); // sh_link
1046 Write32(Info); // sh_info
1047 WriteWord(Alignment); // sh_addralign
1048 WriteWord(EntrySize); // sh_entsize
1051 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1053 const MCSectionData *SD) {
1054 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1056 // Sort the relocation entries. Most targets just sort by r_offset, but some
1057 // (e.g., MIPS) have additional constraints.
1058 TargetObjectWriter->sortRelocs(Asm, Relocs);
1060 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1061 ELFRelocationEntry entry = Relocs[e - i - 1];
1065 else if (entry.Index < 0)
1066 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1068 entry.Index += LocalSymbolData.size();
1070 String64(*F, entry.r_offset);
1071 if (TargetObjectWriter->isN64()) {
1072 String32(*F, entry.Index);
1074 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1075 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1076 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1077 String8(*F, TargetObjectWriter->getRType(entry.Type));
1080 struct ELF::Elf64_Rela ERE64;
1081 ERE64.setSymbolAndType(entry.Index, entry.Type);
1082 String64(*F, ERE64.r_info);
1084 if (hasRelocationAddend())
1085 String64(*F, entry.r_addend);
1087 String32(*F, entry.r_offset);
1089 struct ELF::Elf32_Rela ERE32;
1090 ERE32.setSymbolAndType(entry.Index, entry.Type);
1091 String32(*F, ERE32.r_info);
1093 if (hasRelocationAddend())
1094 String32(*F, entry.r_addend);
1099 static int compareBySuffix(const void *a, const void *b) {
1100 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1101 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1102 const StringRef &NameA = secA->getSectionName();
1103 const StringRef &NameB = secB->getSectionName();
1104 const unsigned sizeA = NameA.size();
1105 const unsigned sizeB = NameB.size();
1106 const unsigned len = std::min(sizeA, sizeB);
1107 for (unsigned int i = 0; i < len; ++i) {
1108 char ca = NameA[sizeA - i - 1];
1109 char cb = NameB[sizeB - i - 1];
1114 return sizeB - sizeA;
1117 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1118 MCAsmLayout &Layout,
1119 SectionIndexMapTy &SectionIndexMap,
1120 const RelMapTy &RelMap) {
1121 MCContext &Ctx = Asm.getContext();
1124 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1126 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1127 const MCSectionELF *ShstrtabSection =
1128 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1129 SectionKind::getReadOnly());
1130 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1131 ShstrtabSD.setAlignment(1);
1133 const MCSectionELF *SymtabSection =
1134 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1135 SectionKind::getReadOnly(),
1137 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1138 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1140 MCSectionData *SymtabShndxSD = NULL;
1142 if (NeedsSymtabShndx) {
1143 const MCSectionELF *SymtabShndxSection =
1144 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1145 SectionKind::getReadOnly(), 4, "");
1146 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1147 SymtabShndxSD->setAlignment(4);
1150 const MCSectionELF *StrtabSection;
1151 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1152 SectionKind::getReadOnly());
1153 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1154 StrtabSD.setAlignment(1);
1156 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1158 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1159 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1160 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1163 F = new MCDataFragment(&SymtabSD);
1164 MCDataFragment *ShndxF = NULL;
1165 if (NeedsSymtabShndx) {
1166 ShndxF = new MCDataFragment(SymtabShndxSD);
1168 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1170 F = new MCDataFragment(&StrtabSD);
1171 F->getContents().append(StringTable.begin(), StringTable.end());
1173 F = new MCDataFragment(&ShstrtabSD);
1175 std::vector<const MCSectionELF*> Sections;
1176 for (MCAssembler::const_iterator it = Asm.begin(),
1177 ie = Asm.end(); it != ie; ++it) {
1178 const MCSectionELF &Section =
1179 static_cast<const MCSectionELF&>(it->getSection());
1180 Sections.push_back(&Section);
1182 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1184 // Section header string table.
1186 // The first entry of a string table holds a null character so skip
1189 F->getContents() += '\x00';
1191 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1192 const MCSectionELF &Section = *Sections[I];
1194 StringRef Name = Section.getSectionName();
1196 StringRef PreviousName = Sections[I - 1]->getSectionName();
1197 if (PreviousName.endswith(Name)) {
1198 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1202 // Remember the index into the string table so we can write it
1203 // into the sh_name field of the section header table.
1204 SectionStringTableIndex[&Section] = Index;
1206 Index += Name.size() + 1;
1207 F->getContents() += Name;
1208 F->getContents() += '\x00';
1212 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1213 MCAsmLayout &Layout,
1214 GroupMapTy &GroupMap,
1215 RevGroupMapTy &RevGroupMap,
1216 SectionIndexMapTy &SectionIndexMap,
1217 const RelMapTy &RelMap) {
1218 // Create the .note.GNU-stack section if needed.
1219 MCContext &Ctx = Asm.getContext();
1220 if (Asm.getNoExecStack()) {
1221 const MCSectionELF *GnuStackSection =
1222 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1223 SectionKind::getReadOnly());
1224 Asm.getOrCreateSectionData(*GnuStackSection);
1228 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1230 const MCSectionELF &Section =
1231 static_cast<const MCSectionELF&>(it->getSection());
1232 if (!(Section.getFlags() & ELF::SHF_GROUP))
1235 const MCSymbol *SignatureSymbol = Section.getGroup();
1236 Asm.getOrCreateSymbolData(*SignatureSymbol);
1237 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1239 Group = Ctx.CreateELFGroupSection();
1240 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1241 Data.setAlignment(4);
1242 MCDataFragment *F = new MCDataFragment(&Data);
1243 String32(*F, ELF::GRP_COMDAT);
1245 GroupMap[Group] = SignatureSymbol;
1248 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1250 // Add sections to the groups
1251 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1253 const MCSectionELF &Section =
1254 static_cast<const MCSectionELF&>(it->getSection());
1255 if (!(Section.getFlags() & ELF::SHF_GROUP))
1257 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1258 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1259 // FIXME: we could use the previous fragment
1260 MCDataFragment *F = new MCDataFragment(&Data);
1261 unsigned Index = SectionIndexMap.lookup(&Section);
1262 String32(*F, Index);
1266 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1267 const SectionIndexMapTy &SectionIndexMap,
1268 uint32_t GroupSymbolIndex,
1269 uint64_t Offset, uint64_t Size,
1271 const MCSectionELF &Section) {
1272 uint64_t sh_link = 0;
1273 uint64_t sh_info = 0;
1275 switch(Section.getType()) {
1276 case ELF::SHT_DYNAMIC:
1277 sh_link = SectionStringTableIndex[&Section];
1282 case ELF::SHT_RELA: {
1283 const MCSectionELF *SymtabSection;
1284 const MCSectionELF *InfoSection;
1285 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1287 SectionKind::getReadOnly());
1288 sh_link = SectionIndexMap.lookup(SymtabSection);
1289 assert(sh_link && ".symtab not found");
1291 // Remove ".rel" and ".rela" prefixes.
1292 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1293 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1295 InfoSection = Asm.getContext().getELFSection(SectionName,
1296 ELF::SHT_PROGBITS, 0,
1297 SectionKind::getReadOnly());
1298 sh_info = SectionIndexMap.lookup(InfoSection);
1302 case ELF::SHT_SYMTAB:
1303 case ELF::SHT_DYNSYM:
1304 sh_link = StringTableIndex;
1305 sh_info = LastLocalSymbolIndex;
1308 case ELF::SHT_SYMTAB_SHNDX:
1309 sh_link = SymbolTableIndex;
1312 case ELF::SHT_PROGBITS:
1313 case ELF::SHT_STRTAB:
1314 case ELF::SHT_NOBITS:
1317 case ELF::SHT_ARM_ATTRIBUTES:
1318 case ELF::SHT_INIT_ARRAY:
1319 case ELF::SHT_FINI_ARRAY:
1320 case ELF::SHT_PREINIT_ARRAY:
1321 case ELF::SHT_X86_64_UNWIND:
1325 case ELF::SHT_GROUP:
1326 sh_link = SymbolTableIndex;
1327 sh_info = GroupSymbolIndex;
1331 assert(0 && "FIXME: sh_type value not supported!");
1335 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1336 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1337 Alignment, Section.getEntrySize());
1340 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1341 return SD.getOrdinal() == ~UINT32_C(0) &&
1342 !SD.getSection().isVirtualSection();
1345 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1347 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1349 const MCFragment &F = *i;
1350 assert(F.getKind() == MCFragment::FT_Data);
1351 Ret += cast<MCDataFragment>(F).getContents().size();
1356 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1357 const MCSectionData &SD) {
1358 if (IsELFMetaDataSection(SD))
1359 return DataSectionSize(SD);
1360 return Layout.getSectionFileSize(&SD);
1363 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1364 const MCSectionData &SD) {
1365 if (IsELFMetaDataSection(SD))
1366 return DataSectionSize(SD);
1367 return Layout.getSectionAddressSize(&SD);
1370 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1371 const MCAsmLayout &Layout,
1372 const MCSectionELF &Section) {
1373 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1375 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1376 WriteZeros(Padding);
1378 if (IsELFMetaDataSection(SD)) {
1379 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1381 const MCFragment &F = *i;
1382 assert(F.getKind() == MCFragment::FT_Data);
1383 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1386 Asm.writeSectionData(&SD, Layout);
1390 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1391 const GroupMapTy &GroupMap,
1392 const MCAsmLayout &Layout,
1393 const SectionIndexMapTy &SectionIndexMap,
1394 const SectionOffsetMapTy &SectionOffsetMap) {
1395 const unsigned NumSections = Asm.size() + 1;
1397 std::vector<const MCSectionELF*> Sections;
1398 Sections.resize(NumSections - 1);
1400 for (SectionIndexMapTy::const_iterator i=
1401 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1402 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1403 Sections[p.second - 1] = p.first;
1406 // Null section first.
1407 uint64_t FirstSectionSize =
1408 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1409 uint32_t FirstSectionLink =
1410 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1411 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1413 for (unsigned i = 0; i < NumSections - 1; ++i) {
1414 const MCSectionELF &Section = *Sections[i];
1415 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1416 uint32_t GroupSymbolIndex;
1417 if (Section.getType() != ELF::SHT_GROUP)
1418 GroupSymbolIndex = 0;
1420 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1421 GroupMap.lookup(&Section));
1423 uint64_t Size = GetSectionAddressSize(Layout, SD);
1425 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1426 SectionOffsetMap.lookup(&Section), Size,
1427 SD.getAlignment(), Section);
1431 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1432 std::vector<const MCSectionELF*> &Sections) {
1433 for (MCAssembler::iterator it = Asm.begin(),
1434 ie = Asm.end(); it != ie; ++it) {
1435 const MCSectionELF &Section =
1436 static_cast<const MCSectionELF &>(it->getSection());
1437 if (Section.getType() == ELF::SHT_GROUP)
1438 Sections.push_back(&Section);
1441 for (MCAssembler::iterator it = Asm.begin(),
1442 ie = Asm.end(); it != ie; ++it) {
1443 const MCSectionELF &Section =
1444 static_cast<const MCSectionELF &>(it->getSection());
1445 if (Section.getType() != ELF::SHT_GROUP &&
1446 Section.getType() != ELF::SHT_REL &&
1447 Section.getType() != ELF::SHT_RELA)
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_REL ||
1456 Section.getType() == ELF::SHT_RELA)
1457 Sections.push_back(&Section);
1461 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1462 const MCAsmLayout &Layout) {
1463 GroupMapTy GroupMap;
1464 RevGroupMapTy RevGroupMap;
1465 SectionIndexMapTy SectionIndexMap;
1467 unsigned NumUserSections = Asm.size();
1469 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1470 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1472 const unsigned NumUserAndRelocSections = Asm.size();
1473 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1474 RevGroupMap, SectionIndexMap, RelMap);
1475 const unsigned AllSections = Asm.size();
1476 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1478 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1480 // Compute symbol table information.
1481 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1484 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1486 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1487 const_cast<MCAsmLayout&>(Layout),
1491 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1492 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1493 sizeof(ELF::Elf32_Ehdr);
1494 uint64_t FileOff = HeaderSize;
1496 std::vector<const MCSectionELF*> Sections;
1497 ComputeSectionOrder(Asm, Sections);
1498 unsigned NumSections = Sections.size();
1499 SectionOffsetMapTy SectionOffsetMap;
1500 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1501 const MCSectionELF &Section = *Sections[i];
1502 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1504 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1506 // Remember the offset into the file for this section.
1507 SectionOffsetMap[&Section] = FileOff;
1509 // Get the size of the section in the output file (including padding).
1510 FileOff += GetSectionFileSize(Layout, SD);
1513 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1515 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1517 uint64_t SectionHeaderEntrySize = is64Bit() ?
1518 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1519 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1521 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1522 const MCSectionELF &Section = *Sections[i];
1523 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1525 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1527 // Remember the offset into the file for this section.
1528 SectionOffsetMap[&Section] = FileOff;
1530 // Get the size of the section in the output file (including padding).
1531 FileOff += GetSectionFileSize(Layout, SD);
1534 // Write out the ELF header ...
1535 WriteHeader(SectionHeaderOffset, NumSections + 1);
1537 // ... then the regular sections ...
1538 // + because of .shstrtab
1539 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1540 WriteDataSectionData(Asm, Layout, *Sections[i]);
1542 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1543 WriteZeros(Padding);
1545 // ... then the section header table ...
1546 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1549 // ... and then the remaining sections ...
1550 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1551 WriteDataSectionData(Asm, Layout, *Sections[i]);
1555 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1556 const MCSymbolData &DataA,
1557 const MCFragment &FB,
1559 bool IsPCRel) const {
1560 if (DataA.getFlags() & ELF_STB_Weak)
1562 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1563 Asm, DataA, FB,InSet, IsPCRel);
1566 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1568 bool IsLittleEndian) {
1569 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);