xref: /llvm-project-15.0.7/lld/ELF/MarkLive.cpp (revision ed84df00)
1 //===- MarkLive.cpp -------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements --gc-sections, which is a feature to remove unused
11 // sections from output. Unused sections are sections that are not reachable
12 // from known GC-root symbols or sections. Naturally the feature is
13 // implemented as a mark-sweep garbage collector.
14 //
15 // Here's how it works. Each InputSectionBase has a "Live" bit. The bit is off
16 // by default. Starting with GC-root symbols or sections, markLive function
17 // defined in this file visits all reachable sections to set their Live
18 // bits. Writer will then ignore sections whose Live bits are off, so that
19 // such sections are not included into output.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "InputSection.h"
24 #include "LinkerScript.h"
25 #include "OutputSections.h"
26 #include "Strings.h"
27 #include "SymbolTable.h"
28 #include "Symbols.h"
29 #include "Target.h"
30 #include "Writer.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Object/ELF.h"
33 #include <functional>
34 #include <vector>
35 
36 using namespace llvm;
37 using namespace llvm::ELF;
38 using namespace llvm::object;
39 using namespace llvm::support::endian;
40 
41 using namespace lld;
42 using namespace lld::elf;
43 
44 namespace {
45 // A resolved relocation. The Sec and Offset fields are set if the relocation
46 // was resolved to an offset within a section.
47 template <class ELFT> struct ResolvedReloc {
48   InputSectionBase<ELFT> *Sec;
49   typename ELFT::uint Offset;
50 };
51 } // end anonymous namespace
52 
53 template <class ELFT>
54 static typename ELFT::uint getAddend(InputSectionBase<ELFT> &Sec,
55                                      const typename ELFT::Rel &Rel) {
56   return Target->getImplicitAddend(Sec.Data.begin() + Rel.r_offset,
57                                    Rel.getType(Config->Mips64EL));
58 }
59 
60 template <class ELFT>
61 static typename ELFT::uint getAddend(InputSectionBase<ELFT> &Sec,
62                                      const typename ELFT::Rela &Rel) {
63   return Rel.r_addend;
64 }
65 
66 template <class ELFT, class RelT>
67 static ResolvedReloc<ELFT> resolveReloc(InputSectionBase<ELFT> &Sec,
68                                         RelT &Rel) {
69   SymbolBody &B = Sec.getFile()->getRelocTargetSym(Rel);
70   auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
71   if (!D || !D->Section)
72     return {nullptr, 0};
73   typename ELFT::uint Offset = D->Value;
74   if (D->isSection())
75     Offset += getAddend(Sec, Rel);
76   return {D->Section->Repl, Offset};
77 }
78 
79 // Calls Fn for each section that Sec refers to via relocations.
80 template <class ELFT>
81 static void forEachSuccessor(InputSection<ELFT> &Sec,
82                              std::function<void(ResolvedReloc<ELFT>)> Fn) {
83   ELFFile<ELFT> &Obj = Sec.getFile()->getObj();
84   for (const typename ELFT::Shdr *RelSec : Sec.RelocSections) {
85     if (RelSec->sh_type == SHT_RELA) {
86       for (const typename ELFT::Rela &Rel : Obj.relas(RelSec))
87         Fn(resolveReloc(Sec, Rel));
88     } else {
89       for (const typename ELFT::Rel &Rel : Obj.rels(RelSec))
90         Fn(resolveReloc(Sec, Rel));
91     }
92   }
93   if (Sec.DependentSection)
94     Fn({Sec.DependentSection, 0});
95 }
96 
97 // The .eh_frame section is an unfortunate special case.
98 // The section is divided in CIEs and FDEs and the relocations it can have are
99 // * CIEs can refer to a personality function.
100 // * FDEs can refer to a LSDA
101 // * FDEs refer to the function they contain information about
102 // The last kind of relocation cannot keep the referred section alive, or they
103 // would keep everything alive in a common object file. In fact, each FDE is
104 // alive if the section it refers to is alive.
105 // To keep things simple, in here we just ignore the last relocation kind. The
106 // other two keep the referred section alive.
107 //
108 // A possible improvement would be to fully process .eh_frame in the middle of
109 // the gc pass. With that we would be able to also gc some sections holding
110 // LSDAs and personality functions if we found that they were unused.
111 template <class ELFT, class RelTy>
112 static void
113 scanEhFrameSection(EhInputSection<ELFT> &EH, ArrayRef<RelTy> Rels,
114                    std::function<void(ResolvedReloc<ELFT>)> Enqueue) {
115   const endianness E = ELFT::TargetEndianness;
116   for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) {
117     EhSectionPiece &Piece = EH.Pieces[I];
118     unsigned FirstRelI = Piece.FirstRelocation;
119     if (FirstRelI == (unsigned)-1)
120       continue;
121     if (read32<E>(Piece.data().data() + 4) == 0) {
122       // This is a CIE, we only need to worry about the first relocation. It is
123       // known to point to the personality function.
124       Enqueue(resolveReloc(EH, Rels[FirstRelI]));
125       continue;
126     }
127     // This is a FDE. The relocations point to the described function or to
128     // a LSDA. We only need to keep the LSDA alive, so ignore anything that
129     // points to executable sections.
130     typename ELFT::uint PieceEnd = Piece.InputOff + Piece.size();
131     for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) {
132       const RelTy &Rel = Rels[I2];
133       if (Rel.r_offset >= PieceEnd)
134         break;
135       ResolvedReloc<ELFT> R = resolveReloc(EH, Rels[I2]);
136       if (!R.Sec || R.Sec == &InputSection<ELFT>::Discarded)
137         continue;
138       if (R.Sec->getSectionHdr()->sh_flags & SHF_EXECINSTR)
139         continue;
140       Enqueue({R.Sec, 0});
141     }
142   }
143 }
144 
145 template <class ELFT>
146 static void
147 scanEhFrameSection(EhInputSection<ELFT> &EH,
148                    std::function<void(ResolvedReloc<ELFT>)> Enqueue) {
149   if (!EH.RelocSection)
150     return;
151 
152   // Unfortunately we need to split .eh_frame early since some relocations in
153   // .eh_frame keep other section alive and some don't.
154   EH.split();
155 
156   ELFFile<ELFT> &EObj = EH.getFile()->getObj();
157   if (EH.RelocSection->sh_type == SHT_RELA)
158     scanEhFrameSection(EH, EObj.relas(EH.RelocSection), Enqueue);
159   else
160     scanEhFrameSection(EH, EObj.rels(EH.RelocSection), Enqueue);
161 }
162 
163 // We do not garbage-collect two types of sections:
164 // 1) Sections used by the loader (.init, .fini, .ctors, .dtors or .jcr)
165 // 2) Non-allocatable sections which typically contain debugging information
166 template <class ELFT> static bool isReserved(InputSectionBase<ELFT> *Sec) {
167   switch (Sec->getSectionHdr()->sh_type) {
168   case SHT_FINI_ARRAY:
169   case SHT_INIT_ARRAY:
170   case SHT_NOTE:
171   case SHT_PREINIT_ARRAY:
172     return true;
173   default:
174     if (!(Sec->getSectionHdr()->sh_flags & SHF_ALLOC))
175       return true;
176 
177     // We do not want to reclaim sections if they can be referred
178     // by __start_* and __stop_* symbols.
179     StringRef S = Sec->Name;
180     if (isValidCIdentifier(S))
181       return true;
182 
183     return S.startswith(".ctors") || S.startswith(".dtors") ||
184            S.startswith(".init") || S.startswith(".fini") ||
185            S.startswith(".jcr");
186   }
187 }
188 
189 // This is the main function of the garbage collector.
190 // Starting from GC-root sections, this function visits all reachable
191 // sections to set their "Live" bits.
192 template <class ELFT> void elf::markLive() {
193   SmallVector<InputSection<ELFT> *, 256> Q;
194 
195   auto Enqueue = [&](ResolvedReloc<ELFT> R) {
196     // Skip over discarded sections. This in theory shouldn't happen, because
197     // the ELF spec doesn't allow a relocation to point to a deduplicated
198     // COMDAT section directly. Unfortunately this happens in practice (e.g.
199     // .eh_frame) so we need to add a check.
200     if (!R.Sec || R.Sec == &InputSection<ELFT>::Discarded)
201       return;
202 
203     // We don't gc non alloc sections.
204     if (!(R.Sec->getSectionHdr()->sh_flags & SHF_ALLOC))
205       return;
206 
207     // Usually, a whole section is marked as live or dead, but in mergeable
208     // (splittable) sections, each piece of data has independent liveness bit.
209     // So we explicitly tell it which offset is in use.
210     if (auto *MS = dyn_cast<MergeInputSection<ELFT>>(R.Sec))
211       MS->markLiveAt(R.Offset);
212 
213     if (R.Sec->Live)
214       return;
215     R.Sec->Live = true;
216     // Add input section to the queue.
217     if (InputSection<ELFT> *S = dyn_cast<InputSection<ELFT>>(R.Sec))
218       Q.push_back(S);
219   };
220 
221   auto MarkSymbol = [&](const SymbolBody *Sym) {
222     if (auto *D = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
223       Enqueue({D->Section, D->Value});
224   };
225 
226   // Add GC root symbols.
227   MarkSymbol(Symtab<ELFT>::X->find(Config->Entry));
228   MarkSymbol(Symtab<ELFT>::X->find(Config->Init));
229   MarkSymbol(Symtab<ELFT>::X->find(Config->Fini));
230   for (StringRef S : Config->Undefined)
231     MarkSymbol(Symtab<ELFT>::X->find(S));
232 
233   // Preserve externally-visible symbols if the symbols defined by this
234   // file can interrupt other ELF file's symbols at runtime.
235   for (const Symbol *S : Symtab<ELFT>::X->getSymbols())
236     if (S->includeInDynsym())
237       MarkSymbol(S->body());
238 
239   // Preserve special sections and those which are specified in linker
240   // script KEEP command.
241   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
242     for (InputSectionBase<ELFT> *Sec : F->getSections()) {
243       if (!Sec || Sec == &InputSection<ELFT>::Discarded)
244         continue;
245       // .eh_frame is always marked as live now, but also it can reference to
246       // sections that contain personality. We preserve all non-text sections
247       // referred by .eh_frame here.
248       if (auto *EH = dyn_cast_or_null<EhInputSection<ELFT>>(Sec))
249         scanEhFrameSection<ELFT>(*EH, Enqueue);
250       if (isReserved(Sec) || Script<ELFT>::X->shouldKeep(Sec))
251         Enqueue({Sec, 0});
252     }
253   }
254 
255   // Mark all reachable sections.
256   while (!Q.empty())
257     forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
258 }
259 
260 template void elf::markLive<ELF32LE>();
261 template void elf::markLive<ELF32BE>();
262 template void elf::markLive<ELF64LE>();
263 template void elf::markLive<ELF64BE>();
264