xref: /llvm-project-15.0.7/lld/ELF/MarkLive.cpp (revision e3748b5a)
1 //===- MarkLive.cpp -------------------------------------------------------===//
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 // This file implements --gc-sections, which is a feature to remove unused
10 // sections from output. Unused sections are sections that are not reachable
11 // from known GC-root symbols or sections. Naturally the feature is
12 // implemented as a mark-sweep garbage collector.
13 //
14 // Here's how it works. Each InputSectionBase has a "Live" bit. The bit is off
15 // by default. Starting with GC-root symbols or sections, markLive function
16 // defined in this file visits all reachable sections to set their Live
17 // bits. Writer will then ignore sections whose Live bits are off, so that
18 // such sections are not included into output.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "MarkLive.h"
23 #include "InputSection.h"
24 #include "LinkerScript.h"
25 #include "OutputSections.h"
26 #include "SymbolTable.h"
27 #include "Symbols.h"
28 #include "Target.h"
29 #include "lld/Common/Memory.h"
30 #include "lld/Common/Strings.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 template <class ELFT> class MarkLive {
46 public:
47   void run();
48 
49 private:
50   void enqueue(InputSectionBase *Sec, uint64_t Offset);
51   void markSymbol(Symbol *Sym);
52 
53   template <class RelTy>
54   void resolveReloc(InputSectionBase &Sec, RelTy &Rel, bool IsLSDA);
55 
56   template <class RelTy>
57   void scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels);
58 
59   // A list of sections to visit.
60   SmallVector<InputSection *, 256> Queue;
61 
62   // There are normally few input sections whose names are valid C
63   // identifiers, so we just store a std::vector instead of a multimap.
64   DenseMap<StringRef, std::vector<InputSectionBase *>> CNamedSections;
65 };
66 } // namespace
67 
68 template <class ELFT>
69 static uint64_t getAddend(InputSectionBase &Sec,
70                           const typename ELFT::Rel &Rel) {
71   return Target->getImplicitAddend(Sec.data().begin() + Rel.r_offset,
72                                    Rel.getType(Config->IsMips64EL));
73 }
74 
75 template <class ELFT>
76 static uint64_t getAddend(InputSectionBase &Sec,
77                           const typename ELFT::Rela &Rel) {
78   return Rel.r_addend;
79 }
80 
81 template <class ELFT>
82 template <class RelTy>
83 void MarkLive<ELFT>::resolveReloc(InputSectionBase &Sec, RelTy &Rel,
84                                   bool IsLSDA) {
85   Symbol &Sym = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
86 
87   // If a symbol is referenced in a live section, it is used.
88   Sym.Used = true;
89 
90   if (auto *D = dyn_cast<Defined>(&Sym)) {
91     auto *RelSec = dyn_cast_or_null<InputSectionBase>(D->Section);
92     if (!RelSec)
93       return;
94 
95     uint64_t Offset = D->Value;
96     if (D->isSection())
97       Offset += getAddend<ELFT>(Sec, Rel);
98 
99     if (!IsLSDA || !(RelSec->Flags & SHF_EXECINSTR))
100       enqueue(RelSec, Offset);
101     return;
102   }
103 
104   if (auto *SS = dyn_cast<SharedSymbol>(&Sym))
105     if (!SS->isWeak())
106       SS->getFile().IsNeeded = true;
107 
108   for (InputSectionBase *Sec : CNamedSections.lookup(Sym.getName()))
109     enqueue(Sec, 0);
110 }
111 
112 // The .eh_frame section is an unfortunate special case.
113 // The section is divided in CIEs and FDEs and the relocations it can have are
114 // * CIEs can refer to a personality function.
115 // * FDEs can refer to a LSDA
116 // * FDEs refer to the function they contain information about
117 // The last kind of relocation cannot keep the referred section alive, or they
118 // would keep everything alive in a common object file. In fact, each FDE is
119 // alive if the section it refers to is alive.
120 // To keep things simple, in here we just ignore the last relocation kind. The
121 // other two keep the referred section alive.
122 //
123 // A possible improvement would be to fully process .eh_frame in the middle of
124 // the gc pass. With that we would be able to also gc some sections holding
125 // LSDAs and personality functions if we found that they were unused.
126 template <class ELFT>
127 template <class RelTy>
128 void MarkLive<ELFT>::scanEhFrameSection(EhInputSection &EH,
129                                         ArrayRef<RelTy> Rels) {
130   for (size_t I = 0, End = EH.Pieces.size(); I < End; ++I) {
131     EhSectionPiece &Piece = EH.Pieces[I];
132     size_t FirstRelI = Piece.FirstRelocation;
133     if (FirstRelI == (unsigned)-1)
134       continue;
135 
136     if (read32<ELFT::TargetEndianness>(Piece.data().data() + 4) == 0) {
137       // This is a CIE, we only need to worry about the first relocation. It is
138       // known to point to the personality function.
139       resolveReloc(EH, Rels[FirstRelI], false);
140       continue;
141     }
142 
143     // This is a FDE. The relocations point to the described function or to
144     // a LSDA. We only need to keep the LSDA alive, so ignore anything that
145     // points to executable sections.
146     uint64_t PieceEnd = Piece.InputOff + Piece.Size;
147     for (size_t J = FirstRelI, End2 = Rels.size(); J < End2; ++J)
148       if (Rels[J].r_offset < PieceEnd)
149         resolveReloc(EH, Rels[J], true);
150   }
151 }
152 
153 // Some sections are used directly by the loader, so they should never be
154 // garbage-collected. This function returns true if a given section is such
155 // section.
156 static bool isReserved(InputSectionBase *Sec) {
157   switch (Sec->Type) {
158   case SHT_FINI_ARRAY:
159   case SHT_INIT_ARRAY:
160   case SHT_NOTE:
161   case SHT_PREINIT_ARRAY:
162     return true;
163   default:
164     StringRef S = Sec->Name;
165     return S.startswith(".ctors") || S.startswith(".dtors") ||
166            S.startswith(".init") || S.startswith(".fini") ||
167            S.startswith(".jcr");
168   }
169 }
170 
171 template <class ELFT>
172 void MarkLive<ELFT>::enqueue(InputSectionBase *Sec, uint64_t Offset) {
173   // Skip over discarded sections. This in theory shouldn't happen, because
174   // the ELF spec doesn't allow a relocation to point to a deduplicated
175   // COMDAT section directly. Unfortunately this happens in practice (e.g.
176   // .eh_frame) so we need to add a check.
177   if (Sec == &InputSection::Discarded)
178     return;
179 
180   // Usually, a whole section is marked as live or dead, but in mergeable
181   // (splittable) sections, each piece of data has independent liveness bit.
182   // So we explicitly tell it which offset is in use.
183   if (auto *MS = dyn_cast<MergeInputSection>(Sec))
184     MS->getSectionPiece(Offset)->Live = true;
185 
186   if (Sec->Live)
187     return;
188   Sec->Live = true;
189 
190   // Add input section to the queue.
191   if (InputSection *S = dyn_cast<InputSection>(Sec))
192     Queue.push_back(S);
193 }
194 
195 template <class ELFT> void MarkLive<ELFT>::markSymbol(Symbol *Sym) {
196   if (auto *D = dyn_cast_or_null<Defined>(Sym))
197     if (auto *IS = dyn_cast_or_null<InputSectionBase>(D->Section))
198       enqueue(IS, D->Value);
199 }
200 
201 // This is the main function of the garbage collector.
202 // Starting from GC-root sections, this function visits all reachable
203 // sections to set their "Live" bits.
204 template <class ELFT> void MarkLive<ELFT>::run() {
205   // Add GC root symbols.
206   markSymbol(Symtab->find(Config->Entry));
207   markSymbol(Symtab->find(Config->Init));
208   markSymbol(Symtab->find(Config->Fini));
209   for (StringRef S : Config->Undefined)
210     markSymbol(Symtab->find(S));
211   for (StringRef S : Script->ReferencedSymbols)
212     markSymbol(Symtab->find(S));
213 
214   // Preserve externally-visible symbols if the symbols defined by this
215   // file can interrupt other ELF file's symbols at runtime.
216   for (Symbol *S : Symtab->getSymbols())
217     if (S->includeInDynsym())
218       markSymbol(S);
219 
220   // Preserve special sections and those which are specified in linker
221   // script KEEP command.
222   for (InputSectionBase *Sec : InputSections) {
223     // Mark .eh_frame sections as live because there are usually no relocations
224     // that point to .eh_frames. Otherwise, the garbage collector would drop
225     // all of them. We also want to preserve personality routines and LSDA
226     // referenced by .eh_frame sections, so we scan them for that here.
227     if (auto *EH = dyn_cast<EhInputSection>(Sec)) {
228       EH->Live = true;
229       if (!EH->NumRelocations)
230         continue;
231 
232       if (EH->AreRelocsRela)
233         scanEhFrameSection(*EH, EH->template relas<ELFT>());
234       else
235         scanEhFrameSection(*EH, EH->template rels<ELFT>());
236     }
237 
238     if (Sec->Flags & SHF_LINK_ORDER)
239       continue;
240 
241     if (isReserved(Sec) || Script->shouldKeep(Sec)) {
242       enqueue(Sec, 0);
243     } else if (isValidCIdentifier(Sec->Name)) {
244       CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec);
245       CNamedSections[Saver.save("__stop_" + Sec->Name)].push_back(Sec);
246     }
247   }
248 
249   // Mark all reachable sections.
250   while (!Queue.empty()) {
251     InputSectionBase &Sec = *Queue.pop_back_val();
252 
253     if (Sec.AreRelocsRela) {
254       for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
255         resolveReloc(Sec, Rel, false);
256     } else {
257       for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
258         resolveReloc(Sec, Rel, false);
259     }
260 
261     for (InputSectionBase *IS : Sec.DependentSections)
262       enqueue(IS, 0);
263   }
264 }
265 
266 // Before calling this function, Live bits are off for all
267 // input sections. This function make some or all of them on
268 // so that they are emitted to the output file.
269 template <class ELFT> void elf::markLive() {
270   // If -gc-sections is not given, no sections are removed.
271   if (!Config->GcSections) {
272     for (InputSectionBase *Sec : InputSections)
273       Sec->Live = true;
274 
275     // If a DSO defines a symbol referenced in a regular object, it is needed.
276     for (Symbol *Sym : Symtab->getSymbols())
277       if (auto *S = dyn_cast<SharedSymbol>(Sym))
278         if (S->IsUsedInRegularObj && !S->isWeak())
279           S->getFile().IsNeeded = true;
280     return;
281   }
282 
283   // Otheriwse, do mark-sweep GC.
284   //
285   // The -gc-sections option works only for SHF_ALLOC sections
286   // (sections that are memory-mapped at runtime). So we can
287   // unconditionally make non-SHF_ALLOC sections alive except
288   // SHF_LINK_ORDER and SHT_REL/SHT_RELA sections.
289   //
290   // Usually, SHF_ALLOC sections are not removed even if they are
291   // unreachable through relocations because reachability is not
292   // a good signal whether they are garbage or not (e.g. there is
293   // usually no section referring to a .comment section, but we
294   // want to keep it.).
295   //
296   // Note on SHF_LINK_ORDER: Such sections contain metadata and they
297   // have a reverse dependency on the InputSection they are linked with.
298   // We are able to garbage collect them.
299   //
300   // Note on SHF_REL{,A}: Such sections reach here only when -r
301   // or -emit-reloc were given. And they are subject of garbage
302   // collection because, if we remove a text section, we also
303   // remove its relocation section.
304   for (InputSectionBase *Sec : InputSections) {
305     bool IsAlloc = (Sec->Flags & SHF_ALLOC);
306     bool IsLinkOrder = (Sec->Flags & SHF_LINK_ORDER);
307     bool IsRel = (Sec->Type == SHT_REL || Sec->Type == SHT_RELA);
308 
309     if (!IsAlloc && !IsLinkOrder && !IsRel)
310       Sec->Live = true;
311   }
312 
313   // Follow the graph to mark all live sections.
314   MarkLive<ELFT>().run();
315 
316   // Report garbage-collected sections.
317   if (Config->PrintGcSections)
318     for (InputSectionBase *Sec : InputSections)
319       if (!Sec->Live)
320         message("removing unused section " + toString(Sec));
321 }
322 
323 template void elf::markLive<ELF32LE>();
324 template void elf::markLive<ELF32BE>();
325 template void elf::markLive<ELF64LE>();
326 template void elf::markLive<ELF64BE>();
327