1//===- InputSection.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#ifndef LLD_ELF_INPUT_SECTION_H
10#define LLD_ELF_INPUT_SECTION_H
11
12#include "Config.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"
23
24namespace lld {
25namespace elf {
26
27class InputFile;
28class Symbol;
29
30class Defined;
31class SyntheticSection;
32template <class ELFT> class ObjFile;
33class OutputSection;
34
35// Returned by InputSectionBase::relsOrRelas. At least two members are empty.
36template <class ELFT> struct RelsOrRelas {
37 Relocs<typename ELFT::Rel> rels;
38 Relocs<typename ELFT::Rela> relas;
39 Relocs<typename ELFT::Crel> crels;
40 bool areRelocsRel() const { return rels.size(); }
41 bool areRelocsCrel() const { return crels.size(); }
42};
43
44#define invokeOnRelocs(sec, f, ...) \
45 { \
46 const RelsOrRelas<ELFT> rs = (sec).template relsOrRelas<ELFT>(); \
47 if (rs.areRelocsCrel()) \
48 f(__VA_ARGS__, rs.crels); \
49 else if (rs.areRelocsRel()) \
50 f(__VA_ARGS__, rs.rels); \
51 else \
52 f(__VA_ARGS__, rs.relas); \
53 }
54
55// This is the base class of all sections that lld handles. Some are sections in
56// input files, some are sections in the produced output file and some exist
57// just as a convenience for implementing special ways of combining some
58// sections.
59class SectionBase {
60public:
61 enum Kind : uint8_t {
62 Regular,
63 Synthetic,
64 Spill,
65 EHFrame,
66 Merge,
67 Output,
68 Class,
69 };
70
71 Kind kind() const { return sectionKind; }
72
73 // The file which contains this section. For InputSectionBase, its dynamic
74 // type is usually ObjFile<ELFT>, but may be an InputFile of InternalKind
75 // (for a synthetic section).
76 InputFile *file;
77
78 StringRef name;
79
80 // These corresponds to the fields in Elf_Shdr.
81 uint64_t flags;
82 uint32_t type;
83 uint32_t link;
84 uint32_t info;
85 uint32_t addralign;
86 uint32_t entsize;
87
88 Kind sectionKind;
89 // 0 (dead) or 1 (live).
90 uint8_t partition = 1;
91
92 // The next two bit fields are only used by InputSectionBase, but we
93 // put them here so the struct packs better.
94
95 Ctx &getCtx() const;
96 OutputSection *getOutputSection();
97 const OutputSection *getOutputSection() const {
98 return const_cast<SectionBase *>(this)->getOutputSection();
99 }
100
101 // Translate an offset in the input section to an offset in the output
102 // section.
103 uint64_t getOffset(uint64_t offset) const;
104
105 uint64_t getVA(uint64_t offset = 0) const;
106
107 // Translate an offset in relocations to an address. RelocScan::scanEhSection
108 // has already mapped .eh_frame offsets to the merged output section, so they
109 // must not be translated a second time.
110 uint64_t getRelocVA(uint64_t offset) const;
111
112 bool isLive() const { return partition != 0; }
113 void markLive() { partition = 1; }
114 void markDead() { partition = 0; }
115
116protected:
117 constexpr SectionBase(Kind sectionKind, InputFile *file, StringRef name,
118 uint32_t type, uint64_t flags, uint32_t link,
119 uint32_t info, uint32_t addralign, uint32_t entsize)
120 : file(file), name(name), flags(flags), type(type), link(link),
121 info(info), addralign(addralign), entsize(entsize),
122 sectionKind(sectionKind) {}
123};
124
125struct SymbolAnchor {
126 uint64_t offset;
127 Defined *d;
128 bool end; // true for the anchor of st_value+st_size
129};
130
131struct RelaxAux {
132 // This records symbol start and end offsets which will be adjusted according
133 // to the nearest relocDeltas element.
134 SmallVector<SymbolAnchor, 0> anchors;
135 // For relocations[i], the actual offset is
136 // r_offset - (i ? relocDeltas[i-1] : 0).
137 std::unique_ptr<uint32_t[]> relocDeltas;
138 // For relocations[i], the actual type is relocTypes[i].
139 std::unique_ptr<RelType[]> relocTypes;
140 SmallVector<uint32_t, 0> writes;
141};
142
143// This corresponds to a section of an input file.
144class InputSectionBase : public SectionBase {
145public:
146 struct ObjMsg {
147 const InputSectionBase *sec;
148 uint64_t offset;
149 };
150 struct SrcMsg {
151 const InputSectionBase &sec;
152 const Symbol &sym;
153 uint64_t offset;
154 };
155
156 template <class ELFT>
157 InputSectionBase(ObjFile<ELFT> &file, const typename ELFT::Shdr &header,
158 StringRef name, Kind sectionKind);
159
160 InputSectionBase(InputFile *file, StringRef name, uint32_t type,
161 uint64_t flags, uint32_t link, uint32_t info,
162 uint32_t addralign, uint32_t entsize, ArrayRef<uint8_t> data,
163 Kind sectionKind);
164
165 static bool classof(const SectionBase *s) {
166 return s->kind() != Output && s->kind() != Class;
167 }
168
169 LLVM_PREFERRED_TYPE(bool)
170 uint8_t bss : 1;
171
172 // Whether this section is SHT_CREL and has been decoded to RELA by
173 // relsOrRelas.
174 LLVM_PREFERRED_TYPE(bool)
175 uint8_t decodedCrel : 1;
176
177 // Set for sections that should not be folded by ICF.
178 LLVM_PREFERRED_TYPE(bool)
179 uint8_t keepUnique : 1;
180
181 // Whether the section needs to be padded with a NOP filler due to
182 // deleteFallThruJmpInsn.
183 LLVM_PREFERRED_TYPE(bool)
184 uint8_t nopFiller : 1;
185
186 mutable bool compressed = false;
187
188 // Input sections are part of an output section. Special sections
189 // like .eh_frame and merge sections are first combined into a
190 // synthetic section that is then added to an output section. In all
191 // cases this points one level up.
192 SectionBase *parent = nullptr;
193
194 // Section index of the relocation section if exists.
195 uint32_t relSecIdx = 0;
196
197 // Getter when the dynamic type is ObjFile<ELFT>.
198 template <class ELFT> ObjFile<ELFT> *getFile() const {
199 return cast<ObjFile<ELFT>>(file);
200 }
201
202 // Used by --optimize-bb-jumps and RISC-V linker relaxation temporarily to
203 // indicate the number of bytes which is not counted in the size. This should
204 // be reset to zero after uses.
205 uint32_t bytesDropped = 0;
206
207 void drop_back(unsigned num) {
208 assert(bytesDropped + num < 256);
209 bytesDropped += num;
210 }
211
212 mutable const uint8_t *content_;
213 uint64_t size;
214
215 void trim() {
216 if (bytesDropped) {
217 size -= bytesDropped;
218 bytesDropped = 0;
219 }
220 }
221
222 ArrayRef<uint8_t> content() const {
223 return ArrayRef<uint8_t>(content_, size);
224 }
225 ArrayRef<uint8_t> contentMaybeDecompress() const {
226 if (compressed)
227 decompress();
228 return content();
229 }
230
231 // The next member in the section group if this section is in a group. This is
232 // used by --gc-sections.
233 InputSectionBase *nextInSectionGroup = nullptr;
234
235 template <class ELFT>
236 RelsOrRelas<ELFT> relsOrRelas(bool supportsCrel = true) const;
237
238 // InputSections that are dependent on us (reverse dependency for GC)
239 llvm::TinyPtrVector<InputSection *> dependentSections;
240
241 // Returns the size of this section (even if this is a common or BSS.)
242 size_t getSize() const;
243
244 InputSection *getLinkOrderDep() const;
245
246 // Get a symbol that encloses this offset from within the section. If type is
247 // not zero, return a symbol with the specified type.
248 Defined *getEnclosingSymbol(uint64_t offset, uint8_t type = 0) const;
249 Defined *getEnclosingFunction(uint64_t offset) const {
250 return getEnclosingSymbol(offset, type: llvm::ELF::STT_FUNC);
251 }
252
253 // Returns a source location string. Used to construct an error message.
254 std::string getLocation(uint64_t offset) const;
255 ObjMsg getObjMsg(uint64_t offset) const { return {.sec: this, .offset: offset}; }
256 SrcMsg getSrcMsg(const Symbol &sym, uint64_t offset) const {
257 return {.sec: *this, .sym: sym, .offset: offset};
258 }
259
260 uint64_t getRelocTargetVA(Ctx &, const Relocation &r, uint64_t p) const;
261
262 // The native ELF reloc data type is not very convenient to handle.
263 // So we convert ELF reloc records to our own records in Relocations.cpp.
264 // This vector contains such "cooked" relocations.
265 SmallVector<Relocation, 0> relocations;
266
267 void addReloc(const Relocation &r) { relocations.push_back(Elt: r); }
268 MutableArrayRef<Relocation> relocs() { return relocations; }
269 ArrayRef<Relocation> relocs() const { return relocations; }
270
271 union {
272 // These are modifiers to jump instructions that are necessary when basic
273 // block sections are enabled. Basic block sections creates opportunities
274 // to relax jump instructions at basic block boundaries after reordering the
275 // basic blocks.
276 JumpInstrMod *jumpInstrMod = nullptr;
277
278 // Auxiliary information for RISC-V and LoongArch linker relaxation.
279 // They do not use jumpInstrMod.
280 RelaxAux *relaxAux;
281
282 // The compressed content size when `compressed` is true.
283 size_t compressedSize;
284 };
285
286 // A function compiled with -fsplit-stack calling a function
287 // compiled without -fsplit-stack needs its prologue adjusted. Find
288 // such functions and adjust their prologues. This is very similar
289 // to relocation. See https://gcc.gnu.org/wiki/SplitStacks for more
290 // information.
291 template <typename ELFT>
292 void adjustSplitStackFunctionPrologues(Ctx &, uint8_t *buf, uint8_t *end);
293
294 template <typename T> llvm::ArrayRef<T> getDataAs() const {
295 size_t s = content().size();
296 assert(s % sizeof(T) == 0);
297 assert(reinterpret_cast<uintptr_t>(content().data()) % alignof(T) == 0);
298 return llvm::ArrayRef<T>((const T *)content().data(), s / sizeof(T));
299 }
300
301protected:
302 template <typename ELFT> void parseCompressedHeader(Ctx &);
303 void decompress() const;
304};
305
306// SectionPiece represents a piece of splittable section contents.
307// We allocate a lot of these and binary search on them. This means that they
308// have to be as compact as possible, which is why we don't store the size (can
309// be found by looking at the next one).
310struct SectionPiece {
311 SectionPiece() = default;
312 SectionPiece(size_t off, uint32_t hash, bool live)
313 : inputOff(off), live(live), hash(hash >> 1) {}
314
315 uint32_t inputOff;
316 LLVM_PREFERRED_TYPE(bool)
317 uint32_t live : 1;
318 uint32_t hash : 31;
319 uint64_t outputOff = 0;
320};
321
322static_assert(sizeof(SectionPiece) == 16, "SectionPiece is too big");
323
324// Used by splitSections to pre-resolve section piece indexes. 32 bits of offset
325// supports section piece up to 4GB.
326constexpr unsigned mergeValueShift = 32;
327
328// This corresponds to a SHF_MERGE section of an input file.
329class MergeInputSection : public InputSectionBase {
330public:
331 template <class ELFT>
332 MergeInputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
333 StringRef name);
334 MergeInputSection(Ctx &, StringRef name, uint32_t type, uint64_t flags,
335 uint64_t entsize, ArrayRef<uint8_t> data);
336
337 static bool classof(const SectionBase *s) { return s->kind() == Merge; }
338 void splitIntoPieces();
339
340 // Translate an offset in the input section to an offset in the parent
341 // MergeSyntheticSection. If the offset was pre-resolved by
342 // resolveSymbolPieces (upper bits non-zero), this is O(1).
343 uint64_t getParentOffset(uint64_t offset) const;
344
345 // Splittable sections are handled as a sequence of data
346 // rather than a single large blob of data.
347 SmallVector<SectionPiece, 0> pieces;
348
349 // Returns I'th piece's data. This function is very hot when
350 // string merging is enabled, so we want to inline.
351 LLVM_ATTRIBUTE_ALWAYS_INLINE
352 llvm::CachedHashStringRef getData(size_t i) const {
353 size_t begin = pieces[i].inputOff;
354 size_t end =
355 (pieces.size() - 1 == i) ? content().size() : pieces[i + 1].inputOff;
356 return {toStringRef(Input: content().slice(N: begin, M: end - begin)), pieces[i].hash};
357 }
358
359 // Returns the SectionPiece at a given input section offset.
360 SectionPiece &getSectionPiece(uint64_t offset);
361 const SectionPiece &getSectionPiece(uint64_t offset) const {
362 return const_cast<MergeInputSection *>(this)->getSectionPiece(offset);
363 }
364
365 SyntheticSection *getParent() const {
366 return cast_or_null<SyntheticSection>(Val: parent);
367 }
368
369private:
370 void splitStrings(StringRef s, size_t size);
371 void splitNonStrings(ArrayRef<uint8_t> a, size_t size);
372};
373
374struct EhSectionPiece {
375 EhSectionPiece(size_t off, InputSectionBase *sec, uint32_t size,
376 unsigned firstRelocation)
377 : inputOff(off), sec(sec), size(size), firstRelocation(firstRelocation) {}
378
379 ArrayRef<uint8_t> data() const {
380 return {sec->content().data() + this->inputOff, size};
381 }
382
383 size_t inputOff;
384 ssize_t outputOff = -1;
385 InputSectionBase *sec;
386 uint32_t size;
387 unsigned firstRelocation;
388};
389
390// This corresponds to a .eh_frame section of an input file.
391class EhInputSection : public InputSectionBase {
392public:
393 template <class ELFT>
394 EhInputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
395 StringRef name);
396 static bool classof(const SectionBase *s) { return s->kind() == EHFrame; }
397 template <class ELFT> void split();
398 template <class ELFT, class RelTy> void preprocessRelocs(Relocs<RelTy> rels);
399
400 // Splittable sections are handled as a sequence of data
401 // rather than a single large blob of data.
402 SmallVector<EhSectionPiece, 0> cies, fdes;
403
404 SyntheticSection *getParent() const;
405 uint64_t getParentOffset(uint64_t offset) const;
406
407 // Preprocessed relocations in uniform format to avoid REL/RELA/CREL
408 // relocation format handling throughout the codebase.
409 SmallVector<Relocation, 0> rels;
410};
411
412// This is a section that is added directly to an output section
413// instead of needing special combination via a synthetic section. This
414// includes all input sections with the exceptions of SHF_MERGE and
415// .eh_frame. It also includes the synthetic sections themselves.
416class InputSection : public InputSectionBase {
417public:
418 InputSection(InputFile *f, StringRef name, uint32_t type, uint64_t flags,
419 uint32_t addralign, uint32_t entsize, ArrayRef<uint8_t> data,
420 Kind k = Regular);
421 template <class ELFT>
422 InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
423 StringRef name);
424
425 static bool classof(const SectionBase *s) {
426 return s->kind() == SectionBase::Regular ||
427 s->kind() == SectionBase::Synthetic ||
428 s->kind() == SectionBase::Spill;
429 }
430
431 // Write this section to a mmap'ed file, assuming Buf is pointing to
432 // beginning of the output section.
433 template <class ELFT> void writeTo(Ctx &, uint8_t *buf);
434
435 OutputSection *getParent() const {
436 return reinterpret_cast<OutputSection *>(parent);
437 }
438
439 // This variable has two usages. Initially, it represents an index in the
440 // OutputSection's InputSection list, and is used when ordering SHF_LINK_ORDER
441 // sections. After assignAddresses is called, it represents the offset from
442 // the beginning of the output section this section was assigned to.
443 uint64_t outSecOff = 0;
444
445 InputSectionBase *getRelocatedSection() const;
446
447 // Each section knows how to relocate itself. These functions apply
448 // relocations, assuming that `buf` points to this section's copy in
449 // the mmap'ed output buffer.
450 template <class ELFT, class RelTy>
451 void relocateNonAlloc(Ctx &, uint8_t *buf, Relocs<RelTy> rels);
452 template <class ELFT> void relocate(Ctx &, uint8_t *buf, uint8_t *bufEnd);
453
454 // Points to the canonical section. If ICF folds two sections, repl pointer of
455 // one section points to the other.
456 InputSection *repl = this;
457
458 // Used by ICF.
459 uint32_t eqClass[2] = {0, 0};
460
461 // Called by ICF to merge two input sections.
462 void replace(InputSection *other);
463
464 static InputSection discarded;
465
466private:
467 template <class ELFT, class RelTy> void copyRelocations(Ctx &, uint8_t *buf);
468
469 template <class ELFT, class RelTy, class RelIt>
470 void copyRelocations(Ctx &, uint8_t *buf, llvm::iterator_range<RelIt> rels);
471
472 template <class ELFT> void copyShtGroup(uint8_t *buf);
473};
474
475// A marker for a potential spill location for another input section. This
476// broadly acts as if it were the original section until address assignment.
477// Then it is either replaced with the real input section or removed.
478class PotentialSpillSection : public InputSection {
479public:
480 // The containing input section description; used to quickly replace this stub
481 // with the actual section.
482 InputSectionDescription *isd;
483
484 // Next potential spill location for the same source input section.
485 PotentialSpillSection *next = nullptr;
486
487 PotentialSpillSection(const InputSectionBase &source,
488 InputSectionDescription &isd);
489
490 static bool classof(const SectionBase *sec) {
491 return sec->kind() == InputSectionBase::Spill;
492 }
493};
494
495#ifndef _WIN32
496static_assert(sizeof(InputSection) <= 152, "InputSection is too big");
497#endif
498
499class SyntheticSection : public InputSection {
500public:
501 Ctx &ctx;
502 SyntheticSection(Ctx &ctx, StringRef name, uint32_t type, uint64_t flags,
503 uint32_t addralign)
504 : InputSection(ctx.internalFile, name, type, flags, addralign,
505 /*entsize=*/0, {}, InputSectionBase::Synthetic),
506 ctx(ctx) {}
507
508 virtual ~SyntheticSection() = default;
509 virtual size_t getSize() const = 0;
510 virtual bool updateAllocSize(Ctx &) { return false; }
511 // If the section has the SHF_ALLOC flag and the size may be changed if
512 // thunks are added, update the section size.
513 virtual bool isNeeded() const { return true; }
514 virtual void finalizeContents() {}
515 virtual void writeTo(uint8_t *buf) = 0;
516
517 static bool classof(const SectionBase *sec) {
518 return sec->kind() == InputSectionBase::Synthetic;
519 }
520};
521
522inline bool isStaticRelSecType(uint32_t type) {
523 return type == llvm::ELF::SHT_RELA || type == llvm::ELF::SHT_CREL ||
524 type == llvm::ELF::SHT_REL;
525}
526
527inline bool isDebugSection(const InputSectionBase &sec) {
528 return (sec.flags & llvm::ELF::SHF_ALLOC) == 0 &&
529 sec.name.starts_with(Prefix: ".debug");
530}
531
532std::string toStr(elf::Ctx &, const elf::InputSectionBase *);
533const ELFSyncStream &operator<<(const ELFSyncStream &,
534 const InputSectionBase *);
535const ELFSyncStream &operator<<(const ELFSyncStream &,
536 InputSectionBase::ObjMsg &&);
537const ELFSyncStream &operator<<(const ELFSyncStream &,
538 InputSectionBase::SrcMsg &&);
539} // namespace elf
540} // namespace lld
541
542#endif
543