Record in a MCSymbolELF if it has been used in a relocation.
[oota-llvm.git] / lib / MC / ELFObjectWriter.cpp
1 //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements ELF object file writer information.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/MC/MCELFObjectWriter.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCELFSymbolFlags.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCFixupKindInfo.h"
27 #include "llvm/MC/MCObjectWriter.h"
28 #include "llvm/MC/MCSectionELF.h"
29 #include "llvm/MC/MCSymbolELF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/Compression.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include <vector>
38 using namespace llvm;
39
40 #undef  DEBUG_TYPE
41 #define DEBUG_TYPE "reloc-info"
42
43 namespace {
44
45 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
46
47 class ELFObjectWriter;
48
49 class SymbolTableWriter {
50   ELFObjectWriter &EWriter;
51   bool Is64Bit;
52
53   // indexes we are going to write to .symtab_shndx.
54   std::vector<uint32_t> ShndxIndexes;
55
56   // The numbel of symbols written so far.
57   unsigned NumWritten;
58
59   void createSymtabShndx();
60
61   template <typename T> void write(T Value);
62
63 public:
64   SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
65
66   void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
67                    uint8_t other, uint32_t shndx, bool Reserved);
68
69   ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
70 };
71
72 class ELFObjectWriter : public MCObjectWriter {
73     static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
74     static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
75     static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
76                            bool Used, bool Renamed);
77     static bool isLocal(const MCSymbolELF &Symbol, bool IsSignature);
78
79     /// Helper struct for containing some precomputed information on symbols.
80     struct ELFSymbolData {
81       const MCSymbolELF *Symbol;
82       uint32_t SectionIndex;
83       StringRef Name;
84
85       // Support lexicographic sorting.
86       bool operator<(const ELFSymbolData &RHS) const {
87         unsigned LHSType = Symbol->getType();
88         unsigned RHSType = RHS.Symbol->getType();
89         if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
90           return false;
91         if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
92           return true;
93         if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
94           return SectionIndex < RHS.SectionIndex;
95         return Name < RHS.Name;
96       }
97     };
98
99     /// The target specific ELF writer instance.
100     std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
101
102     SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
103     DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
104
105     llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
106         Relocations;
107
108     /// @}
109     /// @name Symbol Table Data
110     /// @{
111
112     StringTableBuilder StrTabBuilder;
113
114     /// @}
115
116     // This holds the symbol table index of the last local symbol.
117     unsigned LastLocalSymbolIndex;
118     // This holds the .strtab section index.
119     unsigned StringTableIndex;
120     // This holds the .symtab section index.
121     unsigned SymbolTableIndex;
122     // This holds the .symtab_shndx section index.
123     unsigned SymtabShndxSectionIndex = 0;
124
125     // Sections in the order they are to be output in the section table.
126     std::vector<const MCSectionELF *> SectionTable;
127     unsigned addToSectionTable(const MCSectionELF *Sec);
128
129     // TargetObjectWriter wrappers.
130     bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
131     bool hasRelocationAddend() const {
132       return TargetObjectWriter->hasRelocationAddend();
133     }
134     unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
135                           bool IsPCRel) const {
136       return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
137     }
138
139   public:
140     ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
141                     bool IsLittleEndian)
142         : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
143
144     void reset() override {
145       WeakrefUsedInReloc.clear();
146       Renames.clear();
147       Relocations.clear();
148       StrTabBuilder.clear();
149       SectionTable.clear();
150       MCObjectWriter::reset();
151     }
152
153     ~ELFObjectWriter() override;
154
155     void WriteWord(uint64_t W) {
156       if (is64Bit())
157         Write64(W);
158       else
159         Write32(W);
160     }
161
162     template <typename T> void write(T Val) {
163       if (IsLittleEndian)
164         support::endian::Writer<support::little>(OS).write(Val);
165       else
166         support::endian::Writer<support::big>(OS).write(Val);
167     }
168
169     void writeHeader(const MCAssembler &Asm);
170
171     void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
172                      ELFSymbolData &MSD, const MCAsmLayout &Layout);
173
174     // Start and end offset of each section
175     typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
176         SectionOffsetsTy;
177
178     bool shouldRelocateWithSymbol(const MCAssembler &Asm,
179                                   const MCSymbolRefExpr *RefA,
180                                   const MCSymbol *Sym, uint64_t C,
181                                   unsigned Type) const;
182
183     void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
184                           const MCFragment *Fragment, const MCFixup &Fixup,
185                           MCValue Target, bool &IsPCRel,
186                           uint64_t &FixedValue) override;
187
188     // Map from a signature symbol to the group section index
189     typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
190
191     /// Compute the symbol table data
192     ///
193     /// \param Asm - The assembler.
194     /// \param SectionIndexMap - Maps a section to its index.
195     /// \param RevGroupMap - Maps a signature symbol to the group section.
196     void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
197                             const SectionIndexMapTy &SectionIndexMap,
198                             const RevGroupMapTy &RevGroupMap,
199                             SectionOffsetsTy &SectionOffsets);
200
201     MCSectionELF *createRelocationSection(MCContext &Ctx,
202                                           const MCSectionELF &Sec);
203
204     const MCSectionELF *createStringTable(MCContext &Ctx);
205
206     void ExecutePostLayoutBinding(MCAssembler &Asm,
207                                   const MCAsmLayout &Layout) override;
208
209     void writeSectionHeader(const MCAssembler &Asm, const MCAsmLayout &Layout,
210                             const SectionIndexMapTy &SectionIndexMap,
211                             const SectionOffsetsTy &SectionOffsets);
212
213     void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
214                           const MCAsmLayout &Layout);
215
216     void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
217                           uint64_t Address, uint64_t Offset, uint64_t Size,
218                           uint32_t Link, uint32_t Info, uint64_t Alignment,
219                           uint64_t EntrySize);
220
221     void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
222
223     bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
224                                                 const MCSymbol &SymA,
225                                                 const MCFragment &FB,
226                                                 bool InSet,
227                                                 bool IsPCRel) const override;
228
229     bool isWeak(const MCSymbol &Sym) const override;
230
231     void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
232     void writeSection(const SectionIndexMapTy &SectionIndexMap,
233                       uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
234                       const MCSectionELF &Section);
235   };
236 }
237
238 unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
239   SectionTable.push_back(Sec);
240   StrTabBuilder.add(Sec->getSectionName());
241   return SectionTable.size();
242 }
243
244 void SymbolTableWriter::createSymtabShndx() {
245   if (!ShndxIndexes.empty())
246     return;
247
248   ShndxIndexes.resize(NumWritten);
249 }
250
251 template <typename T> void SymbolTableWriter::write(T Value) {
252   EWriter.write(Value);
253 }
254
255 SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
256     : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
257
258 void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
259                                     uint64_t size, uint8_t other,
260                                     uint32_t shndx, bool Reserved) {
261   bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
262
263   if (LargeIndex)
264     createSymtabShndx();
265
266   if (!ShndxIndexes.empty()) {
267     if (LargeIndex)
268       ShndxIndexes.push_back(shndx);
269     else
270       ShndxIndexes.push_back(0);
271   }
272
273   uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
274
275   if (Is64Bit) {
276     write(name);  // st_name
277     write(info);  // st_info
278     write(other); // st_other
279     write(Index); // st_shndx
280     write(value); // st_value
281     write(size);  // st_size
282   } else {
283     write(name);            // st_name
284     write(uint32_t(value)); // st_value
285     write(uint32_t(size));  // st_size
286     write(info);            // st_info
287     write(other);           // st_other
288     write(Index);           // st_shndx
289   }
290
291   ++NumWritten;
292 }
293
294 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
295   const MCFixupKindInfo &FKI =
296     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
297
298   return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
299 }
300
301 ELFObjectWriter::~ELFObjectWriter()
302 {}
303
304 // Emit the ELF header.
305 void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
306   // ELF Header
307   // ----------
308   //
309   // Note
310   // ----
311   // emitWord method behaves differently for ELF32 and ELF64, writing
312   // 4 bytes in the former and 8 in the latter.
313
314   WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
315
316   Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
317
318   // e_ident[EI_DATA]
319   Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
320
321   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
322   // e_ident[EI_OSABI]
323   Write8(TargetObjectWriter->getOSABI());
324   Write8(0);                  // e_ident[EI_ABIVERSION]
325
326   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
327
328   Write16(ELF::ET_REL);             // e_type
329
330   Write16(TargetObjectWriter->getEMachine()); // e_machine = target
331
332   Write32(ELF::EV_CURRENT);         // e_version
333   WriteWord(0);                    // e_entry, no entry point in .o file
334   WriteWord(0);                    // e_phoff, no program header for .o
335   WriteWord(0);                     // e_shoff = sec hdr table off in bytes
336
337   // e_flags = whatever the target wants
338   Write32(Asm.getELFHeaderEFlags());
339
340   // e_ehsize = ELF header size
341   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
342
343   Write16(0);                  // e_phentsize = prog header entry size
344   Write16(0);                  // e_phnum = # prog header entries = 0
345
346   // e_shentsize = Section header entry size
347   Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
348
349   // e_shnum     = # of section header ents
350   Write16(0);
351
352   // e_shstrndx  = Section # of '.shstrtab'
353   assert(StringTableIndex < ELF::SHN_LORESERVE);
354   Write16(StringTableIndex);
355 }
356
357 uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
358                                       const MCAsmLayout &Layout) {
359   if (Sym.isCommon() && Sym.isExternal())
360     return Sym.getCommonAlignment();
361
362   uint64_t Res;
363   if (!Layout.getSymbolOffset(Sym, Res))
364     return 0;
365
366   if (Layout.getAssembler().isThumbFunc(&Sym))
367     Res |= 1;
368
369   return Res;
370 }
371
372 void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
373                                                const MCAsmLayout &Layout) {
374   // The presence of symbol versions causes undefined symbols and
375   // versions declared with @@@ to be renamed.
376
377   for (const MCSymbol &A : Asm.symbols()) {
378     const auto &Alias = cast<MCSymbolELF>(A);
379     // Not an alias.
380     if (!Alias.isVariable())
381       continue;
382     auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
383     if (!Ref)
384       continue;
385     const auto &Symbol = cast<MCSymbolELF>(Ref->getSymbol());
386
387     StringRef AliasName = Alias.getName();
388     size_t Pos = AliasName.find('@');
389     if (Pos == StringRef::npos)
390       continue;
391
392     // Aliases defined with .symvar copy the binding from the symbol they alias.
393     // This is the first place we are able to copy this information.
394     Alias.setExternal(Symbol.isExternal());
395     Alias.setBinding(Symbol.getBinding());
396
397     StringRef Rest = AliasName.substr(Pos);
398     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
399       continue;
400
401     // FIXME: produce a better error message.
402     if (Symbol.isUndefined() && Rest.startswith("@@") &&
403         !Rest.startswith("@@@"))
404       report_fatal_error("A @@ version cannot be undefined");
405
406     Renames.insert(std::make_pair(&Symbol, &Alias));
407   }
408 }
409
410 static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
411   uint8_t Type = newType;
412
413   // Propagation rules:
414   // IFUNC > FUNC > OBJECT > NOTYPE
415   // TLS_OBJECT > OBJECT > NOTYPE
416   //
417   // dont let the new type degrade the old type
418   switch (origType) {
419   default:
420     break;
421   case ELF::STT_GNU_IFUNC:
422     if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
423         Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
424       Type = ELF::STT_GNU_IFUNC;
425     break;
426   case ELF::STT_FUNC:
427     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
428         Type == ELF::STT_TLS)
429       Type = ELF::STT_FUNC;
430     break;
431   case ELF::STT_OBJECT:
432     if (Type == ELF::STT_NOTYPE)
433       Type = ELF::STT_OBJECT;
434     break;
435   case ELF::STT_TLS:
436     if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
437         Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
438       Type = ELF::STT_TLS;
439     break;
440   }
441
442   return Type;
443 }
444
445 void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
446                                   uint32_t StringIndex, ELFSymbolData &MSD,
447                                   const MCAsmLayout &Layout) {
448   const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
449   assert((!Symbol.getFragment() ||
450           (Symbol.getFragment()->getParent() == &Symbol.getSection())) &&
451          "The symbol's section doesn't match the fragment's symbol");
452   const MCSymbolELF *Base =
453       cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
454
455   // This has to be in sync with when computeSymbolTable uses SHN_ABS or
456   // SHN_COMMON.
457   bool IsReserved = !Base || Symbol.isCommon();
458
459   // Binding and Type share the same byte as upper and lower nibbles
460   uint8_t Binding = Symbol.getBinding();
461   uint8_t Type = Symbol.getType();
462   if (Base) {
463     Type = mergeTypeForSet(Type, Base->getType());
464   }
465   uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
466
467   // Other and Visibility share the same byte with Visibility using the lower
468   // 2 bits
469   uint8_t Visibility = Symbol.getVisibility();
470   uint8_t Other = Symbol.getOther() << (ELF_STO_Shift - ELF_STV_Shift);
471   Other |= Visibility;
472
473   uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
474   uint64_t Size = 0;
475
476   const MCExpr *ESize = MSD.Symbol->getSize();
477   if (!ESize && Base)
478     ESize = Base->getSize();
479
480   if (ESize) {
481     int64_t Res;
482     if (!ESize->evaluateKnownAbsolute(Res, Layout))
483       report_fatal_error("Size expression must be absolute.");
484     Size = Res;
485   }
486
487   // Write out the symbol table entry
488   Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
489                      IsReserved);
490 }
491
492 // It is always valid to create a relocation with a symbol. It is preferable
493 // to use a relocation with a section if that is possible. Using the section
494 // allows us to omit some local symbols from the symbol table.
495 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
496                                                const MCSymbolRefExpr *RefA,
497                                                const MCSymbol *S, uint64_t C,
498                                                unsigned Type) const {
499   const auto *Sym = cast_or_null<MCSymbolELF>(S);
500   // A PCRel relocation to an absolute value has no symbol (or section). We
501   // represent that with a relocation to a null section.
502   if (!RefA)
503     return false;
504
505   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
506   switch (Kind) {
507   default:
508     break;
509   // The .odp creation emits a relocation against the symbol ".TOC." which
510   // create a R_PPC64_TOC relocation. However the relocation symbol name
511   // in final object creation should be NULL, since the symbol does not
512   // really exist, it is just the reference to TOC base for the current
513   // object file. Since the symbol is undefined, returning false results
514   // in a relocation with a null section which is the desired result.
515   case MCSymbolRefExpr::VK_PPC_TOCBASE:
516     return false;
517
518   // These VariantKind cause the relocation to refer to something other than
519   // the symbol itself, like a linker generated table. Since the address of
520   // symbol is not relevant, we cannot replace the symbol with the
521   // section and patch the difference in the addend.
522   case MCSymbolRefExpr::VK_GOT:
523   case MCSymbolRefExpr::VK_PLT:
524   case MCSymbolRefExpr::VK_GOTPCREL:
525   case MCSymbolRefExpr::VK_Mips_GOT:
526   case MCSymbolRefExpr::VK_PPC_GOT_LO:
527   case MCSymbolRefExpr::VK_PPC_GOT_HI:
528   case MCSymbolRefExpr::VK_PPC_GOT_HA:
529     return true;
530   }
531
532   // An undefined symbol is not in any section, so the relocation has to point
533   // to the symbol itself.
534   assert(Sym && "Expected a symbol");
535   if (Sym->isUndefined())
536     return true;
537
538   unsigned Binding = Sym->getBinding();
539   switch(Binding) {
540   default:
541     llvm_unreachable("Invalid Binding");
542   case ELF::STB_LOCAL:
543     break;
544   case ELF::STB_WEAK:
545     // If the symbol is weak, it might be overridden by a symbol in another
546     // file. The relocation has to point to the symbol so that the linker
547     // can update it.
548     return true;
549   case ELF::STB_GLOBAL:
550     // Global ELF symbols can be preempted by the dynamic linker. The relocation
551     // has to point to the symbol for a reason analogous to the STB_WEAK case.
552     return true;
553   }
554
555   // If a relocation points to a mergeable section, we have to be careful.
556   // If the offset is zero, a relocation with the section will encode the
557   // same information. With a non-zero offset, the situation is different.
558   // For example, a relocation can point 42 bytes past the end of a string.
559   // If we change such a relocation to use the section, the linker would think
560   // that it pointed to another string and subtracting 42 at runtime will
561   // produce the wrong value.
562   auto &Sec = cast<MCSectionELF>(Sym->getSection());
563   unsigned Flags = Sec.getFlags();
564   if (Flags & ELF::SHF_MERGE) {
565     if (C != 0)
566       return true;
567
568     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
569     // only handle section relocations to mergeable sections if using RELA.
570     if (!hasRelocationAddend())
571       return true;
572   }
573
574   // Most TLS relocations use a got, so they need the symbol. Even those that
575   // are just an offset (@tpoff), require a symbol in gold versions before
576   // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
577   // http://sourceware.org/PR16773.
578   if (Flags & ELF::SHF_TLS)
579     return true;
580
581   // If the symbol is a thumb function the final relocation must set the lowest
582   // bit. With a symbol that is done by just having the symbol have that bit
583   // set, so we would lose the bit if we relocated with the section.
584   // FIXME: We could use the section but add the bit to the relocation value.
585   if (Asm.isThumbFunc(Sym))
586     return true;
587
588   if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
589     return true;
590   return false;
591 }
592
593 static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
594   const MCSymbol &Sym = Ref.getSymbol();
595
596   if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
597     return &Sym;
598
599   if (!Sym.isVariable())
600     return nullptr;
601
602   const MCExpr *Expr = Sym.getVariableValue();
603   const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
604   if (!Inner)
605     return nullptr;
606
607   if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
608     return &Inner->getSymbol();
609   return nullptr;
610 }
611
612 // True if the assembler knows nothing about the final value of the symbol.
613 // This doesn't cover the comdat issues, since in those cases the assembler
614 // can at least know that all symbols in the section will move together.
615 static bool isWeak(const MCSymbolELF &Sym) {
616   if (Sym.getType() == ELF::STT_GNU_IFUNC)
617     return true;
618
619   switch (Sym.getBinding()) {
620   default:
621     llvm_unreachable("Unknown binding");
622   case ELF::STB_LOCAL:
623     return false;
624   case ELF::STB_GLOBAL:
625     return false;
626   case ELF::STB_WEAK:
627   case ELF::STB_GNU_UNIQUE:
628     return true;
629   }
630 }
631
632 void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
633                                        const MCAsmLayout &Layout,
634                                        const MCFragment *Fragment,
635                                        const MCFixup &Fixup, MCValue Target,
636                                        bool &IsPCRel, uint64_t &FixedValue) {
637   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
638   uint64_t C = Target.getConstant();
639   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
640
641   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
642     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
643            "Should not have constructed this");
644
645     // Let A, B and C being the components of Target and R be the location of
646     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
647     // If it is pcrel, we want to compute (A - B + C - R).
648
649     // In general, ELF has no relocations for -B. It can only represent (A + C)
650     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
651     // replace B to implement it: (A - R - K + C)
652     if (IsPCRel)
653       Asm.getContext().reportFatalError(
654           Fixup.getLoc(),
655           "No relocation available to represent this relative expression");
656
657     const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
658
659     if (SymB.isUndefined())
660       Asm.getContext().reportFatalError(
661           Fixup.getLoc(),
662           Twine("symbol '") + SymB.getName() +
663               "' can not be undefined in a subtraction expression");
664
665     assert(!SymB.isAbsolute() && "Should have been folded");
666     const MCSection &SecB = SymB.getSection();
667     if (&SecB != &FixupSection)
668       Asm.getContext().reportFatalError(
669           Fixup.getLoc(), "Cannot represent a difference across sections");
670
671     if (::isWeak(SymB))
672       Asm.getContext().reportFatalError(
673           Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
674
675     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
676     uint64_t K = SymBOffset - FixupOffset;
677     IsPCRel = true;
678     C -= K;
679   }
680
681   // We either rejected the fixup or folded B into C at this point.
682   const MCSymbolRefExpr *RefA = Target.getSymA();
683   const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
684
685   unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
686   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
687   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
688     C += Layout.getSymbolOffset(*SymA);
689
690   uint64_t Addend = 0;
691   if (hasRelocationAddend()) {
692     Addend = C;
693     C = 0;
694   }
695
696   FixedValue = C;
697
698   if (!RelocateWithSymbol) {
699     const MCSection *SecA =
700         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
701     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
702     const auto *SectionSymbol =
703         ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr;
704     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
705     Relocations[&FixupSection].push_back(Rec);
706     return;
707   }
708
709   if (SymA) {
710     if (const MCSymbolELF *R = Renames.lookup(SymA))
711       SymA = R;
712
713     if (const MCSymbol *WeakRef = getWeakRef(*RefA))
714       WeakrefUsedInReloc.insert(WeakRef);
715     else
716       SymA->setUsedInReloc();
717   }
718   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
719   Relocations[&FixupSection].push_back(Rec);
720   return;
721 }
722
723 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
724                                  const MCSymbolELF &Symbol, bool Used,
725                                  bool Renamed) {
726   if (Symbol.isVariable()) {
727     const MCExpr *Expr = Symbol.getVariableValue();
728     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
729       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
730         return false;
731     }
732   }
733
734   if (Used)
735     return true;
736
737   if (Renamed)
738     return false;
739
740   if (Symbol.isVariable() && Symbol.isUndefined()) {
741     // FIXME: this is here just to diagnose the case of a var = commmon_sym.
742     Layout.getBaseSymbol(Symbol);
743     return false;
744   }
745
746   if (Symbol.isUndefined() && !Symbol.isBindingSet())
747     return false;
748
749   if (Symbol.getType() == ELF::STT_SECTION)
750     return true;
751
752   if (Symbol.isTemporary())
753     return false;
754
755   return true;
756 }
757
758 bool ELFObjectWriter::isLocal(const MCSymbolELF &Symbol, bool IsSignature) {
759   if (Symbol.isExternal())
760     return false;
761
762   if (Symbol.isDefined())
763     return true;
764
765   if (Symbol.isUsedInReloc())
766     return false;
767
768   return IsSignature;
769 }
770
771 void ELFObjectWriter::computeSymbolTable(
772     MCAssembler &Asm, const MCAsmLayout &Layout,
773     const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
774     SectionOffsetsTy &SectionOffsets) {
775   MCContext &Ctx = Asm.getContext();
776   SymbolTableWriter Writer(*this, is64Bit());
777
778   // Symbol table
779   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
780   MCSectionELF *SymtabSection =
781       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
782   SymtabSection->setAlignment(is64Bit() ? 8 : 4);
783   SymbolTableIndex = addToSectionTable(SymtabSection);
784
785   uint64_t Padding =
786       OffsetToAlignment(OS.tell(), SymtabSection->getAlignment());
787   WriteZeros(Padding);
788
789   uint64_t SecStart = OS.tell();
790
791   // The first entry is the undefined symbol entry.
792   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
793
794   std::vector<ELFSymbolData> LocalSymbolData;
795   std::vector<ELFSymbolData> ExternalSymbolData;
796
797   // Add the data for the symbols.
798   bool HasLargeSectionIndex = false;
799   for (const MCSymbol &S : Asm.symbols()) {
800     const auto &Symbol = cast<MCSymbolELF>(S);
801     bool Used = Symbol.isUsedInReloc();
802     bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
803     bool isSignature = RevGroupMap.count(&Symbol);
804
805     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
806                     Renames.count(&Symbol)))
807       continue;
808
809     ELFSymbolData MSD;
810     MSD.Symbol = cast<MCSymbolELF>(&Symbol);
811
812     // Undefined symbols are global, but this is the first place we
813     // are able to set it.
814     bool Local = isLocal(Symbol, isSignature);
815     if (!Local && Symbol.getBinding() == ELF::STB_LOCAL)
816       Symbol.setBinding(ELF::STB_GLOBAL);
817
818     if (Symbol.isAbsolute()) {
819       MSD.SectionIndex = ELF::SHN_ABS;
820     } else if (Symbol.isCommon()) {
821       assert(!Local);
822       MSD.SectionIndex = ELF::SHN_COMMON;
823     } else if (Symbol.isUndefined()) {
824       if (isSignature && !Used) {
825         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
826         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
827           HasLargeSectionIndex = true;
828       } else {
829         MSD.SectionIndex = ELF::SHN_UNDEF;
830       }
831       if (!Used && WeakrefUsed)
832         Symbol.setBinding(ELF::STB_WEAK);
833     } else {
834       const MCSectionELF &Section =
835           static_cast<const MCSectionELF &>(Symbol.getSection());
836       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
837       assert(MSD.SectionIndex && "Invalid section index!");
838       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
839         HasLargeSectionIndex = true;
840     }
841
842     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
843     // in defined ones.
844     //
845     // FIXME: All name handling should be done before we get to the writer,
846     // including dealing with GNU-style version suffixes.  Fixing this isn't
847     // trivial.
848     //
849     // We thus have to be careful to not perform the symbol version replacement
850     // blindly:
851     //
852     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
853     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
854     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
855     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
856     // the EFLObjectWriter should not interpret the "@@@" sub-string as
857     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
858     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
859     // "__imp_?" or "__imp_@?".
860     //
861     // It would have been interesting to perform the MS mangling prefix check
862     // only when the target triple is of the form *-pc-windows-elf. But, it
863     // seems that this information is not easily accessible from the
864     // ELFObjectWriter.
865     StringRef Name = Symbol.getName();
866     if (!Name.startswith("?") && !Name.startswith("@?") &&
867         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
868       // This symbol isn't following the MSVC C++ name mangling convention. We
869       // can thus safely interpret the @@@ in symbol names as specifying symbol
870       // versioning.
871       SmallString<32> Buf;
872       size_t Pos = Name.find("@@@");
873       if (Pos != StringRef::npos) {
874         Buf += Name.substr(0, Pos);
875         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
876         Buf += Name.substr(Pos + Skip);
877         Name = Buf;
878       }
879     }
880
881     // Sections have their own string table
882     if (Symbol.getType() != ELF::STT_SECTION)
883       MSD.Name = StrTabBuilder.add(Name);
884
885     if (Local)
886       LocalSymbolData.push_back(MSD);
887     else
888       ExternalSymbolData.push_back(MSD);
889   }
890
891   if (HasLargeSectionIndex) {
892     MCSectionELF *SymtabShndxSection =
893         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
894     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
895     SymtabShndxSection->setAlignment(4);
896   }
897
898   ArrayRef<std::string> FileNames = Asm.getFileNames();
899   for (const std::string &Name : FileNames)
900     StrTabBuilder.add(Name);
901
902   StrTabBuilder.finalize(StringTableBuilder::ELF);
903
904   for (const std::string &Name : FileNames)
905     Writer.writeSymbol(StrTabBuilder.getOffset(Name),
906                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
907                        ELF::SHN_ABS, true);
908
909   // Symbols are required to be in lexicographic order.
910   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
911   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
912
913   // Set the symbol indices. Local symbols must come before all other
914   // symbols with non-local bindings.
915   unsigned Index = FileNames.size() + 1;
916
917   for (ELFSymbolData &MSD : LocalSymbolData) {
918     unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
919                                ? 0
920                                : StrTabBuilder.getOffset(MSD.Name);
921     MSD.Symbol->setIndex(Index++);
922     writeSymbol(Writer, StringIndex, MSD, Layout);
923   }
924
925   // Write the symbol table entries.
926   LastLocalSymbolIndex = Index;
927
928   for (ELFSymbolData &MSD : ExternalSymbolData) {
929     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
930     MSD.Symbol->setIndex(Index++);
931     writeSymbol(Writer, StringIndex, MSD, Layout);
932     assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
933   }
934
935   uint64_t SecEnd = OS.tell();
936   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
937
938   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
939   if (ShndxIndexes.empty()) {
940     assert(SymtabShndxSectionIndex == 0);
941     return;
942   }
943   assert(SymtabShndxSectionIndex != 0);
944
945   SecStart = OS.tell();
946   const MCSectionELF *SymtabShndxSection =
947       SectionTable[SymtabShndxSectionIndex - 1];
948   for (uint32_t Index : ShndxIndexes)
949     write(Index);
950   SecEnd = OS.tell();
951   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
952 }
953
954 MCSectionELF *
955 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
956                                          const MCSectionELF &Sec) {
957   if (Relocations[&Sec].empty())
958     return nullptr;
959
960   const StringRef SectionName = Sec.getSectionName();
961   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
962   RelaSectionName += SectionName;
963
964   unsigned EntrySize;
965   if (hasRelocationAddend())
966     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
967   else
968     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
969
970   unsigned Flags = 0;
971   if (Sec.getFlags() & ELF::SHF_GROUP)
972     Flags = ELF::SHF_GROUP;
973
974   MCSectionELF *RelaSection = Ctx.createELFRelSection(
975       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
976       Flags, EntrySize, Sec.getGroup(), &Sec);
977   RelaSection->setAlignment(is64Bit() ? 8 : 4);
978   return RelaSection;
979 }
980
981 static SmallVector<char, 128>
982 getUncompressedData(const MCAsmLayout &Layout,
983                     const MCSection::FragmentListType &Fragments) {
984   SmallVector<char, 128> UncompressedData;
985   for (const MCFragment &F : Fragments) {
986     const SmallVectorImpl<char> *Contents;
987     switch (F.getKind()) {
988     case MCFragment::FT_Data:
989       Contents = &cast<MCDataFragment>(F).getContents();
990       break;
991     case MCFragment::FT_Dwarf:
992       Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
993       break;
994     case MCFragment::FT_DwarfFrame:
995       Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
996       break;
997     default:
998       llvm_unreachable(
999           "Not expecting any other fragment types in a debug_* section");
1000     }
1001     UncompressedData.append(Contents->begin(), Contents->end());
1002   }
1003   return UncompressedData;
1004 }
1005
1006 // Include the debug info compression header:
1007 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1008 // useful for consumers to preallocate a buffer to decompress into.
1009 static bool
1010 prependCompressionHeader(uint64_t Size,
1011                          SmallVectorImpl<char> &CompressedContents) {
1012   const StringRef Magic = "ZLIB";
1013   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1014     return false;
1015   if (sys::IsLittleEndianHost)
1016     sys::swapByteOrder(Size);
1017   CompressedContents.insert(CompressedContents.begin(),
1018                             Magic.size() + sizeof(Size), 0);
1019   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1020   std::copy(reinterpret_cast<char *>(&Size),
1021             reinterpret_cast<char *>(&Size + 1),
1022             CompressedContents.begin() + Magic.size());
1023   return true;
1024 }
1025
1026 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1027                                        const MCAsmLayout &Layout) {
1028   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1029   StringRef SectionName = Section.getSectionName();
1030
1031   // Compressing debug_frame requires handling alignment fragments which is
1032   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1033   // for writing to arbitrary buffers) for little benefit.
1034   if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1035       !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1036     Asm.writeSectionData(&Section, Layout);
1037     return;
1038   }
1039
1040   // Gather the uncompressed data from all the fragments.
1041   const MCSection::FragmentListType &Fragments = Section.getFragmentList();
1042   SmallVector<char, 128> UncompressedData =
1043       getUncompressedData(Layout, Fragments);
1044
1045   SmallVector<char, 128> CompressedContents;
1046   zlib::Status Success = zlib::compress(
1047       StringRef(UncompressedData.data(), UncompressedData.size()),
1048       CompressedContents);
1049   if (Success != zlib::StatusOK) {
1050     Asm.writeSectionData(&Section, Layout);
1051     return;
1052   }
1053
1054   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1055     Asm.writeSectionData(&Section, Layout);
1056     return;
1057   }
1058   Asm.getContext().renameELFSection(&Section,
1059                                     (".z" + SectionName.drop_front(1)).str());
1060   OS << CompressedContents;
1061 }
1062
1063 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1064                                        uint64_t Flags, uint64_t Address,
1065                                        uint64_t Offset, uint64_t Size,
1066                                        uint32_t Link, uint32_t Info,
1067                                        uint64_t Alignment,
1068                                        uint64_t EntrySize) {
1069   Write32(Name);        // sh_name: index into string table
1070   Write32(Type);        // sh_type
1071   WriteWord(Flags);     // sh_flags
1072   WriteWord(Address);   // sh_addr
1073   WriteWord(Offset);    // sh_offset
1074   WriteWord(Size);      // sh_size
1075   Write32(Link);        // sh_link
1076   Write32(Info);        // sh_info
1077   WriteWord(Alignment); // sh_addralign
1078   WriteWord(EntrySize); // sh_entsize
1079 }
1080
1081 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1082                                        const MCSectionELF &Sec) {
1083   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1084
1085   // Sort the relocation entries. Most targets just sort by Offset, but some
1086   // (e.g., MIPS) have additional constraints.
1087   TargetObjectWriter->sortRelocs(Asm, Relocs);
1088
1089   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1090     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1091     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1092
1093     if (is64Bit()) {
1094       write(Entry.Offset);
1095       if (TargetObjectWriter->isN64()) {
1096         write(uint32_t(Index));
1097
1098         write(TargetObjectWriter->getRSsym(Entry.Type));
1099         write(TargetObjectWriter->getRType3(Entry.Type));
1100         write(TargetObjectWriter->getRType2(Entry.Type));
1101         write(TargetObjectWriter->getRType(Entry.Type));
1102       } else {
1103         struct ELF::Elf64_Rela ERE64;
1104         ERE64.setSymbolAndType(Index, Entry.Type);
1105         write(ERE64.r_info);
1106       }
1107       if (hasRelocationAddend())
1108         write(Entry.Addend);
1109     } else {
1110       write(uint32_t(Entry.Offset));
1111
1112       struct ELF::Elf32_Rela ERE32;
1113       ERE32.setSymbolAndType(Index, Entry.Type);
1114       write(ERE32.r_info);
1115
1116       if (hasRelocationAddend())
1117         write(uint32_t(Entry.Addend));
1118     }
1119   }
1120 }
1121
1122 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1123   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1124   OS << StrTabBuilder.data();
1125   return StrtabSection;
1126 }
1127
1128 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1129                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1130                                    uint64_t Size, const MCSectionELF &Section) {
1131   uint64_t sh_link = 0;
1132   uint64_t sh_info = 0;
1133
1134   switch(Section.getType()) {
1135   default:
1136     // Nothing to do.
1137     break;
1138
1139   case ELF::SHT_DYNAMIC:
1140     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1141
1142   case ELF::SHT_REL:
1143   case ELF::SHT_RELA: {
1144     sh_link = SymbolTableIndex;
1145     assert(sh_link && ".symtab not found");
1146     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1147     sh_info = SectionIndexMap.lookup(InfoSection);
1148     break;
1149   }
1150
1151   case ELF::SHT_SYMTAB:
1152   case ELF::SHT_DYNSYM:
1153     sh_link = StringTableIndex;
1154     sh_info = LastLocalSymbolIndex;
1155     break;
1156
1157   case ELF::SHT_SYMTAB_SHNDX:
1158     sh_link = SymbolTableIndex;
1159     break;
1160
1161   case ELF::SHT_GROUP:
1162     sh_link = SymbolTableIndex;
1163     sh_info = GroupSymbolIndex;
1164     break;
1165   }
1166
1167   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1168       Section.getType() == ELF::SHT_ARM_EXIDX)
1169     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1170
1171   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1172                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1173                    sh_link, sh_info, Section.getAlignment(),
1174                    Section.getEntrySize());
1175 }
1176
1177 void ELFObjectWriter::writeSectionHeader(
1178     const MCAssembler &Asm, const MCAsmLayout &Layout,
1179     const SectionIndexMapTy &SectionIndexMap,
1180     const SectionOffsetsTy &SectionOffsets) {
1181   const unsigned NumSections = SectionTable.size();
1182
1183   // Null section first.
1184   uint64_t FirstSectionSize =
1185       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1186   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1187
1188   for (const MCSectionELF *Section : SectionTable) {
1189     uint32_t GroupSymbolIndex;
1190     unsigned Type = Section->getType();
1191     if (Type != ELF::SHT_GROUP)
1192       GroupSymbolIndex = 0;
1193     else
1194       GroupSymbolIndex = Section->getGroup()->getIndex();
1195
1196     const std::pair<uint64_t, uint64_t> &Offsets =
1197         SectionOffsets.find(Section)->second;
1198     uint64_t Size;
1199     if (Type == ELF::SHT_NOBITS)
1200       Size = Layout.getSectionAddressSize(Section);
1201     else
1202       Size = Offsets.second - Offsets.first;
1203
1204     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1205                  *Section);
1206   }
1207 }
1208
1209 void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1210                                   const MCAsmLayout &Layout) {
1211   MCContext &Ctx = Asm.getContext();
1212   MCSectionELF *StrtabSection =
1213       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1214   StringTableIndex = addToSectionTable(StrtabSection);
1215
1216   RevGroupMapTy RevGroupMap;
1217   SectionIndexMapTy SectionIndexMap;
1218
1219   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1220
1221   // Write out the ELF header ...
1222   writeHeader(Asm);
1223
1224   // ... then the sections ...
1225   SectionOffsetsTy SectionOffsets;
1226   std::vector<MCSectionELF *> Groups;
1227   std::vector<MCSectionELF *> Relocations;
1228   for (MCSection &Sec : Asm) {
1229     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1230
1231     uint64_t Padding = OffsetToAlignment(OS.tell(), Section.getAlignment());
1232     WriteZeros(Padding);
1233
1234     // Remember the offset into the file for this section.
1235     uint64_t SecStart = OS.tell();
1236
1237     const MCSymbolELF *SignatureSymbol = Section.getGroup();
1238     writeSectionData(Asm, Section, Layout);
1239
1240     uint64_t SecEnd = OS.tell();
1241     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1242
1243     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1244
1245     if (SignatureSymbol) {
1246       Asm.registerSymbol(*SignatureSymbol);
1247       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1248       if (!GroupIdx) {
1249         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1250         GroupIdx = addToSectionTable(Group);
1251         Group->setAlignment(4);
1252         Groups.push_back(Group);
1253       }
1254       GroupMembers[SignatureSymbol].push_back(&Section);
1255       if (RelSection)
1256         GroupMembers[SignatureSymbol].push_back(RelSection);
1257     }
1258
1259     SectionIndexMap[&Section] = addToSectionTable(&Section);
1260     if (RelSection) {
1261       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1262       Relocations.push_back(RelSection);
1263     }
1264   }
1265
1266   for (MCSectionELF *Group : Groups) {
1267     uint64_t Padding = OffsetToAlignment(OS.tell(), Group->getAlignment());
1268     WriteZeros(Padding);
1269
1270     // Remember the offset into the file for this section.
1271     uint64_t SecStart = OS.tell();
1272
1273     const MCSymbol *SignatureSymbol = Group->getGroup();
1274     assert(SignatureSymbol);
1275     write(uint32_t(ELF::GRP_COMDAT));
1276     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1277       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1278       write(SecIndex);
1279     }
1280
1281     uint64_t SecEnd = OS.tell();
1282     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1283   }
1284
1285   // Compute symbol table information.
1286   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1287
1288   for (MCSectionELF *RelSection : Relocations) {
1289     uint64_t Padding = OffsetToAlignment(OS.tell(), RelSection->getAlignment());
1290     WriteZeros(Padding);
1291
1292     // Remember the offset into the file for this section.
1293     uint64_t SecStart = OS.tell();
1294
1295     writeRelocations(Asm, *RelSection->getAssociatedSection());
1296
1297     uint64_t SecEnd = OS.tell();
1298     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1299   }
1300
1301   {
1302     uint64_t SecStart = OS.tell();
1303     const MCSectionELF *Sec = createStringTable(Ctx);
1304     uint64_t SecEnd = OS.tell();
1305     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1306   }
1307
1308   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1309   uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
1310   WriteZeros(Padding);
1311
1312   const unsigned SectionHeaderOffset = OS.tell();
1313
1314   // ... then the section header table ...
1315   writeSectionHeader(Asm, Layout, SectionIndexMap, SectionOffsets);
1316
1317   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1318                              ? (uint16_t)ELF::SHN_UNDEF
1319                              : SectionTable.size() + 1;
1320   if (sys::IsLittleEndianHost != IsLittleEndian)
1321     sys::swapByteOrder(NumSections);
1322   unsigned NumSectionsOffset;
1323
1324   if (is64Bit()) {
1325     uint64_t Val = SectionHeaderOffset;
1326     if (sys::IsLittleEndianHost != IsLittleEndian)
1327       sys::swapByteOrder(Val);
1328     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1329               offsetof(ELF::Elf64_Ehdr, e_shoff));
1330     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1331   } else {
1332     uint32_t Val = SectionHeaderOffset;
1333     if (sys::IsLittleEndianHost != IsLittleEndian)
1334       sys::swapByteOrder(Val);
1335     OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1336               offsetof(ELF::Elf32_Ehdr, e_shoff));
1337     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1338   }
1339   OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1340             NumSectionsOffset);
1341 }
1342
1343 bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1344     const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1345     bool InSet, bool IsPCRel) const {
1346   const auto &SymA = cast<MCSymbolELF>(SA);
1347   if (IsPCRel) {
1348     assert(!InSet);
1349     if (::isWeak(SymA))
1350       return false;
1351   }
1352   return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1353                                                                 InSet, IsPCRel);
1354 }
1355
1356 bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
1357   const auto &Sym = cast<MCSymbolELF>(S);
1358   if (::isWeak(Sym))
1359     return true;
1360
1361   // It is invalid to replace a reference to a global in a comdat
1362   // with a reference to a local since out of comdat references
1363   // to a local are forbidden.
1364   // We could try to return false for more cases, like the reference
1365   // being in the same comdat or Sym being an alias to another global,
1366   // but it is not clear if it is worth the effort.
1367   if (Sym.getBinding() != ELF::STB_GLOBAL)
1368     return false;
1369
1370   if (!Sym.isInSection())
1371     return false;
1372
1373   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1374   return Sec.getGroup();
1375 }
1376
1377 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1378                                             raw_pwrite_stream &OS,
1379                                             bool IsLittleEndian) {
1380   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1381 }