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