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