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