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