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