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"
15 #include "lld/Common/LLVM.h"
16 #include "llvm/ADT/CachedHashString.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/TinyPtrVector.h"
19 #include "llvm/Object/ELF.h"
29 class SyntheticSection;
30 class MergeSyntheticSection;
31 template <class ELFT> class ObjFile;
34 extern std::vector<Partition> partitions;
36 // This is the base class of all sections that lld handles. Some are sections in
37 // input files, some are sections in the produced output file and some exist
38 // just as a convenience for implementing special ways of combining some
42 enum Kind { Regular, EHFrame, Merge, Synthetic, Output };
44 Kind kind() const { return (Kind)sectionKind; }
48 // This pointer points to the "real" instance of this instance.
49 // Usually Repl == this. However, if ICF merges two sections,
50 // Repl pointer of one section points to another section. So,
51 // if you need to get a pointer to this instance, do not use
52 // this but instead this->Repl.
55 unsigned sectionKind : 3;
57 // The next three bit fields are only used by InputSectionBase, but we
58 // put them here so the struct packs better.
60 // True if this section has already been placed to a linker script
61 // output section. This is needed because, in a linker script, you
62 // can refer to the same section more than once. For example, in
63 // the following linker script,
65 // .foo : { *(.text) }
66 // .bar : { *(.text) }
68 // .foo takes all .text sections, and .bar becomes empty. To achieve
69 // this, we need to memorize whether a section has been placed or
70 // not for each input section.
71 unsigned assigned : 1;
75 // Set for sections that should not be folded by ICF.
76 unsigned keepUnique : 1;
78 // The 1-indexed partition that this section is assigned to by the garbage
79 // collector, or 0 if this section is dead. Normally there is only one
80 // partition, so this will either be 0 or 1.
82 elf::Partition &getPartition() const;
84 // These corresponds to the fields in Elf_Shdr.
92 OutputSection *getOutputSection();
93 const OutputSection *getOutputSection() const {
94 return const_cast<SectionBase *>(this)->getOutputSection();
97 // Translate an offset in the input section to an offset in the output
99 uint64_t getOffset(uint64_t offset) const;
101 uint64_t getVA(uint64_t offset = 0) const;
103 bool isLive() const { return partition != 0; }
104 void markLive() { partition = 1; }
105 void markDead() { partition = 0; }
108 SectionBase(Kind sectionKind, StringRef name, uint64_t flags,
109 uint64_t entsize, uint64_t alignment, uint32_t type,
110 uint32_t info, uint32_t link)
111 : name(name), repl(this), sectionKind(sectionKind), assigned(false),
112 bss(false), keepUnique(false), partition(0), alignment(alignment),
113 flags(flags), entsize(entsize), type(type), link(link), info(info) {}
116 // This corresponds to a section of an input file.
117 class InputSectionBase : public SectionBase {
119 template <class ELFT>
120 InputSectionBase(ObjFile<ELFT> &file, const typename ELFT::Shdr &header,
121 StringRef name, Kind sectionKind);
123 InputSectionBase(InputFile *file, uint64_t flags, uint32_t type,
124 uint64_t entsize, uint32_t link, uint32_t info,
125 uint32_t alignment, ArrayRef<uint8_t> data, StringRef name,
128 static bool classof(const SectionBase *s) { return s->kind() != Output; }
130 // Relocations that refer to this section.
131 unsigned numRelocations : 31;
132 unsigned areRelocsRela : 1;
133 const void *firstRelocation = nullptr;
135 // The file which contains this section. Its dynamic type is always
136 // ObjFile<ELFT>, but in order to avoid ELFT, we use InputFile as
140 template <class ELFT> ObjFile<ELFT> *getFile() const {
141 return cast_or_null<ObjFile<ELFT>>(file);
144 ArrayRef<uint8_t> data() const {
145 if (uncompressedSize >= 0)
150 uint64_t getOffsetInFile() const;
152 // Input sections are part of an output section. Special sections
153 // like .eh_frame and merge sections are first combined into a
154 // synthetic section that is then added to an output section. In all
155 // cases this points one level up.
156 SectionBase *parent = nullptr;
158 template <class ELFT> ArrayRef<typename ELFT::Rel> rels() const {
159 assert(!areRelocsRela);
160 return llvm::makeArrayRef(
161 static_cast<const typename ELFT::Rel *>(firstRelocation),
165 template <class ELFT> ArrayRef<typename ELFT::Rela> relas() const {
166 assert(areRelocsRela);
167 return llvm::makeArrayRef(
168 static_cast<const typename ELFT::Rela *>(firstRelocation),
172 // InputSections that are dependent on us (reverse dependency for GC)
173 llvm::TinyPtrVector<InputSection *> dependentSections;
175 // Returns the size of this section (even if this is a common or BSS.)
176 size_t getSize() const;
178 InputSection *getLinkOrderDep() const;
180 // Get the function symbol that encloses this offset from within the
182 template <class ELFT>
183 Defined *getEnclosingFunction(uint64_t offset);
185 // Returns a source location string. Used to construct an error message.
186 template <class ELFT> std::string getLocation(uint64_t offset);
187 std::string getSrcMsg(const Symbol &sym, uint64_t offset);
188 std::string getObjMsg(uint64_t offset);
190 // Each section knows how to relocate itself. These functions apply
191 // relocations, assuming that Buf points to this section's copy in
192 // the mmap'ed output buffer.
193 template <class ELFT> void relocate(uint8_t *buf, uint8_t *bufEnd);
194 void relocateAlloc(uint8_t *buf, uint8_t *bufEnd);
196 // The native ELF reloc data type is not very convenient to handle.
197 // So we convert ELF reloc records to our own records in Relocations.cpp.
198 // This vector contains such "cooked" relocations.
199 std::vector<Relocation> relocations;
201 // A function compiled with -fsplit-stack calling a function
202 // compiled without -fsplit-stack needs its prologue adjusted. Find
203 // such functions and adjust their prologues. This is very similar
204 // to relocation. See https://gcc.gnu.org/wiki/SplitStacks for more
206 template <typename ELFT>
207 void adjustSplitStackFunctionPrologues(uint8_t *buf, uint8_t *end);
210 template <typename T> llvm::ArrayRef<T> getDataAs() const {
211 size_t s = data().size();
212 assert(s % sizeof(T) == 0);
213 return llvm::makeArrayRef<T>((const T *)data().data(), s / sizeof(T));
217 void parseCompressedHeader();
218 void uncompress() const;
220 mutable ArrayRef<uint8_t> rawData;
222 // This field stores the uncompressed size of the compressed data in rawData,
223 // or -1 if rawData is not compressed (either because the section wasn't
224 // compressed in the first place, or because we ended up uncompressing it).
225 // Since the feature is not used often, this is usually -1.
226 mutable int64_t uncompressedSize = -1;
229 // SectionPiece represents a piece of splittable section contents.
230 // We allocate a lot of these and binary search on them. This means that they
231 // have to be as compact as possible, which is why we don't store the size (can
232 // be found by looking at the next one).
233 struct SectionPiece {
234 SectionPiece(size_t off, uint32_t hash, bool live)
235 : inputOff(off), live(live || !config->gcSections), hash(hash >> 1) {}
240 uint64_t outputOff = 0;
243 static_assert(sizeof(SectionPiece) == 16, "SectionPiece is too big");
245 // This corresponds to a SHF_MERGE section of an input file.
246 class MergeInputSection : public InputSectionBase {
248 template <class ELFT>
249 MergeInputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
251 MergeInputSection(uint64_t flags, uint32_t type, uint64_t entsize,
252 ArrayRef<uint8_t> data, StringRef name);
254 static bool classof(const SectionBase *s) { return s->kind() == Merge; }
255 void splitIntoPieces();
257 // Translate an offset in the input section to an offset in the parent
258 // MergeSyntheticSection.
259 uint64_t getParentOffset(uint64_t offset) const;
261 // Splittable sections are handled as a sequence of data
262 // rather than a single large blob of data.
263 std::vector<SectionPiece> pieces;
265 // Returns I'th piece's data. This function is very hot when
266 // string merging is enabled, so we want to inline.
267 LLVM_ATTRIBUTE_ALWAYS_INLINE
268 llvm::CachedHashStringRef getData(size_t i) const {
269 size_t begin = pieces[i].inputOff;
271 (pieces.size() - 1 == i) ? data().size() : pieces[i + 1].inputOff;
272 return {toStringRef(data().slice(begin, end - begin)), pieces[i].hash};
275 // Returns the SectionPiece at a given input section offset.
276 SectionPiece *getSectionPiece(uint64_t offset);
277 const SectionPiece *getSectionPiece(uint64_t offset) const {
278 return const_cast<MergeInputSection *>(this)->getSectionPiece(offset);
281 SyntheticSection *getParent() const;
284 void splitStrings(ArrayRef<uint8_t> a, size_t size);
285 void splitNonStrings(ArrayRef<uint8_t> a, size_t size);
288 struct EhSectionPiece {
289 EhSectionPiece(size_t off, InputSectionBase *sec, uint32_t size,
290 unsigned firstRelocation)
291 : inputOff(off), sec(sec), size(size), firstRelocation(firstRelocation) {}
293 ArrayRef<uint8_t> data() {
294 return {sec->data().data() + this->inputOff, size};
298 ssize_t outputOff = -1;
299 InputSectionBase *sec;
301 unsigned firstRelocation;
304 // This corresponds to a .eh_frame section of an input file.
305 class EhInputSection : public InputSectionBase {
307 template <class ELFT>
308 EhInputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
310 static bool classof(const SectionBase *s) { return s->kind() == EHFrame; }
311 template <class ELFT> void split();
312 template <class ELFT, class RelTy> void split(ArrayRef<RelTy> rels);
314 // Splittable sections are handled as a sequence of data
315 // rather than a single large blob of data.
316 std::vector<EhSectionPiece> pieces;
318 SyntheticSection *getParent() const;
321 // This is a section that is added directly to an output section
322 // instead of needing special combination via a synthetic section. This
323 // includes all input sections with the exceptions of SHF_MERGE and
324 // .eh_frame. It also includes the synthetic sections themselves.
325 class InputSection : public InputSectionBase {
327 InputSection(InputFile *f, uint64_t flags, uint32_t type, uint32_t alignment,
328 ArrayRef<uint8_t> data, StringRef name, Kind k = Regular);
329 template <class ELFT>
330 InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
333 // Write this section to a mmap'ed file, assuming Buf is pointing to
334 // beginning of the output section.
335 template <class ELFT> void writeTo(uint8_t *buf);
337 uint64_t getOffset(uint64_t offset) const { return outSecOff + offset; }
339 OutputSection *getParent() const;
341 // This variable has two usages. Initially, it represents an index in the
342 // OutputSection's InputSection list, and is used when ordering SHF_LINK_ORDER
343 // sections. After assignAddresses is called, it represents the offset from
344 // the beginning of the output section this section was assigned to.
345 uint64_t outSecOff = 0;
347 static bool classof(const SectionBase *s);
349 InputSectionBase *getRelocatedSection() const;
351 template <class ELFT, class RelTy>
352 void relocateNonAlloc(uint8_t *buf, llvm::ArrayRef<RelTy> rels);
355 uint32_t eqClass[2] = {0, 0};
357 // Called by ICF to merge two input sections.
358 void replace(InputSection *other);
360 static InputSection discarded;
363 template <class ELFT, class RelTy>
364 void copyRelocations(uint8_t *buf, llvm::ArrayRef<RelTy> rels);
366 template <class ELFT> void copyShtGroup(uint8_t *buf);
369 // The list of all input sections.
370 extern std::vector<InputSectionBase *> inputSections;
374 std::string toString(const elf::InputSectionBase *);