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