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_Mips_GOT:
540   case MCSymbolRefExpr::VK_PPC_GOT_LO:
541   case MCSymbolRefExpr::VK_PPC_GOT_HI:
542   case MCSymbolRefExpr::VK_PPC_GOT_HA:
543     return true;
544   }
545 
546   // An undefined symbol is not in any section, so the relocation has to point
547   // to the symbol itself.
548   assert(Sym && "Expected a symbol");
549   if (Sym->isUndefined())
550     return true;
551 
552   unsigned Binding = Sym->getBinding();
553   switch(Binding) {
554   default:
555     llvm_unreachable("Invalid Binding");
556   case ELF::STB_LOCAL:
557     break;
558   case ELF::STB_WEAK:
559     // If the symbol is weak, it might be overridden by a symbol in another
560     // file. The relocation has to point to the symbol so that the linker
561     // can update it.
562     return true;
563   case ELF::STB_GLOBAL:
564     // Global ELF symbols can be preempted by the dynamic linker. The relocation
565     // has to point to the symbol for a reason analogous to the STB_WEAK case.
566     return true;
567   }
568 
569   // If a relocation points to a mergeable section, we have to be careful.
570   // If the offset is zero, a relocation with the section will encode the
571   // same information. With a non-zero offset, the situation is different.
572   // For example, a relocation can point 42 bytes past the end of a string.
573   // If we change such a relocation to use the section, the linker would think
574   // that it pointed to another string and subtracting 42 at runtime will
575   // produce the wrong value.
576   auto &Sec = cast<MCSectionELF>(Sym->getSection());
577   unsigned Flags = Sec.getFlags();
578   if (Flags & ELF::SHF_MERGE) {
579     if (C != 0)
580       return true;
581 
582     // It looks like gold has a bug (http://sourceware.org/PR16794) and can
583     // only handle section relocations to mergeable sections if using RELA.
584     if (!hasRelocationAddend())
585       return true;
586   }
587 
588   // Most TLS relocations use a got, so they need the symbol. Even those that
589   // are just an offset (@tpoff), require a symbol in gold versions before
590   // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
591   // http://sourceware.org/PR16773.
592   if (Flags & ELF::SHF_TLS)
593     return true;
594 
595   // If the symbol is a thumb function the final relocation must set the lowest
596   // bit. With a symbol that is done by just having the symbol have that bit
597   // set, so we would lose the bit if we relocated with the section.
598   // FIXME: We could use the section but add the bit to the relocation value.
599   if (Asm.isThumbFunc(Sym))
600     return true;
601 
602   if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
603     return true;
604   return false;
605 }
606 
607 // True if the assembler knows nothing about the final value of the symbol.
608 // This doesn't cover the comdat issues, since in those cases the assembler
609 // can at least know that all symbols in the section will move together.
610 static bool isWeak(const MCSymbolELF &Sym) {
611   if (Sym.getType() == ELF::STT_GNU_IFUNC)
612     return true;
613 
614   switch (Sym.getBinding()) {
615   default:
616     llvm_unreachable("Unknown binding");
617   case ELF::STB_LOCAL:
618     return false;
619   case ELF::STB_GLOBAL:
620     return false;
621   case ELF::STB_WEAK:
622   case ELF::STB_GNU_UNIQUE:
623     return true;
624   }
625 }
626 
627 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
628                                        const MCAsmLayout &Layout,
629                                        const MCFragment *Fragment,
630                                        const MCFixup &Fixup, MCValue Target,
631                                        bool &IsPCRel, uint64_t &FixedValue) {
632   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
633   uint64_t C = Target.getConstant();
634   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
635   MCContext &Ctx = Asm.getContext();
636 
637   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
638     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
639            "Should not have constructed this");
640 
641     // Let A, B and C being the components of Target and R be the location of
642     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
643     // If it is pcrel, we want to compute (A - B + C - R).
644 
645     // In general, ELF has no relocations for -B. It can only represent (A + C)
646     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
647     // replace B to implement it: (A - R - K + C)
648     if (IsPCRel) {
649       Ctx.reportError(
650           Fixup.getLoc(),
651           "No relocation available to represent this relative expression");
652       return;
653     }
654 
655     const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
656 
657     if (SymB.isUndefined()) {
658       Ctx.reportError(Fixup.getLoc(),
659                       Twine("symbol '") + SymB.getName() +
660                           "' can not be undefined in a subtraction expression");
661       return;
662     }
663 
664     assert(!SymB.isAbsolute() && "Should have been folded");
665     const MCSection &SecB = SymB.getSection();
666     if (&SecB != &FixupSection) {
667       Ctx.reportError(Fixup.getLoc(),
668                       "Cannot represent a difference across sections");
669       return;
670     }
671 
672     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
673     uint64_t K = SymBOffset - FixupOffset;
674     IsPCRel = true;
675     C -= K;
676   }
677 
678   // We either rejected the fixup or folded B into C at this point.
679   const MCSymbolRefExpr *RefA = Target.getSymA();
680   const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
681 
682   bool ViaWeakRef = false;
683   if (SymA && SymA->isVariable()) {
684     const MCExpr *Expr = SymA->getVariableValue();
685     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
686       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
687         SymA = cast<MCSymbolELF>(&Inner->getSymbol());
688         ViaWeakRef = true;
689       }
690     }
691   }
692 
693   unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel);
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);
715     Relocations[&FixupSection].push_back(Rec);
716     return;
717   }
718 
719   if (SymA) {
720     if (const MCSymbolELF *R = Renames.lookup(SymA))
721       SymA = R;
722 
723     if (ViaWeakRef)
724       SymA->setIsWeakrefUsedInReloc();
725     else
726       SymA->setUsedInReloc();
727   }
728   ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
729   Relocations[&FixupSection].push_back(Rec);
730 }
731 
732 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
733                                  const MCSymbolELF &Symbol, bool Used,
734                                  bool Renamed) {
735   if (Symbol.isVariable()) {
736     const MCExpr *Expr = Symbol.getVariableValue();
737     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
738       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
739         return false;
740     }
741   }
742 
743   if (Used)
744     return true;
745 
746   if (Renamed)
747     return false;
748 
749   if (Symbol.isVariable() && Symbol.isUndefined()) {
750     // FIXME: this is here just to diagnose the case of a var = commmon_sym.
751     Layout.getBaseSymbol(Symbol);
752     return false;
753   }
754 
755   if (Symbol.isUndefined() && !Symbol.isBindingSet())
756     return false;
757 
758   if (Symbol.isTemporary())
759     return false;
760 
761   if (Symbol.getType() == ELF::STT_SECTION)
762     return false;
763 
764   return true;
765 }
766 
767 void ELFObjectWriter::computeSymbolTable(
768     MCAssembler &Asm, const MCAsmLayout &Layout,
769     const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
770     SectionOffsetsTy &SectionOffsets) {
771   MCContext &Ctx = Asm.getContext();
772   SymbolTableWriter Writer(*this, is64Bit());
773 
774   // Symbol table
775   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
776   MCSectionELF *SymtabSection =
777       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
778   SymtabSection->setAlignment(is64Bit() ? 8 : 4);
779   SymbolTableIndex = addToSectionTable(SymtabSection);
780 
781   align(SymtabSection->getAlignment());
782   uint64_t SecStart = getStream().tell();
783 
784   // The first entry is the undefined symbol entry.
785   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
786 
787   std::vector<ELFSymbolData> LocalSymbolData;
788   std::vector<ELFSymbolData> ExternalSymbolData;
789 
790   // Add the data for the symbols.
791   bool HasLargeSectionIndex = false;
792   for (const MCSymbol &S : Asm.symbols()) {
793     const auto &Symbol = cast<MCSymbolELF>(S);
794     bool Used = Symbol.isUsedInReloc();
795     bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
796     bool isSignature = Symbol.isSignature();
797 
798     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
799                     Renames.count(&Symbol)))
800       continue;
801 
802     if (Symbol.isTemporary() && Symbol.isUndefined()) {
803       Ctx.reportError(SMLoc(), "Undefined temporary symbol");
804       continue;
805     }
806 
807     ELFSymbolData MSD;
808     MSD.Symbol = cast<MCSymbolELF>(&Symbol);
809 
810     bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
811     assert(Local || !Symbol.isTemporary());
812 
813     if (Symbol.isAbsolute()) {
814       MSD.SectionIndex = ELF::SHN_ABS;
815     } else if (Symbol.isCommon()) {
816       assert(!Local);
817       MSD.SectionIndex = ELF::SHN_COMMON;
818     } else if (Symbol.isUndefined()) {
819       if (isSignature && !Used) {
820         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
821         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
822           HasLargeSectionIndex = true;
823       } else {
824         MSD.SectionIndex = ELF::SHN_UNDEF;
825       }
826     } else {
827       const MCSectionELF &Section =
828           static_cast<const MCSectionELF &>(Symbol.getSection());
829       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
830       assert(MSD.SectionIndex && "Invalid section index!");
831       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
832         HasLargeSectionIndex = true;
833     }
834 
835     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
836     // in defined ones.
837     //
838     // FIXME: All name handling should be done before we get to the writer,
839     // including dealing with GNU-style version suffixes.  Fixing this isn't
840     // trivial.
841     //
842     // We thus have to be careful to not perform the symbol version replacement
843     // blindly:
844     //
845     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
846     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
847     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
848     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
849     // the EFLObjectWriter should not interpret the "@@@" sub-string as
850     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
851     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
852     // "__imp_?" or "__imp_@?".
853     //
854     // It would have been interesting to perform the MS mangling prefix check
855     // only when the target triple is of the form *-pc-windows-elf. But, it
856     // seems that this information is not easily accessible from the
857     // ELFObjectWriter.
858     StringRef Name = Symbol.getName();
859     SmallString<32> Buf;
860     if (!Name.startswith("?") && !Name.startswith("@?") &&
861         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
862       // This symbol isn't following the MSVC C++ name mangling convention. We
863       // can thus safely interpret the @@@ in symbol names as specifying symbol
864       // versioning.
865       size_t Pos = Name.find("@@@");
866       if (Pos != StringRef::npos) {
867         Buf += Name.substr(0, Pos);
868         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
869         Buf += Name.substr(Pos + Skip);
870         Name = VersionSymSaver.save(Buf.c_str());
871       }
872     }
873 
874     // Sections have their own string table
875     if (Symbol.getType() != ELF::STT_SECTION) {
876       MSD.Name = Name;
877       StrTabBuilder.add(Name);
878     }
879 
880     if (Local)
881       LocalSymbolData.push_back(MSD);
882     else
883       ExternalSymbolData.push_back(MSD);
884   }
885 
886   // This holds the .symtab_shndx section index.
887   unsigned SymtabShndxSectionIndex = 0;
888 
889   if (HasLargeSectionIndex) {
890     MCSectionELF *SymtabShndxSection =
891         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
892     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
893     SymtabShndxSection->setAlignment(4);
894   }
895 
896   ArrayRef<std::string> FileNames = Asm.getFileNames();
897   for (const std::string &Name : FileNames)
898     StrTabBuilder.add(Name);
899 
900   StrTabBuilder.finalize();
901 
902   for (const std::string &Name : FileNames)
903     Writer.writeSymbol(StrTabBuilder.getOffset(Name),
904                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
905                        ELF::SHN_ABS, true);
906 
907   // Symbols are required to be in lexicographic order.
908   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
909   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
910 
911   // Set the symbol indices. Local symbols must come before all other
912   // symbols with non-local bindings.
913   unsigned Index = FileNames.size() + 1;
914 
915   for (ELFSymbolData &MSD : LocalSymbolData) {
916     unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
917                                ? 0
918                                : StrTabBuilder.getOffset(MSD.Name);
919     MSD.Symbol->setIndex(Index++);
920     writeSymbol(Writer, StringIndex, MSD, Layout);
921   }
922 
923   // Write the symbol table entries.
924   LastLocalSymbolIndex = Index;
925 
926   for (ELFSymbolData &MSD : ExternalSymbolData) {
927     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
928     MSD.Symbol->setIndex(Index++);
929     writeSymbol(Writer, StringIndex, MSD, Layout);
930     assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
931   }
932 
933   uint64_t SecEnd = getStream().tell();
934   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
935 
936   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
937   if (ShndxIndexes.empty()) {
938     assert(SymtabShndxSectionIndex == 0);
939     return;
940   }
941   assert(SymtabShndxSectionIndex != 0);
942 
943   SecStart = getStream().tell();
944   const MCSectionELF *SymtabShndxSection =
945       SectionTable[SymtabShndxSectionIndex - 1];
946   for (uint32_t Index : ShndxIndexes)
947     write(Index);
948   SecEnd = getStream().tell();
949   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
950 }
951 
952 MCSectionELF *
953 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
954                                          const MCSectionELF &Sec) {
955   if (Relocations[&Sec].empty())
956     return nullptr;
957 
958   const StringRef SectionName = Sec.getSectionName();
959   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
960   RelaSectionName += SectionName;
961 
962   unsigned EntrySize;
963   if (hasRelocationAddend())
964     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
965   else
966     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
967 
968   unsigned Flags = 0;
969   if (Sec.getFlags() & ELF::SHF_GROUP)
970     Flags = ELF::SHF_GROUP;
971 
972   MCSectionELF *RelaSection = Ctx.createELFRelSection(
973       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
974       Flags, EntrySize, Sec.getGroup(), &Sec);
975   RelaSection->setAlignment(is64Bit() ? 8 : 4);
976   return RelaSection;
977 }
978 
979 // Include the debug info compression header:
980 // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
981 // useful for consumers to preallocate a buffer to decompress into.
982 static bool
983 prependCompressionHeader(uint64_t Size,
984                          SmallVectorImpl<char> &CompressedContents) {
985   const StringRef Magic = "ZLIB";
986   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
987     return false;
988   if (sys::IsLittleEndianHost)
989     sys::swapByteOrder(Size);
990   CompressedContents.insert(CompressedContents.begin(),
991                             Magic.size() + sizeof(Size), 0);
992   std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
993   std::copy(reinterpret_cast<char *>(&Size),
994             reinterpret_cast<char *>(&Size + 1),
995             CompressedContents.begin() + Magic.size());
996   return true;
997 }
998 
999 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1000                                        const MCAsmLayout &Layout) {
1001   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1002   StringRef SectionName = Section.getSectionName();
1003 
1004   // Compressing debug_frame requires handling alignment fragments which is
1005   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1006   // for writing to arbitrary buffers) for little benefit.
1007   if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
1008       !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
1009     Asm.writeSectionData(&Section, Layout);
1010     return;
1011   }
1012 
1013   SmallVector<char, 128> UncompressedData;
1014   raw_svector_ostream VecOS(UncompressedData);
1015   raw_pwrite_stream &OldStream = getStream();
1016   setStream(VecOS);
1017   Asm.writeSectionData(&Section, Layout);
1018   setStream(OldStream);
1019 
1020   SmallVector<char, 128> CompressedContents;
1021   zlib::Status Success = zlib::compress(
1022       StringRef(UncompressedData.data(), UncompressedData.size()),
1023       CompressedContents);
1024   if (Success != zlib::StatusOK) {
1025     getStream() << UncompressedData;
1026     return;
1027   }
1028 
1029   if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
1030     getStream() << UncompressedData;
1031     return;
1032   }
1033   Asm.getContext().renameELFSection(&Section,
1034                                     (".z" + SectionName.drop_front(1)).str());
1035   getStream() << CompressedContents;
1036 }
1037 
1038 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1039                                        uint64_t Flags, uint64_t Address,
1040                                        uint64_t Offset, uint64_t Size,
1041                                        uint32_t Link, uint32_t Info,
1042                                        uint64_t Alignment,
1043                                        uint64_t EntrySize) {
1044   write32(Name);        // sh_name: index into string table
1045   write32(Type);        // sh_type
1046   WriteWord(Flags);     // sh_flags
1047   WriteWord(Address);   // sh_addr
1048   WriteWord(Offset);    // sh_offset
1049   WriteWord(Size);      // sh_size
1050   write32(Link);        // sh_link
1051   write32(Info);        // sh_info
1052   WriteWord(Alignment); // sh_addralign
1053   WriteWord(EntrySize); // sh_entsize
1054 }
1055 
1056 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1057                                        const MCSectionELF &Sec) {
1058   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1059 
1060   // We record relocations by pushing to the end of a vector. Reverse the vector
1061   // to get the relocations in the order they were created.
1062   // In most cases that is not important, but it can be for special sections
1063   // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
1064   std::reverse(Relocs.begin(), Relocs.end());
1065 
1066   // Sort the relocation entries. MIPS needs this.
1067   TargetObjectWriter->sortRelocs(Asm, Relocs);
1068 
1069   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1070     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1071     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1072 
1073     if (is64Bit()) {
1074       write(Entry.Offset);
1075       if (TargetObjectWriter->isN64()) {
1076         write(uint32_t(Index));
1077 
1078         write(TargetObjectWriter->getRSsym(Entry.Type));
1079         write(TargetObjectWriter->getRType3(Entry.Type));
1080         write(TargetObjectWriter->getRType2(Entry.Type));
1081         write(TargetObjectWriter->getRType(Entry.Type));
1082       } else {
1083         struct ELF::Elf64_Rela ERE64;
1084         ERE64.setSymbolAndType(Index, Entry.Type);
1085         write(ERE64.r_info);
1086       }
1087       if (hasRelocationAddend())
1088         write(Entry.Addend);
1089     } else {
1090       write(uint32_t(Entry.Offset));
1091 
1092       struct ELF::Elf32_Rela ERE32;
1093       ERE32.setSymbolAndType(Index, Entry.Type);
1094       write(ERE32.r_info);
1095 
1096       if (hasRelocationAddend())
1097         write(uint32_t(Entry.Addend));
1098     }
1099   }
1100 }
1101 
1102 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1103   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1104   getStream() << StrTabBuilder.data();
1105   return StrtabSection;
1106 }
1107 
1108 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1109                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1110                                    uint64_t Size, const MCSectionELF &Section) {
1111   uint64_t sh_link = 0;
1112   uint64_t sh_info = 0;
1113 
1114   switch(Section.getType()) {
1115   default:
1116     // Nothing to do.
1117     break;
1118 
1119   case ELF::SHT_DYNAMIC:
1120     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1121 
1122   case ELF::SHT_REL:
1123   case ELF::SHT_RELA: {
1124     sh_link = SymbolTableIndex;
1125     assert(sh_link && ".symtab not found");
1126     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1127     sh_info = SectionIndexMap.lookup(InfoSection);
1128     break;
1129   }
1130 
1131   case ELF::SHT_SYMTAB:
1132   case ELF::SHT_DYNSYM:
1133     sh_link = StringTableIndex;
1134     sh_info = LastLocalSymbolIndex;
1135     break;
1136 
1137   case ELF::SHT_SYMTAB_SHNDX:
1138     sh_link = SymbolTableIndex;
1139     break;
1140 
1141   case ELF::SHT_GROUP:
1142     sh_link = SymbolTableIndex;
1143     sh_info = GroupSymbolIndex;
1144     break;
1145   }
1146 
1147   if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1148       Section.getType() == ELF::SHT_ARM_EXIDX)
1149     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1150 
1151   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1152                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1153                    sh_link, sh_info, Section.getAlignment(),
1154                    Section.getEntrySize());
1155 }
1156 
1157 void ELFObjectWriter::writeSectionHeader(
1158     const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1159     const SectionOffsetsTy &SectionOffsets) {
1160   const unsigned NumSections = SectionTable.size();
1161 
1162   // Null section first.
1163   uint64_t FirstSectionSize =
1164       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1165   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1166 
1167   for (const MCSectionELF *Section : SectionTable) {
1168     uint32_t GroupSymbolIndex;
1169     unsigned Type = Section->getType();
1170     if (Type != ELF::SHT_GROUP)
1171       GroupSymbolIndex = 0;
1172     else
1173       GroupSymbolIndex = Section->getGroup()->getIndex();
1174 
1175     const std::pair<uint64_t, uint64_t> &Offsets =
1176         SectionOffsets.find(Section)->second;
1177     uint64_t Size;
1178     if (Type == ELF::SHT_NOBITS)
1179       Size = Layout.getSectionAddressSize(Section);
1180     else
1181       Size = Offsets.second - Offsets.first;
1182 
1183     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1184                  *Section);
1185   }
1186 }
1187 
1188 void ELFObjectWriter::writeObject(MCAssembler &Asm,
1189                                   const MCAsmLayout &Layout) {
1190   MCContext &Ctx = Asm.getContext();
1191   MCSectionELF *StrtabSection =
1192       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1193   StringTableIndex = addToSectionTable(StrtabSection);
1194 
1195   RevGroupMapTy RevGroupMap;
1196   SectionIndexMapTy SectionIndexMap;
1197 
1198   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1199 
1200   // Write out the ELF header ...
1201   writeHeader(Asm);
1202 
1203   // ... then the sections ...
1204   SectionOffsetsTy SectionOffsets;
1205   std::vector<MCSectionELF *> Groups;
1206   std::vector<MCSectionELF *> Relocations;
1207   for (MCSection &Sec : Asm) {
1208     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1209 
1210     align(Section.getAlignment());
1211 
1212     // Remember the offset into the file for this section.
1213     uint64_t SecStart = getStream().tell();
1214 
1215     const MCSymbolELF *SignatureSymbol = Section.getGroup();
1216     writeSectionData(Asm, Section, Layout);
1217 
1218     uint64_t SecEnd = getStream().tell();
1219     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1220 
1221     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1222 
1223     if (SignatureSymbol) {
1224       Asm.registerSymbol(*SignatureSymbol);
1225       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1226       if (!GroupIdx) {
1227         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1228         GroupIdx = addToSectionTable(Group);
1229         Group->setAlignment(4);
1230         Groups.push_back(Group);
1231       }
1232       std::vector<const MCSectionELF *> &Members =
1233           GroupMembers[SignatureSymbol];
1234       Members.push_back(&Section);
1235       if (RelSection)
1236         Members.push_back(RelSection);
1237     }
1238 
1239     SectionIndexMap[&Section] = addToSectionTable(&Section);
1240     if (RelSection) {
1241       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1242       Relocations.push_back(RelSection);
1243     }
1244   }
1245 
1246   for (MCSectionELF *Group : Groups) {
1247     align(Group->getAlignment());
1248 
1249     // Remember the offset into the file for this section.
1250     uint64_t SecStart = getStream().tell();
1251 
1252     const MCSymbol *SignatureSymbol = Group->getGroup();
1253     assert(SignatureSymbol);
1254     write(uint32_t(ELF::GRP_COMDAT));
1255     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1256       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1257       write(SecIndex);
1258     }
1259 
1260     uint64_t SecEnd = getStream().tell();
1261     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1262   }
1263 
1264   // Compute symbol table information.
1265   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1266 
1267   for (MCSectionELF *RelSection : Relocations) {
1268     align(RelSection->getAlignment());
1269 
1270     // Remember the offset into the file for this section.
1271     uint64_t SecStart = getStream().tell();
1272 
1273     writeRelocations(Asm, *RelSection->getAssociatedSection());
1274 
1275     uint64_t SecEnd = getStream().tell();
1276     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1277   }
1278 
1279   {
1280     uint64_t SecStart = getStream().tell();
1281     const MCSectionELF *Sec = createStringTable(Ctx);
1282     uint64_t SecEnd = getStream().tell();
1283     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1284   }
1285 
1286   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1287   align(NaturalAlignment);
1288 
1289   const uint64_t SectionHeaderOffset = getStream().tell();
1290 
1291   // ... then the section header table ...
1292   writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1293 
1294   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1295                              ? (uint16_t)ELF::SHN_UNDEF
1296                              : SectionTable.size() + 1;
1297   if (sys::IsLittleEndianHost != IsLittleEndian)
1298     sys::swapByteOrder(NumSections);
1299   unsigned NumSectionsOffset;
1300 
1301   if (is64Bit()) {
1302     uint64_t Val = SectionHeaderOffset;
1303     if (sys::IsLittleEndianHost != IsLittleEndian)
1304       sys::swapByteOrder(Val);
1305     getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1306                        offsetof(ELF::Elf64_Ehdr, e_shoff));
1307     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1308   } else {
1309     uint32_t Val = SectionHeaderOffset;
1310     if (sys::IsLittleEndianHost != IsLittleEndian)
1311       sys::swapByteOrder(Val);
1312     getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1313                        offsetof(ELF::Elf32_Ehdr, e_shoff));
1314     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1315   }
1316   getStream().pwrite(reinterpret_cast<char *>(&NumSections),
1317                      sizeof(NumSections), NumSectionsOffset);
1318 }
1319 
1320 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1321     const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1322     bool InSet, bool IsPCRel) const {
1323   const auto &SymA = cast<MCSymbolELF>(SA);
1324   if (IsPCRel) {
1325     assert(!InSet);
1326     if (::isWeak(SymA))
1327       return false;
1328   }
1329   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1330                                                                 InSet, IsPCRel);
1331 }
1332 
1333 bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
1334   const auto &Sym = cast<MCSymbolELF>(S);
1335   if (::isWeak(Sym))
1336     return true;
1337 
1338   // It is invalid to replace a reference to a global in a comdat
1339   // with a reference to a local since out of comdat references
1340   // to a local are forbidden.
1341   // We could try to return false for more cases, like the reference
1342   // being in the same comdat or Sym being an alias to another global,
1343   // but it is not clear if it is worth the effort.
1344   if (Sym.getBinding() != ELF::STB_GLOBAL)
1345     return false;
1346 
1347   if (!Sym.isInSection())
1348     return false;
1349 
1350   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1351   return Sec.getGroup();
1352 }
1353 
1354 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1355                                             raw_pwrite_stream &OS,
1356                                             bool IsLittleEndian) {
1357   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1358 }
1359