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