1 //===- InputSection.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 #ifndef LLD_ELF_INPUT_SECTION_H
10 #define LLD_ELF_INPUT_SECTION_H
13 #include "Relocations.h"
14 #include "lld/Common/CommonLinkerContext.h"
15 #include "lld/Common/LLVM.h"
16 #include "lld/Common/Memory.h"
17 #include "llvm/ADT/CachedHashString.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/TinyPtrVector.h"
21 #include "llvm/Object/ELF.h"
22 #include "llvm/Support/Compiler.h"
32 class SyntheticSection
;
33 template <class ELFT
> class ObjFile
;
36 // Returned by InputSectionBase::relsOrRelas. At most one member is empty.
37 template <class ELFT
> struct RelsOrRelas
{
38 Relocs
<typename
ELFT::Rel
> rels
;
39 Relocs
<typename
ELFT::Rela
> relas
;
40 Relocs
<typename
ELFT::Crel
> crels
;
41 bool areRelocsRel() const { return rels
.size(); }
42 bool areRelocsCrel() const { return crels
.size(); }
45 #define invokeOnRelocs(sec, f, ...) \
47 const RelsOrRelas<ELFT> rs = (sec).template relsOrRelas<ELFT>(); \
48 if (rs.areRelocsCrel()) \
49 f(__VA_ARGS__, rs.crels); \
50 else if (rs.areRelocsRel()) \
51 f(__VA_ARGS__, rs.rels); \
53 f(__VA_ARGS__, rs.relas); \
56 // This is the base class of all sections that lld handles. Some are sections in
57 // input files, some are sections in the produced output file and some exist
58 // just as a convenience for implementing special ways of combining some
62 enum Kind
{ Regular
, Synthetic
, Spill
, EHFrame
, Merge
, Output
, Class
};
64 Kind
kind() const { return (Kind
)sectionKind
; }
66 LLVM_PREFERRED_TYPE(Kind
)
67 uint8_t sectionKind
: 3;
69 // The next two bit fields are only used by InputSectionBase, but we
70 // put them here so the struct packs better.
72 LLVM_PREFERRED_TYPE(bool)
75 // Set for sections that should not be folded by ICF.
76 LLVM_PREFERRED_TYPE(bool)
77 uint8_t keepUnique
: 1;
79 uint8_t partition
= 1;
82 // The file which contains this section. For InputSectionBase, its dynamic
83 // type is usually ObjFile<ELFT>, but may be an InputFile of InternalKind
84 // (for a synthetic section).
89 // The 1-indexed partition that this section is assigned to by the garbage
90 // collector, or 0 if this section is dead. Normally there is only one
91 // partition, so this will either be 0 or 1.
92 elf::Partition
&getPartition(Ctx
&) const;
94 // These corresponds to the fields in Elf_Shdr.
102 OutputSection
*getOutputSection();
103 const OutputSection
*getOutputSection() const {
104 return const_cast<SectionBase
*>(this)->getOutputSection();
107 // Translate an offset in the input section to an offset in the output
109 uint64_t getOffset(uint64_t offset
) const;
111 uint64_t getVA(uint64_t offset
= 0) const;
113 bool isLive() const { return partition
!= 0; }
114 void markLive() { partition
= 1; }
115 void markDead() { partition
= 0; }
118 constexpr SectionBase(Kind sectionKind
, InputFile
*file
, StringRef name
,
119 uint64_t flags
, uint32_t entsize
, uint32_t addralign
,
120 uint32_t type
, uint32_t info
, uint32_t link
)
121 : sectionKind(sectionKind
), bss(false), keepUnique(false), type(type
),
122 file(file
), name(name
), flags(flags
), addralign(addralign
),
123 entsize(entsize
), link(link
), info(info
) {}
126 struct SymbolAnchor
{
129 bool end
; // true for the anchor of st_value+st_size
133 // This records symbol start and end offsets which will be adjusted according
134 // to the nearest relocDeltas element.
135 SmallVector
<SymbolAnchor
, 0> anchors
;
136 // For relocations[i], the actual offset is
137 // r_offset - (i ? relocDeltas[i-1] : 0).
138 std::unique_ptr
<uint32_t[]> relocDeltas
;
139 // For relocations[i], the actual type is relocTypes[i].
140 std::unique_ptr
<RelType
[]> relocTypes
;
141 SmallVector
<uint32_t, 0> writes
;
144 // This corresponds to a section of an input file.
145 class InputSectionBase
: public SectionBase
{
147 template <class ELFT
>
148 InputSectionBase(ObjFile
<ELFT
> &file
, const typename
ELFT::Shdr
&header
,
149 StringRef name
, Kind sectionKind
);
151 InputSectionBase(InputFile
*file
, uint64_t flags
, uint32_t type
,
152 uint64_t entsize
, uint32_t link
, uint32_t info
,
153 uint32_t addralign
, ArrayRef
<uint8_t> data
, StringRef name
,
156 static bool classof(const SectionBase
*s
) {
157 return s
->kind() != Output
&& s
->kind() != Class
;
160 // Input sections are part of an output section. Special sections
161 // like .eh_frame and merge sections are first combined into a
162 // synthetic section that is then added to an output section. In all
163 // cases this points one level up.
164 SectionBase
*parent
= nullptr;
166 // Section index of the relocation section if exists.
167 uint32_t relSecIdx
= 0;
169 // Getter when the dynamic type is ObjFile<ELFT>.
170 template <class ELFT
> ObjFile
<ELFT
> *getFile() const {
171 return cast
<ObjFile
<ELFT
>>(file
);
174 // Used by --optimize-bb-jumps and RISC-V linker relaxation temporarily to
175 // indicate the number of bytes which is not counted in the size. This should
176 // be reset to zero after uses.
177 uint32_t bytesDropped
= 0;
179 mutable bool compressed
= false;
181 // Whether this section is SHT_CREL and has been decoded to RELA by
183 bool decodedCrel
= false;
185 // Whether the section needs to be padded with a NOP filler due to
186 // deleteFallThruJmpInsn.
187 bool nopFiller
= false;
189 void drop_back(unsigned num
) {
190 assert(bytesDropped
+ num
< 256);
194 void push_back(uint64_t num
) {
195 assert(bytesDropped
>= num
);
199 mutable const uint8_t *content_
;
204 size
-= bytesDropped
;
209 ArrayRef
<uint8_t> content() const {
210 return ArrayRef
<uint8_t>(content_
, size
);
212 ArrayRef
<uint8_t> contentMaybeDecompress() const {
218 // The next member in the section group if this section is in a group. This is
219 // used by --gc-sections.
220 InputSectionBase
*nextInSectionGroup
= nullptr;
222 template <class ELFT
>
223 RelsOrRelas
<ELFT
> relsOrRelas(bool supportsCrel
= true) const;
225 // InputSections that are dependent on us (reverse dependency for GC)
226 llvm::TinyPtrVector
<InputSection
*> dependentSections
;
228 // Returns the size of this section (even if this is a common or BSS.)
229 size_t getSize() const;
231 InputSection
*getLinkOrderDep() const;
233 // Get a symbol that encloses this offset from within the section. If type is
234 // not zero, return a symbol with the specified type.
235 Defined
*getEnclosingSymbol(uint64_t offset
, uint8_t type
= 0) const;
236 Defined
*getEnclosingFunction(uint64_t offset
) const {
237 return getEnclosingSymbol(offset
, llvm::ELF::STT_FUNC
);
240 // Returns a source location string. Used to construct an error message.
241 std::string
getLocation(uint64_t offset
) const;
242 std::string
getSrcMsg(const Symbol
&sym
, uint64_t offset
) const;
243 std::string
getObjMsg(uint64_t offset
) const;
245 // Each section knows how to relocate itself. These functions apply
246 // relocations, assuming that Buf points to this section's copy in
247 // the mmap'ed output buffer.
248 template <class ELFT
> void relocate(Ctx
&, uint8_t *buf
, uint8_t *bufEnd
);
249 uint64_t getRelocTargetVA(Ctx
&, const Relocation
&r
, uint64_t p
) const;
251 // The native ELF reloc data type is not very convenient to handle.
252 // So we convert ELF reloc records to our own records in Relocations.cpp.
253 // This vector contains such "cooked" relocations.
254 SmallVector
<Relocation
, 0> relocations
;
256 void addReloc(const Relocation
&r
) { relocations
.push_back(r
); }
257 MutableArrayRef
<Relocation
> relocs() { return relocations
; }
258 ArrayRef
<Relocation
> relocs() const { return relocations
; }
261 // These are modifiers to jump instructions that are necessary when basic
262 // block sections are enabled. Basic block sections creates opportunities
263 // to relax jump instructions at basic block boundaries after reordering the
265 JumpInstrMod
*jumpInstrMod
= nullptr;
267 // Auxiliary information for RISC-V and LoongArch linker relaxation.
268 // They do not use jumpInstrMod.
271 // The compressed content size when `compressed` is true.
272 size_t compressedSize
;
275 // A function compiled with -fsplit-stack calling a function
276 // compiled without -fsplit-stack needs its prologue adjusted. Find
277 // such functions and adjust their prologues. This is very similar
278 // to relocation. See https://gcc.gnu.org/wiki/SplitStacks for more
280 template <typename ELFT
>
281 void adjustSplitStackFunctionPrologues(Ctx
&, uint8_t *buf
, uint8_t *end
);
283 template <typename T
> llvm::ArrayRef
<T
> getDataAs() const {
284 size_t s
= content().size();
285 assert(s
% sizeof(T
) == 0);
286 return llvm::ArrayRef
<T
>((const T
*)content().data(), s
/ sizeof(T
));
290 template <typename ELFT
> void parseCompressedHeader(Ctx
&);
291 void decompress() const;
294 // SectionPiece represents a piece of splittable section contents.
295 // We allocate a lot of these and binary search on them. This means that they
296 // have to be as compact as possible, which is why we don't store the size (can
297 // be found by looking at the next one).
298 struct SectionPiece
{
299 SectionPiece() = default;
300 SectionPiece(size_t off
, uint32_t hash
, bool live
)
301 : inputOff(off
), live(live
), hash(hash
>> 1) {}
304 LLVM_PREFERRED_TYPE(bool)
307 uint64_t outputOff
= 0;
310 static_assert(sizeof(SectionPiece
) == 16, "SectionPiece is too big");
312 // This corresponds to a SHF_MERGE section of an input file.
313 class MergeInputSection
: public InputSectionBase
{
315 template <class ELFT
>
316 MergeInputSection(ObjFile
<ELFT
> &f
, const typename
ELFT::Shdr
&header
,
318 MergeInputSection(Ctx
&, uint64_t flags
, uint32_t type
, uint64_t entsize
,
319 ArrayRef
<uint8_t> data
, StringRef name
);
321 static bool classof(const SectionBase
*s
) { return s
->kind() == Merge
; }
322 void splitIntoPieces();
324 // Translate an offset in the input section to an offset in the parent
325 // MergeSyntheticSection.
326 uint64_t getParentOffset(uint64_t offset
) const;
328 // Splittable sections are handled as a sequence of data
329 // rather than a single large blob of data.
330 SmallVector
<SectionPiece
, 0> pieces
;
332 // Returns I'th piece's data. This function is very hot when
333 // string merging is enabled, so we want to inline.
334 LLVM_ATTRIBUTE_ALWAYS_INLINE
335 llvm::CachedHashStringRef
getData(size_t i
) const {
336 size_t begin
= pieces
[i
].inputOff
;
338 (pieces
.size() - 1 == i
) ? content().size() : pieces
[i
+ 1].inputOff
;
339 return {toStringRef(content().slice(begin
, end
- begin
)), pieces
[i
].hash
};
342 // Returns the SectionPiece at a given input section offset.
343 SectionPiece
&getSectionPiece(uint64_t offset
);
344 const SectionPiece
&getSectionPiece(uint64_t offset
) const {
345 return const_cast<MergeInputSection
*>(this)->getSectionPiece(offset
);
348 SyntheticSection
*getParent() const {
349 return cast_or_null
<SyntheticSection
>(parent
);
353 void splitStrings(StringRef s
, size_t size
);
354 void splitNonStrings(ArrayRef
<uint8_t> a
, size_t size
);
357 struct EhSectionPiece
{
358 EhSectionPiece(size_t off
, InputSectionBase
*sec
, uint32_t size
,
359 unsigned firstRelocation
)
360 : inputOff(off
), sec(sec
), size(size
), firstRelocation(firstRelocation
) {}
362 ArrayRef
<uint8_t> data() const {
363 return {sec
->content().data() + this->inputOff
, size
};
367 ssize_t outputOff
= -1;
368 InputSectionBase
*sec
;
370 unsigned firstRelocation
;
373 // This corresponds to a .eh_frame section of an input file.
374 class EhInputSection
: public InputSectionBase
{
376 template <class ELFT
>
377 EhInputSection(ObjFile
<ELFT
> &f
, const typename
ELFT::Shdr
&header
,
379 static bool classof(const SectionBase
*s
) { return s
->kind() == EHFrame
; }
380 template <class ELFT
> void split();
381 template <class ELFT
, class RelTy
> void split(ArrayRef
<RelTy
> rels
);
383 // Splittable sections are handled as a sequence of data
384 // rather than a single large blob of data.
385 SmallVector
<EhSectionPiece
, 0> cies
, fdes
;
387 SyntheticSection
*getParent() const;
388 uint64_t getParentOffset(uint64_t offset
) const;
391 // This is a section that is added directly to an output section
392 // instead of needing special combination via a synthetic section. This
393 // includes all input sections with the exceptions of SHF_MERGE and
394 // .eh_frame. It also includes the synthetic sections themselves.
395 class InputSection
: public InputSectionBase
{
397 InputSection(InputFile
*f
, uint64_t flags
, uint32_t type
, uint32_t addralign
,
398 ArrayRef
<uint8_t> data
, StringRef name
, Kind k
= Regular
);
399 template <class ELFT
>
400 InputSection(ObjFile
<ELFT
> &f
, const typename
ELFT::Shdr
&header
,
403 static bool classof(const SectionBase
*s
) {
404 return s
->kind() == SectionBase::Regular
||
405 s
->kind() == SectionBase::Synthetic
||
406 s
->kind() == SectionBase::Spill
;
409 // Write this section to a mmap'ed file, assuming Buf is pointing to
410 // beginning of the output section.
411 template <class ELFT
> void writeTo(Ctx
&, uint8_t *buf
);
413 OutputSection
*getParent() const {
414 return reinterpret_cast<OutputSection
*>(parent
);
417 // This variable has two usages. Initially, it represents an index in the
418 // OutputSection's InputSection list, and is used when ordering SHF_LINK_ORDER
419 // sections. After assignAddresses is called, it represents the offset from
420 // the beginning of the output section this section was assigned to.
421 uint64_t outSecOff
= 0;
423 InputSectionBase
*getRelocatedSection() const;
425 template <class ELFT
, class RelTy
>
426 void relocateNonAlloc(Ctx
&, uint8_t *buf
, Relocs
<RelTy
> rels
);
428 // Points to the canonical section. If ICF folds two sections, repl pointer of
429 // one section points to the other.
430 InputSection
*repl
= this;
433 uint32_t eqClass
[2] = {0, 0};
435 // Called by ICF to merge two input sections.
436 void replace(InputSection
*other
);
438 static InputSection discarded
;
441 template <class ELFT
, class RelTy
> void copyRelocations(Ctx
&, uint8_t *buf
);
443 template <class ELFT
, class RelTy
, class RelIt
>
444 void copyRelocations(Ctx
&, uint8_t *buf
, llvm::iterator_range
<RelIt
> rels
);
446 template <class ELFT
> void copyShtGroup(uint8_t *buf
);
449 // A marker for a potential spill location for another input section. This
450 // broadly acts as if it were the original section until address assignment.
451 // Then it is either replaced with the real input section or removed.
452 class PotentialSpillSection
: public InputSection
{
454 // The containing input section description; used to quickly replace this stub
455 // with the actual section.
456 InputSectionDescription
*isd
;
458 // Next potential spill location for the same source input section.
459 PotentialSpillSection
*next
= nullptr;
461 PotentialSpillSection(const InputSectionBase
&source
,
462 InputSectionDescription
&isd
);
464 static bool classof(const SectionBase
*sec
) {
465 return sec
->kind() == InputSectionBase::Spill
;
469 static_assert(sizeof(InputSection
) <= 160, "InputSection is too big");
471 class SyntheticSection
: public InputSection
{
474 SyntheticSection(Ctx
&ctx
, uint64_t flags
, uint32_t type
, uint32_t addralign
,
476 : InputSection(ctx
.internalFile
, flags
, type
, addralign
, {}, name
,
477 InputSectionBase::Synthetic
),
480 virtual ~SyntheticSection() = default;
481 virtual size_t getSize() const = 0;
482 virtual bool updateAllocSize(Ctx
&) { return false; }
483 // If the section has the SHF_ALLOC flag and the size may be changed if
484 // thunks are added, update the section size.
485 virtual bool isNeeded() const { return true; }
486 virtual void finalizeContents() {}
487 virtual void writeTo(uint8_t *buf
) = 0;
489 static bool classof(const SectionBase
*sec
) {
490 return sec
->kind() == InputSectionBase::Synthetic
;
494 inline bool isStaticRelSecType(uint32_t type
) {
495 return type
== llvm::ELF::SHT_RELA
|| type
== llvm::ELF::SHT_CREL
||
496 type
== llvm::ELF::SHT_REL
;
499 inline bool isDebugSection(const InputSectionBase
&sec
) {
500 return (sec
.flags
& llvm::ELF::SHF_ALLOC
) == 0 &&
501 sec
.name
.starts_with(".debug");
504 std::string
toStr(elf::Ctx
&, const elf::InputSectionBase
*);
505 const ELFSyncStream
&operator<<(const ELFSyncStream
&,
506 const InputSectionBase
*);