]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/SyntheticSections.h
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / SyntheticSections.h
1 //===- SyntheticSection.h ---------------------------------------*- C++ -*-===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Synthetic sections represent chunks of linker-created data. If you
11 // need to create a chunk of data that to be included in some section
12 // in the result, you probably want to create that as a synthetic section.
13 //
14 // Synthetic sections are designed as input sections as opposed to
15 // output sections because we want to allow them to be manipulated
16 // using linker scripts just like other input sections from regular
17 // files.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLD_ELF_SYNTHETIC_SECTION_H
22 #define LLD_ELF_SYNTHETIC_SECTION_H
23
24 #include "EhFrame.h"
25 #include "GdbIndex.h"
26 #include "InputSection.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/MC/StringTableBuilder.h"
29 #include "llvm/Support/Endian.h"
30 #include <functional>
31
32 namespace lld {
33 namespace elf {
34 class Defined;
35 class SharedSymbol;
36
37 class SyntheticSection : public InputSection {
38 public:
39   SyntheticSection(uint64_t Flags, uint32_t Type, uint32_t Alignment,
40                    StringRef Name)
41       : InputSection(nullptr, Flags, Type, Alignment, {}, Name,
42                      InputSectionBase::Synthetic) {
43     this->Live = true;
44   }
45
46   virtual ~SyntheticSection() = default;
47   virtual void writeTo(uint8_t *Buf) = 0;
48   virtual size_t getSize() const = 0;
49   virtual void finalizeContents() {}
50   // If the section has the SHF_ALLOC flag and the size may be changed if
51   // thunks are added, update the section size.
52   virtual bool updateAllocSize() { return false; }
53   // If any additional finalization of contents are needed post thunk creation.
54   virtual void postThunkContents() {}
55   virtual bool empty() const { return false; }
56
57   static bool classof(const SectionBase *D) {
58     return D->kind() == InputSectionBase::Synthetic;
59   }
60 };
61
62 struct CieRecord {
63   EhSectionPiece *Cie = nullptr;
64   std::vector<EhSectionPiece *> Fdes;
65 };
66
67 // Section for .eh_frame.
68 class EhFrameSection final : public SyntheticSection {
69 public:
70   EhFrameSection();
71   void writeTo(uint8_t *Buf) override;
72   void finalizeContents() override;
73   bool empty() const override { return Sections.empty(); }
74   size_t getSize() const override { return Size; }
75
76   template <class ELFT> void addSection(InputSectionBase *S);
77
78   std::vector<EhInputSection *> Sections;
79   size_t NumFdes = 0;
80
81   struct FdeData {
82     uint32_t PcRel;
83     uint32_t FdeVARel;
84   };
85
86   std::vector<FdeData> getFdeData() const;
87   ArrayRef<CieRecord *> getCieRecords() const { return CieRecords; }
88
89 private:
90   // This is used only when parsing EhInputSection. We keep it here to avoid
91   // allocating one for each EhInputSection.
92   llvm::DenseMap<size_t, CieRecord *> OffsetToCie;
93
94   uint64_t Size = 0;
95
96   template <class ELFT, class RelTy>
97   void addSectionAux(EhInputSection *S, llvm::ArrayRef<RelTy> Rels);
98
99   template <class ELFT, class RelTy>
100   CieRecord *addCie(EhSectionPiece &Piece, ArrayRef<RelTy> Rels);
101
102   template <class ELFT, class RelTy>
103   bool isFdeLive(EhSectionPiece &Piece, ArrayRef<RelTy> Rels);
104
105   uint64_t getFdePc(uint8_t *Buf, size_t Off, uint8_t Enc) const;
106
107   std::vector<CieRecord *> CieRecords;
108
109   // CIE records are uniquified by their contents and personality functions.
110   llvm::DenseMap<std::pair<ArrayRef<uint8_t>, Symbol *>, CieRecord *> CieMap;
111 };
112
113 class GotSection : public SyntheticSection {
114 public:
115   GotSection();
116   size_t getSize() const override { return Size; }
117   void finalizeContents() override;
118   bool empty() const override;
119   void writeTo(uint8_t *Buf) override;
120
121   void addEntry(Symbol &Sym);
122   bool addDynTlsEntry(Symbol &Sym);
123   bool addTlsIndex();
124   uint64_t getGlobalDynAddr(const Symbol &B) const;
125   uint64_t getGlobalDynOffset(const Symbol &B) const;
126
127   uint64_t getTlsIndexVA() { return this->getVA() + TlsIndexOff; }
128   uint32_t getTlsIndexOff() const { return TlsIndexOff; }
129
130   // Flag to force GOT to be in output if we have relocations
131   // that relies on its address.
132   bool HasGotOffRel = false;
133
134 protected:
135   size_t NumEntries = 0;
136   uint32_t TlsIndexOff = -1;
137   uint64_t Size = 0;
138 };
139
140 // .note.gnu.build-id section.
141 class BuildIdSection : public SyntheticSection {
142   // First 16 bytes are a header.
143   static const unsigned HeaderSize = 16;
144
145 public:
146   BuildIdSection();
147   void writeTo(uint8_t *Buf) override;
148   size_t getSize() const override { return HeaderSize + HashSize; }
149   void writeBuildId(llvm::ArrayRef<uint8_t> Buf);
150
151 private:
152   void computeHash(llvm::ArrayRef<uint8_t> Buf,
153                    std::function<void(uint8_t *, ArrayRef<uint8_t>)> Hash);
154
155   size_t HashSize;
156   uint8_t *HashBuf;
157 };
158
159 // BssSection is used to reserve space for copy relocations and common symbols.
160 // We create three instances of this class for .bss, .bss.rel.ro and "COMMON",
161 // that are used for writable symbols, read-only symbols and common symbols,
162 // respectively.
163 class BssSection final : public SyntheticSection {
164 public:
165   BssSection(StringRef Name, uint64_t Size, uint32_t Alignment);
166   void writeTo(uint8_t *) override {}
167   bool empty() const override { return getSize() == 0; }
168   size_t getSize() const override { return Size; }
169
170   static bool classof(const SectionBase *S) { return S->Bss; }
171   uint64_t Size;
172 };
173
174 class MipsGotSection final : public SyntheticSection {
175 public:
176   MipsGotSection();
177   void writeTo(uint8_t *Buf) override;
178   size_t getSize() const override { return Size; }
179   bool updateAllocSize() override;
180   void finalizeContents() override;
181   bool empty() const override;
182
183   // Join separate GOTs built for each input file to generate
184   // primary and optional multiple secondary GOTs.
185   template <class ELFT> void build();
186
187   void addEntry(InputFile &File, Symbol &Sym, int64_t Addend, RelExpr Expr);
188   void addDynTlsEntry(InputFile &File, Symbol &Sym);
189   void addTlsIndex(InputFile &File);
190
191   uint64_t getPageEntryOffset(const InputFile *F, const Symbol &S,
192                               int64_t Addend) const;
193   uint64_t getSymEntryOffset(const InputFile *F, const Symbol &S,
194                              int64_t Addend) const;
195   uint64_t getGlobalDynOffset(const InputFile *F, const Symbol &S) const;
196   uint64_t getTlsIndexOffset(const InputFile *F) const;
197
198   // Returns the symbol which corresponds to the first entry of the global part
199   // of GOT on MIPS platform. It is required to fill up MIPS-specific dynamic
200   // table properties.
201   // Returns nullptr if the global part is empty.
202   const Symbol *getFirstGlobalEntry() const;
203
204   // Returns the number of entries in the local part of GOT including
205   // the number of reserved entries.
206   unsigned getLocalEntriesNum() const;
207
208   // Return _gp value for primary GOT (nullptr) or particular input file.
209   uint64_t getGp(const InputFile *F = nullptr) const;
210
211 private:
212   // MIPS GOT consists of three parts: local, global and tls. Each part
213   // contains different types of entries. Here is a layout of GOT:
214   // - Header entries                |
215   // - Page entries                  |   Local part
216   // - Local entries (16-bit access) |
217   // - Local entries (32-bit access) |
218   // - Normal global entries         ||  Global part
219   // - Reloc-only global entries     ||
220   // - TLS entries                   ||| TLS part
221   //
222   // Header:
223   //   Two entries hold predefined value 0x0 and 0x80000000.
224   // Page entries:
225   //   These entries created by R_MIPS_GOT_PAGE relocation and R_MIPS_GOT16
226   //   relocation against local symbols. They are initialized by higher 16-bit
227   //   of the corresponding symbol's value. So each 64kb of address space
228   //   requires a single GOT entry.
229   // Local entries (16-bit access):
230   //   These entries created by GOT relocations against global non-preemptible
231   //   symbols so dynamic linker is not necessary to resolve the symbol's
232   //   values. "16-bit access" means that corresponding relocations address
233   //   GOT using 16-bit index. Each unique Symbol-Addend pair has its own
234   //   GOT entry.
235   // Local entries (32-bit access):
236   //   These entries are the same as above but created by relocations which
237   //   address GOT using 32-bit index (R_MIPS_GOT_HI16/LO16 etc).
238   // Normal global entries:
239   //   These entries created by GOT relocations against preemptible global
240   //   symbols. They need to be initialized by dynamic linker and they ordered
241   //   exactly as the corresponding entries in the dynamic symbols table.
242   // Reloc-only global entries:
243   //   These entries created for symbols that are referenced by dynamic
244   //   relocations R_MIPS_REL32. These entries are not accessed with gp-relative
245   //   addressing, but MIPS ABI requires that these entries be present in GOT.
246   // TLS entries:
247   //   Entries created by TLS relocations.
248   //
249   // If the sum of local, global and tls entries is less than 64K only single
250   // got is enough. Otherwise, multi-got is created. Series of primary and
251   // multiple secondary GOTs have the following layout:
252   // - Primary GOT
253   //     Header
254   //     Local entries
255   //     Global entries
256   //     Relocation only entries
257   //     TLS entries
258   //
259   // - Secondary GOT
260   //     Local entries
261   //     Global entries
262   //     TLS entries
263   // ...
264   //
265   // All GOT entries required by relocations from a single input file entirely
266   // belong to either primary or one of secondary GOTs. To reference GOT entries
267   // each GOT has its own _gp value points to the "middle" of the GOT.
268   // In the code this value loaded to the register which is used for GOT access.
269   //
270   // MIPS 32 function's prologue:
271   //   lui     v0,0x0
272   //   0: R_MIPS_HI16  _gp_disp
273   //   addiu   v0,v0,0
274   //   4: R_MIPS_LO16  _gp_disp
275   //
276   // MIPS 64:
277   //   lui     at,0x0
278   //   14: R_MIPS_GPREL16  main
279   //
280   // Dynamic linker does not know anything about secondary GOTs and cannot
281   // use a regular MIPS mechanism for GOT entries initialization. So we have
282   // to use an approach accepted by other architectures and create dynamic
283   // relocations R_MIPS_REL32 to initialize global entries (and local in case
284   // of PIC code) in secondary GOTs. But ironically MIPS dynamic linker
285   // requires GOT entries and correspondingly ordered dynamic symbol table
286   // entries to deal with dynamic relocations. To handle this problem
287   // relocation-only section in the primary GOT contains entries for all
288   // symbols referenced in global parts of secondary GOTs. Although the sum
289   // of local and normal global entries of the primary got should be less
290   // than 64K, the size of the primary got (including relocation-only entries
291   // can be greater than 64K, because parts of the primary got that overflow
292   // the 64K limit are used only by the dynamic linker at dynamic link-time
293   // and not by 16-bit gp-relative addressing at run-time.
294   //
295   // For complete multi-GOT description see the following link
296   // https://dmz-portal.mips.com/wiki/MIPS_Multi_GOT
297
298   // Number of "Header" entries.
299   static const unsigned HeaderEntriesNum = 2;
300
301   uint64_t Size = 0;
302
303   size_t LocalEntriesNum = 0;
304
305   // Symbol and addend.
306   typedef std::pair<Symbol *, int64_t> GotEntry;
307
308   struct FileGot {
309     InputFile *File = nullptr;
310     size_t StartIndex = 0;
311
312     struct PageBlock {
313       size_t FirstIndex = 0;
314       size_t Count = 0;
315     };
316
317     // Map output sections referenced by MIPS GOT relocations
318     // to the description (index/count) "page" entries allocated
319     // for this section.
320     llvm::SmallMapVector<const OutputSection *, PageBlock, 16> PagesMap;
321     // Maps from Symbol+Addend pair or just Symbol to the GOT entry index.
322     llvm::MapVector<GotEntry, size_t> Local16;
323     llvm::MapVector<GotEntry, size_t> Local32;
324     llvm::MapVector<Symbol *, size_t> Global;
325     llvm::MapVector<Symbol *, size_t> Relocs;
326     llvm::MapVector<Symbol *, size_t> Tls;
327     // Set of symbols referenced by dynamic TLS relocations.
328     llvm::MapVector<Symbol *, size_t> DynTlsSymbols;
329
330     // Total number of all entries.
331     size_t getEntriesNum() const;
332     // Number of "page" entries.
333     size_t getPageEntriesNum() const;
334     // Number of entries require 16-bit index to access.
335     size_t getIndexedEntriesNum() const;
336
337     bool isOverflow() const;
338   };
339
340   // Container of GOT created for each input file.
341   // After building a final series of GOTs this container
342   // holds primary and secondary GOT's.
343   std::vector<FileGot> Gots;
344
345   // Return (and create if necessary) `FileGot`.
346   FileGot &getGot(InputFile &F);
347
348   // Try to merge two GOTs. In case of success the `Dst` contains
349   // result of merging and the function returns true. In case of
350   // ovwerflow the `Dst` is unchanged and the function returns false.
351   bool tryMergeGots(FileGot & Dst, FileGot & Src, bool IsPrimary);
352 };
353
354 class GotPltSection final : public SyntheticSection {
355 public:
356   GotPltSection();
357   void addEntry(Symbol &Sym);
358   size_t getSize() const override;
359   void writeTo(uint8_t *Buf) override;
360   bool empty() const override;
361
362 private:
363   std::vector<const Symbol *> Entries;
364 };
365
366 // The IgotPltSection is a Got associated with the PltSection for GNU Ifunc
367 // Symbols that will be relocated by Target->IRelativeRel.
368 // On most Targets the IgotPltSection will immediately follow the GotPltSection
369 // on ARM the IgotPltSection will immediately follow the GotSection.
370 class IgotPltSection final : public SyntheticSection {
371 public:
372   IgotPltSection();
373   void addEntry(Symbol &Sym);
374   size_t getSize() const override;
375   void writeTo(uint8_t *Buf) override;
376   bool empty() const override { return Entries.empty(); }
377
378 private:
379   std::vector<const Symbol *> Entries;
380 };
381
382 class StringTableSection final : public SyntheticSection {
383 public:
384   StringTableSection(StringRef Name, bool Dynamic);
385   unsigned addString(StringRef S, bool HashIt = true);
386   void writeTo(uint8_t *Buf) override;
387   size_t getSize() const override { return Size; }
388   bool isDynamic() const { return Dynamic; }
389
390 private:
391   const bool Dynamic;
392
393   uint64_t Size = 0;
394
395   llvm::DenseMap<StringRef, unsigned> StringMap;
396   std::vector<StringRef> Strings;
397 };
398
399 class DynamicReloc {
400 public:
401   DynamicReloc(RelType Type, const InputSectionBase *InputSec,
402                uint64_t OffsetInSec, bool UseSymVA, Symbol *Sym, int64_t Addend)
403       : Type(Type), Sym(Sym), InputSec(InputSec), OffsetInSec(OffsetInSec),
404         UseSymVA(UseSymVA), Addend(Addend), OutputSec(nullptr) {}
405   // This constructor records dynamic relocation settings used by MIPS
406   // multi-GOT implementation. It's to relocate addresses of 64kb pages
407   // lie inside the output section.
408   DynamicReloc(RelType Type, const InputSectionBase *InputSec,
409                uint64_t OffsetInSec, const OutputSection *OutputSec,
410                int64_t Addend)
411       : Type(Type), Sym(nullptr), InputSec(InputSec), OffsetInSec(OffsetInSec),
412         UseSymVA(false), Addend(Addend), OutputSec(OutputSec) {}
413
414   uint64_t getOffset() const;
415   uint32_t getSymIndex() const;
416   const InputSectionBase *getInputSec() const { return InputSec; }
417
418   // Computes the addend of the dynamic relocation. Note that this is not the
419   // same as the Addend member variable as it also includes the symbol address
420   // if UseSymVA is true.
421   int64_t computeAddend() const;
422
423   RelType Type;
424
425 private:
426   Symbol *Sym;
427   const InputSectionBase *InputSec = nullptr;
428   uint64_t OffsetInSec;
429   // If this member is true, the dynamic relocation will not be against the
430   // symbol but will instead be a relative relocation that simply adds the
431   // load address. This means we need to write the symbol virtual address
432   // plus the original addend as the final relocation addend.
433   bool UseSymVA;
434   int64_t Addend;
435   const OutputSection *OutputSec;
436 };
437
438 template <class ELFT> class DynamicSection final : public SyntheticSection {
439   typedef typename ELFT::Dyn Elf_Dyn;
440   typedef typename ELFT::Rel Elf_Rel;
441   typedef typename ELFT::Rela Elf_Rela;
442   typedef typename ELFT::Relr Elf_Relr;
443   typedef typename ELFT::Shdr Elf_Shdr;
444   typedef typename ELFT::Sym Elf_Sym;
445
446   // finalizeContents() fills this vector with the section contents.
447   std::vector<std::pair<int32_t, std::function<uint64_t()>>> Entries;
448
449 public:
450   DynamicSection();
451   void finalizeContents() override;
452   void writeTo(uint8_t *Buf) override;
453   size_t getSize() const override { return Size; }
454
455 private:
456   void add(int32_t Tag, std::function<uint64_t()> Fn);
457   void addInt(int32_t Tag, uint64_t Val);
458   void addInSec(int32_t Tag, InputSection *Sec);
459   void addInSecRelative(int32_t Tag, InputSection *Sec);
460   void addOutSec(int32_t Tag, OutputSection *Sec);
461   void addSize(int32_t Tag, OutputSection *Sec);
462   void addSym(int32_t Tag, Symbol *Sym);
463
464   uint64_t Size = 0;
465 };
466
467 class RelocationBaseSection : public SyntheticSection {
468 public:
469   RelocationBaseSection(StringRef Name, uint32_t Type, int32_t DynamicTag,
470                         int32_t SizeDynamicTag);
471   void addReloc(RelType DynType, InputSectionBase *IS, uint64_t OffsetInSec,
472                 Symbol *Sym);
473   // Add a dynamic relocation that might need an addend. This takes care of
474   // writing the addend to the output section if needed.
475   void addReloc(RelType DynType, InputSectionBase *InputSec,
476                 uint64_t OffsetInSec, Symbol *Sym, int64_t Addend, RelExpr Expr,
477                 RelType Type);
478   void addReloc(const DynamicReloc &Reloc);
479   bool empty() const override { return Relocs.empty(); }
480   size_t getSize() const override { return Relocs.size() * this->Entsize; }
481   size_t getRelativeRelocCount() const { return NumRelativeRelocs; }
482   void finalizeContents() override;
483   int32_t DynamicTag, SizeDynamicTag;
484
485 protected:
486   std::vector<DynamicReloc> Relocs;
487   size_t NumRelativeRelocs = 0;
488 };
489
490 template <class ELFT>
491 class RelocationSection final : public RelocationBaseSection {
492   typedef typename ELFT::Rel Elf_Rel;
493   typedef typename ELFT::Rela Elf_Rela;
494
495 public:
496   RelocationSection(StringRef Name, bool Sort);
497   unsigned getRelocOffset();
498   void writeTo(uint8_t *Buf) override;
499
500 private:
501   bool Sort;
502 };
503
504 template <class ELFT>
505 class AndroidPackedRelocationSection final : public RelocationBaseSection {
506   typedef typename ELFT::Rel Elf_Rel;
507   typedef typename ELFT::Rela Elf_Rela;
508
509 public:
510   AndroidPackedRelocationSection(StringRef Name);
511
512   bool updateAllocSize() override;
513   size_t getSize() const override { return RelocData.size(); }
514   void writeTo(uint8_t *Buf) override {
515     memcpy(Buf, RelocData.data(), RelocData.size());
516   }
517
518 private:
519   SmallVector<char, 0> RelocData;
520 };
521
522 struct RelativeReloc {
523   uint64_t getOffset() const { return InputSec->getVA(OffsetInSec); }
524
525   const InputSectionBase *InputSec;
526   uint64_t OffsetInSec;
527 };
528
529 class RelrBaseSection : public SyntheticSection {
530 public:
531   RelrBaseSection();
532   std::vector<RelativeReloc> Relocs;
533 };
534
535 // RelrSection is used to encode offsets for relative relocations.
536 // Proposal for adding SHT_RELR sections to generic-abi is here:
537 //   https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
538 // For more details, see the comment in RelrSection::updateAllocSize().
539 template <class ELFT> class RelrSection final : public RelrBaseSection {
540   typedef typename ELFT::Relr Elf_Relr;
541
542 public:
543   RelrSection();
544
545   bool updateAllocSize() override;
546   size_t getSize() const override { return RelrRelocs.size() * this->Entsize; }
547   void writeTo(uint8_t *Buf) override {
548     memcpy(Buf, RelrRelocs.data(), getSize());
549   }
550
551 private:
552   std::vector<Elf_Relr> RelrRelocs;
553 };
554
555 struct SymbolTableEntry {
556   Symbol *Sym;
557   size_t StrTabOffset;
558 };
559
560 class SymbolTableBaseSection : public SyntheticSection {
561 public:
562   SymbolTableBaseSection(StringTableSection &StrTabSec);
563   void finalizeContents() override;
564   void postThunkContents() override;
565   size_t getSize() const override { return getNumSymbols() * Entsize; }
566   void addSymbol(Symbol *Sym);
567   unsigned getNumSymbols() const { return Symbols.size() + 1; }
568   size_t getSymbolIndex(Symbol *Sym);
569   ArrayRef<SymbolTableEntry> getSymbols() const { return Symbols; }
570
571 protected:
572   // A vector of symbols and their string table offsets.
573   std::vector<SymbolTableEntry> Symbols;
574
575   StringTableSection &StrTabSec;
576
577   llvm::once_flag OnceFlag;
578   llvm::DenseMap<Symbol *, size_t> SymbolIndexMap;
579   llvm::DenseMap<OutputSection *, size_t> SectionIndexMap;
580 };
581
582 template <class ELFT>
583 class SymbolTableSection final : public SymbolTableBaseSection {
584   typedef typename ELFT::Sym Elf_Sym;
585
586 public:
587   SymbolTableSection(StringTableSection &StrTabSec);
588   void writeTo(uint8_t *Buf) override;
589 };
590
591 class SymtabShndxSection final : public SyntheticSection {
592 public:
593   SymtabShndxSection();
594
595   void writeTo(uint8_t *Buf) override;
596   size_t getSize() const override;
597   bool empty() const override;
598   void finalizeContents() override;
599 };
600
601 // Outputs GNU Hash section. For detailed explanation see:
602 // https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections
603 class GnuHashTableSection final : public SyntheticSection {
604 public:
605   GnuHashTableSection();
606   void finalizeContents() override;
607   void writeTo(uint8_t *Buf) override;
608   size_t getSize() const override { return Size; }
609
610   // Adds symbols to the hash table.
611   // Sorts the input to satisfy GNU hash section requirements.
612   void addSymbols(std::vector<SymbolTableEntry> &Symbols);
613
614 private:
615   enum { Shift2 = 6 };
616
617   void writeBloomFilter(uint8_t *Buf);
618   void writeHashTable(uint8_t *Buf);
619
620   struct Entry {
621     Symbol *Sym;
622     size_t StrTabOffset;
623     uint32_t Hash;
624     uint32_t BucketIdx;
625   };
626
627   std::vector<Entry> Symbols;
628   size_t MaskWords;
629   size_t NBuckets = 0;
630   size_t Size = 0;
631 };
632
633 class HashTableSection final : public SyntheticSection {
634 public:
635   HashTableSection();
636   void finalizeContents() override;
637   void writeTo(uint8_t *Buf) override;
638   size_t getSize() const override { return Size; }
639
640 private:
641   size_t Size = 0;
642 };
643
644 // The PltSection is used for both the Plt and Iplt. The former usually has a
645 // header as its first entry that is used at run-time to resolve lazy binding.
646 // The latter is used for GNU Ifunc symbols, that will be subject to a
647 // Target->IRelativeRel.
648 class PltSection : public SyntheticSection {
649 public:
650   PltSection(bool IsIplt);
651   void writeTo(uint8_t *Buf) override;
652   size_t getSize() const override;
653   bool empty() const override { return Entries.empty(); }
654   void addSymbols();
655
656   template <class ELFT> void addEntry(Symbol &Sym);
657
658 private:
659   unsigned getPltRelocOff() const;
660   std::vector<std::pair<const Symbol *, unsigned>> Entries;
661   size_t HeaderSize;
662   bool IsIplt;
663 };
664
665 class GdbIndexSection final : public SyntheticSection {
666 public:
667   struct AddressEntry {
668     InputSection *Section;
669     uint64_t LowAddress;
670     uint64_t HighAddress;
671     uint32_t CuIndex;
672   };
673
674   struct CuEntry {
675     uint64_t CuOffset;
676     uint64_t CuLength;
677   };
678
679   struct NameTypeEntry {
680     llvm::CachedHashStringRef Name;
681     uint32_t Type;
682   };
683
684   struct GdbChunk {
685     InputSection *Sec;
686     std::vector<AddressEntry> AddressAreas;
687     std::vector<CuEntry> CompilationUnits;
688   };
689
690   struct GdbSymbol {
691     llvm::CachedHashStringRef Name;
692     std::vector<uint32_t> CuVector;
693     uint32_t NameOff;
694     uint32_t CuVectorOff;
695   };
696
697   GdbIndexSection();
698   template <typename ELFT> static GdbIndexSection *create();
699   void writeTo(uint8_t *Buf) override;
700   size_t getSize() const override { return Size; }
701   bool empty() const override;
702
703 private:
704   struct GdbIndexHeader {
705     llvm::support::ulittle32_t Version;
706     llvm::support::ulittle32_t CuListOff;
707     llvm::support::ulittle32_t CuTypesOff;
708     llvm::support::ulittle32_t AddressAreaOff;
709     llvm::support::ulittle32_t SymtabOff;
710     llvm::support::ulittle32_t ConstantPoolOff;
711   };
712
713   void initOutputSize();
714   size_t computeSymtabSize() const;
715
716   // Each chunk contains information gathered from debug sections of a
717   // single object file.
718   std::vector<GdbChunk> Chunks;
719
720   // A symbol table for this .gdb_index section.
721   std::vector<GdbSymbol> Symbols;
722
723   size_t Size;
724 };
725
726 // --eh-frame-hdr option tells linker to construct a header for all the
727 // .eh_frame sections. This header is placed to a section named .eh_frame_hdr
728 // and also to a PT_GNU_EH_FRAME segment.
729 // At runtime the unwinder then can find all the PT_GNU_EH_FRAME segments by
730 // calling dl_iterate_phdr.
731 // This section contains a lookup table for quick binary search of FDEs.
732 // Detailed info about internals can be found in Ian Lance Taylor's blog:
733 // http://www.airs.com/blog/archives/460 (".eh_frame")
734 // http://www.airs.com/blog/archives/462 (".eh_frame_hdr")
735 class EhFrameHeader final : public SyntheticSection {
736 public:
737   EhFrameHeader();
738   void writeTo(uint8_t *Buf) override;
739   size_t getSize() const override;
740   bool empty() const override;
741 };
742
743 // For more information about .gnu.version and .gnu.version_r see:
744 // https://www.akkadia.org/drepper/symbol-versioning
745
746 // The .gnu.version_d section which has a section type of SHT_GNU_verdef shall
747 // contain symbol version definitions. The number of entries in this section
748 // shall be contained in the DT_VERDEFNUM entry of the .dynamic section.
749 // The section shall contain an array of Elf_Verdef structures, optionally
750 // followed by an array of Elf_Verdaux structures.
751 template <class ELFT>
752 class VersionDefinitionSection final : public SyntheticSection {
753   typedef typename ELFT::Verdef Elf_Verdef;
754   typedef typename ELFT::Verdaux Elf_Verdaux;
755
756 public:
757   VersionDefinitionSection();
758   void finalizeContents() override;
759   size_t getSize() const override;
760   void writeTo(uint8_t *Buf) override;
761
762 private:
763   void writeOne(uint8_t *Buf, uint32_t Index, StringRef Name, size_t NameOff);
764
765   unsigned FileDefNameOff;
766 };
767
768 // The .gnu.version section specifies the required version of each symbol in the
769 // dynamic symbol table. It contains one Elf_Versym for each dynamic symbol
770 // table entry. An Elf_Versym is just a 16-bit integer that refers to a version
771 // identifier defined in the either .gnu.version_r or .gnu.version_d section.
772 // The values 0 and 1 are reserved. All other values are used for versions in
773 // the own object or in any of the dependencies.
774 template <class ELFT>
775 class VersionTableSection final : public SyntheticSection {
776   typedef typename ELFT::Versym Elf_Versym;
777
778 public:
779   VersionTableSection();
780   void finalizeContents() override;
781   size_t getSize() const override;
782   void writeTo(uint8_t *Buf) override;
783   bool empty() const override;
784 };
785
786 // The .gnu.version_r section defines the version identifiers used by
787 // .gnu.version. It contains a linked list of Elf_Verneed data structures. Each
788 // Elf_Verneed specifies the version requirements for a single DSO, and contains
789 // a reference to a linked list of Elf_Vernaux data structures which define the
790 // mapping from version identifiers to version names.
791 template <class ELFT> class VersionNeedSection final : public SyntheticSection {
792   typedef typename ELFT::Verneed Elf_Verneed;
793   typedef typename ELFT::Vernaux Elf_Vernaux;
794
795   // A vector of shared files that need Elf_Verneed data structures and the
796   // string table offsets of their sonames.
797   std::vector<std::pair<SharedFile<ELFT> *, size_t>> Needed;
798
799   // The next available version identifier.
800   unsigned NextIndex;
801
802 public:
803   VersionNeedSection();
804   void addSymbol(Symbol *Sym);
805   void finalizeContents() override;
806   void writeTo(uint8_t *Buf) override;
807   size_t getSize() const override;
808   size_t getNeedNum() const { return Needed.size(); }
809   bool empty() const override;
810 };
811
812 // MergeSyntheticSection is a class that allows us to put mergeable sections
813 // with different attributes in a single output sections. To do that
814 // we put them into MergeSyntheticSection synthetic input sections which are
815 // attached to regular output sections.
816 class MergeSyntheticSection : public SyntheticSection {
817 public:
818   void addSection(MergeInputSection *MS);
819   std::vector<MergeInputSection *> Sections;
820
821 protected:
822   MergeSyntheticSection(StringRef Name, uint32_t Type, uint64_t Flags,
823                         uint32_t Alignment)
824       : SyntheticSection(Flags, Type, Alignment, Name) {}
825 };
826
827 class MergeTailSection final : public MergeSyntheticSection {
828 public:
829   MergeTailSection(StringRef Name, uint32_t Type, uint64_t Flags,
830                    uint32_t Alignment);
831
832   size_t getSize() const override;
833   void writeTo(uint8_t *Buf) override;
834   void finalizeContents() override;
835
836 private:
837   llvm::StringTableBuilder Builder;
838 };
839
840 class MergeNoTailSection final : public MergeSyntheticSection {
841 public:
842   MergeNoTailSection(StringRef Name, uint32_t Type, uint64_t Flags,
843                      uint32_t Alignment)
844       : MergeSyntheticSection(Name, Type, Flags, Alignment) {}
845
846   size_t getSize() const override { return Size; }
847   void writeTo(uint8_t *Buf) override;
848   void finalizeContents() override;
849
850 private:
851   // We use the most significant bits of a hash as a shard ID.
852   // The reason why we don't want to use the least significant bits is
853   // because DenseMap also uses lower bits to determine a bucket ID.
854   // If we use lower bits, it significantly increases the probability of
855   // hash collisons.
856   size_t getShardId(uint32_t Hash) {
857     return Hash >> (32 - llvm::countTrailingZeros(NumShards));
858   }
859
860   // Section size
861   size_t Size;
862
863   // String table contents
864   constexpr static size_t NumShards = 32;
865   std::vector<llvm::StringTableBuilder> Shards;
866   size_t ShardOffsets[NumShards];
867 };
868
869 // .MIPS.abiflags section.
870 template <class ELFT>
871 class MipsAbiFlagsSection final : public SyntheticSection {
872   typedef llvm::object::Elf_Mips_ABIFlags<ELFT> Elf_Mips_ABIFlags;
873
874 public:
875   static MipsAbiFlagsSection *create();
876
877   MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags);
878   size_t getSize() const override { return sizeof(Elf_Mips_ABIFlags); }
879   void writeTo(uint8_t *Buf) override;
880
881 private:
882   Elf_Mips_ABIFlags Flags;
883 };
884
885 // .MIPS.options section.
886 template <class ELFT> class MipsOptionsSection final : public SyntheticSection {
887   typedef llvm::object::Elf_Mips_Options<ELFT> Elf_Mips_Options;
888   typedef llvm::object::Elf_Mips_RegInfo<ELFT> Elf_Mips_RegInfo;
889
890 public:
891   static MipsOptionsSection *create();
892
893   MipsOptionsSection(Elf_Mips_RegInfo Reginfo);
894   void writeTo(uint8_t *Buf) override;
895
896   size_t getSize() const override {
897     return sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
898   }
899
900 private:
901   Elf_Mips_RegInfo Reginfo;
902 };
903
904 // MIPS .reginfo section.
905 template <class ELFT> class MipsReginfoSection final : public SyntheticSection {
906   typedef llvm::object::Elf_Mips_RegInfo<ELFT> Elf_Mips_RegInfo;
907
908 public:
909   static MipsReginfoSection *create();
910
911   MipsReginfoSection(Elf_Mips_RegInfo Reginfo);
912   size_t getSize() const override { return sizeof(Elf_Mips_RegInfo); }
913   void writeTo(uint8_t *Buf) override;
914
915 private:
916   Elf_Mips_RegInfo Reginfo;
917 };
918
919 // This is a MIPS specific section to hold a space within the data segment
920 // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
921 // See "Dynamic section" in Chapter 5 in the following document:
922 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
923 class MipsRldMapSection : public SyntheticSection {
924 public:
925   MipsRldMapSection();
926   size_t getSize() const override { return Config->Wordsize; }
927   void writeTo(uint8_t *Buf) override {}
928 };
929
930 class ARMExidxSentinelSection : public SyntheticSection {
931 public:
932   ARMExidxSentinelSection();
933   size_t getSize() const override { return 8; }
934   void writeTo(uint8_t *Buf) override;
935   bool empty() const override;
936
937   static bool classof(const SectionBase *D);
938
939   // The last section referenced by a regular .ARM.exidx section.
940   // It is found and filled in Writer<ELFT>::resolveShfLinkOrder().
941   // The sentinel points at the end of that section.
942   InputSection *Highest = nullptr;
943 };
944
945 // A container for one or more linker generated thunks. Instances of these
946 // thunks including ARM interworking and Mips LA25 PI to non-PI thunks.
947 class ThunkSection : public SyntheticSection {
948 public:
949   // ThunkSection in OS, with desired OutSecOff of Off
950   ThunkSection(OutputSection *OS, uint64_t Off);
951
952   // Add a newly created Thunk to this container:
953   // Thunk is given offset from start of this InputSection
954   // Thunk defines a symbol in this InputSection that can be used as target
955   // of a relocation
956   void addThunk(Thunk *T);
957   size_t getSize() const override { return Size; }
958   void writeTo(uint8_t *Buf) override;
959   InputSection *getTargetInputSection() const;
960   bool assignOffsets();
961
962 private:
963   std::vector<Thunk *> Thunks;
964   size_t Size = 0;
965 };
966
967 InputSection *createInterpSection();
968 MergeInputSection *createCommentSection();
969 void decompressSections();
970 template <class ELFT> void splitSections();
971 void mergeSections();
972
973 Defined *addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value,
974                            uint64_t Size, InputSectionBase &Section);
975
976 // Linker generated sections which can be used as inputs.
977 struct InX {
978   static InputSection *ARMAttributes;
979   static BssSection *Bss;
980   static BssSection *BssRelRo;
981   static BuildIdSection *BuildId;
982   static EhFrameHeader *EhFrameHdr;
983   static EhFrameSection *EhFrame;
984   static SyntheticSection *Dynamic;
985   static StringTableSection *DynStrTab;
986   static SymbolTableBaseSection *DynSymTab;
987   static GnuHashTableSection *GnuHashTab;
988   static HashTableSection *HashTab;
989   static InputSection *Interp;
990   static GdbIndexSection *GdbIndex;
991   static GotSection *Got;
992   static GotPltSection *GotPlt;
993   static IgotPltSection *IgotPlt;
994   static MipsGotSection *MipsGot;
995   static MipsRldMapSection *MipsRldMap;
996   static PltSection *Plt;
997   static PltSection *Iplt;
998   static RelocationBaseSection *RelaDyn;
999   static RelrBaseSection *RelrDyn;
1000   static RelocationBaseSection *RelaPlt;
1001   static RelocationBaseSection *RelaIplt;
1002   static StringTableSection *ShStrTab;
1003   static StringTableSection *StrTab;
1004   static SymbolTableBaseSection *SymTab;
1005   static SymtabShndxSection* SymTabShndx;
1006 };
1007
1008 template <class ELFT> struct In {
1009   static VersionDefinitionSection<ELFT> *VerDef;
1010   static VersionTableSection<ELFT> *VerSym;
1011   static VersionNeedSection<ELFT> *VerNeed;
1012 };
1013
1014 template <class ELFT> VersionDefinitionSection<ELFT> *In<ELFT>::VerDef;
1015 template <class ELFT> VersionTableSection<ELFT> *In<ELFT>::VerSym;
1016 template <class ELFT> VersionNeedSection<ELFT> *In<ELFT>::VerNeed;
1017 } // namespace elf
1018 } // namespace lld
1019
1020 #endif