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