xref: /freebsd-src/contrib/llvm-project/llvm/lib/MC/ELFObjectWriter.cpp (revision a7dea1671b87c07d2d266f836bfa8b58efc7c134)
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.isUndefined() && !Symbol.isBindingSet())
619     return false;
620 
621   if (Symbol.isTemporary())
622     return false;
623 
624   if (Symbol.getType() == ELF::STT_SECTION)
625     return false;
626 
627   return true;
628 }
629 
630 void ELFWriter::computeSymbolTable(
631     MCAssembler &Asm, const MCAsmLayout &Layout,
632     const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
633     SectionOffsetsTy &SectionOffsets) {
634   MCContext &Ctx = Asm.getContext();
635   SymbolTableWriter Writer(*this, is64Bit());
636 
637   // Symbol table
638   unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
639   MCSectionELF *SymtabSection =
640       Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
641   SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
642   SymbolTableIndex = addToSectionTable(SymtabSection);
643 
644   align(SymtabSection->getAlignment());
645   uint64_t SecStart = W.OS.tell();
646 
647   // The first entry is the undefined symbol entry.
648   Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
649 
650   std::vector<ELFSymbolData> LocalSymbolData;
651   std::vector<ELFSymbolData> ExternalSymbolData;
652 
653   // Add the data for the symbols.
654   bool HasLargeSectionIndex = false;
655   for (const MCSymbol &S : Asm.symbols()) {
656     const auto &Symbol = cast<MCSymbolELF>(S);
657     bool Used = Symbol.isUsedInReloc();
658     bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
659     bool isSignature = Symbol.isSignature();
660 
661     if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
662                     OWriter.Renames.count(&Symbol)))
663       continue;
664 
665     if (Symbol.isTemporary() && Symbol.isUndefined()) {
666       Ctx.reportError(SMLoc(), "Undefined temporary symbol");
667       continue;
668     }
669 
670     ELFSymbolData MSD;
671     MSD.Symbol = cast<MCSymbolELF>(&Symbol);
672 
673     bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
674     assert(Local || !Symbol.isTemporary());
675 
676     if (Symbol.isAbsolute()) {
677       MSD.SectionIndex = ELF::SHN_ABS;
678     } else if (Symbol.isCommon()) {
679       if (Symbol.isTargetCommon()) {
680         MSD.SectionIndex = Symbol.getIndex();
681       } else {
682         assert(!Local);
683         MSD.SectionIndex = ELF::SHN_COMMON;
684       }
685     } else if (Symbol.isUndefined()) {
686       if (isSignature && !Used) {
687         MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
688         if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
689           HasLargeSectionIndex = true;
690       } else {
691         MSD.SectionIndex = ELF::SHN_UNDEF;
692       }
693     } else {
694       const MCSectionELF &Section =
695           static_cast<const MCSectionELF &>(Symbol.getSection());
696 
697       // We may end up with a situation when section symbol is technically
698       // defined, but should not be. That happens because we explicitly
699       // pre-create few .debug_* sections to have accessors.
700       // And if these sections were not really defined in the code, but were
701       // referenced, we simply error out.
702       if (!Section.isRegistered()) {
703         assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
704                ELF::STT_SECTION);
705         Ctx.reportError(SMLoc(),
706                         "Undefined section reference: " + Symbol.getName());
707         continue;
708       }
709 
710       if (Mode == NonDwoOnly && isDwoSection(Section))
711         continue;
712       MSD.SectionIndex = SectionIndexMap.lookup(&Section);
713       assert(MSD.SectionIndex && "Invalid section index!");
714       if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
715         HasLargeSectionIndex = true;
716     }
717 
718     StringRef Name = Symbol.getName();
719 
720     // Sections have their own string table
721     if (Symbol.getType() != ELF::STT_SECTION) {
722       MSD.Name = Name;
723       StrTabBuilder.add(Name);
724     }
725 
726     if (Local)
727       LocalSymbolData.push_back(MSD);
728     else
729       ExternalSymbolData.push_back(MSD);
730   }
731 
732   // This holds the .symtab_shndx section index.
733   unsigned SymtabShndxSectionIndex = 0;
734 
735   if (HasLargeSectionIndex) {
736     MCSectionELF *SymtabShndxSection =
737         Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
738     SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
739     SymtabShndxSection->setAlignment(Align(4));
740   }
741 
742   ArrayRef<std::string> FileNames = Asm.getFileNames();
743   for (const std::string &Name : FileNames)
744     StrTabBuilder.add(Name);
745 
746   StrTabBuilder.finalize();
747 
748   // File symbols are emitted first and handled separately from normal symbols,
749   // i.e. a non-STT_FILE symbol with the same name may appear.
750   for (const std::string &Name : FileNames)
751     Writer.writeSymbol(StrTabBuilder.getOffset(Name),
752                        ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
753                        ELF::SHN_ABS, true);
754 
755   // Symbols are required to be in lexicographic order.
756   array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
757   array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
758 
759   // Set the symbol indices. Local symbols must come before all other
760   // symbols with non-local bindings.
761   unsigned Index = FileNames.size() + 1;
762 
763   for (ELFSymbolData &MSD : LocalSymbolData) {
764     unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
765                                ? 0
766                                : StrTabBuilder.getOffset(MSD.Name);
767     MSD.Symbol->setIndex(Index++);
768     writeSymbol(Writer, StringIndex, MSD, Layout);
769   }
770 
771   // Write the symbol table entries.
772   LastLocalSymbolIndex = Index;
773 
774   for (ELFSymbolData &MSD : ExternalSymbolData) {
775     unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
776     MSD.Symbol->setIndex(Index++);
777     writeSymbol(Writer, StringIndex, MSD, Layout);
778     assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
779   }
780 
781   uint64_t SecEnd = W.OS.tell();
782   SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
783 
784   ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
785   if (ShndxIndexes.empty()) {
786     assert(SymtabShndxSectionIndex == 0);
787     return;
788   }
789   assert(SymtabShndxSectionIndex != 0);
790 
791   SecStart = W.OS.tell();
792   const MCSectionELF *SymtabShndxSection =
793       SectionTable[SymtabShndxSectionIndex - 1];
794   for (uint32_t Index : ShndxIndexes)
795     write(Index);
796   SecEnd = W.OS.tell();
797   SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
798 }
799 
800 void ELFWriter::writeAddrsigSection() {
801   for (const MCSymbol *Sym : OWriter.AddrsigSyms)
802     encodeULEB128(Sym->getIndex(), W.OS);
803 }
804 
805 MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
806                                                  const MCSectionELF &Sec) {
807   if (OWriter.Relocations[&Sec].empty())
808     return nullptr;
809 
810   const StringRef SectionName = Sec.getSectionName();
811   std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
812   RelaSectionName += SectionName;
813 
814   unsigned EntrySize;
815   if (hasRelocationAddend())
816     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
817   else
818     EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
819 
820   unsigned Flags = 0;
821   if (Sec.getFlags() & ELF::SHF_GROUP)
822     Flags = ELF::SHF_GROUP;
823 
824   MCSectionELF *RelaSection = Ctx.createELFRelSection(
825       RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
826       Flags, EntrySize, Sec.getGroup(), &Sec);
827   RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
828   return RelaSection;
829 }
830 
831 // Include the debug info compression header.
832 bool ELFWriter::maybeWriteCompression(
833     uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
834     unsigned Alignment) {
835   if (ZLibStyle) {
836     uint64_t HdrSize =
837         is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
838     if (Size <= HdrSize + CompressedContents.size())
839       return false;
840     // Platform specific header is followed by compressed data.
841     if (is64Bit()) {
842       // Write Elf64_Chdr header.
843       write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
844       write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
845       write(static_cast<ELF::Elf64_Xword>(Size));
846       write(static_cast<ELF::Elf64_Xword>(Alignment));
847     } else {
848       // Write Elf32_Chdr header otherwise.
849       write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
850       write(static_cast<ELF::Elf32_Word>(Size));
851       write(static_cast<ELF::Elf32_Word>(Alignment));
852     }
853     return true;
854   }
855 
856   // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
857   // useful for consumers to preallocate a buffer to decompress into.
858   const StringRef Magic = "ZLIB";
859   if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
860     return false;
861   W.OS << Magic;
862   support::endian::write(W.OS, Size, support::big);
863   return true;
864 }
865 
866 void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
867                                  const MCAsmLayout &Layout) {
868   MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
869   StringRef SectionName = Section.getSectionName();
870 
871   auto &MC = Asm.getContext();
872   const auto &MAI = MC.getAsmInfo();
873 
874   // Compressing debug_frame requires handling alignment fragments which is
875   // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
876   // for writing to arbitrary buffers) for little benefit.
877   bool CompressionEnabled =
878       MAI->compressDebugSections() != DebugCompressionType::None;
879   if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
880       SectionName == ".debug_frame") {
881     Asm.writeSectionData(W.OS, &Section, Layout);
882     return;
883   }
884 
885   assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
886           MAI->compressDebugSections() == DebugCompressionType::GNU) &&
887          "expected zlib or zlib-gnu style compression");
888 
889   SmallVector<char, 128> UncompressedData;
890   raw_svector_ostream VecOS(UncompressedData);
891   Asm.writeSectionData(VecOS, &Section, Layout);
892 
893   SmallVector<char, 128> CompressedContents;
894   if (Error E = zlib::compress(
895           StringRef(UncompressedData.data(), UncompressedData.size()),
896           CompressedContents)) {
897     consumeError(std::move(E));
898     W.OS << UncompressedData;
899     return;
900   }
901 
902   bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
903   if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
904                              ZlibStyle, Sec.getAlignment())) {
905     W.OS << UncompressedData;
906     return;
907   }
908 
909   if (ZlibStyle) {
910     // Set the compressed flag. That is zlib style.
911     Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
912     // Alignment field should reflect the requirements of
913     // the compressed section header.
914     Section.setAlignment(is64Bit() ? Align(8) : Align(4));
915   } else {
916     // Add "z" prefix to section name. This is zlib-gnu style.
917     MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
918   }
919   W.OS << CompressedContents;
920 }
921 
922 void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
923                                  uint64_t Address, uint64_t Offset,
924                                  uint64_t Size, uint32_t Link, uint32_t Info,
925                                  uint64_t Alignment, uint64_t EntrySize) {
926   W.write<uint32_t>(Name);        // sh_name: index into string table
927   W.write<uint32_t>(Type);        // sh_type
928   WriteWord(Flags);     // sh_flags
929   WriteWord(Address);   // sh_addr
930   WriteWord(Offset);    // sh_offset
931   WriteWord(Size);      // sh_size
932   W.write<uint32_t>(Link);        // sh_link
933   W.write<uint32_t>(Info);        // sh_info
934   WriteWord(Alignment); // sh_addralign
935   WriteWord(EntrySize); // sh_entsize
936 }
937 
938 void ELFWriter::writeRelocations(const MCAssembler &Asm,
939                                        const MCSectionELF &Sec) {
940   std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
941 
942   // We record relocations by pushing to the end of a vector. Reverse the vector
943   // to get the relocations in the order they were created.
944   // In most cases that is not important, but it can be for special sections
945   // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
946   std::reverse(Relocs.begin(), Relocs.end());
947 
948   // Sort the relocation entries. MIPS needs this.
949   OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
950 
951   for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
952     const ELFRelocationEntry &Entry = Relocs[e - i - 1];
953     unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
954 
955     if (is64Bit()) {
956       write(Entry.Offset);
957       if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
958         write(uint32_t(Index));
959 
960         write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
961         write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
962         write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
963         write(OWriter.TargetObjectWriter->getRType(Entry.Type));
964       } else {
965         struct ELF::Elf64_Rela ERE64;
966         ERE64.setSymbolAndType(Index, Entry.Type);
967         write(ERE64.r_info);
968       }
969       if (hasRelocationAddend())
970         write(Entry.Addend);
971     } else {
972       write(uint32_t(Entry.Offset));
973 
974       struct ELF::Elf32_Rela ERE32;
975       ERE32.setSymbolAndType(Index, Entry.Type);
976       write(ERE32.r_info);
977 
978       if (hasRelocationAddend())
979         write(uint32_t(Entry.Addend));
980 
981       if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
982         if (uint32_t RType =
983                 OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
984           write(uint32_t(Entry.Offset));
985 
986           ERE32.setSymbolAndType(0, RType);
987           write(ERE32.r_info);
988           write(uint32_t(0));
989         }
990         if (uint32_t RType =
991                 OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
992           write(uint32_t(Entry.Offset));
993 
994           ERE32.setSymbolAndType(0, RType);
995           write(ERE32.r_info);
996           write(uint32_t(0));
997         }
998       }
999     }
1000   }
1001 }
1002 
1003 const MCSectionELF *ELFWriter::createStringTable(MCContext &Ctx) {
1004   const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
1005   StrTabBuilder.write(W.OS);
1006   return StrtabSection;
1007 }
1008 
1009 void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
1010                              uint32_t GroupSymbolIndex, uint64_t Offset,
1011                              uint64_t Size, const MCSectionELF &Section) {
1012   uint64_t sh_link = 0;
1013   uint64_t sh_info = 0;
1014 
1015   switch(Section.getType()) {
1016   default:
1017     // Nothing to do.
1018     break;
1019 
1020   case ELF::SHT_DYNAMIC:
1021     llvm_unreachable("SHT_DYNAMIC in a relocatable object");
1022 
1023   case ELF::SHT_REL:
1024   case ELF::SHT_RELA: {
1025     sh_link = SymbolTableIndex;
1026     assert(sh_link && ".symtab not found");
1027     const MCSection *InfoSection = Section.getAssociatedSection();
1028     sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
1029     break;
1030   }
1031 
1032   case ELF::SHT_SYMTAB:
1033     sh_link = StringTableIndex;
1034     sh_info = LastLocalSymbolIndex;
1035     break;
1036 
1037   case ELF::SHT_SYMTAB_SHNDX:
1038   case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
1039   case ELF::SHT_LLVM_ADDRSIG:
1040     sh_link = SymbolTableIndex;
1041     break;
1042 
1043   case ELF::SHT_GROUP:
1044     sh_link = SymbolTableIndex;
1045     sh_info = GroupSymbolIndex;
1046     break;
1047   }
1048 
1049   if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
1050     const MCSymbol *Sym = Section.getAssociatedSymbol();
1051     const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
1052     sh_link = SectionIndexMap.lookup(Sec);
1053   }
1054 
1055   WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
1056                    Section.getType(), Section.getFlags(), 0, Offset, Size,
1057                    sh_link, sh_info, Section.getAlignment(),
1058                    Section.getEntrySize());
1059 }
1060 
1061 void ELFWriter::writeSectionHeader(
1062     const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
1063     const SectionOffsetsTy &SectionOffsets) {
1064   const unsigned NumSections = SectionTable.size();
1065 
1066   // Null section first.
1067   uint64_t FirstSectionSize =
1068       (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
1069   WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
1070 
1071   for (const MCSectionELF *Section : SectionTable) {
1072     uint32_t GroupSymbolIndex;
1073     unsigned Type = Section->getType();
1074     if (Type != ELF::SHT_GROUP)
1075       GroupSymbolIndex = 0;
1076     else
1077       GroupSymbolIndex = Section->getGroup()->getIndex();
1078 
1079     const std::pair<uint64_t, uint64_t> &Offsets =
1080         SectionOffsets.find(Section)->second;
1081     uint64_t Size;
1082     if (Type == ELF::SHT_NOBITS)
1083       Size = Layout.getSectionAddressSize(Section);
1084     else
1085       Size = Offsets.second - Offsets.first;
1086 
1087     writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1088                  *Section);
1089   }
1090 }
1091 
1092 uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1093   uint64_t StartOffset = W.OS.tell();
1094 
1095   MCContext &Ctx = Asm.getContext();
1096   MCSectionELF *StrtabSection =
1097       Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1098   StringTableIndex = addToSectionTable(StrtabSection);
1099 
1100   RevGroupMapTy RevGroupMap;
1101   SectionIndexMapTy SectionIndexMap;
1102 
1103   std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
1104 
1105   // Write out the ELF header ...
1106   writeHeader(Asm);
1107 
1108   // ... then the sections ...
1109   SectionOffsetsTy SectionOffsets;
1110   std::vector<MCSectionELF *> Groups;
1111   std::vector<MCSectionELF *> Relocations;
1112   for (MCSection &Sec : Asm) {
1113     MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
1114     if (Mode == NonDwoOnly && isDwoSection(Section))
1115       continue;
1116     if (Mode == DwoOnly && !isDwoSection(Section))
1117       continue;
1118 
1119     align(Section.getAlignment());
1120 
1121     // Remember the offset into the file for this section.
1122     uint64_t SecStart = W.OS.tell();
1123 
1124     const MCSymbolELF *SignatureSymbol = Section.getGroup();
1125     writeSectionData(Asm, Section, Layout);
1126 
1127     uint64_t SecEnd = W.OS.tell();
1128     SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
1129 
1130     MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
1131 
1132     if (SignatureSymbol) {
1133       Asm.registerSymbol(*SignatureSymbol);
1134       unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1135       if (!GroupIdx) {
1136         MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
1137         GroupIdx = addToSectionTable(Group);
1138         Group->setAlignment(Align(4));
1139         Groups.push_back(Group);
1140       }
1141       std::vector<const MCSectionELF *> &Members =
1142           GroupMembers[SignatureSymbol];
1143       Members.push_back(&Section);
1144       if (RelSection)
1145         Members.push_back(RelSection);
1146     }
1147 
1148     SectionIndexMap[&Section] = addToSectionTable(&Section);
1149     if (RelSection) {
1150       SectionIndexMap[RelSection] = addToSectionTable(RelSection);
1151       Relocations.push_back(RelSection);
1152     }
1153 
1154     OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
1155   }
1156 
1157   MCSectionELF *CGProfileSection = nullptr;
1158   if (!Asm.CGProfile.empty()) {
1159     CGProfileSection = Ctx.getELFSection(".llvm.call-graph-profile",
1160                                          ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
1161                                          ELF::SHF_EXCLUDE, 16, "");
1162     SectionIndexMap[CGProfileSection] = addToSectionTable(CGProfileSection);
1163   }
1164 
1165   for (MCSectionELF *Group : Groups) {
1166     align(Group->getAlignment());
1167 
1168     // Remember the offset into the file for this section.
1169     uint64_t SecStart = W.OS.tell();
1170 
1171     const MCSymbol *SignatureSymbol = Group->getGroup();
1172     assert(SignatureSymbol);
1173     write(uint32_t(ELF::GRP_COMDAT));
1174     for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
1175       uint32_t SecIndex = SectionIndexMap.lookup(Member);
1176       write(SecIndex);
1177     }
1178 
1179     uint64_t SecEnd = W.OS.tell();
1180     SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
1181   }
1182 
1183   if (Mode == DwoOnly) {
1184     // dwo files don't have symbol tables or relocations, but they do have
1185     // string tables.
1186     StrTabBuilder.finalize();
1187   } else {
1188     MCSectionELF *AddrsigSection;
1189     if (OWriter.EmitAddrsigSection) {
1190       AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
1191                                          ELF::SHF_EXCLUDE);
1192       addToSectionTable(AddrsigSection);
1193     }
1194 
1195     // Compute symbol table information.
1196     computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1197                        SectionOffsets);
1198 
1199     for (MCSectionELF *RelSection : Relocations) {
1200       align(RelSection->getAlignment());
1201 
1202       // Remember the offset into the file for this section.
1203       uint64_t SecStart = W.OS.tell();
1204 
1205       writeRelocations(Asm,
1206                        cast<MCSectionELF>(*RelSection->getAssociatedSection()));
1207 
1208       uint64_t SecEnd = W.OS.tell();
1209       SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
1210     }
1211 
1212     if (OWriter.EmitAddrsigSection) {
1213       uint64_t SecStart = W.OS.tell();
1214       writeAddrsigSection();
1215       uint64_t SecEnd = W.OS.tell();
1216       SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
1217     }
1218   }
1219 
1220   if (CGProfileSection) {
1221     uint64_t SecStart = W.OS.tell();
1222     for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
1223       W.write<uint32_t>(CGPE.From->getSymbol().getIndex());
1224       W.write<uint32_t>(CGPE.To->getSymbol().getIndex());
1225       W.write<uint64_t>(CGPE.Count);
1226     }
1227     uint64_t SecEnd = W.OS.tell();
1228     SectionOffsets[CGProfileSection] = std::make_pair(SecStart, SecEnd);
1229   }
1230 
1231   {
1232     uint64_t SecStart = W.OS.tell();
1233     const MCSectionELF *Sec = createStringTable(Ctx);
1234     uint64_t SecEnd = W.OS.tell();
1235     SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
1236   }
1237 
1238   uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1239   align(NaturalAlignment);
1240 
1241   const uint64_t SectionHeaderOffset = W.OS.tell();
1242 
1243   // ... then the section header table ...
1244   writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
1245 
1246   uint16_t NumSections = support::endian::byte_swap<uint16_t>(
1247       (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
1248                                                       : SectionTable.size() + 1,
1249       W.Endian);
1250   unsigned NumSectionsOffset;
1251 
1252   auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
1253   if (is64Bit()) {
1254     uint64_t Val =
1255         support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
1256     Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1257                   offsetof(ELF::Elf64_Ehdr, e_shoff));
1258     NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
1259   } else {
1260     uint32_t Val =
1261         support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
1262     Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1263                   offsetof(ELF::Elf32_Ehdr, e_shoff));
1264     NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
1265   }
1266   Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1267                 NumSectionsOffset);
1268 
1269   return W.OS.tell() - StartOffset;
1270 }
1271 
1272 bool ELFObjectWriter::hasRelocationAddend() const {
1273   return TargetObjectWriter->hasRelocationAddend();
1274 }
1275 
1276 void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
1277                                                const MCAsmLayout &Layout) {
1278   // The presence of symbol versions causes undefined symbols and
1279   // versions declared with @@@ to be renamed.
1280   for (const std::pair<StringRef, const MCSymbol *> &P : Asm.Symvers) {
1281     StringRef AliasName = P.first;
1282     const auto &Symbol = cast<MCSymbolELF>(*P.second);
1283     size_t Pos = AliasName.find('@');
1284     assert(Pos != StringRef::npos);
1285 
1286     StringRef Prefix = AliasName.substr(0, Pos);
1287     StringRef Rest = AliasName.substr(Pos);
1288     StringRef Tail = Rest;
1289     if (Rest.startswith("@@@"))
1290       Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
1291 
1292     auto *Alias =
1293         cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
1294     Asm.registerSymbol(*Alias);
1295     const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
1296     Alias->setVariableValue(Value);
1297 
1298     // Aliases defined with .symvar copy the binding from the symbol they alias.
1299     // This is the first place we are able to copy this information.
1300     Alias->setExternal(Symbol.isExternal());
1301     Alias->setBinding(Symbol.getBinding());
1302     Alias->setOther(Symbol.getOther());
1303 
1304     if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
1305       continue;
1306 
1307     // FIXME: Get source locations for these errors or diagnose them earlier.
1308     if (Symbol.isUndefined() && Rest.startswith("@@") &&
1309         !Rest.startswith("@@@")) {
1310       Asm.getContext().reportError(SMLoc(), "versioned symbol " + AliasName +
1311                                                 " must be defined");
1312       continue;
1313     }
1314 
1315     if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
1316       Asm.getContext().reportError(
1317           SMLoc(), llvm::Twine("multiple symbol versions defined for ") +
1318                        Symbol.getName());
1319       continue;
1320     }
1321 
1322     Renames.insert(std::make_pair(&Symbol, Alias));
1323   }
1324 
1325   for (const MCSymbol *&Sym : AddrsigSyms) {
1326     if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
1327       Sym = R;
1328     if (Sym->isInSection() && Sym->getName().startswith(".L"))
1329       Sym = Sym->getSection().getBeginSymbol();
1330     Sym->setUsedInReloc();
1331   }
1332 }
1333 
1334 // It is always valid to create a relocation with a symbol. It is preferable
1335 // to use a relocation with a section if that is possible. Using the section
1336 // allows us to omit some local symbols from the symbol table.
1337 bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
1338                                                const MCSymbolRefExpr *RefA,
1339                                                const MCSymbolELF *Sym,
1340                                                uint64_t C,
1341                                                unsigned Type) const {
1342   // A PCRel relocation to an absolute value has no symbol (or section). We
1343   // represent that with a relocation to a null section.
1344   if (!RefA)
1345     return false;
1346 
1347   MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
1348   switch (Kind) {
1349   default:
1350     break;
1351   // The .odp creation emits a relocation against the symbol ".TOC." which
1352   // create a R_PPC64_TOC relocation. However the relocation symbol name
1353   // in final object creation should be NULL, since the symbol does not
1354   // really exist, it is just the reference to TOC base for the current
1355   // object file. Since the symbol is undefined, returning false results
1356   // in a relocation with a null section which is the desired result.
1357   case MCSymbolRefExpr::VK_PPC_TOCBASE:
1358     return false;
1359 
1360   // These VariantKind cause the relocation to refer to something other than
1361   // the symbol itself, like a linker generated table. Since the address of
1362   // symbol is not relevant, we cannot replace the symbol with the
1363   // section and patch the difference in the addend.
1364   case MCSymbolRefExpr::VK_GOT:
1365   case MCSymbolRefExpr::VK_PLT:
1366   case MCSymbolRefExpr::VK_GOTPCREL:
1367   case MCSymbolRefExpr::VK_PPC_GOT_LO:
1368   case MCSymbolRefExpr::VK_PPC_GOT_HI:
1369   case MCSymbolRefExpr::VK_PPC_GOT_HA:
1370     return true;
1371   }
1372 
1373   // An undefined symbol is not in any section, so the relocation has to point
1374   // to the symbol itself.
1375   assert(Sym && "Expected a symbol");
1376   if (Sym->isUndefined())
1377     return true;
1378 
1379   unsigned Binding = Sym->getBinding();
1380   switch(Binding) {
1381   default:
1382     llvm_unreachable("Invalid Binding");
1383   case ELF::STB_LOCAL:
1384     break;
1385   case ELF::STB_WEAK:
1386     // If the symbol is weak, it might be overridden by a symbol in another
1387     // file. The relocation has to point to the symbol so that the linker
1388     // can update it.
1389     return true;
1390   case ELF::STB_GLOBAL:
1391     // Global ELF symbols can be preempted by the dynamic linker. The relocation
1392     // has to point to the symbol for a reason analogous to the STB_WEAK case.
1393     return true;
1394   }
1395 
1396   // Keep symbol type for a local ifunc because it may result in an IRELATIVE
1397   // reloc that the dynamic loader will use to resolve the address at startup
1398   // time.
1399   if (Sym->getType() == ELF::STT_GNU_IFUNC)
1400     return true;
1401 
1402   // If a relocation points to a mergeable section, we have to be careful.
1403   // If the offset is zero, a relocation with the section will encode the
1404   // same information. With a non-zero offset, the situation is different.
1405   // For example, a relocation can point 42 bytes past the end of a string.
1406   // If we change such a relocation to use the section, the linker would think
1407   // that it pointed to another string and subtracting 42 at runtime will
1408   // produce the wrong value.
1409   if (Sym->isInSection()) {
1410     auto &Sec = cast<MCSectionELF>(Sym->getSection());
1411     unsigned Flags = Sec.getFlags();
1412     if (Flags & ELF::SHF_MERGE) {
1413       if (C != 0)
1414         return true;
1415 
1416       // It looks like gold has a bug (http://sourceware.org/PR16794) and can
1417       // only handle section relocations to mergeable sections if using RELA.
1418       if (!hasRelocationAddend())
1419         return true;
1420     }
1421 
1422     // Most TLS relocations use a got, so they need the symbol. Even those that
1423     // are just an offset (@tpoff), require a symbol in gold versions before
1424     // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
1425     // http://sourceware.org/PR16773.
1426     if (Flags & ELF::SHF_TLS)
1427       return true;
1428   }
1429 
1430   // If the symbol is a thumb function the final relocation must set the lowest
1431   // bit. With a symbol that is done by just having the symbol have that bit
1432   // set, so we would lose the bit if we relocated with the section.
1433   // FIXME: We could use the section but add the bit to the relocation value.
1434   if (Asm.isThumbFunc(Sym))
1435     return true;
1436 
1437   if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
1438     return true;
1439   return false;
1440 }
1441 
1442 void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
1443                                        const MCAsmLayout &Layout,
1444                                        const MCFragment *Fragment,
1445                                        const MCFixup &Fixup, MCValue Target,
1446                                        uint64_t &FixedValue) {
1447   MCAsmBackend &Backend = Asm.getBackend();
1448   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
1449                  MCFixupKindInfo::FKF_IsPCRel;
1450   const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
1451   uint64_t C = Target.getConstant();
1452   uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
1453   MCContext &Ctx = Asm.getContext();
1454 
1455   if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
1456     const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
1457     if (SymB.isUndefined()) {
1458       Ctx.reportError(Fixup.getLoc(),
1459                       Twine("symbol '") + SymB.getName() +
1460                           "' can not be undefined in a subtraction expression");
1461       return;
1462     }
1463 
1464     assert(!SymB.isAbsolute() && "Should have been folded");
1465     const MCSection &SecB = SymB.getSection();
1466     if (&SecB != &FixupSection) {
1467       Ctx.reportError(Fixup.getLoc(),
1468                       "Cannot represent a difference across sections");
1469       return;
1470     }
1471 
1472     assert(!IsPCRel && "should have been folded");
1473     IsPCRel = true;
1474     C += FixupOffset - Layout.getSymbolOffset(SymB);
1475   }
1476 
1477   // We either rejected the fixup or folded B into C at this point.
1478   const MCSymbolRefExpr *RefA = Target.getSymA();
1479   const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
1480 
1481   bool ViaWeakRef = false;
1482   if (SymA && SymA->isVariable()) {
1483     const MCExpr *Expr = SymA->getVariableValue();
1484     if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
1485       if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
1486         SymA = cast<MCSymbolELF>(&Inner->getSymbol());
1487         ViaWeakRef = true;
1488       }
1489     }
1490   }
1491 
1492   const MCSectionELF *SecA = (SymA && SymA->isInSection())
1493                                  ? cast<MCSectionELF>(&SymA->getSection())
1494                                  : nullptr;
1495   if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
1496     return;
1497 
1498   unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
1499   bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
1500   uint64_t Addend = 0;
1501 
1502   FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
1503                    ? C + Layout.getSymbolOffset(*SymA)
1504                    : C;
1505   if (hasRelocationAddend()) {
1506     Addend = FixedValue;
1507     FixedValue = 0;
1508   }
1509 
1510   if (!RelocateWithSymbol) {
1511     const auto *SectionSymbol =
1512         SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
1513     if (SectionSymbol)
1514       SectionSymbol->setUsedInReloc();
1515     ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
1516     Relocations[&FixupSection].push_back(Rec);
1517     return;
1518   }
1519 
1520   const MCSymbolELF *RenamedSymA = SymA;
1521   if (SymA) {
1522     if (const MCSymbolELF *R = Renames.lookup(SymA))
1523       RenamedSymA = R;
1524 
1525     if (ViaWeakRef)
1526       RenamedSymA->setIsWeakrefUsedInReloc();
1527     else
1528       RenamedSymA->setUsedInReloc();
1529   }
1530   ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
1531   Relocations[&FixupSection].push_back(Rec);
1532 }
1533 
1534 bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
1535     const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
1536     bool InSet, bool IsPCRel) const {
1537   const auto &SymA = cast<MCSymbolELF>(SA);
1538   if (IsPCRel) {
1539     assert(!InSet);
1540     if (isWeak(SymA))
1541       return false;
1542   }
1543   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
1544                                                                 InSet, IsPCRel);
1545 }
1546 
1547 std::unique_ptr<MCObjectWriter>
1548 llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1549                             raw_pwrite_stream &OS, bool IsLittleEndian) {
1550   return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
1551                                                   IsLittleEndian);
1552 }
1553 
1554 std::unique_ptr<MCObjectWriter>
1555 llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
1556                                raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
1557                                bool IsLittleEndian) {
1558   return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
1559                                                IsLittleEndian);
1560 }
1561