xref: /freebsd/contrib/llvm-project/lld/ELF/SyntheticSections.h (revision e9ac41698b2f322d55ccf9da50a3596edb2c1800)
1 //===- SyntheticSection.h ---------------------------------------*- C++ -*-===//
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 // Synthetic sections represent chunks of linker-created data. If you
10 // need to create a chunk of data that to be included in some section
11 // in the result, you probably want to create that as a synthetic section.
12 //
13 // Synthetic sections are designed as input sections as opposed to
14 // output sections because we want to allow them to be manipulated
15 // using linker scripts just like other input sections from regular
16 // files.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #ifndef LLD_ELF_SYNTHETIC_SECTIONS_H
21 #define LLD_ELF_SYNTHETIC_SECTIONS_H
22 
23 #include "Config.h"
24 #include "InputSection.h"
25 #include "Symbols.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/BinaryFormat/ELF.h"
29 #include "llvm/MC/StringTableBuilder.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/Parallel.h"
33 #include "llvm/Support/Threading.h"
34 
35 namespace lld::elf {
36 class Defined;
37 struct PhdrEntry;
38 class SymbolTableBaseSection;
39 
40 struct CieRecord {
41   EhSectionPiece *cie = nullptr;
42   SmallVector<EhSectionPiece *, 0> fdes;
43 };
44 
45 // Section for .eh_frame.
46 class EhFrameSection final : public SyntheticSection {
47 public:
48   EhFrameSection();
49   void writeTo(uint8_t *buf) override;
50   void finalizeContents() override;
51   bool isNeeded() const override { return !sections.empty(); }
52   size_t getSize() const override { return size; }
53 
54   static bool classof(const SectionBase *d) {
55     return SyntheticSection::classof(d) && d->name == ".eh_frame";
56   }
57 
58   SmallVector<EhInputSection *, 0> sections;
59   size_t numFdes = 0;
60 
61   struct FdeData {
62     uint32_t pcRel;
63     uint32_t fdeVARel;
64   };
65 
66   SmallVector<FdeData, 0> getFdeData() const;
67   ArrayRef<CieRecord *> getCieRecords() const { return cieRecords; }
68   template <class ELFT>
69   void iterateFDEWithLSDA(llvm::function_ref<void(InputSection &)> fn);
70 
71 private:
72   // This is used only when parsing EhInputSection. We keep it here to avoid
73   // allocating one for each EhInputSection.
74   llvm::DenseMap<size_t, CieRecord *> offsetToCie;
75 
76   uint64_t size = 0;
77 
78   template <class ELFT, class RelTy>
79   void addRecords(EhInputSection *s, llvm::ArrayRef<RelTy> rels);
80   template <class ELFT> void addSectionAux(EhInputSection *s);
81   template <class ELFT, class RelTy>
82   void iterateFDEWithLSDAAux(EhInputSection &sec, ArrayRef<RelTy> rels,
83                              llvm::DenseSet<size_t> &ciesWithLSDA,
84                              llvm::function_ref<void(InputSection &)> fn);
85 
86   template <class ELFT, class RelTy>
87   CieRecord *addCie(EhSectionPiece &piece, ArrayRef<RelTy> rels);
88 
89   template <class ELFT, class RelTy>
90   Defined *isFdeLive(EhSectionPiece &piece, ArrayRef<RelTy> rels);
91 
92   uint64_t getFdePc(uint8_t *buf, size_t off, uint8_t enc) const;
93 
94   SmallVector<CieRecord *, 0> cieRecords;
95 
96   // CIE records are uniquified by their contents and personality functions.
97   llvm::DenseMap<std::pair<ArrayRef<uint8_t>, Symbol *>, CieRecord *> cieMap;
98 };
99 
100 class GotSection final : public SyntheticSection {
101 public:
102   GotSection();
103   size_t getSize() const override { return size; }
104   void finalizeContents() override;
105   bool isNeeded() const override;
106   void writeTo(uint8_t *buf) override;
107 
108   void addConstant(const Relocation &r);
109   void addEntry(Symbol &sym);
110   bool addTlsDescEntry(Symbol &sym);
111   bool addDynTlsEntry(Symbol &sym);
112   bool addTlsIndex();
113   uint32_t getTlsDescOffset(const Symbol &sym) const;
114   uint64_t getTlsDescAddr(const Symbol &sym) const;
115   uint64_t getGlobalDynAddr(const Symbol &b) const;
116   uint64_t getGlobalDynOffset(const Symbol &b) const;
117 
118   uint64_t getTlsIndexVA() { return this->getVA() + tlsIndexOff; }
119   uint32_t getTlsIndexOff() const { return tlsIndexOff; }
120 
121   // Flag to force GOT to be in output if we have relocations
122   // that relies on its address.
123   std::atomic<bool> hasGotOffRel = false;
124 
125 protected:
126   size_t numEntries = 0;
127   uint32_t tlsIndexOff = -1;
128   uint64_t size = 0;
129 };
130 
131 // .note.GNU-stack section.
132 class GnuStackSection : public SyntheticSection {
133 public:
134   GnuStackSection()
135       : SyntheticSection(0, llvm::ELF::SHT_PROGBITS, 1, ".note.GNU-stack") {}
136   void writeTo(uint8_t *buf) override {}
137   size_t getSize() const override { return 0; }
138 };
139 
140 class GnuPropertySection final : public SyntheticSection {
141 public:
142   GnuPropertySection();
143   void writeTo(uint8_t *buf) override;
144   size_t getSize() const override;
145 };
146 
147 // .note.gnu.build-id section.
148 class BuildIdSection : public SyntheticSection {
149   // First 16 bytes are a header.
150   static const unsigned headerSize = 16;
151 
152 public:
153   const size_t hashSize;
154   BuildIdSection();
155   void writeTo(uint8_t *buf) override;
156   size_t getSize() const override { return headerSize + hashSize; }
157   void writeBuildId(llvm::ArrayRef<uint8_t> buf);
158 
159 private:
160   uint8_t *hashBuf;
161 };
162 
163 // BssSection is used to reserve space for copy relocations and common symbols.
164 // We create three instances of this class for .bss, .bss.rel.ro and "COMMON",
165 // that are used for writable symbols, read-only symbols and common symbols,
166 // respectively.
167 class BssSection final : public SyntheticSection {
168 public:
169   BssSection(StringRef name, uint64_t size, uint32_t addralign);
170   void writeTo(uint8_t *) override {}
171   bool isNeeded() const override { return size != 0; }
172   size_t getSize() const override { return size; }
173 
174   static bool classof(const SectionBase *s) { return s->bss; }
175   uint64_t size;
176 };
177 
178 class MipsGotSection final : public SyntheticSection {
179 public:
180   MipsGotSection();
181   void writeTo(uint8_t *buf) override;
182   size_t getSize() const override { return size; }
183   bool updateAllocSize() override;
184   void finalizeContents() override;
185   bool isNeeded() const override;
186 
187   // Join separate GOTs built for each input file to generate
188   // primary and optional multiple secondary GOTs.
189   void build();
190 
191   void addEntry(InputFile &file, Symbol &sym, int64_t addend, RelExpr expr);
192   void addDynTlsEntry(InputFile &file, Symbol &sym);
193   void addTlsIndex(InputFile &file);
194 
195   uint64_t getPageEntryOffset(const InputFile *f, const Symbol &s,
196                               int64_t addend) const;
197   uint64_t getSymEntryOffset(const InputFile *f, const Symbol &s,
198                              int64_t addend) const;
199   uint64_t getGlobalDynOffset(const InputFile *f, const Symbol &s) const;
200   uint64_t getTlsIndexOffset(const InputFile *f) const;
201 
202   // Returns the symbol which corresponds to the first entry of the global part
203   // of GOT on MIPS platform. It is required to fill up MIPS-specific dynamic
204   // table properties.
205   // Returns nullptr if the global part is empty.
206   const Symbol *getFirstGlobalEntry() const;
207 
208   // Returns the number of entries in the local part of GOT including
209   // the number of reserved entries.
210   unsigned getLocalEntriesNum() const;
211 
212   // Return _gp value for primary GOT (nullptr) or particular input file.
213   uint64_t getGp(const InputFile *f = nullptr) const;
214 
215 private:
216   // MIPS GOT consists of three parts: local, global and tls. Each part
217   // contains different types of entries. Here is a layout of GOT:
218   // - Header entries                |
219   // - Page entries                  |   Local part
220   // - Local entries (16-bit access) |
221   // - Local entries (32-bit access) |
222   // - Normal global entries         ||  Global part
223   // - Reloc-only global entries     ||
224   // - TLS entries                   ||| TLS part
225   //
226   // Header:
227   //   Two entries hold predefined value 0x0 and 0x80000000.
228   // Page entries:
229   //   These entries created by R_MIPS_GOT_PAGE relocation and R_MIPS_GOT16
230   //   relocation against local symbols. They are initialized by higher 16-bit
231   //   of the corresponding symbol's value. So each 64kb of address space
232   //   requires a single GOT entry.
233   // Local entries (16-bit access):
234   //   These entries created by GOT relocations against global non-preemptible
235   //   symbols so dynamic linker is not necessary to resolve the symbol's
236   //   values. "16-bit access" means that corresponding relocations address
237   //   GOT using 16-bit index. Each unique Symbol-Addend pair has its own
238   //   GOT entry.
239   // Local entries (32-bit access):
240   //   These entries are the same as above but created by relocations which
241   //   address GOT using 32-bit index (R_MIPS_GOT_HI16/LO16 etc).
242   // Normal global entries:
243   //   These entries created by GOT relocations against preemptible global
244   //   symbols. They need to be initialized by dynamic linker and they ordered
245   //   exactly as the corresponding entries in the dynamic symbols table.
246   // Reloc-only global entries:
247   //   These entries created for symbols that are referenced by dynamic
248   //   relocations R_MIPS_REL32. These entries are not accessed with gp-relative
249   //   addressing, but MIPS ABI requires that these entries be present in GOT.
250   // TLS entries:
251   //   Entries created by TLS relocations.
252   //
253   // If the sum of local, global and tls entries is less than 64K only single
254   // got is enough. Otherwise, multi-got is created. Series of primary and
255   // multiple secondary GOTs have the following layout:
256   // - Primary GOT
257   //     Header
258   //     Local entries
259   //     Global entries
260   //     Relocation only entries
261   //     TLS entries
262   //
263   // - Secondary GOT
264   //     Local entries
265   //     Global entries
266   //     TLS entries
267   // ...
268   //
269   // All GOT entries required by relocations from a single input file entirely
270   // belong to either primary or one of secondary GOTs. To reference GOT entries
271   // each GOT has its own _gp value points to the "middle" of the GOT.
272   // In the code this value loaded to the register which is used for GOT access.
273   //
274   // MIPS 32 function's prologue:
275   //   lui     v0,0x0
276   //   0: R_MIPS_HI16  _gp_disp
277   //   addiu   v0,v0,0
278   //   4: R_MIPS_LO16  _gp_disp
279   //
280   // MIPS 64:
281   //   lui     at,0x0
282   //   14: R_MIPS_GPREL16  main
283   //
284   // Dynamic linker does not know anything about secondary GOTs and cannot
285   // use a regular MIPS mechanism for GOT entries initialization. So we have
286   // to use an approach accepted by other architectures and create dynamic
287   // relocations R_MIPS_REL32 to initialize global entries (and local in case
288   // of PIC code) in secondary GOTs. But ironically MIPS dynamic linker
289   // requires GOT entries and correspondingly ordered dynamic symbol table
290   // entries to deal with dynamic relocations. To handle this problem
291   // relocation-only section in the primary GOT contains entries for all
292   // symbols referenced in global parts of secondary GOTs. Although the sum
293   // of local and normal global entries of the primary got should be less
294   // than 64K, the size of the primary got (including relocation-only entries
295   // can be greater than 64K, because parts of the primary got that overflow
296   // the 64K limit are used only by the dynamic linker at dynamic link-time
297   // and not by 16-bit gp-relative addressing at run-time.
298   //
299   // For complete multi-GOT description see the following link
300   // https://dmz-portal.mips.com/wiki/MIPS_Multi_GOT
301 
302   // Number of "Header" entries.
303   static const unsigned headerEntriesNum = 2;
304 
305   uint64_t size = 0;
306 
307   // Symbol and addend.
308   using GotEntry = std::pair<Symbol *, int64_t>;
309 
310   struct FileGot {
311     InputFile *file = nullptr;
312     size_t startIndex = 0;
313 
314     struct PageBlock {
315       size_t firstIndex;
316       size_t count;
317       PageBlock() : firstIndex(0), count(0) {}
318     };
319 
320     // Map output sections referenced by MIPS GOT relocations
321     // to the description (index/count) "page" entries allocated
322     // for this section.
323     llvm::SmallMapVector<const OutputSection *, PageBlock, 16> pagesMap;
324     // Maps from Symbol+Addend pair or just Symbol to the GOT entry index.
325     llvm::MapVector<GotEntry, size_t> local16;
326     llvm::MapVector<GotEntry, size_t> local32;
327     llvm::MapVector<Symbol *, size_t> global;
328     llvm::MapVector<Symbol *, size_t> relocs;
329     llvm::MapVector<Symbol *, size_t> tls;
330     // Set of symbols referenced by dynamic TLS relocations.
331     llvm::MapVector<Symbol *, size_t> dynTlsSymbols;
332 
333     // Total number of all entries.
334     size_t getEntriesNum() const;
335     // Number of "page" entries.
336     size_t getPageEntriesNum() const;
337     // Number of entries require 16-bit index to access.
338     size_t getIndexedEntriesNum() const;
339   };
340 
341   // Container of GOT created for each input file.
342   // After building a final series of GOTs this container
343   // holds primary and secondary GOT's.
344   std::vector<FileGot> gots;
345 
346   // Return (and create if necessary) `FileGot`.
347   FileGot &getGot(InputFile &f);
348 
349   // Try to merge two GOTs. In case of success the `Dst` contains
350   // result of merging and the function returns true. In case of
351   // overflow the `Dst` is unchanged and the function returns false.
352   bool tryMergeGots(FileGot & dst, FileGot & src, bool isPrimary);
353 };
354 
355 class GotPltSection final : public SyntheticSection {
356 public:
357   GotPltSection();
358   void addEntry(Symbol &sym);
359   size_t getSize() const override;
360   void writeTo(uint8_t *buf) override;
361   bool isNeeded() const override;
362 
363   // Flag to force GotPlt to be in output if we have relocations
364   // that relies on its address.
365   std::atomic<bool> hasGotPltOffRel = false;
366 
367 private:
368   SmallVector<const Symbol *, 0> entries;
369 };
370 
371 // The IgotPltSection is a Got associated with the PltSection for GNU Ifunc
372 // Symbols that will be relocated by Target->IRelativeRel.
373 // On most Targets the IgotPltSection will immediately follow the GotPltSection
374 // on ARM the IgotPltSection will immediately follow the GotSection.
375 class IgotPltSection final : public SyntheticSection {
376 public:
377   IgotPltSection();
378   void addEntry(Symbol &sym);
379   size_t getSize() const override;
380   void writeTo(uint8_t *buf) override;
381   bool isNeeded() const override { return !entries.empty(); }
382 
383 private:
384   SmallVector<const Symbol *, 0> entries;
385 };
386 
387 class StringTableSection final : public SyntheticSection {
388 public:
389   StringTableSection(StringRef name, bool dynamic);
390   unsigned addString(StringRef s, bool hashIt = true);
391   void writeTo(uint8_t *buf) override;
392   size_t getSize() const override { return size; }
393   bool isDynamic() const { return dynamic; }
394 
395 private:
396   const bool dynamic;
397 
398   uint64_t size = 0;
399 
400   llvm::DenseMap<llvm::CachedHashStringRef, unsigned> stringMap;
401   SmallVector<StringRef, 0> strings;
402 };
403 
404 class DynamicReloc {
405 public:
406   enum Kind {
407     /// The resulting dynamic relocation does not reference a symbol (#sym must
408     /// be nullptr) and uses #addend as the result of computeAddend().
409     AddendOnly,
410     /// The resulting dynamic relocation will not reference a symbol: #sym is
411     /// only used to compute the addend with InputSection::getRelocTargetVA().
412     /// Useful for various relative and TLS relocations (e.g. R_X86_64_TPOFF64).
413     AddendOnlyWithTargetVA,
414     /// The resulting dynamic relocation references symbol #sym from the dynamic
415     /// symbol table and uses #addend as the value of computeAddend().
416     AgainstSymbol,
417     /// The resulting dynamic relocation references symbol #sym from the dynamic
418     /// symbol table and uses InputSection::getRelocTargetVA() + #addend for the
419     /// final addend. It can be used for relocations that write the symbol VA as
420     // the addend (e.g. R_MIPS_TLS_TPREL64) but still reference the symbol.
421     AgainstSymbolWithTargetVA,
422     /// This is used by the MIPS multi-GOT implementation. It relocates
423     /// addresses of 64kb pages that lie inside the output section.
424     MipsMultiGotPage,
425   };
426   /// This constructor records a relocation against a symbol.
427   DynamicReloc(RelType type, const InputSectionBase *inputSec,
428                uint64_t offsetInSec, Kind kind, Symbol &sym, int64_t addend,
429                RelExpr expr)
430       : sym(&sym), inputSec(inputSec), offsetInSec(offsetInSec), type(type),
431         addend(addend), kind(kind), expr(expr) {}
432   /// This constructor records a relative relocation with no symbol.
433   DynamicReloc(RelType type, const InputSectionBase *inputSec,
434                uint64_t offsetInSec, int64_t addend = 0)
435       : sym(nullptr), inputSec(inputSec), offsetInSec(offsetInSec), type(type),
436         addend(addend), kind(AddendOnly), expr(R_ADDEND) {}
437   /// This constructor records dynamic relocation settings used by the MIPS
438   /// multi-GOT implementation.
439   DynamicReloc(RelType type, const InputSectionBase *inputSec,
440                uint64_t offsetInSec, const OutputSection *outputSec,
441                int64_t addend)
442       : sym(nullptr), outputSec(outputSec), inputSec(inputSec),
443         offsetInSec(offsetInSec), type(type), addend(addend),
444         kind(MipsMultiGotPage), expr(R_ADDEND) {}
445 
446   uint64_t getOffset() const;
447   uint32_t getSymIndex(SymbolTableBaseSection *symTab) const;
448   bool needsDynSymIndex() const {
449     return kind == AgainstSymbol || kind == AgainstSymbolWithTargetVA;
450   }
451 
452   /// Computes the addend of the dynamic relocation. Note that this is not the
453   /// same as the #addend member variable as it may also include the symbol
454   /// address/the address of the corresponding GOT entry/etc.
455   int64_t computeAddend() const;
456 
457   void computeRaw(SymbolTableBaseSection *symtab);
458 
459   Symbol *sym;
460   const OutputSection *outputSec = nullptr;
461   const InputSectionBase *inputSec;
462   uint64_t offsetInSec;
463   uint64_t r_offset;
464   RelType type;
465   uint32_t r_sym;
466   // Initially input addend, then the output addend after
467   // RelocationSection<ELFT>::writeTo.
468   int64_t addend;
469 
470 private:
471   Kind kind;
472   // The kind of expression used to calculate the added (required e.g. for
473   // relative GOT relocations).
474   RelExpr expr;
475 };
476 
477 template <class ELFT> class DynamicSection final : public SyntheticSection {
478   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
479 
480 public:
481   DynamicSection();
482   void finalizeContents() override;
483   void writeTo(uint8_t *buf) override;
484   size_t getSize() const override { return size; }
485 
486 private:
487   std::vector<std::pair<int32_t, uint64_t>> computeContents();
488   uint64_t size = 0;
489 };
490 
491 class RelocationBaseSection : public SyntheticSection {
492 public:
493   RelocationBaseSection(StringRef name, uint32_t type, int32_t dynamicTag,
494                         int32_t sizeDynamicTag, bool combreloc,
495                         unsigned concurrency);
496   /// Add a dynamic relocation without writing an addend to the output section.
497   /// This overload can be used if the addends are written directly instead of
498   /// using relocations on the input section (e.g. MipsGotSection::writeTo()).
499   template <bool shard = false> void addReloc(const DynamicReloc &reloc) {
500     relocs.push_back(reloc);
501   }
502   /// Add a dynamic relocation against \p sym with an optional addend.
503   void addSymbolReloc(RelType dynType, InputSectionBase &isec,
504                       uint64_t offsetInSec, Symbol &sym, int64_t addend = 0,
505                       std::optional<RelType> addendRelType = {});
506   /// Add a relative dynamic relocation that uses the target address of \p sym
507   /// (i.e. InputSection::getRelocTargetVA()) + \p addend as the addend.
508   /// This function should only be called for non-preemptible symbols or
509   /// RelExpr values that refer to an address inside the output file (e.g. the
510   /// address of the GOT entry for a potentially preemptible symbol).
511   template <bool shard = false>
512   void addRelativeReloc(RelType dynType, InputSectionBase &isec,
513                         uint64_t offsetInSec, Symbol &sym, int64_t addend,
514                         RelType addendRelType, RelExpr expr) {
515     assert(expr != R_ADDEND && "expected non-addend relocation expression");
516     addReloc<shard>(DynamicReloc::AddendOnlyWithTargetVA, dynType, isec,
517                     offsetInSec, sym, addend, expr, addendRelType);
518   }
519   /// Add a dynamic relocation using the target address of \p sym as the addend
520   /// if \p sym is non-preemptible. Otherwise add a relocation against \p sym.
521   void addAddendOnlyRelocIfNonPreemptible(RelType dynType, GotSection &sec,
522                                           uint64_t offsetInSec, Symbol &sym,
523                                           RelType addendRelType);
524   template <bool shard = false>
525   void addReloc(DynamicReloc::Kind kind, RelType dynType, InputSectionBase &sec,
526                 uint64_t offsetInSec, Symbol &sym, int64_t addend, RelExpr expr,
527                 RelType addendRelType) {
528     // Write the addends to the relocated address if required. We skip
529     // it if the written value would be zero.
530     if (config->writeAddends && (expr != R_ADDEND || addend != 0))
531       sec.addReloc({expr, addendRelType, offsetInSec, addend, &sym});
532     addReloc<shard>({dynType, &sec, offsetInSec, kind, sym, addend, expr});
533   }
534   bool isNeeded() const override {
535     return !relocs.empty() ||
536            llvm::any_of(relocsVec, [](auto &v) { return !v.empty(); });
537   }
538   size_t getSize() const override { return relocs.size() * this->entsize; }
539   size_t getRelativeRelocCount() const { return numRelativeRelocs; }
540   void mergeRels();
541   void partitionRels();
542   void finalizeContents() override;
543   static bool classof(const SectionBase *d) {
544     return SyntheticSection::classof(d) &&
545            (d->type == llvm::ELF::SHT_RELA || d->type == llvm::ELF::SHT_REL ||
546             d->type == llvm::ELF::SHT_RELR);
547   }
548   int32_t dynamicTag, sizeDynamicTag;
549   SmallVector<DynamicReloc, 0> relocs;
550 
551 protected:
552   void computeRels();
553   // Used when parallel relocation scanning adds relocations. The elements
554   // will be moved into relocs by mergeRel().
555   SmallVector<SmallVector<DynamicReloc, 0>, 0> relocsVec;
556   size_t numRelativeRelocs = 0; // used by -z combreloc
557   bool combreloc;
558 };
559 
560 template <>
561 inline void RelocationBaseSection::addReloc<true>(const DynamicReloc &reloc) {
562   relocsVec[llvm::parallel::getThreadIndex()].push_back(reloc);
563 }
564 
565 template <class ELFT>
566 class RelocationSection final : public RelocationBaseSection {
567   using Elf_Rel = typename ELFT::Rel;
568   using Elf_Rela = typename ELFT::Rela;
569 
570 public:
571   RelocationSection(StringRef name, bool combreloc, unsigned concurrency);
572   void writeTo(uint8_t *buf) override;
573 };
574 
575 template <class ELFT>
576 class AndroidPackedRelocationSection final : public RelocationBaseSection {
577   using Elf_Rel = typename ELFT::Rel;
578   using Elf_Rela = typename ELFT::Rela;
579 
580 public:
581   AndroidPackedRelocationSection(StringRef name, unsigned concurrency);
582 
583   bool updateAllocSize() override;
584   size_t getSize() const override { return relocData.size(); }
585   void writeTo(uint8_t *buf) override {
586     memcpy(buf, relocData.data(), relocData.size());
587   }
588 
589 private:
590   SmallVector<char, 0> relocData;
591 };
592 
593 struct RelativeReloc {
594   uint64_t getOffset() const { return inputSec->getVA(offsetInSec); }
595 
596   const InputSectionBase *inputSec;
597   uint64_t offsetInSec;
598 };
599 
600 class RelrBaseSection : public SyntheticSection {
601 public:
602   RelrBaseSection(unsigned concurrency);
603   void mergeRels();
604   bool isNeeded() const override {
605     return !relocs.empty() ||
606            llvm::any_of(relocsVec, [](auto &v) { return !v.empty(); });
607   }
608   SmallVector<RelativeReloc, 0> relocs;
609   SmallVector<SmallVector<RelativeReloc, 0>, 0> relocsVec;
610 };
611 
612 // RelrSection is used to encode offsets for relative relocations.
613 // Proposal for adding SHT_RELR sections to generic-abi is here:
614 //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
615 // For more details, see the comment in RelrSection::updateAllocSize().
616 template <class ELFT> class RelrSection final : public RelrBaseSection {
617   using Elf_Relr = typename ELFT::Relr;
618 
619 public:
620   RelrSection(unsigned concurrency);
621 
622   bool updateAllocSize() override;
623   size_t getSize() const override { return relrRelocs.size() * this->entsize; }
624   void writeTo(uint8_t *buf) override {
625     memcpy(buf, relrRelocs.data(), getSize());
626   }
627 
628 private:
629   SmallVector<Elf_Relr, 0> relrRelocs;
630 };
631 
632 struct SymbolTableEntry {
633   Symbol *sym;
634   size_t strTabOffset;
635 };
636 
637 class SymbolTableBaseSection : public SyntheticSection {
638 public:
639   SymbolTableBaseSection(StringTableSection &strTabSec);
640   void finalizeContents() override;
641   size_t getSize() const override { return getNumSymbols() * entsize; }
642   void addSymbol(Symbol *sym);
643   unsigned getNumSymbols() const { return symbols.size() + 1; }
644   size_t getSymbolIndex(Symbol *sym);
645   ArrayRef<SymbolTableEntry> getSymbols() const { return symbols; }
646 
647 protected:
648   void sortSymTabSymbols();
649 
650   // A vector of symbols and their string table offsets.
651   SmallVector<SymbolTableEntry, 0> symbols;
652 
653   StringTableSection &strTabSec;
654 
655   llvm::once_flag onceFlag;
656   llvm::DenseMap<Symbol *, size_t> symbolIndexMap;
657   llvm::DenseMap<OutputSection *, size_t> sectionIndexMap;
658 };
659 
660 template <class ELFT>
661 class SymbolTableSection final : public SymbolTableBaseSection {
662   using Elf_Sym = typename ELFT::Sym;
663 
664 public:
665   SymbolTableSection(StringTableSection &strTabSec);
666   void writeTo(uint8_t *buf) override;
667 };
668 
669 class SymtabShndxSection final : public SyntheticSection {
670 public:
671   SymtabShndxSection();
672 
673   void writeTo(uint8_t *buf) override;
674   size_t getSize() const override;
675   bool isNeeded() const override;
676   void finalizeContents() override;
677 };
678 
679 // Outputs GNU Hash section. For detailed explanation see:
680 // https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections
681 class GnuHashTableSection final : public SyntheticSection {
682 public:
683   GnuHashTableSection();
684   void finalizeContents() override;
685   void writeTo(uint8_t *buf) override;
686   size_t getSize() const override { return size; }
687 
688   // Adds symbols to the hash table.
689   // Sorts the input to satisfy GNU hash section requirements.
690   void addSymbols(llvm::SmallVectorImpl<SymbolTableEntry> &symbols);
691 
692 private:
693   // See the comment in writeBloomFilter.
694   enum { Shift2 = 26 };
695 
696   struct Entry {
697     Symbol *sym;
698     size_t strTabOffset;
699     uint32_t hash;
700     uint32_t bucketIdx;
701   };
702 
703   SmallVector<Entry, 0> symbols;
704   size_t maskWords;
705   size_t nBuckets = 0;
706   size_t size = 0;
707 };
708 
709 class HashTableSection final : public SyntheticSection {
710 public:
711   HashTableSection();
712   void finalizeContents() override;
713   void writeTo(uint8_t *buf) override;
714   size_t getSize() const override { return size; }
715 
716 private:
717   size_t size = 0;
718 };
719 
720 // Used for PLT entries. It usually has a PLT header for lazy binding. Each PLT
721 // entry is associated with a JUMP_SLOT relocation, which may be resolved lazily
722 // at runtime.
723 //
724 // On PowerPC, this section contains lazy symbol resolvers. A branch instruction
725 // jumps to a PLT call stub, which will then jump to the target (BIND_NOW) or a
726 // lazy symbol resolver.
727 //
728 // On x86 when IBT is enabled, this section (.plt.sec) contains PLT call stubs.
729 // A call instruction jumps to a .plt.sec entry, which will then jump to the
730 // target (BIND_NOW) or a .plt entry.
731 class PltSection : public SyntheticSection {
732 public:
733   PltSection();
734   void writeTo(uint8_t *buf) override;
735   size_t getSize() const override;
736   bool isNeeded() const override;
737   void addSymbols();
738   void addEntry(Symbol &sym);
739   size_t getNumEntries() const { return entries.size(); }
740 
741   size_t headerSize;
742 
743   SmallVector<const Symbol *, 0> entries;
744 };
745 
746 // Used for non-preemptible ifuncs. It does not have a header. Each entry is
747 // associated with an IRELATIVE relocation, which will be resolved eagerly at
748 // runtime. PltSection can only contain entries associated with JUMP_SLOT
749 // relocations, so IPLT entries are in a separate section.
750 class IpltSection final : public SyntheticSection {
751   SmallVector<const Symbol *, 0> entries;
752 
753 public:
754   IpltSection();
755   void writeTo(uint8_t *buf) override;
756   size_t getSize() const override;
757   bool isNeeded() const override { return !entries.empty(); }
758   void addSymbols();
759   void addEntry(Symbol &sym);
760 };
761 
762 class PPC32GlinkSection : public PltSection {
763 public:
764   PPC32GlinkSection();
765   void writeTo(uint8_t *buf) override;
766   size_t getSize() const override;
767 
768   SmallVector<const Symbol *, 0> canonical_plts;
769   static constexpr size_t footerSize = 64;
770 };
771 
772 // This is x86-only.
773 class IBTPltSection : public SyntheticSection {
774 public:
775   IBTPltSection();
776   void writeTo(uint8_t *Buf) override;
777   bool isNeeded() const override;
778   size_t getSize() const override;
779 };
780 
781 // Used to align the end of the PT_GNU_RELRO segment and the associated PT_LOAD
782 // segment to a common-page-size boundary. This padding section ensures that all
783 // pages in the PT_LOAD segment is covered by at least one section.
784 class RelroPaddingSection final : public SyntheticSection {
785 public:
786   RelroPaddingSection();
787   size_t getSize() const override { return 0; }
788   void writeTo(uint8_t *buf) override {}
789 };
790 
791 class GdbIndexSection final : public SyntheticSection {
792 public:
793   struct AddressEntry {
794     InputSection *section;
795     uint64_t lowAddress;
796     uint64_t highAddress;
797     uint32_t cuIndex;
798   };
799 
800   struct CuEntry {
801     uint64_t cuOffset;
802     uint64_t cuLength;
803   };
804 
805   struct NameAttrEntry {
806     llvm::CachedHashStringRef name;
807     uint32_t cuIndexAndAttrs;
808   };
809 
810   struct GdbChunk {
811     InputSection *sec;
812     SmallVector<AddressEntry, 0> addressAreas;
813     SmallVector<CuEntry, 0> compilationUnits;
814   };
815 
816   struct GdbSymbol {
817     llvm::CachedHashStringRef name;
818     SmallVector<uint32_t, 0> cuVector;
819     uint32_t nameOff;
820     uint32_t cuVectorOff;
821   };
822 
823   GdbIndexSection();
824   template <typename ELFT> static GdbIndexSection *create();
825   void writeTo(uint8_t *buf) override;
826   size_t getSize() const override { return size; }
827   bool isNeeded() const override;
828 
829 private:
830   struct GdbIndexHeader {
831     llvm::support::ulittle32_t version;
832     llvm::support::ulittle32_t cuListOff;
833     llvm::support::ulittle32_t cuTypesOff;
834     llvm::support::ulittle32_t addressAreaOff;
835     llvm::support::ulittle32_t symtabOff;
836     llvm::support::ulittle32_t constantPoolOff;
837   };
838 
839   size_t computeSymtabSize() const;
840 
841   // Each chunk contains information gathered from debug sections of a
842   // single object file.
843   SmallVector<GdbChunk, 0> chunks;
844 
845   // A symbol table for this .gdb_index section.
846   SmallVector<GdbSymbol, 0> symbols;
847 
848   size_t size;
849 };
850 
851 // --eh-frame-hdr option tells linker to construct a header for all the
852 // .eh_frame sections. This header is placed to a section named .eh_frame_hdr
853 // and also to a PT_GNU_EH_FRAME segment.
854 // At runtime the unwinder then can find all the PT_GNU_EH_FRAME segments by
855 // calling dl_iterate_phdr.
856 // This section contains a lookup table for quick binary search of FDEs.
857 // Detailed info about internals can be found in Ian Lance Taylor's blog:
858 // http://www.airs.com/blog/archives/460 (".eh_frame")
859 // http://www.airs.com/blog/archives/462 (".eh_frame_hdr")
860 class EhFrameHeader final : public SyntheticSection {
861 public:
862   EhFrameHeader();
863   void write();
864   void writeTo(uint8_t *buf) override;
865   size_t getSize() const override;
866   bool isNeeded() const override;
867 };
868 
869 // For more information about .gnu.version and .gnu.version_r see:
870 // https://www.akkadia.org/drepper/symbol-versioning
871 
872 // The .gnu.version_d section which has a section type of SHT_GNU_verdef shall
873 // contain symbol version definitions. The number of entries in this section
874 // shall be contained in the DT_VERDEFNUM entry of the .dynamic section.
875 // The section shall contain an array of Elf_Verdef structures, optionally
876 // followed by an array of Elf_Verdaux structures.
877 class VersionDefinitionSection final : public SyntheticSection {
878 public:
879   VersionDefinitionSection();
880   void finalizeContents() override;
881   size_t getSize() const override;
882   void writeTo(uint8_t *buf) override;
883 
884 private:
885   enum { EntrySize = 28 };
886   void writeOne(uint8_t *buf, uint32_t index, StringRef name, size_t nameOff);
887   StringRef getFileDefName();
888 
889   unsigned fileDefNameOff;
890   SmallVector<unsigned, 0> verDefNameOffs;
891 };
892 
893 // The .gnu.version section specifies the required version of each symbol in the
894 // dynamic symbol table. It contains one Elf_Versym for each dynamic symbol
895 // table entry. An Elf_Versym is just a 16-bit integer that refers to a version
896 // identifier defined in the either .gnu.version_r or .gnu.version_d section.
897 // The values 0 and 1 are reserved. All other values are used for versions in
898 // the own object or in any of the dependencies.
899 class VersionTableSection final : public SyntheticSection {
900 public:
901   VersionTableSection();
902   void finalizeContents() override;
903   size_t getSize() const override;
904   void writeTo(uint8_t *buf) override;
905   bool isNeeded() const override;
906 };
907 
908 // The .gnu.version_r section defines the version identifiers used by
909 // .gnu.version. It contains a linked list of Elf_Verneed data structures. Each
910 // Elf_Verneed specifies the version requirements for a single DSO, and contains
911 // a reference to a linked list of Elf_Vernaux data structures which define the
912 // mapping from version identifiers to version names.
913 template <class ELFT>
914 class VersionNeedSection final : public SyntheticSection {
915   using Elf_Verneed = typename ELFT::Verneed;
916   using Elf_Vernaux = typename ELFT::Vernaux;
917 
918   struct Vernaux {
919     uint64_t hash;
920     uint32_t verneedIndex;
921     uint64_t nameStrTab;
922   };
923 
924   struct Verneed {
925     uint64_t nameStrTab;
926     std::vector<Vernaux> vernauxs;
927   };
928 
929   SmallVector<Verneed, 0> verneeds;
930 
931 public:
932   VersionNeedSection();
933   void finalizeContents() override;
934   void writeTo(uint8_t *buf) override;
935   size_t getSize() const override;
936   bool isNeeded() const override;
937 };
938 
939 // MergeSyntheticSection is a class that allows us to put mergeable sections
940 // with different attributes in a single output sections. To do that
941 // we put them into MergeSyntheticSection synthetic input sections which are
942 // attached to regular output sections.
943 class MergeSyntheticSection : public SyntheticSection {
944 public:
945   void addSection(MergeInputSection *ms);
946   SmallVector<MergeInputSection *, 0> sections;
947 
948 protected:
949   MergeSyntheticSection(StringRef name, uint32_t type, uint64_t flags,
950                         uint32_t addralign)
951       : SyntheticSection(flags, type, addralign, name) {}
952 };
953 
954 class MergeTailSection final : public MergeSyntheticSection {
955 public:
956   MergeTailSection(StringRef name, uint32_t type, uint64_t flags,
957                    uint32_t addralign);
958 
959   size_t getSize() const override;
960   void writeTo(uint8_t *buf) override;
961   void finalizeContents() override;
962 
963 private:
964   llvm::StringTableBuilder builder;
965 };
966 
967 class MergeNoTailSection final : public MergeSyntheticSection {
968 public:
969   MergeNoTailSection(StringRef name, uint32_t type, uint64_t flags,
970                      uint32_t addralign)
971       : MergeSyntheticSection(name, type, flags, addralign) {}
972 
973   size_t getSize() const override { return size; }
974   void writeTo(uint8_t *buf) override;
975   void finalizeContents() override;
976 
977 private:
978   // We use the most significant bits of a hash as a shard ID.
979   // The reason why we don't want to use the least significant bits is
980   // because DenseMap also uses lower bits to determine a bucket ID.
981   // If we use lower bits, it significantly increases the probability of
982   // hash collisions.
983   size_t getShardId(uint32_t hash) {
984     assert((hash >> 31) == 0);
985     return hash >> (31 - llvm::countr_zero(numShards));
986   }
987 
988   // Section size
989   size_t size;
990 
991   // String table contents
992   constexpr static size_t numShards = 32;
993   SmallVector<llvm::StringTableBuilder, 0> shards;
994   size_t shardOffsets[numShards];
995 };
996 
997 // .MIPS.abiflags section.
998 template <class ELFT>
999 class MipsAbiFlagsSection final : public SyntheticSection {
1000   using Elf_Mips_ABIFlags = llvm::object::Elf_Mips_ABIFlags<ELFT>;
1001 
1002 public:
1003   static std::unique_ptr<MipsAbiFlagsSection> create();
1004 
1005   MipsAbiFlagsSection(Elf_Mips_ABIFlags flags);
1006   size_t getSize() const override { return sizeof(Elf_Mips_ABIFlags); }
1007   void writeTo(uint8_t *buf) override;
1008 
1009 private:
1010   Elf_Mips_ABIFlags flags;
1011 };
1012 
1013 // .MIPS.options section.
1014 template <class ELFT> class MipsOptionsSection final : public SyntheticSection {
1015   using Elf_Mips_Options = llvm::object::Elf_Mips_Options<ELFT>;
1016   using Elf_Mips_RegInfo = llvm::object::Elf_Mips_RegInfo<ELFT>;
1017 
1018 public:
1019   static std::unique_ptr<MipsOptionsSection<ELFT>> create();
1020 
1021   MipsOptionsSection(Elf_Mips_RegInfo reginfo);
1022   void writeTo(uint8_t *buf) override;
1023 
1024   size_t getSize() const override {
1025     return sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1026   }
1027 
1028 private:
1029   Elf_Mips_RegInfo reginfo;
1030 };
1031 
1032 // MIPS .reginfo section.
1033 template <class ELFT> class MipsReginfoSection final : public SyntheticSection {
1034   using Elf_Mips_RegInfo = llvm::object::Elf_Mips_RegInfo<ELFT>;
1035 
1036 public:
1037   static std::unique_ptr<MipsReginfoSection> create();
1038 
1039   MipsReginfoSection(Elf_Mips_RegInfo reginfo);
1040   size_t getSize() const override { return sizeof(Elf_Mips_RegInfo); }
1041   void writeTo(uint8_t *buf) override;
1042 
1043 private:
1044   Elf_Mips_RegInfo reginfo;
1045 };
1046 
1047 // This is a MIPS specific section to hold a space within the data segment
1048 // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
1049 // See "Dynamic section" in Chapter 5 in the following document:
1050 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1051 class MipsRldMapSection final : public SyntheticSection {
1052 public:
1053   MipsRldMapSection();
1054   size_t getSize() const override { return config->wordsize; }
1055   void writeTo(uint8_t *buf) override {}
1056 };
1057 
1058 // Representation of the combined .ARM.Exidx input sections. We process these
1059 // as a SyntheticSection like .eh_frame as we need to merge duplicate entries
1060 // and add terminating sentinel entries.
1061 //
1062 // The .ARM.exidx input sections after SHF_LINK_ORDER processing is done form
1063 // a table that the unwinder can derive (Addresses are encoded as offsets from
1064 // table):
1065 // | Address of function | Unwind instructions for function |
1066 // where the unwind instructions are either a small number of unwind or the
1067 // special EXIDX_CANTUNWIND entry representing no unwinding information.
1068 // When an exception is thrown from an address A, the unwinder searches the
1069 // table for the closest table entry with Address of function <= A. This means
1070 // that for two consecutive table entries:
1071 // | A1 | U1 |
1072 // | A2 | U2 |
1073 // The range of addresses described by U1 is [A1, A2)
1074 //
1075 // There are two cases where we need a linker generated table entry to fixup
1076 // the address ranges in the table
1077 // Case 1:
1078 // - A sentinel entry added with an address higher than all
1079 // executable sections. This was needed to work around libunwind bug pr31091.
1080 // - After address assignment we need to find the highest addressed executable
1081 // section and use the limit of that section so that the unwinder never
1082 // matches it.
1083 // Case 2:
1084 // - InputSections without a .ARM.exidx section (usually from Assembly)
1085 // need a table entry so that they terminate the range of the previously
1086 // function. This is pr40277.
1087 //
1088 // Instead of storing pointers to the .ARM.exidx InputSections from
1089 // InputObjects, we store pointers to the executable sections that need
1090 // .ARM.exidx sections. We can then use the dependentSections of these to
1091 // either find the .ARM.exidx section or know that we need to generate one.
1092 class ARMExidxSyntheticSection : public SyntheticSection {
1093 public:
1094   ARMExidxSyntheticSection();
1095 
1096   // Add an input section to the ARMExidxSyntheticSection. Returns whether the
1097   // section needs to be removed from the main input section list.
1098   bool addSection(InputSection *isec);
1099 
1100   size_t getSize() const override { return size; }
1101   void writeTo(uint8_t *buf) override;
1102   bool isNeeded() const override;
1103   // Sort and remove duplicate entries.
1104   void finalizeContents() override;
1105   InputSection *getLinkOrderDep() const;
1106 
1107   static bool classof(const SectionBase *sec) {
1108     return sec->kind() == InputSectionBase::Synthetic &&
1109            sec->type == llvm::ELF::SHT_ARM_EXIDX;
1110   }
1111 
1112   // Links to the ARMExidxSections so we can transfer the relocations once the
1113   // layout is known.
1114   SmallVector<InputSection *, 0> exidxSections;
1115 
1116 private:
1117   size_t size = 0;
1118 
1119   // Instead of storing pointers to the .ARM.exidx InputSections from
1120   // InputObjects, we store pointers to the executable sections that need
1121   // .ARM.exidx sections. We can then use the dependentSections of these to
1122   // either find the .ARM.exidx section or know that we need to generate one.
1123   SmallVector<InputSection *, 0> executableSections;
1124 
1125   // The executable InputSection with the highest address to use for the
1126   // sentinel. We store separately from ExecutableSections as merging of
1127   // duplicate entries may mean this InputSection is removed from
1128   // ExecutableSections.
1129   InputSection *sentinel = nullptr;
1130 };
1131 
1132 // A container for one or more linker generated thunks. Instances of these
1133 // thunks including ARM interworking and Mips LA25 PI to non-PI thunks.
1134 class ThunkSection final : public SyntheticSection {
1135 public:
1136   // ThunkSection in OS, with desired outSecOff of Off
1137   ThunkSection(OutputSection *os, uint64_t off);
1138 
1139   // Add a newly created Thunk to this container:
1140   // Thunk is given offset from start of this InputSection
1141   // Thunk defines a symbol in this InputSection that can be used as target
1142   // of a relocation
1143   void addThunk(Thunk *t);
1144   size_t getSize() const override;
1145   void writeTo(uint8_t *buf) override;
1146   InputSection *getTargetInputSection() const;
1147   bool assignOffsets();
1148 
1149   // When true, round up reported size of section to 4 KiB. See comment
1150   // in addThunkSection() for more details.
1151   bool roundUpSizeForErrata = false;
1152 
1153 private:
1154   SmallVector<Thunk *, 0> thunks;
1155   size_t size = 0;
1156 };
1157 
1158 // Cortex-M Security Extensions. Prefix for functions that should be exported
1159 // for the non-secure world.
1160 const char ACLESESYM_PREFIX[] = "__acle_se_";
1161 const int ACLESESYM_SIZE = 8;
1162 
1163 class ArmCmseSGVeneer;
1164 
1165 class ArmCmseSGSection final : public SyntheticSection {
1166 public:
1167   ArmCmseSGSection();
1168   bool isNeeded() const override { return !entries.empty(); }
1169   size_t getSize() const override;
1170   void writeTo(uint8_t *buf) override;
1171   void addSGVeneer(Symbol *sym, Symbol *ext_sym);
1172   void addMappingSymbol();
1173   void finalizeContents() override;
1174   void exportEntries(SymbolTableBaseSection *symTab);
1175   uint64_t impLibMaxAddr = 0;
1176 
1177 private:
1178   SmallVector<std::pair<Symbol *, Symbol *>, 0> entries;
1179   SmallVector<ArmCmseSGVeneer *, 0> sgVeneers;
1180   uint64_t newEntries = 0;
1181 };
1182 
1183 // Used to compute outSecOff of .got2 in each object file. This is needed to
1184 // synthesize PLT entries for PPC32 Secure PLT ABI.
1185 class PPC32Got2Section final : public SyntheticSection {
1186 public:
1187   PPC32Got2Section();
1188   size_t getSize() const override { return 0; }
1189   bool isNeeded() const override;
1190   void finalizeContents() override;
1191   void writeTo(uint8_t *buf) override {}
1192 };
1193 
1194 // This section is used to store the addresses of functions that are called
1195 // in range-extending thunks on PowerPC64. When producing position dependent
1196 // code the addresses are link-time constants and the table is written out to
1197 // the binary. When producing position-dependent code the table is allocated and
1198 // filled in by the dynamic linker.
1199 class PPC64LongBranchTargetSection final : public SyntheticSection {
1200 public:
1201   PPC64LongBranchTargetSection();
1202   uint64_t getEntryVA(const Symbol *sym, int64_t addend);
1203   std::optional<uint32_t> addEntry(const Symbol *sym, int64_t addend);
1204   size_t getSize() const override;
1205   void writeTo(uint8_t *buf) override;
1206   bool isNeeded() const override;
1207   void finalizeContents() override { finalized = true; }
1208 
1209 private:
1210   SmallVector<std::pair<const Symbol *, int64_t>, 0> entries;
1211   llvm::DenseMap<std::pair<const Symbol *, int64_t>, uint32_t> entry_index;
1212   bool finalized = false;
1213 };
1214 
1215 template <typename ELFT>
1216 class PartitionElfHeaderSection final : public SyntheticSection {
1217 public:
1218   PartitionElfHeaderSection();
1219   size_t getSize() const override;
1220   void writeTo(uint8_t *buf) override;
1221 };
1222 
1223 template <typename ELFT>
1224 class PartitionProgramHeadersSection final : public SyntheticSection {
1225 public:
1226   PartitionProgramHeadersSection();
1227   size_t getSize() const override;
1228   void writeTo(uint8_t *buf) override;
1229 };
1230 
1231 class PartitionIndexSection final : public SyntheticSection {
1232 public:
1233   PartitionIndexSection();
1234   size_t getSize() const override;
1235   void finalizeContents() override;
1236   void writeTo(uint8_t *buf) override;
1237 };
1238 
1239 // See the following link for the Android-specific loader code that operates on
1240 // this section:
1241 // https://cs.android.com/android/platform/superproject/+/master:bionic/libc/bionic/libc_init_static.cpp;drc=9425b16978f9c5aa8f2c50c873db470819480d1d;l=192
1242 class MemtagAndroidNote final : public SyntheticSection {
1243 public:
1244   MemtagAndroidNote()
1245       : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
1246                          /*alignment=*/4, ".note.android.memtag") {}
1247   void writeTo(uint8_t *buf) override;
1248   size_t getSize() const override;
1249 };
1250 
1251 class PackageMetadataNote final : public SyntheticSection {
1252 public:
1253   PackageMetadataNote()
1254       : SyntheticSection(llvm::ELF::SHF_ALLOC, llvm::ELF::SHT_NOTE,
1255                          /*alignment=*/4, ".note.package") {}
1256   void writeTo(uint8_t *buf) override;
1257   size_t getSize() const override;
1258 };
1259 
1260 class MemtagGlobalDescriptors final : public SyntheticSection {
1261 public:
1262   MemtagGlobalDescriptors()
1263       : SyntheticSection(llvm::ELF::SHF_ALLOC,
1264                          llvm::ELF::SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC,
1265                          /*alignment=*/4, ".memtag.globals.dynamic") {}
1266   void writeTo(uint8_t *buf) override;
1267   // The size of the section is non-computable until all addresses are
1268   // synthetized, because the section's contents contain a sorted
1269   // varint-compressed list of pointers to global variables. We only know the
1270   // final size after `finalizeAddressDependentContent()`.
1271   size_t getSize() const override;
1272   bool updateAllocSize() override;
1273 
1274   void addSymbol(const Symbol &sym) {
1275     symbols.push_back(&sym);
1276   }
1277 
1278   bool isNeeded() const override {
1279     return !symbols.empty();
1280   }
1281 
1282 private:
1283   SmallVector<const Symbol *, 0> symbols;
1284 };
1285 
1286 InputSection *createInterpSection();
1287 MergeInputSection *createCommentSection();
1288 template <class ELFT> void splitSections();
1289 void combineEhSections();
1290 
1291 template <typename ELFT> void writeEhdr(uint8_t *buf, Partition &part);
1292 template <typename ELFT> void writePhdrs(uint8_t *buf, Partition &part);
1293 
1294 Defined *addSyntheticLocal(StringRef name, uint8_t type, uint64_t value,
1295                            uint64_t size, InputSectionBase &section);
1296 
1297 void addVerneed(Symbol *ss);
1298 
1299 // Linker generated per-partition sections.
1300 struct Partition {
1301   StringRef name;
1302   uint64_t nameStrTab;
1303 
1304   std::unique_ptr<SyntheticSection> elfHeader;
1305   std::unique_ptr<SyntheticSection> programHeaders;
1306   SmallVector<PhdrEntry *, 0> phdrs;
1307 
1308   std::unique_ptr<ARMExidxSyntheticSection> armExidx;
1309   std::unique_ptr<BuildIdSection> buildId;
1310   std::unique_ptr<SyntheticSection> dynamic;
1311   std::unique_ptr<StringTableSection> dynStrTab;
1312   std::unique_ptr<SymbolTableBaseSection> dynSymTab;
1313   std::unique_ptr<EhFrameHeader> ehFrameHdr;
1314   std::unique_ptr<EhFrameSection> ehFrame;
1315   std::unique_ptr<GnuHashTableSection> gnuHashTab;
1316   std::unique_ptr<HashTableSection> hashTab;
1317   std::unique_ptr<MemtagAndroidNote> memtagAndroidNote;
1318   std::unique_ptr<MemtagGlobalDescriptors> memtagGlobalDescriptors;
1319   std::unique_ptr<PackageMetadataNote> packageMetadataNote;
1320   std::unique_ptr<RelocationBaseSection> relaDyn;
1321   std::unique_ptr<RelrBaseSection> relrDyn;
1322   std::unique_ptr<VersionDefinitionSection> verDef;
1323   std::unique_ptr<SyntheticSection> verNeed;
1324   std::unique_ptr<VersionTableSection> verSym;
1325 
1326   unsigned getNumber() const { return this - &partitions[0] + 1; }
1327 };
1328 
1329 LLVM_LIBRARY_VISIBILITY extern Partition *mainPart;
1330 
1331 inline Partition &SectionBase::getPartition() const {
1332   assert(isLive());
1333   return partitions[partition - 1];
1334 }
1335 
1336 // Linker generated sections which can be used as inputs and are not specific to
1337 // a partition.
1338 struct InStruct {
1339   std::unique_ptr<InputSection> attributes;
1340   std::unique_ptr<SyntheticSection> riscvAttributes;
1341   std::unique_ptr<BssSection> bss;
1342   std::unique_ptr<BssSection> bssRelRo;
1343   std::unique_ptr<GotSection> got;
1344   std::unique_ptr<GotPltSection> gotPlt;
1345   std::unique_ptr<IgotPltSection> igotPlt;
1346   std::unique_ptr<RelroPaddingSection> relroPadding;
1347   std::unique_ptr<SyntheticSection> armCmseSGSection;
1348   std::unique_ptr<PPC64LongBranchTargetSection> ppc64LongBranchTarget;
1349   std::unique_ptr<SyntheticSection> mipsAbiFlags;
1350   std::unique_ptr<MipsGotSection> mipsGot;
1351   std::unique_ptr<SyntheticSection> mipsOptions;
1352   std::unique_ptr<SyntheticSection> mipsReginfo;
1353   std::unique_ptr<MipsRldMapSection> mipsRldMap;
1354   std::unique_ptr<SyntheticSection> partEnd;
1355   std::unique_ptr<SyntheticSection> partIndex;
1356   std::unique_ptr<PltSection> plt;
1357   std::unique_ptr<IpltSection> iplt;
1358   std::unique_ptr<PPC32Got2Section> ppc32Got2;
1359   std::unique_ptr<IBTPltSection> ibtPlt;
1360   std::unique_ptr<RelocationBaseSection> relaPlt;
1361   std::unique_ptr<RelocationBaseSection> relaIplt;
1362   std::unique_ptr<StringTableSection> shStrTab;
1363   std::unique_ptr<StringTableSection> strTab;
1364   std::unique_ptr<SymbolTableBaseSection> symTab;
1365   std::unique_ptr<SymtabShndxSection> symTabShndx;
1366 
1367   void reset();
1368 };
1369 
1370 LLVM_LIBRARY_VISIBILITY extern InStruct in;
1371 
1372 } // namespace lld::elf
1373 
1374 #endif
1375