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/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAsmLayout.h"
23 #include "llvm/MC/MCAssembler.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCELFObjectWriter.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCFixup.h"
28 #include "llvm/MC/MCFragment.h"
29 #include "llvm/MC/MCObjectWriter.h"
30 #include "llvm/MC/MCSection.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCSymbolELF.h"
34 #include "llvm/MC/MCValue.h"
35 #include "llvm/MC/StringTableBuilder.h"
36 #include "llvm/Support/Allocator.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compression.h"
39 #include "llvm/Support/ELF.h"
40 #include "llvm/Support/Endian.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/SMLoc.h"
46 #include "llvm/Support/StringSaver.h"
47 #include "llvm/Support/SwapByteOrder.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstddef>
52 #include <cstdint>
53 #include <map>
54 #include <memory>
55 #include <string>
56 #include <utility>
57 #include <vector>
58 
59 using namespace llvm;
60 
61 #undef  DEBUG_TYPE
62 #define DEBUG_TYPE "reloc-info"
63 
64 namespace {
65 
66 typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
67 
68 class ELFObjectWriter;
69 
70 class SymbolTableWriter {
71   ELFObjectWriter &EWriter;
72   bool Is64Bit;
73 
74   // indexes we are going to write to .symtab_shndx.
75   std::vector<uint32_t> ShndxIndexes;
76 
77   // The numbel of symbols written so far.
78   unsigned NumWritten;
79 
80   void createSymtabShndx();
81 
82   template <typename T> void write(T Value);
83 
84 public:
85   SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
86 
87   void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
88                    uint8_t other, uint32_t shndx, bool Reserved);
89 
90   ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
91 };
92 
93 class ELFObjectWriter : public MCObjectWriter {
94   static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
95   static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
96                          bool Used, bool Renamed);
97 
98   /// Helper struct for containing some precomputed information on symbols.
99   struct ELFSymbolData {
100     const MCSymbolELF *Symbol;
101     uint32_t SectionIndex;
102     StringRef Name;
103 
104     // Support lexicographic sorting.
105     bool operator<(const ELFSymbolData &RHS) const {
106       unsigned LHSType = Symbol->getType();
107       unsigned RHSType = RHS.Symbol->getType();
108       if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
109         return false;
110       if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
111         return true;
112       if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
113         return SectionIndex < RHS.SectionIndex;
114       return Name < RHS.Name;
115     }
116   };
117 
118   /// The target specific ELF writer instance.
119   std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
120 
121   DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
122 
123   DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> Relocations;
124 
125   /// @}
126   /// @name Symbol Table Data
127   /// @{
128 
129   BumpPtrAllocator Alloc;
130   StringSaver VersionSymSaver{Alloc};
131   StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
132 
133   /// @}
134 
135   // This holds the symbol table index of the last local symbol.
136   unsigned LastLocalSymbolIndex;
137   // This holds the .strtab section index.
138   unsigned StringTableIndex;
139   // This holds the .symtab section index.
140   unsigned SymbolTableIndex;
141 
142   // Sections in the order they are to be output in the section table.
143   std::vector<const MCSectionELF *> SectionTable;
144   unsigned addToSectionTable(const MCSectionELF *Sec);
145 
146   // TargetObjectWriter wrappers.
147   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
148   bool hasRelocationAddend() const {
149     return TargetObjectWriter->hasRelocationAddend();
150   }
151   unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
152                         const MCFixup &Fixup, bool IsPCRel) const {
153     return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
154   }
155 
156   void align(unsigned Alignment);
157 
158   bool maybeWriteCompression(uint64_t Size,
159                              SmallVectorImpl<char> &CompressedContents,
160                              bool ZLibStyle, unsigned Alignment);
161 
162 public:
163   ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
164                   bool IsLittleEndian)
165       : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
166 
167   ~ELFObjectWriter() override = default;
168 
169   void reset() override {
170     Renames.clear();
171     Relocations.clear();
172     StrTabBuilder.clear();
173     SectionTable.clear();
174     MCObjectWriter::reset();
175   }
176 
177   void WriteWord(uint64_t W) {
178     if (is64Bit())
179       write64(W);
180     else
181       write32(W);
182   }
183 
184   template <typename T> void write(T Val) {
185     if (IsLittleEndian)
186       support::endian::Writer<support::little>(getStream()).write(Val);
187     else
188       support::endian::Writer<support::big>(getStream()).write(Val);
189   }
190 
191   void writeHeader(const MCAssembler &Asm);
192 
193   void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
194                    ELFSymbolData &MSD, const MCAsmLayout &Layout);
195 
196   // Start and end offset of each section
197   typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
198       SectionOffsetsTy;
199 
200   bool shouldRelocateWithSymbol(const MCAssembler &Asm,
201                                 const MCSymbolRefExpr *RefA,
202                                 const MCSymbol *Sym, uint64_t C,
203                                 unsigned Type) const;
204 
205   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
206                         const MCFragment *Fragment, const MCFixup &Fixup,
207                         MCValue Target, bool &IsPCRel,
208                         uint64_t &FixedValue) override;
209 
210   // Map from a signature symbol to the group section index
211   typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
212 
213   /// Compute the symbol table data
214   ///
215   /// \param Asm - The assembler.
216   /// \param SectionIndexMap - Maps a section to its index.
217   /// \param RevGroupMap - Maps a signature symbol to the group section.
218   void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
219                           const SectionIndexMapTy &SectionIndexMap,
220                           const RevGroupMapTy &RevGroupMap,
221                           SectionOffsetsTy &SectionOffsets);
222 
223   MCSectionELF *createRelocationSection(MCContext &Ctx,
224                                         const MCSectionELF &Sec);
225 
226   const MCSectionELF *createStringTable(MCContext &Ctx);
227 
228   void executePostLayoutBinding(MCAssembler &Asm,
229                                 const MCAsmLayout &Layout) override;
230 
231   void writeSectionHeader(const MCAsmLayout &Layout,
232                           const SectionIndexMapTy &SectionIndexMap,
233                           const SectionOffsetsTy &SectionOffsets);
234 
235   void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
236                         const MCAsmLayout &Layout);
237 
238   void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
239                         uint64_t Address, uint64_t Offset, uint64_t Size,
240                         uint32_t Link, uint32_t Info, uint64_t Alignment,
241                         uint64_t EntrySize);
242 
243   void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
244 
245   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
246                                               const MCSymbol &SymA,
247                                               const MCFragment &FB, bool InSet,
248                                               bool IsPCRel) const override;
249 
250   bool isWeak(const MCSymbol &Sym) 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                                        bool &IsPCRel, uint64_t &FixedValue) {
631   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
632   uint64_t C = Target.getConstant();
633   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
634   MCContext &Ctx = Asm.getContext();
635 
636   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
637     assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
638            "Should not have constructed this");
639 
640     // Let A, B and C being the components of Target and R be the location of
641     // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
642     // If it is pcrel, we want to compute (A - B + C - R).
643 
644     // In general, ELF has no relocations for -B. It can only represent (A + C)
645     // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
646     // replace B to implement it: (A - R - K + C)
647     if (IsPCRel) {
648       Ctx.reportError(
649           Fixup.getLoc(),
650           "No relocation available to represent this relative expression");
651       return;
652     }
653 
654     const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
655 
656     if (SymB.isUndefined()) {
657       Ctx.reportError(Fixup.getLoc(),
658                       Twine("symbol '") + SymB.getName() +
659                           "' can not be undefined in a subtraction expression");
660       return;
661     }
662 
663     assert(!SymB.isAbsolute() && "Should have been folded");
664     const MCSection &SecB = SymB.getSection();
665     if (&SecB != &FixupSection) {
666       Ctx.reportError(Fixup.getLoc(),
667                       "Cannot represent a difference across sections");
668       return;
669     }
670 
671     uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
672     uint64_t K = SymBOffset - FixupOffset;
673     IsPCRel = true;
674     C -= K;
675   }
676 
677   // We either rejected the fixup or folded B into C at this point.
678   const MCSymbolRefExpr *RefA = Target.getSymA();
679   const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
680 
681   bool ViaWeakRef = false;
682   if (SymA && SymA->isVariable()) {
683     const MCExpr *Expr = SymA->getVariableValue();
684     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
685       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
686         SymA = cast<MCSymbolELF>(&Inner->getSymbol());
687         ViaWeakRef = true;
688       }
689     }
690   }
691 
692   unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel);
693   uint64_t OriginalC = C;
694   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
695   if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
696     C += Layout.getSymbolOffset(*SymA);
697 
698   uint64_t Addend = 0;
699   if (hasRelocationAddend()) {
700     Addend = C;
701     C = 0;
702   }
703 
704   FixedValue = C;
705 
706   if (!RelocateWithSymbol) {
707     const MCSection *SecA =
708         (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
709     auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
710     const auto *SectionSymbol =
711         ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr;
712     if (SectionSymbol)
713       SectionSymbol->setUsedInReloc();
714     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA,
715                            OriginalC);
716     Relocations[&FixupSection].push_back(Rec);
717     return;
718   }
719 
720   const auto *RenamedSymA = SymA;
721   if (SymA) {
722     if (const MCSymbolELF *R = Renames.lookup(SymA))
723       RenamedSymA = R;
724 
725     if (ViaWeakRef)
726       RenamedSymA->setIsWeakrefUsedInReloc();
727     else
728       RenamedSymA->setUsedInReloc();
729   }
730   ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA,
731                          OriginalC);
732   Relocations[&FixupSection].push_back(Rec);
733 }
734 
735 bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
736                                  const MCSymbolELF &Symbol, bool Used,
737                                  bool Renamed) {
738   if (Symbol.isVariable()) {
739     const MCExpr *Expr = Symbol.getVariableValue();
740     if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
741       if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
742         return false;
743     }
744   }
745 
746   if (Used)
747     return true;
748 
749   if (Renamed)
750     return false;
751 
752   if (Symbol.isVariable() && Symbol.isUndefined()) {
753     // FIXME: this is here just to diagnose the case of a var = commmon_sym.
754     Layout.getBaseSymbol(Symbol);
755     return false;
756   }
757 
758   if (Symbol.isUndefined() && !Symbol.isBindingSet())
759     return false;
760 
761   if (Symbol.isTemporary())
762     return false;
763 
764   if (Symbol.getType() == ELF::STT_SECTION)
765     return false;
766 
767   return true;
768 }
769 
770 void ELFObjectWriter::computeSymbolTable(
771     MCAssembler &Asm, const MCAsmLayout &Layout,
772     const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
773     SectionOffsetsTy &SectionOffsets) {
774   MCContext &Ctx = Asm.getContext();
775   SymbolTableWriter Writer(*this, is64Bit());
776 
777   // Symbol table
778   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
779   MCSectionELF *SymtabSection =
780       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
781   SymtabSection->setAlignment(is64Bit() ? 8 : 4);
782   SymbolTableIndex = addToSectionTable(SymtabSection);
783 
784   align(SymtabSection->getAlignment());
785   uint64_t SecStart = getStream().tell();
786 
787   // The first entry is the undefined symbol entry.
788   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
789 
790   std::vector<ELFSymbolData> LocalSymbolData;
791   std::vector<ELFSymbolData> ExternalSymbolData;
792 
793   // Add the data for the symbols.
794   bool HasLargeSectionIndex = false;
795   for (const MCSymbol &S : Asm.symbols()) {
796     const auto &Symbol = cast<MCSymbolELF>(S);
797     bool Used = Symbol.isUsedInReloc();
798     bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
799     bool isSignature = Symbol.isSignature();
800 
801     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
802                     Renames.count(&Symbol)))
803       continue;
804 
805     if (Symbol.isTemporary() && Symbol.isUndefined()) {
806       Ctx.reportError(SMLoc(), "Undefined temporary symbol");
807       continue;
808     }
809 
810     ELFSymbolData MSD;
811     MSD.Symbol = cast<MCSymbolELF>(&Symbol);
812 
813     bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
814     assert(Local || !Symbol.isTemporary());
815 
816     if (Symbol.isAbsolute()) {
817       MSD.SectionIndex = ELF::SHN_ABS;
818     } else if (Symbol.isCommon()) {
819       assert(!Local);
820       MSD.SectionIndex = ELF::SHN_COMMON;
821     } else if (Symbol.isUndefined()) {
822       if (isSignature && !Used) {
823         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
824         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
825           HasLargeSectionIndex = true;
826       } else {
827         MSD.SectionIndex = ELF::SHN_UNDEF;
828       }
829     } else {
830       const MCSectionELF &Section =
831           static_cast<const MCSectionELF &>(Symbol.getSection());
832       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
833       assert(MSD.SectionIndex && "Invalid section index!");
834       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
835         HasLargeSectionIndex = true;
836     }
837 
838     // The @@@ in symbol version is replaced with @ in undefined symbols and @@
839     // in defined ones.
840     //
841     // FIXME: All name handling should be done before we get to the writer,
842     // including dealing with GNU-style version suffixes.  Fixing this isn't
843     // trivial.
844     //
845     // We thus have to be careful to not perform the symbol version replacement
846     // blindly:
847     //
848     // The ELF format is used on Windows by the MCJIT engine.  Thus, on
849     // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
850     // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
851     // C++ name mangling can legally have "@@@" as a sub-string. In that case,
852     // the EFLObjectWriter should not interpret the "@@@" sub-string as
853     // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
854     // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
855     // "__imp_?" or "__imp_@?".
856     //
857     // It would have been interesting to perform the MS mangling prefix check
858     // only when the target triple is of the form *-pc-windows-elf. But, it
859     // seems that this information is not easily accessible from the
860     // ELFObjectWriter.
861     StringRef Name = Symbol.getName();
862     SmallString<32> Buf;
863     if (!Name.startswith("?") && !Name.startswith("@?") &&
864         !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
865       // This symbol isn't following the MSVC C++ name mangling convention. We
866       // can thus safely interpret the @@@ in symbol names as specifying symbol
867       // versioning.
868       size_t Pos = Name.find("@@@");
869       if (Pos != StringRef::npos) {
870         Buf += Name.substr(0, Pos);
871         unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
872         Buf += Name.substr(Pos + Skip);
873         Name = VersionSymSaver.save(Buf.c_str());
874       }
875     }
876 
877     // Sections have their own string table
878     if (Symbol.getType() != ELF::STT_SECTION) {
879       MSD.Name = Name;
880       StrTabBuilder.add(Name);
881     }
882 
883     if (Local)
884       LocalSymbolData.push_back(MSD);
885     else
886       ExternalSymbolData.push_back(MSD);
887   }
888 
889   // This holds the .symtab_shndx section index.
890   unsigned SymtabShndxSectionIndex = 0;
891 
892   if (HasLargeSectionIndex) {
893     MCSectionELF *SymtabShndxSection =
894         Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
895     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
896     SymtabShndxSection->setAlignment(4);
897   }
898 
899   ArrayRef<std::string> FileNames = Asm.getFileNames();
900   for (const std::string &Name : FileNames)
901     StrTabBuilder.add(Name);
902 
903   StrTabBuilder.finalize();
904 
905   for (const std::string &Name : FileNames)
906     Writer.writeSymbol(StrTabBuilder.getOffset(Name),
907                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
908                        ELF::SHN_ABS, true);
909 
910   // Symbols are required to be in lexicographic order.
911   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
912   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
913 
914   // Set the symbol indices. Local symbols must come before all other
915   // symbols with non-local bindings.
916   unsigned Index = FileNames.size() + 1;
917 
918   for (ELFSymbolData &MSD : LocalSymbolData) {
919     unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
920                                ? 0
921                                : StrTabBuilder.getOffset(MSD.Name);
922     MSD.Symbol->setIndex(Index++);
923     writeSymbol(Writer, StringIndex, MSD, Layout);
924   }
925 
926   // Write the symbol table entries.
927   LastLocalSymbolIndex = Index;
928 
929   for (ELFSymbolData &MSD : ExternalSymbolData) {
930     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
931     MSD.Symbol->setIndex(Index++);
932     writeSymbol(Writer, StringIndex, MSD, Layout);
933     assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
934   }
935 
936   uint64_t SecEnd = getStream().tell();
937   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
938 
939   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
940   if (ShndxIndexes.empty()) {
941     assert(SymtabShndxSectionIndex == 0);
942     return;
943   }
944   assert(SymtabShndxSectionIndex != 0);
945 
946   SecStart = getStream().tell();
947   const MCSectionELF *SymtabShndxSection =
948       SectionTable[SymtabShndxSectionIndex - 1];
949   for (uint32_t Index : ShndxIndexes)
950     write(Index);
951   SecEnd = getStream().tell();
952   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
953 }
954 
955 MCSectionELF *
956 ELFObjectWriter::createRelocationSection(MCContext &Ctx,
957                                          const MCSectionELF &Sec) {
958   if (Relocations[&Sec].empty())
959     return nullptr;
960 
961   const StringRef SectionName = Sec.getSectionName();
962   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
963   RelaSectionName += SectionName;
964 
965   unsigned EntrySize;
966   if (hasRelocationAddend())
967     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
968   else
969     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
970 
971   unsigned Flags = 0;
972   if (Sec.getFlags() & ELF::SHF_GROUP)
973     Flags = ELF::SHF_GROUP;
974 
975   MCSectionELF *RelaSection = Ctx.createELFRelSection(
976       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
977       Flags, EntrySize, Sec.getGroup(), &Sec);
978   RelaSection->setAlignment(is64Bit() ? 8 : 4);
979   return RelaSection;
980 }
981 
982 // Include the debug info compression header.
983 bool ELFObjectWriter::maybeWriteCompression(
984     uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
985     unsigned Alignment) {
986   if (ZLibStyle) {
987     uint64_t HdrSize =
988         is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
989     if (Size <= HdrSize + CompressedContents.size())
990       return false;
991     // Platform specific header is followed by compressed data.
992     if (is64Bit()) {
993       // Write Elf64_Chdr header.
994       write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
995       write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
996       write(static_cast<ELF::Elf64_Xword>(Size));
997       write(static_cast<ELF::Elf64_Xword>(Alignment));
998     } else {
999       // Write Elf32_Chdr header otherwise.
1000       write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
1001       write(static_cast<ELF::Elf32_Word>(Size));
1002       write(static_cast<ELF::Elf32_Word>(Alignment));
1003     }
1004     return true;
1005   }
1006 
1007   // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1008   // useful for consumers to preallocate a buffer to decompress into.
1009   const StringRef Magic = "ZLIB";
1010   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1011     return false;
1012   write(ArrayRef<char>(Magic.begin(), Magic.size()));
1013   writeBE64(Size);
1014   return true;
1015 }
1016 
1017 void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
1018                                        const MCAsmLayout &Layout) {
1019   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1020   StringRef SectionName = Section.getSectionName();
1021 
1022   // Compressing debug_frame requires handling alignment fragments which is
1023   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1024   // for writing to arbitrary buffers) for little benefit.
1025   bool CompressionEnabled =
1026       Asm.getContext().getAsmInfo()->compressDebugSections() !=
1027       DebugCompressionType::DCT_None;
1028   if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
1029       SectionName == ".debug_frame") {
1030     Asm.writeSectionData(&Section, Layout);
1031     return;
1032   }
1033 
1034   SmallVector<char, 128> UncompressedData;
1035   raw_svector_ostream VecOS(UncompressedData);
1036   raw_pwrite_stream &OldStream = getStream();
1037   setStream(VecOS);
1038   Asm.writeSectionData(&Section, Layout);
1039   setStream(OldStream);
1040 
1041   SmallVector<char, 128> CompressedContents;
1042   if (Error E = zlib::compress(
1043           StringRef(UncompressedData.data(), UncompressedData.size()),
1044           CompressedContents)) {
1045     consumeError(std::move(E));
1046     getStream() << UncompressedData;
1047     return;
1048   }
1049 
1050   bool ZlibStyle = Asm.getContext().getAsmInfo()->compressDebugSections() ==
1051                    DebugCompressionType::DCT_Zlib;
1052   if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
1053                              ZlibStyle, Sec.getAlignment())) {
1054     getStream() << UncompressedData;
1055     return;
1056   }
1057 
1058   if (ZlibStyle)
1059     // Set the compressed flag. That is zlib style.
1060     Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
1061   else
1062     // Add "z" prefix to section name. This is zlib-gnu style.
1063     Asm.getContext().renameELFSection(&Section,
1064                                       (".z" + SectionName.drop_front(1)).str());
1065   getStream() << CompressedContents;
1066 }
1067 
1068 void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1069                                        uint64_t Flags, uint64_t Address,
1070                                        uint64_t Offset, uint64_t Size,
1071                                        uint32_t Link, uint32_t Info,
1072                                        uint64_t Alignment,
1073                                        uint64_t EntrySize) {
1074   write32(Name);        // sh_name: index into string table
1075   write32(Type);        // sh_type
1076   WriteWord(Flags);     // sh_flags
1077   WriteWord(Address);   // sh_addr
1078   WriteWord(Offset);    // sh_offset
1079   WriteWord(Size);      // sh_size
1080   write32(Link);        // sh_link
1081   write32(Info);        // sh_info
1082   WriteWord(Alignment); // sh_addralign
1083   WriteWord(EntrySize); // sh_entsize
1084 }
1085 
1086 void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
1087                                        const MCSectionELF &Sec) {
1088   std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
1089 
1090   // We record relocations by pushing to the end of a vector. Reverse the vector
1091   // to get the relocations in the order they were created.
1092   // In most cases that is not important, but it can be for special sections
1093   // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
1094   std::reverse(Relocs.begin(), Relocs.end());
1095 
1096   // Sort the relocation entries. MIPS needs this.
1097   TargetObjectWriter->sortRelocs(Asm, Relocs);
1098 
1099   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1100     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
1101     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
1102 
1103     if (is64Bit()) {
1104       write(Entry.Offset);
1105       if (TargetObjectWriter->isN64()) {
1106         write(uint32_t(Index));
1107 
1108         write(TargetObjectWriter->getRSsym(Entry.Type));
1109         write(TargetObjectWriter->getRType3(Entry.Type));
1110         write(TargetObjectWriter->getRType2(Entry.Type));
1111         write(TargetObjectWriter->getRType(Entry.Type));
1112       } else {
1113         struct ELF::Elf64_Rela ERE64;
1114         ERE64.setSymbolAndType(Index, Entry.Type);
1115         write(ERE64.r_info);
1116       }
1117       if (hasRelocationAddend())
1118         write(Entry.Addend);
1119     } else {
1120       write(uint32_t(Entry.Offset));
1121 
1122       struct ELF::Elf32_Rela ERE32;
1123       ERE32.setSymbolAndType(Index, Entry.Type);
1124       write(ERE32.r_info);
1125 
1126       if (hasRelocationAddend())
1127         write(uint32_t(Entry.Addend));
1128     }
1129   }
1130 }
1131 
1132 const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
1133   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1134   StrTabBuilder.write(getStream());
1135   return StrtabSection;
1136 }
1137 
1138 void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1139                                    uint32_t GroupSymbolIndex, uint64_t Offset,
1140                                    uint64_t Size, const MCSectionELF &Section) {
1141   uint64_t sh_link = 0;
1142   uint64_t sh_info = 0;
1143 
1144   switch(Section.getType()) {
1145   default:
1146     // Nothing to do.
1147     break;
1148 
1149   case ELF::SHT_DYNAMIC:
1150     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1151 
1152   case ELF::SHT_REL:
1153   case ELF::SHT_RELA: {
1154     sh_link = SymbolTableIndex;
1155     assert(sh_link && ".symtab not found");
1156     const MCSectionELF *InfoSection = Section.getAssociatedSection();
1157     sh_info = SectionIndexMap.lookup(InfoSection);
1158     break;
1159   }
1160 
1161   case ELF::SHT_SYMTAB:
1162   case ELF::SHT_DYNSYM:
1163     sh_link = StringTableIndex;
1164     sh_info = LastLocalSymbolIndex;
1165     break;
1166 
1167   case ELF::SHT_SYMTAB_SHNDX:
1168     sh_link = SymbolTableIndex;
1169     break;
1170 
1171   case ELF::SHT_GROUP:
1172     sh_link = SymbolTableIndex;
1173     sh_info = GroupSymbolIndex;
1174     break;
1175   }
1176 
1177   if (Section.getFlags() & ELF::SHF_LINK_ORDER)
1178     sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
1179 
1180   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1181                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1182                    sh_link, sh_info, Section.getAlignment(),
1183                    Section.getEntrySize());
1184 }
1185 
1186 void ELFObjectWriter::writeSectionHeader(
1187     const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1188     const SectionOffsetsTy &SectionOffsets) {
1189   const unsigned NumSections = SectionTable.size();
1190 
1191   // Null section first.
1192   uint64_t FirstSectionSize =
1193       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1194   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1195 
1196   for (const MCSectionELF *Section : SectionTable) {
1197     uint32_t GroupSymbolIndex;
1198     unsigned Type = Section->getType();
1199     if (Type != ELF::SHT_GROUP)
1200       GroupSymbolIndex = 0;
1201     else
1202       GroupSymbolIndex = Section->getGroup()->getIndex();
1203 
1204     const std::pair<uint64_t, uint64_t> &Offsets =
1205         SectionOffsets.find(Section)->second;
1206     uint64_t Size;
1207     if (Type == ELF::SHT_NOBITS)
1208       Size = Layout.getSectionAddressSize(Section);
1209     else
1210       Size = Offsets.second - Offsets.first;
1211 
1212     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1213                  *Section);
1214   }
1215 }
1216 
1217 void ELFObjectWriter::writeObject(MCAssembler &Asm,
1218                                   const MCAsmLayout &Layout) {
1219   MCContext &Ctx = Asm.getContext();
1220   MCSectionELF *StrtabSection =
1221       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1222   StringTableIndex = addToSectionTable(StrtabSection);
1223 
1224   RevGroupMapTy RevGroupMap;
1225   SectionIndexMapTy SectionIndexMap;
1226 
1227   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1228 
1229   // Write out the ELF header ...
1230   writeHeader(Asm);
1231 
1232   // ... then the sections ...
1233   SectionOffsetsTy SectionOffsets;
1234   std::vector<MCSectionELF *> Groups;
1235   std::vector<MCSectionELF *> Relocations;
1236   for (MCSection &Sec : Asm) {
1237     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1238 
1239     align(Section.getAlignment());
1240 
1241     // Remember the offset into the file for this section.
1242     uint64_t SecStart = getStream().tell();
1243 
1244     const MCSymbolELF *SignatureSymbol = Section.getGroup();
1245     writeSectionData(Asm, Section, Layout);
1246 
1247     uint64_t SecEnd = getStream().tell();
1248     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1249 
1250     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1251 
1252     if (SignatureSymbol) {
1253       Asm.registerSymbol(*SignatureSymbol);
1254       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1255       if (!GroupIdx) {
1256         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1257         GroupIdx = addToSectionTable(Group);
1258         Group->setAlignment(4);
1259         Groups.push_back(Group);
1260       }
1261       std::vector<const MCSectionELF *> &Members =
1262           GroupMembers[SignatureSymbol];
1263       Members.push_back(&Section);
1264       if (RelSection)
1265         Members.push_back(RelSection);
1266     }
1267 
1268     SectionIndexMap[&Section] = addToSectionTable(&Section);
1269     if (RelSection) {
1270       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1271       Relocations.push_back(RelSection);
1272     }
1273   }
1274 
1275   for (MCSectionELF *Group : Groups) {
1276     align(Group->getAlignment());
1277 
1278     // Remember the offset into the file for this section.
1279     uint64_t SecStart = getStream().tell();
1280 
1281     const MCSymbol *SignatureSymbol = Group->getGroup();
1282     assert(SignatureSymbol);
1283     write(uint32_t(ELF::GRP_COMDAT));
1284     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1285       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1286       write(SecIndex);
1287     }
1288 
1289     uint64_t SecEnd = getStream().tell();
1290     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1291   }
1292 
1293   // Compute symbol table information.
1294   computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
1295 
1296   for (MCSectionELF *RelSection : Relocations) {
1297     align(RelSection->getAlignment());
1298 
1299     // Remember the offset into the file for this section.
1300     uint64_t SecStart = getStream().tell();
1301 
1302     writeRelocations(Asm, *RelSection->getAssociatedSection());
1303 
1304     uint64_t SecEnd = getStream().tell();
1305     SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1306   }
1307 
1308   {
1309     uint64_t SecStart = getStream().tell();
1310     const MCSectionELF *Sec = createStringTable(Ctx);
1311     uint64_t SecEnd = getStream().tell();
1312     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1313   }
1314 
1315   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1316   align(NaturalAlignment);
1317 
1318   const uint64_t SectionHeaderOffset = getStream().tell();
1319 
1320   // ... then the section header table ...
1321   writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1322 
1323   uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
1324                              ? (uint16_t)ELF::SHN_UNDEF
1325                              : SectionTable.size() + 1;
1326   if (sys::IsLittleEndianHost != IsLittleEndian)
1327     sys::swapByteOrder(NumSections);
1328   unsigned NumSectionsOffset;
1329 
1330   if (is64Bit()) {
1331     uint64_t Val = SectionHeaderOffset;
1332     if (sys::IsLittleEndianHost != IsLittleEndian)
1333       sys::swapByteOrder(Val);
1334     getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1335                        offsetof(ELF::Elf64_Ehdr, e_shoff));
1336     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1337   } else {
1338     uint32_t Val = SectionHeaderOffset;
1339     if (sys::IsLittleEndianHost != IsLittleEndian)
1340       sys::swapByteOrder(Val);
1341     getStream().pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1342                        offsetof(ELF::Elf32_Ehdr, e_shoff));
1343     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1344   }
1345   getStream().pwrite(reinterpret_cast<char *>(&NumSections),
1346                      sizeof(NumSections), NumSectionsOffset);
1347 }
1348 
1349 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1350     const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1351     bool InSet, bool IsPCRel) const {
1352   const auto &SymA = cast<MCSymbolELF>(SA);
1353   if (IsPCRel) {
1354     assert(!InSet);
1355     if (::isWeak(SymA))
1356       return false;
1357   }
1358   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1359                                                                 InSet, IsPCRel);
1360 }
1361 
1362 bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
1363   const auto &Sym = cast<MCSymbolELF>(S);
1364   if (::isWeak(Sym))
1365     return true;
1366 
1367   // It is invalid to replace a reference to a global in a comdat
1368   // with a reference to a local since out of comdat references
1369   // to a local are forbidden.
1370   // We could try to return false for more cases, like the reference
1371   // being in the same comdat or Sym being an alias to another global,
1372   // but it is not clear if it is worth the effort.
1373   if (Sym.getBinding() != ELF::STB_GLOBAL)
1374     return false;
1375 
1376   if (!Sym.isInSection())
1377     return false;
1378 
1379   const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1380   return Sec.getGroup();
1381 }
1382 
1383 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1384                                             raw_pwrite_stream &OS,
1385                                             bool IsLittleEndian) {
1386   return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
1387 }
1388