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