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