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