1 //===- SyntheticSection.h ---------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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.
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
18 //===----------------------------------------------------------------------===//
20 #ifndef LLD_ELF_SYNTHETIC_SECTIONS_H
21 #define LLD_ELF_SYNTHETIC_SECTIONS_H
25 #include "InputSection.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/FoldingSet.h"
29 #include "llvm/ADT/MapVector.h"
30 #include "llvm/ADT/STLFunctionalExtras.h"
31 #include "llvm/BinaryFormat/ELF.h"
32 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
33 #include "llvm/MC/StringTableBuilder.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/Parallel.h"
38 #include "llvm/Support/Threading.h"
43 class SymbolTableBaseSection
;
46 EhSectionPiece
*cie
= nullptr;
47 SmallVector
<EhSectionPiece
*, 0> fdes
;
50 // Section for .eh_frame.
51 class EhFrameSection final
: public SyntheticSection
{
53 EhFrameSection(Ctx
&);
54 void writeTo(uint8_t *buf
) override
;
55 void finalizeContents() override
;
56 bool isNeeded() const override
{ return !sections
.empty(); }
57 size_t getSize() const override
{ return size
; }
59 static bool classof(const SectionBase
*d
) {
60 return SyntheticSection::classof(d
) && d
->name
== ".eh_frame";
63 SmallVector
<EhInputSection
*, 0> sections
;
71 SmallVector
<FdeData
, 0> getFdeData() const;
72 ArrayRef
<CieRecord
*> getCieRecords() const { return cieRecords
; }
74 void iterateFDEWithLSDA(llvm::function_ref
<void(InputSection
&)> fn
);
77 // This is used only when parsing EhInputSection. We keep it here to avoid
78 // allocating one for each EhInputSection.
79 llvm::DenseMap
<size_t, CieRecord
*> offsetToCie
;
83 template <class ELFT
, class RelTy
>
84 void addRecords(EhInputSection
*s
, llvm::ArrayRef
<RelTy
> rels
);
85 template <class ELFT
> void addSectionAux(EhInputSection
*s
);
86 template <class ELFT
, class RelTy
>
87 void iterateFDEWithLSDAAux(EhInputSection
&sec
, ArrayRef
<RelTy
> rels
,
88 llvm::DenseSet
<size_t> &ciesWithLSDA
,
89 llvm::function_ref
<void(InputSection
&)> fn
);
91 template <class ELFT
, class RelTy
>
92 CieRecord
*addCie(EhSectionPiece
&piece
, ArrayRef
<RelTy
> rels
);
94 template <class ELFT
, class RelTy
>
95 Defined
*isFdeLive(EhSectionPiece
&piece
, ArrayRef
<RelTy
> rels
);
97 uint64_t getFdePc(uint8_t *buf
, size_t off
, uint8_t enc
) const;
99 SmallVector
<CieRecord
*, 0> cieRecords
;
101 // CIE records are uniquified by their contents and personality functions.
102 llvm::DenseMap
<std::pair
<ArrayRef
<uint8_t>, Symbol
*>, CieRecord
*> cieMap
;
105 class GotSection final
: public SyntheticSection
{
108 size_t getSize() const override
{ return size
; }
109 void finalizeContents() override
;
110 bool isNeeded() const override
;
111 void writeTo(uint8_t *buf
) override
;
113 void addConstant(const Relocation
&r
);
114 void addEntry(const Symbol
&sym
);
115 void addAuthEntry(const Symbol
&sym
);
116 bool addTlsDescEntry(const Symbol
&sym
);
117 bool addDynTlsEntry(const Symbol
&sym
);
119 uint32_t getTlsDescOffset(const Symbol
&sym
) const;
120 uint64_t getTlsDescAddr(const Symbol
&sym
) const;
121 uint64_t getGlobalDynAddr(const Symbol
&b
) const;
122 uint64_t getGlobalDynOffset(const Symbol
&b
) const;
124 uint64_t getTlsIndexVA() { return this->getVA() + tlsIndexOff
; }
125 uint32_t getTlsIndexOff() const { return tlsIndexOff
; }
127 // Flag to force GOT to be in output if we have relocations
128 // that relies on its address.
129 std::atomic
<bool> hasGotOffRel
= false;
132 size_t numEntries
= 0;
133 uint32_t tlsIndexOff
= -1;
135 struct AuthEntryInfo
{
139 SmallVector
<AuthEntryInfo
, 0> authEntries
;
142 // .note.GNU-stack section.
143 class GnuStackSection
: public SyntheticSection
{
145 GnuStackSection(Ctx
&ctx
)
146 : SyntheticSection(ctx
, ".note.GNU-stack", llvm::ELF::SHT_PROGBITS
, 0,
148 void writeTo(uint8_t *buf
) override
{}
149 size_t getSize() const override
{ return 0; }
152 class GnuPropertySection final
: public SyntheticSection
{
154 GnuPropertySection(Ctx
&);
155 void writeTo(uint8_t *buf
) override
;
156 size_t getSize() const override
;
159 // .note.gnu.build-id section.
160 class BuildIdSection
: public SyntheticSection
{
161 // First 16 bytes are a header.
162 static const unsigned headerSize
= 16;
165 const size_t hashSize
;
166 BuildIdSection(Ctx
&);
167 void writeTo(uint8_t *buf
) override
;
168 size_t getSize() const override
{ return headerSize
+ hashSize
; }
169 void writeBuildId(llvm::ArrayRef
<uint8_t> buf
);
175 // BssSection is used to reserve space for copy relocations and common symbols.
176 // We create three instances of this class for .bss, .bss.rel.ro and "COMMON",
177 // that are used for writable symbols, read-only symbols and common symbols,
179 class BssSection final
: public SyntheticSection
{
181 BssSection(Ctx
&, StringRef name
, uint64_t size
, uint32_t addralign
);
182 void writeTo(uint8_t *) override
{}
183 bool isNeeded() const override
{ return size
!= 0; }
184 size_t getSize() const override
{ return size
; }
186 static bool classof(const SectionBase
*s
) {
187 return isa
<SyntheticSection
>(s
) && cast
<SyntheticSection
>(s
)->bss
;
192 class MipsGotSection final
: public SyntheticSection
{
194 MipsGotSection(Ctx
&);
195 void writeTo(uint8_t *buf
) override
;
196 size_t getSize() const override
{ return size
; }
197 bool updateAllocSize(Ctx
&) override
;
198 void finalizeContents() override
;
199 bool isNeeded() const override
;
201 // Join separate GOTs built for each input file to generate
202 // primary and optional multiple secondary GOTs.
205 void addEntry(InputFile
&file
, Symbol
&sym
, int64_t addend
, RelExpr expr
);
206 void addDynTlsEntry(InputFile
&file
, Symbol
&sym
);
207 void addTlsIndex(InputFile
&file
);
209 uint64_t getPageEntryOffset(const InputFile
*f
, const Symbol
&s
,
210 int64_t addend
) const;
211 uint64_t getSymEntryOffset(const InputFile
*f
, const Symbol
&s
,
212 int64_t addend
) const;
213 uint64_t getGlobalDynOffset(const InputFile
*f
, const Symbol
&s
) const;
214 uint64_t getTlsIndexOffset(const InputFile
*f
) const;
216 // Returns the symbol which corresponds to the first entry of the global part
217 // of GOT on MIPS platform. It is required to fill up MIPS-specific dynamic
219 // Returns nullptr if the global part is empty.
220 const Symbol
*getFirstGlobalEntry() const;
222 // Returns the number of entries in the local part of GOT including
223 // the number of reserved entries.
224 unsigned getLocalEntriesNum() const;
226 // Return _gp value for primary GOT (nullptr) or particular input file.
227 uint64_t getGp(const InputFile
*f
= nullptr) const;
230 // MIPS GOT consists of three parts: local, global and tls. Each part
231 // contains different types of entries. Here is a layout of GOT:
232 // - Header entries |
233 // - Page entries | Local part
234 // - Local entries (16-bit access) |
235 // - Local entries (32-bit access) |
236 // - Normal global entries || Global part
237 // - Reloc-only global entries ||
238 // - TLS entries ||| TLS part
241 // Two entries hold predefined value 0x0 and 0x80000000.
243 // These entries created by R_MIPS_GOT_PAGE relocation and R_MIPS_GOT16
244 // relocation against local symbols. They are initialized by higher 16-bit
245 // of the corresponding symbol's value. So each 64kb of address space
246 // requires a single GOT entry.
247 // Local entries (16-bit access):
248 // These entries created by GOT relocations against global non-preemptible
249 // symbols so dynamic linker is not necessary to resolve the symbol's
250 // values. "16-bit access" means that corresponding relocations address
251 // GOT using 16-bit index. Each unique Symbol-Addend pair has its own
253 // Local entries (32-bit access):
254 // These entries are the same as above but created by relocations which
255 // address GOT using 32-bit index (R_MIPS_GOT_HI16/LO16 etc).
256 // Normal global entries:
257 // These entries created by GOT relocations against preemptible global
258 // symbols. They need to be initialized by dynamic linker and they ordered
259 // exactly as the corresponding entries in the dynamic symbols table.
260 // Reloc-only global entries:
261 // These entries created for symbols that are referenced by dynamic
262 // relocations R_MIPS_REL32. These entries are not accessed with gp-relative
263 // addressing, but MIPS ABI requires that these entries be present in GOT.
265 // Entries created by TLS relocations.
267 // If the sum of local, global and tls entries is less than 64K only single
268 // got is enough. Otherwise, multi-got is created. Series of primary and
269 // multiple secondary GOTs have the following layout:
274 // Relocation only entries
283 // All GOT entries required by relocations from a single input file entirely
284 // belong to either primary or one of secondary GOTs. To reference GOT entries
285 // each GOT has its own _gp value points to the "middle" of the GOT.
286 // In the code this value loaded to the register which is used for GOT access.
288 // MIPS 32 function's prologue:
290 // 0: R_MIPS_HI16 _gp_disp
292 // 4: R_MIPS_LO16 _gp_disp
296 // 14: R_MIPS_GPREL16 main
298 // Dynamic linker does not know anything about secondary GOTs and cannot
299 // use a regular MIPS mechanism for GOT entries initialization. So we have
300 // to use an approach accepted by other architectures and create dynamic
301 // relocations R_MIPS_REL32 to initialize global entries (and local in case
302 // of PIC code) in secondary GOTs. But ironically MIPS dynamic linker
303 // requires GOT entries and correspondingly ordered dynamic symbol table
304 // entries to deal with dynamic relocations. To handle this problem
305 // relocation-only section in the primary GOT contains entries for all
306 // symbols referenced in global parts of secondary GOTs. Although the sum
307 // of local and normal global entries of the primary got should be less
308 // than 64K, the size of the primary got (including relocation-only entries
309 // can be greater than 64K, because parts of the primary got that overflow
310 // the 64K limit are used only by the dynamic linker at dynamic link-time
311 // and not by 16-bit gp-relative addressing at run-time.
313 // For complete multi-GOT description see the following link
314 // https://dmz-portal.mips.com/wiki/MIPS_Multi_GOT
316 // Number of "Header" entries.
317 static const unsigned headerEntriesNum
= 2;
321 // Symbol and addend.
322 using GotEntry
= std::pair
<Symbol
*, int64_t>;
325 InputFile
*file
= nullptr;
326 size_t startIndex
= 0;
331 PageBlock() : firstIndex(0), count(0) {}
334 // Map output sections referenced by MIPS GOT relocations
335 // to the description (index/count) "page" entries allocated
337 llvm::SmallMapVector
<const OutputSection
*, PageBlock
, 16> pagesMap
;
338 // Maps from Symbol+Addend pair or just Symbol to the GOT entry index.
339 llvm::MapVector
<GotEntry
, size_t> local16
;
340 llvm::MapVector
<GotEntry
, size_t> local32
;
341 llvm::MapVector
<Symbol
*, size_t> global
;
342 llvm::MapVector
<Symbol
*, size_t> relocs
;
343 llvm::MapVector
<Symbol
*, size_t> tls
;
344 // Set of symbols referenced by dynamic TLS relocations.
345 llvm::MapVector
<Symbol
*, size_t> dynTlsSymbols
;
347 // Total number of all entries.
348 size_t getEntriesNum() const;
349 // Number of "page" entries.
350 size_t getPageEntriesNum() const;
351 // Number of entries require 16-bit index to access.
352 size_t getIndexedEntriesNum() const;
355 // Container of GOT created for each input file.
356 // After building a final series of GOTs this container
357 // holds primary and secondary GOT's.
358 std::vector
<FileGot
> gots
;
360 // Return (and create if necessary) `FileGot`.
361 FileGot
&getGot(InputFile
&f
);
363 // Try to merge two GOTs. In case of success the `Dst` contains
364 // result of merging and the function returns true. In case of
365 // overflow the `Dst` is unchanged and the function returns false.
366 bool tryMergeGots(FileGot
& dst
, FileGot
& src
, bool isPrimary
);
369 class GotPltSection final
: public SyntheticSection
{
371 GotPltSection(Ctx
&);
372 void addEntry(Symbol
&sym
);
373 size_t getSize() const override
;
374 void writeTo(uint8_t *buf
) override
;
375 bool isNeeded() const override
;
377 // Flag to force GotPlt to be in output if we have relocations
378 // that relies on its address.
379 std::atomic
<bool> hasGotPltOffRel
= false;
382 SmallVector
<const Symbol
*, 0> entries
;
385 // The IgotPltSection is a Got associated with the PltSection for GNU Ifunc
386 // Symbols that will be relocated by Target->IRelativeRel.
387 // On most Targets the IgotPltSection will immediately follow the GotPltSection
388 // on ARM the IgotPltSection will immediately follow the GotSection.
389 class IgotPltSection final
: public SyntheticSection
{
391 IgotPltSection(Ctx
&);
392 void addEntry(Symbol
&sym
);
393 size_t getSize() const override
;
394 void writeTo(uint8_t *buf
) override
;
395 bool isNeeded() const override
{ return !entries
.empty(); }
398 SmallVector
<const Symbol
*, 0> entries
;
401 class StringTableSection final
: public SyntheticSection
{
403 StringTableSection(Ctx
&, StringRef name
, bool dynamic
);
404 unsigned addString(StringRef s
, bool hashIt
= true);
405 void writeTo(uint8_t *buf
) override
;
406 size_t getSize() const override
{ return size
; }
407 bool isDynamic() const { return dynamic
; }
414 llvm::DenseMap
<llvm::CachedHashStringRef
, unsigned> stringMap
;
415 SmallVector
<StringRef
, 0> strings
;
421 /// The resulting dynamic relocation does not reference a symbol (#sym must
422 /// be nullptr) and uses #addend as the result of computeAddend(ctx).
424 /// The resulting dynamic relocation will not reference a symbol: #sym is
425 /// only used to compute the addend with InputSection::getRelocTargetVA().
426 /// Useful for various relative and TLS relocations (e.g. R_X86_64_TPOFF64).
427 AddendOnlyWithTargetVA
,
428 /// The resulting dynamic relocation references symbol #sym from the dynamic
429 /// symbol table and uses #addend as the value of computeAddend(ctx).
431 /// The resulting dynamic relocation references symbol #sym from the dynamic
432 /// symbol table and uses InputSection::getRelocTargetVA() + #addend for the
433 /// final addend. It can be used for relocations that write the symbol VA as
434 // the addend (e.g. R_MIPS_TLS_TPREL64) but still reference the symbol.
435 AgainstSymbolWithTargetVA
,
436 /// This is used by the MIPS multi-GOT implementation. It relocates
437 /// addresses of 64kb pages that lie inside the output section.
440 /// This constructor records a relocation against a symbol.
441 DynamicReloc(RelType type
, const InputSectionBase
*inputSec
,
442 uint64_t offsetInSec
, Kind kind
, Symbol
&sym
, int64_t addend
,
444 : sym(&sym
), inputSec(inputSec
), offsetInSec(offsetInSec
), type(type
),
445 addend(addend
), kind(kind
), expr(expr
) {}
446 /// This constructor records a relative relocation with no symbol.
447 DynamicReloc(RelType type
, const InputSectionBase
*inputSec
,
448 uint64_t offsetInSec
, int64_t addend
= 0)
449 : sym(nullptr), inputSec(inputSec
), offsetInSec(offsetInSec
), type(type
),
450 addend(addend
), kind(AddendOnly
), expr(R_ADDEND
) {}
451 /// This constructor records dynamic relocation settings used by the MIPS
452 /// multi-GOT implementation.
453 DynamicReloc(RelType type
, const InputSectionBase
*inputSec
,
454 uint64_t offsetInSec
, const OutputSection
*outputSec
,
456 : sym(nullptr), outputSec(outputSec
), inputSec(inputSec
),
457 offsetInSec(offsetInSec
), type(type
), addend(addend
),
458 kind(MipsMultiGotPage
), expr(R_ADDEND
) {}
460 uint64_t getOffset() const;
461 uint32_t getSymIndex(SymbolTableBaseSection
*symTab
) const;
462 bool needsDynSymIndex() const {
463 return kind
== AgainstSymbol
|| kind
== AgainstSymbolWithTargetVA
;
466 /// Computes the addend of the dynamic relocation. Note that this is not the
467 /// same as the #addend member variable as it may also include the symbol
468 /// address/the address of the corresponding GOT entry/etc.
469 int64_t computeAddend(Ctx
&) const;
471 void computeRaw(Ctx
&, SymbolTableBaseSection
*symt
);
474 const OutputSection
*outputSec
= nullptr;
475 const InputSectionBase
*inputSec
;
476 uint64_t offsetInSec
;
480 // Initially input addend, then the output addend after
481 // RelocationSection<ELFT>::writeTo.
486 // The kind of expression used to calculate the added (required e.g. for
487 // relative GOT relocations).
491 template <class ELFT
> class DynamicSection final
: public SyntheticSection
{
492 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT
)
495 DynamicSection(Ctx
&);
496 void finalizeContents() override
;
497 void writeTo(uint8_t *buf
) override
;
498 size_t getSize() const override
{ return size
; }
501 std::vector
<std::pair
<int32_t, uint64_t>> computeContents();
505 class RelocationBaseSection
: public SyntheticSection
{
507 RelocationBaseSection(Ctx
&, StringRef name
, uint32_t type
,
508 int32_t dynamicTag
, int32_t sizeDynamicTag
,
509 bool combreloc
, unsigned concurrency
);
510 /// Add a dynamic relocation without writing an addend to the output section.
511 /// This overload can be used if the addends are written directly instead of
512 /// using relocations on the input section (e.g. MipsGotSection::writeTo()).
513 template <bool shard
= false> void addReloc(const DynamicReloc
&reloc
) {
514 relocs
.push_back(reloc
);
516 /// Add a dynamic relocation against \p sym with an optional addend.
517 void addSymbolReloc(RelType dynType
, InputSectionBase
&isec
,
518 uint64_t offsetInSec
, Symbol
&sym
, int64_t addend
= 0,
519 std::optional
<RelType
> addendRelType
= {});
520 /// Add a relative dynamic relocation that uses the target address of \p sym
521 /// (i.e. InputSection::getRelocTargetVA()) + \p addend as the addend.
522 /// This function should only be called for non-preemptible symbols or
523 /// RelExpr values that refer to an address inside the output file (e.g. the
524 /// address of the GOT entry for a potentially preemptible symbol).
525 template <bool shard
= false>
526 void addRelativeReloc(RelType dynType
, InputSectionBase
&isec
,
527 uint64_t offsetInSec
, Symbol
&sym
, int64_t addend
,
528 RelType addendRelType
, RelExpr expr
) {
529 assert(expr
!= R_ADDEND
&& "expected non-addend relocation expression");
530 addReloc
<shard
>(DynamicReloc::AddendOnlyWithTargetVA
, dynType
, isec
,
531 offsetInSec
, sym
, addend
, expr
, addendRelType
);
533 /// Add a dynamic relocation using the target address of \p sym as the addend
534 /// if \p sym is non-preemptible. Otherwise add a relocation against \p sym.
535 void addAddendOnlyRelocIfNonPreemptible(RelType dynType
,
536 InputSectionBase
&isec
,
537 uint64_t offsetInSec
, Symbol
&sym
,
538 RelType addendRelType
);
539 template <bool shard
= false>
540 void addReloc(DynamicReloc::Kind kind
, RelType dynType
, InputSectionBase
&sec
,
541 uint64_t offsetInSec
, Symbol
&sym
, int64_t addend
, RelExpr expr
,
542 RelType addendRelType
) {
543 // Write the addends to the relocated address if required. We skip
544 // it if the written value would be zero.
545 if (ctx
.arg
.writeAddends
&& (expr
!= R_ADDEND
|| addend
!= 0))
546 sec
.addReloc({expr
, addendRelType
, offsetInSec
, addend
, &sym
});
547 addReloc
<shard
>({dynType
, &sec
, offsetInSec
, kind
, sym
, addend
, expr
});
549 bool isNeeded() const override
{
550 return !relocs
.empty() ||
551 llvm::any_of(relocsVec
, [](auto &v
) { return !v
.empty(); });
553 size_t getSize() const override
{ return relocs
.size() * this->entsize
; }
554 size_t getRelativeRelocCount() const { return numRelativeRelocs
; }
556 void partitionRels();
557 void finalizeContents() override
;
559 int32_t dynamicTag
, sizeDynamicTag
;
560 SmallVector
<DynamicReloc
, 0> relocs
;
564 // Used when parallel relocation scanning adds relocations. The elements
565 // will be moved into relocs by mergeRel().
566 SmallVector
<SmallVector
<DynamicReloc
, 0>, 0> relocsVec
;
567 size_t numRelativeRelocs
= 0; // used by -z combreloc
572 inline void RelocationBaseSection::addReloc
<true>(const DynamicReloc
&reloc
) {
573 relocsVec
[llvm::parallel::getThreadIndex()].push_back(reloc
);
576 template <class ELFT
>
577 class RelocationSection final
: public RelocationBaseSection
{
578 using Elf_Rel
= typename
ELFT::Rel
;
579 using Elf_Rela
= typename
ELFT::Rela
;
582 RelocationSection(Ctx
&, StringRef name
, bool combreloc
,
583 unsigned concurrency
);
584 void writeTo(uint8_t *buf
) override
;
587 template <class ELFT
>
588 class AndroidPackedRelocationSection final
: public RelocationBaseSection
{
589 using Elf_Rel
= typename
ELFT::Rel
;
590 using Elf_Rela
= typename
ELFT::Rela
;
593 AndroidPackedRelocationSection(Ctx
&, StringRef name
, unsigned concurrency
);
595 bool updateAllocSize(Ctx
&) override
;
596 size_t getSize() const override
{ return relocData
.size(); }
597 void writeTo(uint8_t *buf
) override
{
598 memcpy(buf
, relocData
.data(), relocData
.size());
602 SmallVector
<char, 0> relocData
;
605 struct RelativeReloc
{
606 uint64_t getOffset() const {
607 return inputSec
->getVA(inputSec
->relocs()[relocIdx
].offset
);
610 const InputSectionBase
*inputSec
;
614 class RelrBaseSection
: public SyntheticSection
{
616 RelrBaseSection(Ctx
&, unsigned concurrency
, bool isAArch64Auth
= false);
618 bool isNeeded() const override
{
619 return !relocs
.empty() ||
620 llvm::any_of(relocsVec
, [](auto &v
) { return !v
.empty(); });
622 SmallVector
<RelativeReloc
, 0> relocs
;
623 SmallVector
<SmallVector
<RelativeReloc
, 0>, 0> relocsVec
;
626 // RelrSection is used to encode offsets for relative relocations.
627 // Proposal for adding SHT_RELR sections to generic-abi is here:
628 // https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg
629 // For more details, see the comment in RelrSection::updateAllocSize(Ctx &ctx).
630 template <class ELFT
> class RelrSection final
: public RelrBaseSection
{
631 using Elf_Relr
= typename
ELFT::Relr
;
634 RelrSection(Ctx
&, unsigned concurrency
, bool isAArch64Auth
= false);
636 bool updateAllocSize(Ctx
&) override
;
637 size_t getSize() const override
{ return relrRelocs
.size() * this->entsize
; }
638 void writeTo(uint8_t *buf
) override
{
639 memcpy(buf
, relrRelocs
.data(), getSize());
643 SmallVector
<Elf_Relr
, 0> relrRelocs
;
646 struct SymbolTableEntry
{
651 class SymbolTableBaseSection
: public SyntheticSection
{
653 SymbolTableBaseSection(Ctx
&ctx
, StringTableSection
&strTabSec
);
654 void finalizeContents() override
;
655 size_t getSize() const override
{ return getNumSymbols() * entsize
; }
656 void addSymbol(Symbol
*sym
);
657 unsigned getNumSymbols() const { return symbols
.size() + 1; }
658 size_t getSymbolIndex(const Symbol
&sym
);
659 ArrayRef
<SymbolTableEntry
> getSymbols() const { return symbols
; }
662 void sortSymTabSymbols();
664 // A vector of symbols and their string table offsets.
665 SmallVector
<SymbolTableEntry
, 0> symbols
;
667 StringTableSection
&strTabSec
;
669 llvm::once_flag onceFlag
;
670 llvm::DenseMap
<Symbol
*, size_t> symbolIndexMap
;
671 llvm::DenseMap
<OutputSection
*, size_t> sectionIndexMap
;
674 template <class ELFT
>
675 class SymbolTableSection final
: public SymbolTableBaseSection
{
676 using Elf_Sym
= typename
ELFT::Sym
;
679 SymbolTableSection(Ctx
&, StringTableSection
&strTabSec
);
680 void writeTo(uint8_t *buf
) override
;
683 class SymtabShndxSection final
: public SyntheticSection
{
685 SymtabShndxSection(Ctx
&);
687 void writeTo(uint8_t *buf
) override
;
688 size_t getSize() const override
;
689 bool isNeeded() const override
;
690 void finalizeContents() override
;
693 // Outputs GNU Hash section. For detailed explanation see:
694 // https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections
695 class GnuHashTableSection final
: public SyntheticSection
{
697 GnuHashTableSection(Ctx
&);
698 void finalizeContents() override
;
699 void writeTo(uint8_t *buf
) override
;
700 size_t getSize() const override
{ return size
; }
702 // Adds symbols to the hash table.
703 // Sorts the input to satisfy GNU hash section requirements.
704 void addSymbols(llvm::SmallVectorImpl
<SymbolTableEntry
> &symbols
);
707 // See the comment in writeBloomFilter.
708 enum { Shift2
= 26 };
717 SmallVector
<Entry
, 0> symbols
;
723 class HashTableSection final
: public SyntheticSection
{
725 HashTableSection(Ctx
&);
726 void finalizeContents() override
;
727 void writeTo(uint8_t *buf
) override
;
728 size_t getSize() const override
{ return size
; }
734 // Used for PLT entries. It usually has a PLT header for lazy binding. Each PLT
735 // entry is associated with a JUMP_SLOT relocation, which may be resolved lazily
738 // On PowerPC, this section contains lazy symbol resolvers. A branch instruction
739 // jumps to a PLT call stub, which will then jump to the target (BIND_NOW) or a
740 // lazy symbol resolver.
742 // On x86 when IBT is enabled, this section (.plt.sec) contains PLT call stubs.
743 // A call instruction jumps to a .plt.sec entry, which will then jump to the
744 // target (BIND_NOW) or a .plt entry.
745 class PltSection
: public SyntheticSection
{
748 void writeTo(uint8_t *buf
) override
;
749 size_t getSize() const override
;
750 bool isNeeded() const override
;
752 void addEntry(Symbol
&sym
);
753 size_t getNumEntries() const { return entries
.size(); }
757 SmallVector
<const Symbol
*, 0> entries
;
760 // Used for non-preemptible ifuncs. It does not have a header. Each entry is
761 // associated with an IRELATIVE relocation, which will be resolved eagerly at
762 // runtime. PltSection can only contain entries associated with JUMP_SLOT
763 // relocations, so IPLT entries are in a separate section.
764 class IpltSection final
: public SyntheticSection
{
765 SmallVector
<const Symbol
*, 0> entries
;
769 void writeTo(uint8_t *buf
) override
;
770 size_t getSize() const override
;
771 bool isNeeded() const override
{ return !entries
.empty(); }
773 void addEntry(Symbol
&sym
);
776 class PPC32GlinkSection
: public PltSection
{
778 PPC32GlinkSection(Ctx
&);
779 void writeTo(uint8_t *buf
) override
;
780 size_t getSize() const override
;
782 SmallVector
<const Symbol
*, 0> canonical_plts
;
783 static constexpr size_t footerSize
= 64;
787 class IBTPltSection
: public SyntheticSection
{
789 IBTPltSection(Ctx
&);
790 void writeTo(uint8_t *Buf
) override
;
791 bool isNeeded() const override
;
792 size_t getSize() const override
;
795 // Used to align the end of the PT_GNU_RELRO segment and the associated PT_LOAD
796 // segment to a common-page-size boundary. This padding section ensures that all
797 // pages in the PT_LOAD segment is covered by at least one section.
798 class RelroPaddingSection final
: public SyntheticSection
{
800 RelroPaddingSection(Ctx
&);
801 size_t getSize() const override
{ return 0; }
802 void writeTo(uint8_t *buf
) override
{}
805 class RandomizePaddingSection final
: public SyntheticSection
{
809 RandomizePaddingSection(Ctx
&ctx
, uint64_t size
, OutputSection
*parent
);
810 size_t getSize() const override
{ return size
; }
811 void writeTo(uint8_t *buf
) override
;
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.
816 class DebugNamesBaseSection
: public SyntheticSection
{
818 struct Abbrev
: llvm::FoldingSetNode
{
821 SmallVector
<llvm::DWARFDebugNames::AttributeEncoding
, 2> attributes
;
823 void Profile(llvm::FoldingSetNodeID
&id
) const;
835 uint64_t parentOffset
= 0;
836 IndexEntry
*parentEntry
;
838 SmallVector
<AttrValue
, 3> attrValues
;
844 uint32_t stringOffset
;
845 uint32_t entryOffset
;
846 // Used to relocate `stringOffset` in the merged section.
848 SmallVector
<IndexEntry
*, 0> indexEntries
;
850 llvm::iterator_range
<
851 llvm::pointee_iterator
<typename SmallVector
<IndexEntry
*, 0>::iterator
>>
853 return llvm::make_pointee_range(indexEntries
);
857 // The contents of one input .debug_names section. An InputChunk
858 // typically contains one NameData, but might contain more, especially
861 llvm::DWARFDebugNames::Header hdr
;
862 llvm::DenseMap
<uint32_t, uint32_t> abbrevCodeMap
;
863 SmallVector
<NameEntry
, 0> nameEntries
;
866 // InputChunk and OutputChunk hold per-file contributions to the merged index.
867 // InputChunk instances will be discarded after `init` completes.
870 LLDDWARFSection section
;
871 SmallVector
<NameData
, 0> nameData
;
872 std::optional
<llvm::DWARFDebugNames
> llvmDebugNames
;
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
;
884 DebugNamesBaseSection(Ctx
&);
885 size_t getSize() const override
{ return size
; }
886 bool isNeeded() const override
{ return numChunks
> 0; }
889 void init(llvm::function_ref
<void(InputFile
*, InputChunk
&, OutputChunk
&)>);
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
&)>
898 void computeHdrAndAbbrevTable(MutableArrayRef
<InputChunk
> inputChunks
);
899 std::pair
<uint32_t, uint32_t>
900 computeEntryPool(MutableArrayRef
<InputChunk
> inputChunks
);
902 // Input .debug_names sections for relocating string offsets in the name table
903 // in `finalizeContents`.
904 SmallVector
<InputSection
*, 0> inputSections
;
906 llvm::DWARFDebugNames::Header hdr
;
908 std::unique_ptr
<OutputChunk
[]> chunks
;
909 llvm::SpecificBumpPtrAllocator
<Abbrev
> abbrevAlloc
;
910 SmallVector
<Abbrev
*, 0> abbrevTable
;
911 SmallVector
<char, 0> abbrevTableBuf
;
913 ArrayRef
<OutputChunk
> getChunks() const {
914 return ArrayRef(chunks
.get(), numChunks
);
917 // Sharded name entries that will be used to compute bucket_count and the
919 static constexpr size_t numShards
= 32;
920 SmallVector
<NameEntry
, 0> nameVecs
[numShards
];
923 // Complement DebugNamesBaseSection for ELFT-aware code: reading offsets,
924 // relocating string offsets, and writeTo.
925 template <class ELFT
>
926 class DebugNamesSection final
: public DebugNamesBaseSection
{
928 DebugNamesSection(Ctx
&);
929 void finalizeContents() override
;
930 void writeTo(uint8_t *buf
) override
;
932 template <class RelTy
>
933 void getNameRelocs(const InputFile
&file
,
934 llvm::DenseMap
<uint32_t, uint32_t> &relocs
,
938 static void readOffsets(InputChunk
&inputChunk
, OutputChunk
&chunk
,
939 llvm::DWARFDataExtractor
&namesExtractor
,
940 llvm::DataExtractor
&strExtractor
);
943 class GdbIndexSection final
: public SyntheticSection
{
945 struct AddressEntry
{
946 InputSection
*section
;
948 uint64_t highAddress
;
957 struct NameAttrEntry
{
958 llvm::CachedHashStringRef name
;
959 uint32_t cuIndexAndAttrs
;
964 SmallVector
<AddressEntry
, 0> addressAreas
;
965 SmallVector
<CuEntry
, 0> compilationUnits
;
969 llvm::CachedHashStringRef name
;
970 SmallVector
<uint32_t, 0> cuVector
;
972 uint32_t cuVectorOff
;
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
;
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
;
992 size_t computeSymtabSize() const;
994 // Each chunk contains information gathered from debug sections of a
995 // single object file.
996 SmallVector
<GdbChunk
, 0> chunks
;
998 // A symbol table for this .gdb_index section.
999 SmallVector
<GdbSymbol
, 0> symbols
;
1004 // --eh-frame-hdr option tells linker to construct a header for all the
1005 // .eh_frame sections. This header is placed to a section named .eh_frame_hdr
1006 // and also to a PT_GNU_EH_FRAME segment.
1007 // At runtime the unwinder then can find all the PT_GNU_EH_FRAME segments by
1008 // calling dl_iterate_phdr.
1009 // This section contains a lookup table for quick binary search of FDEs.
1010 // Detailed info about internals can be found in Ian Lance Taylor's blog:
1011 // http://www.airs.com/blog/archives/460 (".eh_frame")
1012 // http://www.airs.com/blog/archives/462 (".eh_frame_hdr")
1013 class EhFrameHeader final
: public SyntheticSection
{
1015 EhFrameHeader(Ctx
&);
1017 void writeTo(uint8_t *buf
) override
;
1018 size_t getSize() const override
;
1019 bool isNeeded() const override
;
1022 // For more information about .gnu.version and .gnu.version_r see:
1023 // https://www.akkadia.org/drepper/symbol-versioning
1025 // The .gnu.version_d section which has a section type of SHT_GNU_verdef shall
1026 // contain symbol version definitions. The number of entries in this section
1027 // shall be contained in the DT_VERDEFNUM entry of the .dynamic section.
1028 // The section shall contain an array of Elf_Verdef structures, optionally
1029 // followed by an array of Elf_Verdaux structures.
1030 class VersionDefinitionSection final
: public SyntheticSection
{
1032 VersionDefinitionSection(Ctx
&);
1033 void finalizeContents() override
;
1034 size_t getSize() const override
;
1035 void writeTo(uint8_t *buf
) override
;
1038 enum { EntrySize
= 28 };
1039 void writeOne(uint8_t *buf
, uint32_t index
, StringRef name
, size_t nameOff
);
1040 StringRef
getFileDefName();
1042 unsigned fileDefNameOff
;
1043 SmallVector
<unsigned, 0> verDefNameOffs
;
1046 // The .gnu.version section specifies the required version of each symbol in the
1047 // dynamic symbol table. It contains one Elf_Versym for each dynamic symbol
1048 // table entry. An Elf_Versym is just a 16-bit integer that refers to a version
1049 // identifier defined in the either .gnu.version_r or .gnu.version_d section.
1050 // The values 0 and 1 are reserved. All other values are used for versions in
1051 // the own object or in any of the dependencies.
1052 class VersionTableSection final
: public SyntheticSection
{
1054 VersionTableSection(Ctx
&);
1055 void finalizeContents() override
;
1056 size_t getSize() const override
;
1057 void writeTo(uint8_t *buf
) override
;
1058 bool isNeeded() const override
;
1061 // The .gnu.version_r section defines the version identifiers used by
1062 // .gnu.version. It contains a linked list of Elf_Verneed data structures. Each
1063 // Elf_Verneed specifies the version requirements for a single DSO, and contains
1064 // a reference to a linked list of Elf_Vernaux data structures which define the
1065 // mapping from version identifiers to version names.
1066 template <class ELFT
>
1067 class VersionNeedSection final
: public SyntheticSection
{
1068 using Elf_Verneed
= typename
ELFT::Verneed
;
1069 using Elf_Vernaux
= typename
ELFT::Vernaux
;
1073 uint32_t verneedIndex
;
1074 uint64_t nameStrTab
;
1078 uint64_t nameStrTab
;
1079 std::vector
<Vernaux
> vernauxs
;
1082 SmallVector
<Verneed
, 0> verneeds
;
1085 VersionNeedSection(Ctx
&);
1086 void finalizeContents() override
;
1087 void writeTo(uint8_t *buf
) override
;
1088 size_t getSize() const override
;
1089 bool isNeeded() const override
;
1092 // MergeSyntheticSection is a class that allows us to put mergeable sections
1093 // with different attributes in a single output sections. To do that
1094 // we put them into MergeSyntheticSection synthetic input sections which are
1095 // attached to regular output sections.
1096 class MergeSyntheticSection
: public SyntheticSection
{
1098 void addSection(MergeInputSection
*ms
);
1099 SmallVector
<MergeInputSection
*, 0> sections
;
1102 MergeSyntheticSection(Ctx
&ctx
, StringRef name
, uint32_t type
, uint64_t flags
,
1104 : SyntheticSection(ctx
, name
, type
, flags
, addralign
) {}
1107 class MergeTailSection final
: public MergeSyntheticSection
{
1109 MergeTailSection(Ctx
&ctx
, StringRef name
, uint32_t type
, uint64_t flags
,
1110 uint32_t addralign
);
1112 size_t getSize() const override
;
1113 void writeTo(uint8_t *buf
) override
;
1114 void finalizeContents() override
;
1117 llvm::StringTableBuilder builder
;
1120 class MergeNoTailSection final
: public MergeSyntheticSection
{
1122 MergeNoTailSection(Ctx
&ctx
, StringRef name
, uint32_t type
, uint64_t flags
,
1124 : MergeSyntheticSection(ctx
, name
, type
, flags
, addralign
) {}
1126 size_t getSize() const override
{ return size
; }
1127 void writeTo(uint8_t *buf
) override
;
1128 void finalizeContents() override
;
1131 // We use the most significant bits of a hash as a shard ID.
1132 // The reason why we don't want to use the least significant bits is
1133 // because DenseMap also uses lower bits to determine a bucket ID.
1134 // If we use lower bits, it significantly increases the probability of
1136 size_t getShardId(uint32_t hash
) {
1137 assert((hash
>> 31) == 0);
1138 return hash
>> (31 - llvm::countr_zero(numShards
));
1144 // String table contents
1145 constexpr static size_t numShards
= 32;
1146 SmallVector
<llvm::StringTableBuilder
, 0> shards
;
1147 size_t shardOffsets
[numShards
];
1150 // .MIPS.abiflags section.
1151 template <class ELFT
>
1152 class MipsAbiFlagsSection final
: public SyntheticSection
{
1153 using Elf_Mips_ABIFlags
= llvm::object::Elf_Mips_ABIFlags
<ELFT
>;
1156 static std::unique_ptr
<MipsAbiFlagsSection
> create(Ctx
&);
1158 MipsAbiFlagsSection(Ctx
&, Elf_Mips_ABIFlags flags
);
1159 size_t getSize() const override
{ return sizeof(Elf_Mips_ABIFlags
); }
1160 void writeTo(uint8_t *buf
) override
;
1163 Elf_Mips_ABIFlags flags
;
1166 // .MIPS.options section.
1167 template <class ELFT
> class MipsOptionsSection final
: public SyntheticSection
{
1168 using Elf_Mips_Options
= llvm::object::Elf_Mips_Options
<ELFT
>;
1169 using Elf_Mips_RegInfo
= llvm::object::Elf_Mips_RegInfo
<ELFT
>;
1172 static std::unique_ptr
<MipsOptionsSection
<ELFT
>> create(Ctx
&);
1174 MipsOptionsSection(Ctx
&, Elf_Mips_RegInfo reginfo
);
1175 void writeTo(uint8_t *buf
) override
;
1177 size_t getSize() const override
{
1178 return sizeof(Elf_Mips_Options
) + sizeof(Elf_Mips_RegInfo
);
1182 Elf_Mips_RegInfo reginfo
;
1185 // MIPS .reginfo section.
1186 template <class ELFT
> class MipsReginfoSection final
: public SyntheticSection
{
1187 using Elf_Mips_RegInfo
= llvm::object::Elf_Mips_RegInfo
<ELFT
>;
1190 static std::unique_ptr
<MipsReginfoSection
> create(Ctx
&);
1192 MipsReginfoSection(Ctx
&, Elf_Mips_RegInfo reginfo
);
1193 size_t getSize() const override
{ return sizeof(Elf_Mips_RegInfo
); }
1194 void writeTo(uint8_t *buf
) override
;
1197 Elf_Mips_RegInfo reginfo
;
1200 // This is a MIPS specific section to hold a space within the data segment
1201 // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
1202 // See "Dynamic section" in Chapter 5 in the following document:
1203 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1204 class MipsRldMapSection final
: public SyntheticSection
{
1206 MipsRldMapSection(Ctx
&);
1207 size_t getSize() const override
{ return ctx
.arg
.wordsize
; }
1208 void writeTo(uint8_t *buf
) override
{}
1211 // Representation of the combined .ARM.Exidx input sections. We process these
1212 // as a SyntheticSection like .eh_frame as we need to merge duplicate entries
1213 // and add terminating sentinel entries.
1215 // The .ARM.exidx input sections after SHF_LINK_ORDER processing is done form
1216 // a table that the unwinder can derive (Addresses are encoded as offsets from
1218 // | Address of function | Unwind instructions for function |
1219 // where the unwind instructions are either a small number of unwind or the
1220 // special EXIDX_CANTUNWIND entry representing no unwinding information.
1221 // When an exception is thrown from an address A, the unwinder searches the
1222 // table for the closest table entry with Address of function <= A. This means
1223 // that for two consecutive table entries:
1226 // The range of addresses described by U1 is [A1, A2)
1228 // There are two cases where we need a linker generated table entry to fixup
1229 // the address ranges in the table
1231 // - A sentinel entry added with an address higher than all
1232 // executable sections. This was needed to work around libunwind bug pr31091.
1233 // - After address assignment we need to find the highest addressed executable
1234 // section and use the limit of that section so that the unwinder never
1237 // - InputSections without a .ARM.exidx section (usually from Assembly)
1238 // need a table entry so that they terminate the range of the previously
1239 // function. This is pr40277.
1241 // Instead of storing pointers to the .ARM.exidx InputSections from
1242 // InputObjects, we store pointers to the executable sections that need
1243 // .ARM.exidx sections. We can then use the dependentSections of these to
1244 // either find the .ARM.exidx section or know that we need to generate one.
1245 class ARMExidxSyntheticSection
: public SyntheticSection
{
1247 ARMExidxSyntheticSection(Ctx
&);
1249 // Add an input section to the ARMExidxSyntheticSection. Returns whether the
1250 // section needs to be removed from the main input section list.
1251 bool addSection(InputSection
*isec
);
1253 size_t getSize() const override
{ return size
; }
1254 void writeTo(uint8_t *buf
) override
;
1255 bool isNeeded() const override
;
1256 // Sort and remove duplicate entries.
1257 void finalizeContents() override
;
1258 InputSection
*getLinkOrderDep() const;
1260 static bool classof(const SectionBase
*sec
) {
1261 return sec
->kind() == InputSectionBase::Synthetic
&&
1262 sec
->type
== llvm::ELF::SHT_ARM_EXIDX
;
1265 // Links to the ARMExidxSections so we can transfer the relocations once the
1267 SmallVector
<InputSection
*, 0> exidxSections
;
1272 // Instead of storing pointers to the .ARM.exidx InputSections from
1273 // InputObjects, we store pointers to the executable sections that need
1274 // .ARM.exidx sections. We can then use the dependentSections of these to
1275 // either find the .ARM.exidx section or know that we need to generate one.
1276 SmallVector
<InputSection
*, 0> executableSections
;
1278 // Value of executableSecitons before finalizeContents(), so that it can be
1279 // run repeateadly during fixed point iteration.
1280 SmallVector
<InputSection
*, 0> originalExecutableSections
;
1282 // The executable InputSection with the highest address to use for the
1283 // sentinel. We store separately from ExecutableSections as merging of
1284 // duplicate entries may mean this InputSection is removed from
1285 // ExecutableSections.
1286 InputSection
*sentinel
= nullptr;
1289 // A container for one or more linker generated thunks. Instances of these
1290 // thunks including ARM interworking and Mips LA25 PI to non-PI thunks.
1291 class ThunkSection final
: public SyntheticSection
{
1293 // ThunkSection in OS, with desired outSecOff of Off
1294 ThunkSection(Ctx
&, OutputSection
*os
, uint64_t off
);
1296 // Add a newly created Thunk to this container:
1297 // Thunk is given offset from start of this InputSection
1298 // Thunk defines a symbol in this InputSection that can be used as target
1300 void addThunk(Thunk
*t
);
1301 size_t getSize() const override
;
1302 void writeTo(uint8_t *buf
) override
;
1303 InputSection
*getTargetInputSection() const;
1304 bool assignOffsets();
1306 // When true, round up reported size of section to 4 KiB. See comment
1307 // in addThunkSection() for more details.
1308 bool roundUpSizeForErrata
= false;
1311 SmallVector
<Thunk
*, 0> thunks
;
1315 // Cortex-M Security Extensions. Prefix for functions that should be exported
1316 // for the non-secure world.
1317 const char ACLESESYM_PREFIX
[] = "__acle_se_";
1318 const int ACLESESYM_SIZE
= 8;
1320 class ArmCmseSGVeneer
{
1322 ArmCmseSGVeneer(Symbol
*sym
, Symbol
*acleSeSym
,
1323 std::optional
<uint64_t> addr
= std::nullopt
)
1324 : sym(sym
), acleSeSym(acleSeSym
), entAddr
{addr
} {}
1325 static const size_t size
{ACLESESYM_SIZE
};
1326 const std::optional
<uint64_t> getAddr() const { return entAddr
; };
1330 uint64_t offset
= 0;
1333 const std::optional
<uint64_t> entAddr
;
1336 class ArmCmseSGSection final
: public SyntheticSection
{
1338 ArmCmseSGSection(Ctx
&ctx
);
1339 bool isNeeded() const override
{ return !entries
.empty(); }
1340 size_t getSize() const override
;
1341 void writeTo(uint8_t *buf
) override
;
1342 void addSGVeneer(Symbol
*sym
, Symbol
*ext_sym
);
1343 void addMappingSymbol();
1344 void finalizeContents() override
;
1345 void exportEntries(SymbolTableBaseSection
*symTab
);
1346 uint64_t impLibMaxAddr
= 0;
1349 SmallVector
<std::pair
<Symbol
*, Symbol
*>, 0> entries
;
1350 SmallVector
<std::unique_ptr
<ArmCmseSGVeneer
>, 0> sgVeneers
;
1351 uint64_t newEntries
= 0;
1354 // Used to compute outSecOff of .got2 in each object file. This is needed to
1355 // synthesize PLT entries for PPC32 Secure PLT ABI.
1356 class PPC32Got2Section final
: public SyntheticSection
{
1358 PPC32Got2Section(Ctx
&);
1359 size_t getSize() const override
{ return 0; }
1360 bool isNeeded() const override
;
1361 void finalizeContents() override
;
1362 void writeTo(uint8_t *buf
) override
{}
1365 // This section is used to store the addresses of functions that are called
1366 // in range-extending thunks on PowerPC64. When producing position dependent
1367 // code the addresses are link-time constants and the table is written out to
1368 // the binary. When producing position-dependent code the table is allocated and
1369 // filled in by the dynamic linker.
1370 class PPC64LongBranchTargetSection final
: public SyntheticSection
{
1372 PPC64LongBranchTargetSection(Ctx
&);
1373 uint64_t getEntryVA(const Symbol
*sym
, int64_t addend
);
1374 std::optional
<uint32_t> addEntry(const Symbol
*sym
, int64_t addend
);
1375 size_t getSize() const override
;
1376 void writeTo(uint8_t *buf
) override
;
1377 bool isNeeded() const override
;
1378 void finalizeContents() override
{ finalized
= true; }
1381 SmallVector
<std::pair
<const Symbol
*, int64_t>, 0> entries
;
1382 llvm::DenseMap
<std::pair
<const Symbol
*, int64_t>, uint32_t> entry_index
;
1383 bool finalized
= false;
1386 template <typename ELFT
>
1387 class PartitionElfHeaderSection final
: public SyntheticSection
{
1389 PartitionElfHeaderSection(Ctx
&);
1390 size_t getSize() const override
;
1391 void writeTo(uint8_t *buf
) override
;
1394 template <typename ELFT
>
1395 class PartitionProgramHeadersSection final
: public SyntheticSection
{
1397 PartitionProgramHeadersSection(Ctx
&);
1398 size_t getSize() const override
;
1399 void writeTo(uint8_t *buf
) override
;
1402 class PartitionIndexSection final
: public SyntheticSection
{
1404 PartitionIndexSection(Ctx
&);
1405 size_t getSize() const override
;
1406 void finalizeContents() override
;
1407 void writeTo(uint8_t *buf
) override
;
1410 // See the following link for the Android-specific loader code that operates on
1412 // https://cs.android.com/android/platform/superproject/+/master:bionic/libc/bionic/libc_init_static.cpp;drc=9425b16978f9c5aa8f2c50c873db470819480d1d;l=192
1413 class MemtagAndroidNote final
: public SyntheticSection
{
1415 MemtagAndroidNote(Ctx
&ctx
)
1416 : SyntheticSection(ctx
, ".note.android.memtag", llvm::ELF::SHT_NOTE
,
1417 llvm::ELF::SHF_ALLOC
, /*addralign=*/4) {}
1418 void writeTo(uint8_t *buf
) override
;
1419 size_t getSize() const override
;
1422 class PackageMetadataNote final
: public SyntheticSection
{
1424 PackageMetadataNote(Ctx
&ctx
)
1425 : SyntheticSection(ctx
, ".note.package", llvm::ELF::SHT_NOTE
,
1426 llvm::ELF::SHF_ALLOC
, /*addralign=*/4) {}
1427 void writeTo(uint8_t *buf
) override
;
1428 size_t getSize() const override
;
1431 class MemtagGlobalDescriptors final
: public SyntheticSection
{
1433 MemtagGlobalDescriptors(Ctx
&ctx
)
1434 : SyntheticSection(ctx
, ".memtag.globals.dynamic",
1435 llvm::ELF::SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC
,
1436 llvm::ELF::SHF_ALLOC
, /*addralign=*/4) {}
1437 void writeTo(uint8_t *buf
) override
;
1438 // The size of the section is non-computable until all addresses are
1439 // synthetized, because the section's contents contain a sorted
1440 // varint-compressed list of pointers to global variables. We only know the
1441 // final size after `finalizeAddressDependentContent()`.
1442 size_t getSize() const override
;
1443 bool updateAllocSize(Ctx
&) override
;
1445 void addSymbol(const Symbol
&sym
) {
1446 symbols
.push_back(&sym
);
1449 bool isNeeded() const override
{ return !symbols
.empty(); }
1452 SmallVector
<const Symbol
*, 0> symbols
;
1455 template <class ELFT
> void createSyntheticSections(Ctx
&);
1456 InputSection
*createInterpSection(Ctx
&);
1457 MergeInputSection
*createCommentSection(Ctx
&);
1458 template <class ELFT
> void splitSections(Ctx
&);
1459 void combineEhSections(Ctx
&);
1461 bool hasMemtag(Ctx
&);
1462 bool canHaveMemtagGlobals(Ctx
&);
1464 template <typename ELFT
> void writeEhdr(Ctx
&, uint8_t *buf
, Partition
&part
);
1465 template <typename ELFT
> void writePhdrs(uint8_t *buf
, Partition
&part
);
1467 Defined
*addSyntheticLocal(Ctx
&ctx
, StringRef name
, uint8_t type
,
1468 uint64_t value
, uint64_t size
,
1469 InputSectionBase
§ion
);
1471 void addVerneed(Ctx
&, Symbol
&ss
);
1473 // This describes a program header entry.
1474 // Each contains type, access flags and range of output sections that will be
1477 PhdrEntry(Ctx
&ctx
, unsigned type
, unsigned flags
)
1478 : p_align(type
== llvm::ELF::PT_LOAD
? ctx
.arg
.maxPageSize
: 0),
1479 p_type(type
), p_flags(flags
) {}
1480 void add(OutputSection
*sec
);
1482 uint64_t p_paddr
= 0;
1483 uint64_t p_vaddr
= 0;
1484 uint64_t p_memsz
= 0;
1485 uint64_t p_filesz
= 0;
1486 uint64_t p_offset
= 0;
1487 uint32_t p_align
= 0;
1488 uint32_t p_type
= 0;
1489 uint32_t p_flags
= 0;
1491 OutputSection
*firstSec
= nullptr;
1492 OutputSection
*lastSec
= nullptr;
1493 bool hasLMA
= false;
1495 uint64_t lmaOffset
= 0;
1498 // Linker generated per-partition sections.
1502 uint64_t nameStrTab
;
1504 std::unique_ptr
<SyntheticSection
> elfHeader
;
1505 std::unique_ptr
<SyntheticSection
> programHeaders
;
1506 SmallVector
<std::unique_ptr
<PhdrEntry
>, 0> phdrs
;
1508 std::unique_ptr
<ARMExidxSyntheticSection
> armExidx
;
1509 std::unique_ptr
<BuildIdSection
> buildId
;
1510 std::unique_ptr
<SyntheticSection
> dynamic
;
1511 std::unique_ptr
<StringTableSection
> dynStrTab
;
1512 std::unique_ptr
<SymbolTableBaseSection
> dynSymTab
;
1513 std::unique_ptr
<EhFrameHeader
> ehFrameHdr
;
1514 std::unique_ptr
<EhFrameSection
> ehFrame
;
1515 std::unique_ptr
<GnuHashTableSection
> gnuHashTab
;
1516 std::unique_ptr
<HashTableSection
> hashTab
;
1517 std::unique_ptr
<MemtagAndroidNote
> memtagAndroidNote
;
1518 std::unique_ptr
<MemtagGlobalDescriptors
> memtagGlobalDescriptors
;
1519 std::unique_ptr
<PackageMetadataNote
> packageMetadataNote
;
1520 std::unique_ptr
<RelocationBaseSection
> relaDyn
;
1521 std::unique_ptr
<RelrBaseSection
> relrDyn
;
1522 std::unique_ptr
<RelrBaseSection
> relrAuthDyn
;
1523 std::unique_ptr
<VersionDefinitionSection
> verDef
;
1524 std::unique_ptr
<SyntheticSection
> verNeed
;
1525 std::unique_ptr
<VersionTableSection
> verSym
;
1527 Partition(Ctx
&ctx
) : ctx(ctx
) {}
1528 unsigned getNumber(Ctx
&ctx
) const { return this - &ctx
.partitions
[0] + 1; }
1531 inline Partition
&SectionBase::getPartition(Ctx
&ctx
) const {
1533 return ctx
.partitions
[partition
- 1];
1536 } // namespace lld::elf