1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements ELF object file writer information.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELFObjectWriter.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixupKindInfo.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/ELF.h"
39 #define DEBUG_TYPE "reloc-info"
42 class ELFObjectWriter : public MCObjectWriter {
45 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
46 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
47 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
48 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
49 bool Used, bool Renamed);
50 static bool isLocal(const MCSymbolData &Data, bool isSignature,
52 static bool IsELFMetaDataSection(const MCSectionData &SD);
53 static uint64_t DataSectionSize(const MCSectionData &SD);
54 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
55 const MCSectionData &SD);
56 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
57 const MCSectionData &SD);
59 void WriteDataSectionData(MCAssembler &Asm,
60 const MCAsmLayout &Layout,
61 const MCSectionELF &Section);
63 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
64 return Kind == X86::reloc_riprel_4byte ||
65 Kind == X86::reloc_riprel_4byte_movq_load;
68 /// ELFSymbolData - Helper struct for containing some precomputed
69 /// information on symbols.
70 struct ELFSymbolData {
71 MCSymbolData *SymbolData;
73 uint32_t SectionIndex;
75 // Support lexicographic sorting.
76 bool operator<(const ELFSymbolData &RHS) const {
77 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
79 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
81 return SymbolData->getSymbol().getName() <
82 RHS.SymbolData->getSymbol().getName();
86 /// The target specific ELF writer instance.
87 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
89 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
90 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
91 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
93 llvm::DenseMap<const MCSectionData*,
94 std::vector<ELFRelocationEntry> > Relocations;
95 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
98 /// @name Symbol Table Data
101 SmallString<256> StringTable;
102 std::vector<ELFSymbolData> LocalSymbolData;
103 std::vector<ELFSymbolData> ExternalSymbolData;
104 std::vector<ELFSymbolData> UndefinedSymbolData;
110 bool NeedsSymtabShndx;
112 // This holds the symbol table index of the last local symbol.
113 unsigned LastLocalSymbolIndex;
114 // This holds the .strtab section index.
115 unsigned StringTableIndex;
116 // This holds the .symtab section index.
117 unsigned SymbolTableIndex;
119 unsigned ShstrtabIndex;
122 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
123 const MCValue &Target,
125 const MCFixup &Fixup,
128 // TargetObjectWriter wrappers.
129 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
130 const MCValue &Target,
132 const MCFixup &Fixup,
133 bool IsPCRel) const {
134 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
137 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
138 bool hasRelocationAddend() const {
139 return TargetObjectWriter->hasRelocationAddend();
141 unsigned getEFlags() const {
142 return TargetObjectWriter->getEFlags();
144 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
145 bool IsPCRel, bool IsRelocWithSymbol,
146 int64_t Addend) const {
147 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
148 IsRelocWithSymbol, Addend);
153 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
154 raw_ostream &_OS, bool IsLittleEndian)
155 : MCObjectWriter(_OS, IsLittleEndian),
156 TargetObjectWriter(MOTW),
157 NeedsGOT(false), NeedsSymtabShndx(false){
160 virtual ~ELFObjectWriter();
162 void WriteWord(uint64_t W) {
169 void StringLE16(char *buf, uint16_t Value) {
170 buf[0] = char(Value >> 0);
171 buf[1] = char(Value >> 8);
174 void StringLE32(char *buf, uint32_t Value) {
175 StringLE16(buf, uint16_t(Value >> 0));
176 StringLE16(buf + 2, uint16_t(Value >> 16));
179 void StringLE64(char *buf, uint64_t Value) {
180 StringLE32(buf, uint32_t(Value >> 0));
181 StringLE32(buf + 4, uint32_t(Value >> 32));
184 void StringBE16(char *buf ,uint16_t Value) {
185 buf[0] = char(Value >> 8);
186 buf[1] = char(Value >> 0);
189 void StringBE32(char *buf, uint32_t Value) {
190 StringBE16(buf, uint16_t(Value >> 16));
191 StringBE16(buf + 2, uint16_t(Value >> 0));
194 void StringBE64(char *buf, uint64_t Value) {
195 StringBE32(buf, uint32_t(Value >> 32));
196 StringBE32(buf + 4, uint32_t(Value >> 0));
199 void String8(MCDataFragment &F, uint8_t Value) {
202 F.getContents() += StringRef(buf, 1);
205 void String16(MCDataFragment &F, uint16_t Value) {
207 if (isLittleEndian())
208 StringLE16(buf, Value);
210 StringBE16(buf, Value);
211 F.getContents() += StringRef(buf, 2);
214 void String32(MCDataFragment &F, uint32_t Value) {
216 if (isLittleEndian())
217 StringLE32(buf, Value);
219 StringBE32(buf, Value);
220 F.getContents() += StringRef(buf, 4);
223 void String64(MCDataFragment &F, uint64_t Value) {
225 if (isLittleEndian())
226 StringLE64(buf, Value);
228 StringBE64(buf, Value);
229 F.getContents() += StringRef(buf, 8);
232 void WriteHeader(uint64_t SectionDataSize,
233 unsigned NumberOfSections);
235 void WriteSymbolEntry(MCDataFragment *SymtabF,
236 MCDataFragment *ShndxF,
237 uint64_t name, uint8_t info,
238 uint64_t value, uint64_t size,
239 uint8_t other, uint32_t shndx,
242 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
244 const MCAsmLayout &Layout);
246 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
247 void WriteSymbolTable(MCDataFragment *SymtabF,
248 MCDataFragment *ShndxF,
249 const MCAssembler &Asm,
250 const MCAsmLayout &Layout,
251 const SectionIndexMapTy &SectionIndexMap);
253 virtual void RecordRelocation(const MCAssembler &Asm,
254 const MCAsmLayout &Layout,
255 const MCFragment *Fragment,
256 const MCFixup &Fixup,
257 MCValue Target, uint64_t &FixedValue);
259 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
262 // Map from a group section to the signature symbol
263 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
264 // Map from a signature symbol to the group section
265 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
266 // Map from a section to the section with the relocations
267 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
268 // Map from a section to its offset
269 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
271 /// ComputeSymbolTable - Compute the symbol table data
273 /// \param StringTable [out] - The string table data.
274 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
276 void ComputeSymbolTable(MCAssembler &Asm,
277 const SectionIndexMapTy &SectionIndexMap,
278 RevGroupMapTy RevGroupMap,
279 unsigned NumRegularSections);
281 void ComputeIndexMap(MCAssembler &Asm,
282 SectionIndexMapTy &SectionIndexMap,
283 const RelMapTy &RelMap);
285 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
288 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
289 const RelMapTy &RelMap);
291 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
292 SectionIndexMapTy &SectionIndexMap,
293 const RelMapTy &RelMap);
295 // Create the sections that show up in the symbol table. Currently
296 // those are the .note.GNU-stack section and the group sections.
297 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
298 GroupMapTy &GroupMap,
299 RevGroupMapTy &RevGroupMap,
300 SectionIndexMapTy &SectionIndexMap,
301 const RelMapTy &RelMap);
303 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
304 const MCAsmLayout &Layout);
306 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
307 const MCAsmLayout &Layout,
308 const SectionIndexMapTy &SectionIndexMap,
309 const SectionOffsetMapTy &SectionOffsetMap);
311 void ComputeSectionOrder(MCAssembler &Asm,
312 std::vector<const MCSectionELF*> &Sections);
314 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
315 uint64_t Address, uint64_t Offset,
316 uint64_t Size, uint32_t Link, uint32_t Info,
317 uint64_t Alignment, uint64_t EntrySize);
319 void WriteRelocationsFragment(const MCAssembler &Asm,
321 const MCSectionData *SD);
324 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
325 const MCSymbolData &DataA,
326 const MCFragment &FB,
330 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
331 void WriteSection(MCAssembler &Asm,
332 const SectionIndexMapTy &SectionIndexMap,
333 uint32_t GroupSymbolIndex,
334 uint64_t Offset, uint64_t Size, uint64_t Alignment,
335 const MCSectionELF &Section);
339 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
340 const MCFixupKindInfo &FKI =
341 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
343 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
346 bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
350 case MCSymbolRefExpr::VK_GOT:
351 case MCSymbolRefExpr::VK_PLT:
352 case MCSymbolRefExpr::VK_GOTPCREL:
353 case MCSymbolRefExpr::VK_GOTOFF:
354 case MCSymbolRefExpr::VK_TPOFF:
355 case MCSymbolRefExpr::VK_TLSGD:
356 case MCSymbolRefExpr::VK_GOTTPOFF:
357 case MCSymbolRefExpr::VK_INDNTPOFF:
358 case MCSymbolRefExpr::VK_NTPOFF:
359 case MCSymbolRefExpr::VK_GOTNTPOFF:
360 case MCSymbolRefExpr::VK_TLSLDM:
361 case MCSymbolRefExpr::VK_DTPOFF:
362 case MCSymbolRefExpr::VK_TLSLD:
367 ELFObjectWriter::~ELFObjectWriter()
370 // Emit the ELF header.
371 void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
372 unsigned NumberOfSections) {
378 // emitWord method behaves differently for ELF32 and ELF64, writing
379 // 4 bytes in the former and 8 in the latter.
381 Write8(0x7f); // e_ident[EI_MAG0]
382 Write8('E'); // e_ident[EI_MAG1]
383 Write8('L'); // e_ident[EI_MAG2]
384 Write8('F'); // e_ident[EI_MAG3]
386 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
389 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
391 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
393 Write8(TargetObjectWriter->getOSABI());
394 Write8(0); // e_ident[EI_ABIVERSION]
396 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
398 Write16(ELF::ET_REL); // e_type
400 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
402 Write32(ELF::EV_CURRENT); // e_version
403 WriteWord(0); // e_entry, no entry point in .o file
404 WriteWord(0); // e_phoff, no program header for .o
405 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
406 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
408 // e_flags = whatever the target wants
409 Write32(getEFlags());
411 // e_ehsize = ELF header size
412 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
414 Write16(0); // e_phentsize = prog header entry size
415 Write16(0); // e_phnum = # prog header entries = 0
417 // e_shentsize = Section header entry size
418 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
420 // e_shnum = # of section header ents
421 if (NumberOfSections >= ELF::SHN_LORESERVE)
422 Write16(ELF::SHN_UNDEF);
424 Write16(NumberOfSections);
426 // e_shstrndx = Section # of '.shstrtab'
427 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
428 Write16(ELF::SHN_XINDEX);
430 Write16(ShstrtabIndex);
433 void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
434 MCDataFragment *ShndxF,
436 uint8_t info, uint64_t value,
437 uint64_t size, uint8_t other,
441 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
442 String32(*ShndxF, shndx);
444 String32(*ShndxF, 0);
447 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
448 uint16_t(ELF::SHN_XINDEX) : shndx;
451 String32(*SymtabF, name); // st_name
452 String8(*SymtabF, info); // st_info
453 String8(*SymtabF, other); // st_other
454 String16(*SymtabF, Index); // st_shndx
455 String64(*SymtabF, value); // st_value
456 String64(*SymtabF, size); // st_size
458 String32(*SymtabF, name); // st_name
459 String32(*SymtabF, value); // st_value
460 String32(*SymtabF, size); // st_size
461 String8(*SymtabF, info); // st_info
462 String8(*SymtabF, other); // st_other
463 String16(*SymtabF, Index); // st_shndx
467 uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
468 const MCAsmLayout &Layout) {
469 if (Data.isCommon() && Data.isExternal())
470 return Data.getCommonAlignment();
472 const MCSymbol &Symbol = Data.getSymbol();
474 if (Symbol.isAbsolute() && Symbol.isVariable()) {
475 if (const MCExpr *Value = Symbol.getVariableValue()) {
477 if (Value->EvaluateAsAbsolute(IntValue, Layout))
478 return (uint64_t)IntValue;
482 if (!Symbol.isInSection())
486 if (Data.getFragment()) {
487 if (Data.getFlags() & ELF_Other_ThumbFunc)
488 return Layout.getSymbolOffset(&Data)+1;
490 return Layout.getSymbolOffset(&Data);
496 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
497 const MCAsmLayout &Layout) {
498 // The presence of symbol versions causes undefined symbols and
499 // versions declared with @@@ to be renamed.
501 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
502 ie = Asm.symbol_end(); it != ie; ++it) {
503 const MCSymbol &Alias = it->getSymbol();
504 const MCSymbol &Symbol = Alias.AliasedSymbol();
505 MCSymbolData &SD = Asm.getSymbolData(Symbol);
508 if (&Symbol == &Alias)
511 StringRef AliasName = Alias.getName();
512 size_t Pos = AliasName.find('@');
513 if (Pos == StringRef::npos)
516 // Aliases defined with .symvar copy the binding from the symbol they alias.
517 // This is the first place we are able to copy this information.
518 it->setExternal(SD.isExternal());
519 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
521 StringRef Rest = AliasName.substr(Pos);
522 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
525 // FIXME: produce a better error message.
526 if (Symbol.isUndefined() && Rest.startswith("@@") &&
527 !Rest.startswith("@@@"))
528 report_fatal_error("A @@ version cannot be undefined");
530 Renames.insert(std::make_pair(&Symbol, &Alias));
534 void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
535 MCDataFragment *ShndxF,
537 const MCAsmLayout &Layout) {
538 MCSymbolData &OrigData = *MSD.SymbolData;
540 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
542 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
543 Data.getSymbol().isVariable();
545 uint8_t Binding = MCELF::GetBinding(OrigData);
546 uint8_t Visibility = MCELF::GetVisibility(OrigData);
547 uint8_t Type = MCELF::GetType(Data);
549 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
550 uint8_t Other = Visibility;
552 uint64_t Value = SymbolValue(Data, Layout);
555 assert(!(Data.isCommon() && !Data.isExternal()));
557 const MCExpr *ESize = Data.getSize();
560 if (!ESize->EvaluateAsAbsolute(Res, Layout))
561 report_fatal_error("Size expression must be absolute.");
565 // Write out the symbol table entry
566 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
567 Size, Other, MSD.SectionIndex, IsReserved);
570 void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
571 MCDataFragment *ShndxF,
572 const MCAssembler &Asm,
573 const MCAsmLayout &Layout,
574 const SectionIndexMapTy &SectionIndexMap) {
575 // The string table must be emitted first because we need the index
576 // into the string table for all the symbol names.
577 assert(StringTable.size() && "Missing string table");
579 // FIXME: Make sure the start of the symbol table is aligned.
581 // The first entry is the undefined symbol entry.
582 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
584 // Write the symbol table entries.
585 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
586 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
587 ELFSymbolData &MSD = LocalSymbolData[i];
588 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
591 // Write out a symbol table entry for each regular section.
592 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
594 const MCSectionELF &Section =
595 static_cast<const MCSectionELF&>(i->getSection());
596 if (Section.getType() == ELF::SHT_RELA ||
597 Section.getType() == ELF::SHT_REL ||
598 Section.getType() == ELF::SHT_STRTAB ||
599 Section.getType() == ELF::SHT_SYMTAB ||
600 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
602 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
603 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
605 LastLocalSymbolIndex++;
608 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
609 ELFSymbolData &MSD = ExternalSymbolData[i];
610 MCSymbolData &Data = *MSD.SymbolData;
611 assert(((Data.getFlags() & ELF_STB_Global) ||
612 (Data.getFlags() & ELF_STB_Weak)) &&
613 "External symbol requires STB_GLOBAL or STB_WEAK flag");
614 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
615 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
616 LastLocalSymbolIndex++;
619 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
620 ELFSymbolData &MSD = UndefinedSymbolData[i];
621 MCSymbolData &Data = *MSD.SymbolData;
622 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
623 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
624 LastLocalSymbolIndex++;
628 const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
629 const MCValue &Target,
631 const MCFixup &Fixup,
632 bool IsPCRel) const {
633 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
634 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
635 const MCSymbol *Renamed = Renames.lookup(&Symbol);
636 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
638 if (ASymbol.isUndefined()) {
644 if (SD.isExternal()) {
650 const MCSectionELF &Section =
651 static_cast<const MCSectionELF&>(ASymbol.getSection());
652 const SectionKind secKind = Section.getKind();
655 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
657 if (secKind.isThreadLocal()) {
663 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
664 const MCSectionELF &Sec2 =
665 static_cast<const MCSectionELF&>(F.getParent()->getSection());
667 if (&Sec2 != &Section &&
668 (Kind == MCSymbolRefExpr::VK_PLT ||
669 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
670 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
676 if (Section.getFlags() & ELF::SHF_MERGE) {
677 if (Target.getConstant() == 0)
678 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
684 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
689 void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
690 const MCAsmLayout &Layout,
691 const MCFragment *Fragment,
692 const MCFixup &Fixup,
694 uint64_t &FixedValue) {
697 int64_t Value = Target.getConstant();
698 const MCSymbol *RelocSymbol = NULL;
700 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
701 if (!Target.isAbsolute()) {
702 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
703 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
704 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
706 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
707 const MCSymbol &SymbolB = RefB->getSymbol();
708 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
711 // Offset of the symbol in the section
712 int64_t a = Layout.getSymbolOffset(&SDB);
714 // Offset of the relocation in the section
715 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
720 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
721 MCFragment *F = SD.getFragment();
723 Index = F->getParent()->getOrdinal() + 1;
725 // Offset of the symbol in the section
726 Value += Layout.getSymbolOffset(&SD);
728 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
729 WeakrefUsedInReloc.insert(RelocSymbol);
731 UsedInReloc.insert(RelocSymbol);
735 // Compensate for the addend on i386.
741 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
742 (RelocSymbol != 0), Addend);
743 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
744 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
745 if (RelocNeedsGOT(Modifier))
748 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
751 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
752 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
754 if (!hasRelocationAddend())
758 assert(isInt<64>(Addend));
760 assert(isInt<32>(Addend));
762 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
763 Relocations[Fragment->getParent()].push_back(ERE);
768 ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
770 MCSymbolData &SD = Asm.getSymbolData(*S);
771 return SD.getIndex();
774 bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
775 const MCSymbolData &Data,
776 bool Used, bool Renamed) {
777 if (Data.getFlags() & ELF_Other_Weakref)
786 const MCSymbol &Symbol = Data.getSymbol();
788 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
791 const MCSymbol &A = Symbol.AliasedSymbol();
792 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
795 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
796 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
799 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
802 if (Symbol.isTemporary())
808 bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
809 bool isUsedInReloc) {
810 if (Data.isExternal())
813 const MCSymbol &Symbol = Data.getSymbol();
814 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
816 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
817 if (isSignature && !isUsedInReloc)
826 void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
827 SectionIndexMapTy &SectionIndexMap,
828 const RelMapTy &RelMap) {
830 for (MCAssembler::iterator it = Asm.begin(),
831 ie = Asm.end(); it != ie; ++it) {
832 const MCSectionELF &Section =
833 static_cast<const MCSectionELF &>(it->getSection());
834 if (Section.getType() != ELF::SHT_GROUP)
836 SectionIndexMap[&Section] = Index++;
839 for (MCAssembler::iterator it = Asm.begin(),
840 ie = Asm.end(); it != ie; ++it) {
841 const MCSectionELF &Section =
842 static_cast<const MCSectionELF &>(it->getSection());
843 if (Section.getType() == ELF::SHT_GROUP ||
844 Section.getType() == ELF::SHT_REL ||
845 Section.getType() == ELF::SHT_RELA)
847 SectionIndexMap[&Section] = Index++;
848 const MCSectionELF *RelSection = RelMap.lookup(&Section);
850 SectionIndexMap[RelSection] = Index++;
854 void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
855 const SectionIndexMapTy &SectionIndexMap,
856 RevGroupMapTy RevGroupMap,
857 unsigned NumRegularSections) {
858 // FIXME: Is this the correct place to do this?
859 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
861 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
862 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
863 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
864 Data.setExternal(true);
865 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
868 // Index 0 is always the empty string.
869 StringMap<uint64_t> StringIndexMap;
870 StringTable += '\x00';
872 // FIXME: We could optimize suffixes in strtab in the same way we
873 // optimize them in shstrtab.
875 // Add the data for the symbols.
876 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
877 ie = Asm.symbol_end(); it != ie; ++it) {
878 const MCSymbol &Symbol = it->getSymbol();
880 bool Used = UsedInReloc.count(&Symbol);
881 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
882 bool isSignature = RevGroupMap.count(&Symbol);
884 if (!isInSymtab(Asm, *it,
885 Used || WeakrefUsed || isSignature,
886 Renames.count(&Symbol)))
891 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
893 // Undefined symbols are global, but this is the first place we
894 // are able to set it.
895 bool Local = isLocal(*it, isSignature, Used);
896 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
897 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
898 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
899 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
902 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
903 MCELF::SetBinding(*it, ELF::STB_WEAK);
905 if (it->isCommon()) {
907 MSD.SectionIndex = ELF::SHN_COMMON;
908 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
909 MSD.SectionIndex = ELF::SHN_ABS;
910 } else if (RefSymbol.isUndefined()) {
911 if (isSignature && !Used)
912 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
914 MSD.SectionIndex = ELF::SHN_UNDEF;
916 const MCSectionELF &Section =
917 static_cast<const MCSectionELF&>(RefSymbol.getSection());
918 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
919 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
920 NeedsSymtabShndx = true;
921 assert(MSD.SectionIndex && "Invalid section index!");
924 // The @@@ in symbol version is replaced with @ in undefined symbols and
925 // @@ in defined ones.
926 StringRef Name = Symbol.getName();
929 size_t Pos = Name.find("@@@");
930 if (Pos != StringRef::npos) {
931 Buf += Name.substr(0, Pos);
932 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
933 Buf += Name.substr(Pos + Skip);
937 uint64_t &Entry = StringIndexMap[Name];
939 Entry = StringTable.size();
941 StringTable += '\x00';
943 MSD.StringIndex = Entry;
944 if (MSD.SectionIndex == ELF::SHN_UNDEF)
945 UndefinedSymbolData.push_back(MSD);
947 LocalSymbolData.push_back(MSD);
949 ExternalSymbolData.push_back(MSD);
952 // Symbols are required to be in lexicographic order.
953 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
954 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
955 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
957 // Set the symbol indices. Local symbols must come before all other
958 // symbols with non-local bindings.
960 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
961 LocalSymbolData[i].SymbolData->setIndex(Index++);
963 Index += NumRegularSections;
965 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
966 ExternalSymbolData[i].SymbolData->setIndex(Index++);
967 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
968 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
970 if (NumRegularSections > ELF::SHN_LORESERVE)
971 NeedsSymtabShndx = true;
974 void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
977 for (MCAssembler::const_iterator it = Asm.begin(),
978 ie = Asm.end(); it != ie; ++it) {
979 const MCSectionData &SD = *it;
980 if (Relocations[&SD].empty())
983 MCContext &Ctx = Asm.getContext();
984 const MCSectionELF &Section =
985 static_cast<const MCSectionELF&>(SD.getSection());
987 const StringRef SectionName = Section.getSectionName();
988 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
989 RelaSectionName += SectionName;
992 if (hasRelocationAddend())
993 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
995 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
997 const MCSectionELF *RelaSection =
998 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
999 ELF::SHT_RELA : ELF::SHT_REL, 0,
1000 SectionKind::getReadOnly(),
1002 RelMap[&Section] = RelaSection;
1003 Asm.getOrCreateSectionData(*RelaSection);
1007 void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1008 const RelMapTy &RelMap) {
1009 for (MCAssembler::const_iterator it = Asm.begin(),
1010 ie = Asm.end(); it != ie; ++it) {
1011 const MCSectionData &SD = *it;
1012 const MCSectionELF &Section =
1013 static_cast<const MCSectionELF&>(SD.getSection());
1015 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1018 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1019 RelaSD.setAlignment(is64Bit() ? 8 : 4);
1021 MCDataFragment *F = new MCDataFragment(&RelaSD);
1022 WriteRelocationsFragment(Asm, F, &*it);
1026 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1027 uint64_t Flags, uint64_t Address,
1028 uint64_t Offset, uint64_t Size,
1029 uint32_t Link, uint32_t Info,
1031 uint64_t EntrySize) {
1032 Write32(Name); // sh_name: index into string table
1033 Write32(Type); // sh_type
1034 WriteWord(Flags); // sh_flags
1035 WriteWord(Address); // sh_addr
1036 WriteWord(Offset); // sh_offset
1037 WriteWord(Size); // sh_size
1038 Write32(Link); // sh_link
1039 Write32(Info); // sh_info
1040 WriteWord(Alignment); // sh_addralign
1041 WriteWord(EntrySize); // sh_entsize
1044 void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1046 const MCSectionData *SD) {
1047 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1049 // Sort the relocation entries. Most targets just sort by r_offset, but some
1050 // (e.g., MIPS) have additional constraints.
1051 TargetObjectWriter->sortRelocs(Asm, Relocs);
1053 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1054 ELFRelocationEntry entry = Relocs[e - i - 1];
1058 else if (entry.Index < 0)
1059 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1061 entry.Index += LocalSymbolData.size();
1063 String64(*F, entry.r_offset);
1064 if (TargetObjectWriter->isN64()) {
1065 String32(*F, entry.Index);
1067 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1068 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1069 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1070 String8(*F, TargetObjectWriter->getRType(entry.Type));
1073 struct ELF::Elf64_Rela ERE64;
1074 ERE64.setSymbolAndType(entry.Index, entry.Type);
1075 String64(*F, ERE64.r_info);
1077 if (hasRelocationAddend())
1078 String64(*F, entry.r_addend);
1080 String32(*F, entry.r_offset);
1082 struct ELF::Elf32_Rela ERE32;
1083 ERE32.setSymbolAndType(entry.Index, entry.Type);
1084 String32(*F, ERE32.r_info);
1086 if (hasRelocationAddend())
1087 String32(*F, entry.r_addend);
1092 static int compareBySuffix(const void *a, const void *b) {
1093 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1094 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1095 const StringRef &NameA = secA->getSectionName();
1096 const StringRef &NameB = secB->getSectionName();
1097 const unsigned sizeA = NameA.size();
1098 const unsigned sizeB = NameB.size();
1099 const unsigned len = std::min(sizeA, sizeB);
1100 for (unsigned int i = 0; i < len; ++i) {
1101 char ca = NameA[sizeA - i - 1];
1102 char cb = NameB[sizeB - i - 1];
1107 return sizeB - sizeA;
1110 void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1111 MCAsmLayout &Layout,
1112 SectionIndexMapTy &SectionIndexMap,
1113 const RelMapTy &RelMap) {
1114 MCContext &Ctx = Asm.getContext();
1117 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1119 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
1120 const MCSectionELF *ShstrtabSection =
1121 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1122 SectionKind::getReadOnly());
1123 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1124 ShstrtabSD.setAlignment(1);
1126 const MCSectionELF *SymtabSection =
1127 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1128 SectionKind::getReadOnly(),
1130 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
1131 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
1133 MCSectionData *SymtabShndxSD = NULL;
1135 if (NeedsSymtabShndx) {
1136 const MCSectionELF *SymtabShndxSection =
1137 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
1138 SectionKind::getReadOnly(), 4, "");
1139 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1140 SymtabShndxSD->setAlignment(4);
1143 const MCSectionELF *StrtabSection;
1144 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1145 SectionKind::getReadOnly());
1146 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1147 StrtabSD.setAlignment(1);
1149 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1151 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1152 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1153 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
1156 F = new MCDataFragment(&SymtabSD);
1157 MCDataFragment *ShndxF = NULL;
1158 if (NeedsSymtabShndx) {
1159 ShndxF = new MCDataFragment(SymtabShndxSD);
1161 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
1163 F = new MCDataFragment(&StrtabSD);
1164 F->getContents().append(StringTable.begin(), StringTable.end());
1166 F = new MCDataFragment(&ShstrtabSD);
1168 std::vector<const MCSectionELF*> Sections;
1169 for (MCAssembler::const_iterator it = Asm.begin(),
1170 ie = Asm.end(); it != ie; ++it) {
1171 const MCSectionELF &Section =
1172 static_cast<const MCSectionELF&>(it->getSection());
1173 Sections.push_back(&Section);
1175 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1177 // Section header string table.
1179 // The first entry of a string table holds a null character so skip
1182 F->getContents() += '\x00';
1184 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1185 const MCSectionELF &Section = *Sections[I];
1187 StringRef Name = Section.getSectionName();
1189 StringRef PreviousName = Sections[I - 1]->getSectionName();
1190 if (PreviousName.endswith(Name)) {
1191 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1195 // Remember the index into the string table so we can write it
1196 // into the sh_name field of the section header table.
1197 SectionStringTableIndex[&Section] = Index;
1199 Index += Name.size() + 1;
1200 F->getContents() += Name;
1201 F->getContents() += '\x00';
1205 void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1206 MCAsmLayout &Layout,
1207 GroupMapTy &GroupMap,
1208 RevGroupMapTy &RevGroupMap,
1209 SectionIndexMapTy &SectionIndexMap,
1210 const RelMapTy &RelMap) {
1211 // Create the .note.GNU-stack section if needed.
1212 MCContext &Ctx = Asm.getContext();
1213 if (Asm.getNoExecStack()) {
1214 const MCSectionELF *GnuStackSection =
1215 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1216 SectionKind::getReadOnly());
1217 Asm.getOrCreateSectionData(*GnuStackSection);
1221 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1223 const MCSectionELF &Section =
1224 static_cast<const MCSectionELF&>(it->getSection());
1225 if (!(Section.getFlags() & ELF::SHF_GROUP))
1228 const MCSymbol *SignatureSymbol = Section.getGroup();
1229 Asm.getOrCreateSymbolData(*SignatureSymbol);
1230 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
1232 Group = Ctx.CreateELFGroupSection();
1233 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1234 Data.setAlignment(4);
1235 MCDataFragment *F = new MCDataFragment(&Data);
1236 String32(*F, ELF::GRP_COMDAT);
1238 GroupMap[Group] = SignatureSymbol;
1241 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1243 // Add sections to the groups
1244 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1246 const MCSectionELF &Section =
1247 static_cast<const MCSectionELF&>(it->getSection());
1248 if (!(Section.getFlags() & ELF::SHF_GROUP))
1250 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
1251 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1252 // FIXME: we could use the previous fragment
1253 MCDataFragment *F = new MCDataFragment(&Data);
1254 unsigned Index = SectionIndexMap.lookup(&Section);
1255 String32(*F, Index);
1259 void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1260 const SectionIndexMapTy &SectionIndexMap,
1261 uint32_t GroupSymbolIndex,
1262 uint64_t Offset, uint64_t Size,
1264 const MCSectionELF &Section) {
1265 uint64_t sh_link = 0;
1266 uint64_t sh_info = 0;
1268 switch(Section.getType()) {
1269 case ELF::SHT_DYNAMIC:
1270 sh_link = SectionStringTableIndex[&Section];
1275 case ELF::SHT_RELA: {
1276 const MCSectionELF *SymtabSection;
1277 const MCSectionELF *InfoSection;
1278 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1280 SectionKind::getReadOnly());
1281 sh_link = SectionIndexMap.lookup(SymtabSection);
1282 assert(sh_link && ".symtab not found");
1284 // Remove ".rel" and ".rela" prefixes.
1285 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1286 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1288 InfoSection = Asm.getContext().getELFSection(SectionName,
1289 ELF::SHT_PROGBITS, 0,
1290 SectionKind::getReadOnly());
1291 sh_info = SectionIndexMap.lookup(InfoSection);
1295 case ELF::SHT_SYMTAB:
1296 case ELF::SHT_DYNSYM:
1297 sh_link = StringTableIndex;
1298 sh_info = LastLocalSymbolIndex;
1301 case ELF::SHT_SYMTAB_SHNDX:
1302 sh_link = SymbolTableIndex;
1305 case ELF::SHT_PROGBITS:
1306 case ELF::SHT_STRTAB:
1307 case ELF::SHT_NOBITS:
1310 case ELF::SHT_ARM_ATTRIBUTES:
1311 case ELF::SHT_INIT_ARRAY:
1312 case ELF::SHT_FINI_ARRAY:
1313 case ELF::SHT_PREINIT_ARRAY:
1314 case ELF::SHT_X86_64_UNWIND:
1318 case ELF::SHT_GROUP:
1319 sh_link = SymbolTableIndex;
1320 sh_info = GroupSymbolIndex;
1324 assert(0 && "FIXME: sh_type value not supported!");
1328 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1329 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1330 Alignment, Section.getEntrySize());
1333 bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
1334 return SD.getOrdinal() == ~UINT32_C(0) &&
1335 !SD.getSection().isVirtualSection();
1338 uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
1340 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1342 const MCFragment &F = *i;
1343 assert(F.getKind() == MCFragment::FT_Data);
1344 Ret += cast<MCDataFragment>(F).getContents().size();
1349 uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1350 const MCSectionData &SD) {
1351 if (IsELFMetaDataSection(SD))
1352 return DataSectionSize(SD);
1353 return Layout.getSectionFileSize(&SD);
1356 uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1357 const MCSectionData &SD) {
1358 if (IsELFMetaDataSection(SD))
1359 return DataSectionSize(SD);
1360 return Layout.getSectionAddressSize(&SD);
1363 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1364 const MCAsmLayout &Layout,
1365 const MCSectionELF &Section) {
1366 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1368 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1369 WriteZeros(Padding);
1371 if (IsELFMetaDataSection(SD)) {
1372 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1374 const MCFragment &F = *i;
1375 assert(F.getKind() == MCFragment::FT_Data);
1376 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1379 Asm.writeSectionData(&SD, Layout);
1383 void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1384 const GroupMapTy &GroupMap,
1385 const MCAsmLayout &Layout,
1386 const SectionIndexMapTy &SectionIndexMap,
1387 const SectionOffsetMapTy &SectionOffsetMap) {
1388 const unsigned NumSections = Asm.size() + 1;
1390 std::vector<const MCSectionELF*> Sections;
1391 Sections.resize(NumSections - 1);
1393 for (SectionIndexMapTy::const_iterator i=
1394 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1395 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
1396 Sections[p.second - 1] = p.first;
1399 // Null section first.
1400 uint64_t FirstSectionSize =
1401 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1402 uint32_t FirstSectionLink =
1403 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1404 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
1406 for (unsigned i = 0; i < NumSections - 1; ++i) {
1407 const MCSectionELF &Section = *Sections[i];
1408 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1409 uint32_t GroupSymbolIndex;
1410 if (Section.getType() != ELF::SHT_GROUP)
1411 GroupSymbolIndex = 0;
1413 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1414 GroupMap.lookup(&Section));
1416 uint64_t Size = GetSectionAddressSize(Layout, SD);
1418 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
1419 SectionOffsetMap.lookup(&Section), Size,
1420 SD.getAlignment(), Section);
1424 void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1425 std::vector<const MCSectionELF*> &Sections) {
1426 for (MCAssembler::iterator it = Asm.begin(),
1427 ie = Asm.end(); it != ie; ++it) {
1428 const MCSectionELF &Section =
1429 static_cast<const MCSectionELF &>(it->getSection());
1430 if (Section.getType() == ELF::SHT_GROUP)
1431 Sections.push_back(&Section);
1434 for (MCAssembler::iterator it = Asm.begin(),
1435 ie = Asm.end(); it != ie; ++it) {
1436 const MCSectionELF &Section =
1437 static_cast<const MCSectionELF &>(it->getSection());
1438 if (Section.getType() != ELF::SHT_GROUP &&
1439 Section.getType() != ELF::SHT_REL &&
1440 Section.getType() != ELF::SHT_RELA)
1441 Sections.push_back(&Section);
1444 for (MCAssembler::iterator it = Asm.begin(),
1445 ie = Asm.end(); it != ie; ++it) {
1446 const MCSectionELF &Section =
1447 static_cast<const MCSectionELF &>(it->getSection());
1448 if (Section.getType() == ELF::SHT_REL ||
1449 Section.getType() == ELF::SHT_RELA)
1450 Sections.push_back(&Section);
1454 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1455 const MCAsmLayout &Layout) {
1456 GroupMapTy GroupMap;
1457 RevGroupMapTy RevGroupMap;
1458 SectionIndexMapTy SectionIndexMap;
1460 unsigned NumUserSections = Asm.size();
1462 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1463 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1465 const unsigned NumUserAndRelocSections = Asm.size();
1466 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1467 RevGroupMap, SectionIndexMap, RelMap);
1468 const unsigned AllSections = Asm.size();
1469 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1471 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1473 // Compute symbol table information.
1474 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1477 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1479 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1480 const_cast<MCAsmLayout&>(Layout),
1484 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1485 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1486 sizeof(ELF::Elf32_Ehdr);
1487 uint64_t FileOff = HeaderSize;
1489 std::vector<const MCSectionELF*> Sections;
1490 ComputeSectionOrder(Asm, Sections);
1491 unsigned NumSections = Sections.size();
1492 SectionOffsetMapTy SectionOffsetMap;
1493 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1494 const MCSectionELF &Section = *Sections[i];
1495 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1497 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1499 // Remember the offset into the file for this section.
1500 SectionOffsetMap[&Section] = FileOff;
1502 // Get the size of the section in the output file (including padding).
1503 FileOff += GetSectionFileSize(Layout, SD);
1506 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1508 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1510 uint64_t SectionHeaderEntrySize = is64Bit() ?
1511 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1512 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1514 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1515 const MCSectionELF &Section = *Sections[i];
1516 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1518 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1520 // Remember the offset into the file for this section.
1521 SectionOffsetMap[&Section] = FileOff;
1523 // Get the size of the section in the output file (including padding).
1524 FileOff += GetSectionFileSize(Layout, SD);
1527 // Write out the ELF header ...
1528 WriteHeader(SectionHeaderOffset, NumSections + 1);
1530 // ... then the regular sections ...
1531 // + because of .shstrtab
1532 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1533 WriteDataSectionData(Asm, Layout, *Sections[i]);
1535 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1536 WriteZeros(Padding);
1538 // ... then the section header table ...
1539 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1542 // ... and then the remaining sections ...
1543 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1544 WriteDataSectionData(Asm, Layout, *Sections[i]);
1548 ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1549 const MCSymbolData &DataA,
1550 const MCFragment &FB,
1552 bool IsPCRel) const {
1553 if (DataA.getFlags() & ELF_STB_Weak)
1555 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1556 Asm, DataA, FB,InSet, IsPCRel);
1559 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1561 bool IsLittleEndian) {
1562 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);