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