xref: /llvm-project-15.0.7/lld/ELF/MarkLive.cpp (revision b7760210)
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 *Sec;
49   typename ELFT::uint Offset;
50 };
51 } // end anonymous namespace
52 
53 template <class ELFT>
54 static typename ELFT::uint getAddend(InputSectionBase &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 &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 &Sec, RelT &Rel) {
68   SymbolBody &B = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
69   auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
70   if (!D || !D->Section)
71     return {nullptr, 0};
72   typename ELFT::uint Offset = D->Value;
73   if (D->isSection())
74     Offset += getAddend<ELFT>(Sec, Rel);
75   return {D->Section->Repl, Offset};
76 }
77 
78 // Calls Fn for each section that Sec refers to via relocations.
79 template <class ELFT>
80 static void forEachSuccessor(InputSection &Sec,
81                              std::function<void(ResolvedReloc<ELFT>)> Fn) {
82   if (Sec.AreRelocsRela) {
83     for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
84       Fn(resolveReloc<ELFT>(Sec, Rel));
85   } else {
86     for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
87       Fn(resolveReloc<ELFT>(Sec, Rel));
88   }
89   for (InputSectionBase *IS : Sec.DependentSections)
90     Fn({IS, 0});
91 }
92 
93 // The .eh_frame section is an unfortunate special case.
94 // The section is divided in CIEs and FDEs and the relocations it can have are
95 // * CIEs can refer to a personality function.
96 // * FDEs can refer to a LSDA
97 // * FDEs refer to the function they contain information about
98 // The last kind of relocation cannot keep the referred section alive, or they
99 // would keep everything alive in a common object file. In fact, each FDE is
100 // alive if the section it refers to is alive.
101 // To keep things simple, in here we just ignore the last relocation kind. The
102 // other two keep the referred section alive.
103 //
104 // A possible improvement would be to fully process .eh_frame in the middle of
105 // the gc pass. With that we would be able to also gc some sections holding
106 // LSDAs and personality functions if we found that they were unused.
107 template <class ELFT, class RelTy>
108 static void
109 scanEhFrameSection(EhInputSection<ELFT> &EH, ArrayRef<RelTy> Rels,
110                    std::function<void(ResolvedReloc<ELFT>)> Enqueue) {
111   const endianness E = ELFT::TargetEndianness;
112   for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) {
113     EhSectionPiece &Piece = EH.Pieces[I];
114     unsigned FirstRelI = Piece.FirstRelocation;
115     if (FirstRelI == (unsigned)-1)
116       continue;
117     if (read32<E>(Piece.data().data() + 4) == 0) {
118       // This is a CIE, we only need to worry about the first relocation. It is
119       // known to point to the personality function.
120       Enqueue(resolveReloc<ELFT>(EH, Rels[FirstRelI]));
121       continue;
122     }
123     // This is a FDE. The relocations point to the described function or to
124     // a LSDA. We only need to keep the LSDA alive, so ignore anything that
125     // points to executable sections.
126     typename ELFT::uint PieceEnd = Piece.InputOff + Piece.size();
127     for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) {
128       const RelTy &Rel = Rels[I2];
129       if (Rel.r_offset >= PieceEnd)
130         break;
131       ResolvedReloc<ELFT> R = resolveReloc<ELFT>(EH, Rels[I2]);
132       if (!R.Sec || R.Sec == &InputSection::Discarded)
133         continue;
134       if (R.Sec->Flags & SHF_EXECINSTR)
135         continue;
136       Enqueue({R.Sec, 0});
137     }
138   }
139 }
140 
141 template <class ELFT>
142 static void
143 scanEhFrameSection(EhInputSection<ELFT> &EH,
144                    std::function<void(ResolvedReloc<ELFT>)> Enqueue) {
145   if (!EH.NumRelocations)
146     return;
147 
148   // Unfortunately we need to split .eh_frame early since some relocations in
149   // .eh_frame keep other section alive and some don't.
150   EH.split();
151 
152   if (EH.AreRelocsRela)
153     scanEhFrameSection(EH, EH.template relas<ELFT>(), Enqueue);
154   else
155     scanEhFrameSection(EH, EH.template rels<ELFT>(), Enqueue);
156 }
157 
158 // We do not garbage-collect two types of sections:
159 // 1) Sections used by the loader (.init, .fini, .ctors, .dtors or .jcr)
160 // 2) Non-allocatable sections which typically contain debugging information
161 template <class ELFT> static bool isReserved(InputSectionBase *Sec) {
162   switch (Sec->Type) {
163   case SHT_FINI_ARRAY:
164   case SHT_INIT_ARRAY:
165   case SHT_NOTE:
166   case SHT_PREINIT_ARRAY:
167     return true;
168   default:
169     if (Sec->Flags & SHF_LINK_ORDER)
170       return false;
171 
172     if (!(Sec->Flags & SHF_ALLOC))
173       return true;
174 
175     // We do not want to reclaim sections if they can be referred
176     // by __start_* and __stop_* symbols.
177     StringRef S = Sec->Name;
178     if (isValidCIdentifier(S))
179       return true;
180 
181     return S.startswith(".ctors") || S.startswith(".dtors") ||
182            S.startswith(".init") || S.startswith(".fini") ||
183            S.startswith(".jcr");
184   }
185 }
186 
187 // This is the main function of the garbage collector.
188 // Starting from GC-root sections, this function visits all reachable
189 // sections to set their "Live" bits.
190 template <class ELFT> void elf::markLive() {
191   SmallVector<InputSection *, 256> Q;
192 
193   auto Enqueue = [&](ResolvedReloc<ELFT> R) {
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 (!R.Sec || R.Sec == &InputSection::Discarded)
199       return;
200 
201     // We don't gc non alloc sections.
202     if (!(R.Sec->Flags & SHF_ALLOC))
203       return;
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<ELFT>>(R.Sec))
209       MS->markLiveAt(R.Offset);
210 
211     if (R.Sec->Live)
212       return;
213     R.Sec->Live = true;
214     // Add input section to the queue.
215     if (InputSection *S = dyn_cast<InputSection>(R.Sec))
216       Q.push_back(S);
217   };
218 
219   auto MarkSymbol = [&](const SymbolBody *Sym) {
220     if (auto *D = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
221       Enqueue({D->Section, D->Value});
222   };
223 
224   // Add GC root symbols.
225   MarkSymbol(Symtab<ELFT>::X->find(Config->Entry));
226   MarkSymbol(Symtab<ELFT>::X->find(Config->Init));
227   MarkSymbol(Symtab<ELFT>::X->find(Config->Fini));
228   for (StringRef S : Config->Undefined)
229     MarkSymbol(Symtab<ELFT>::X->find(S));
230 
231   // Preserve externally-visible symbols if the symbols defined by this
232   // file can interrupt other ELF file's symbols at runtime.
233   for (const Symbol *S : Symtab<ELFT>::X->getSymbols())
234     if (S->includeInDynsym())
235       MarkSymbol(S->body());
236 
237   // Preserve special sections and those which are specified in linker
238   // script KEEP command.
239   for (InputSectionBase *Sec : Symtab<ELFT>::X->Sections) {
240     // .eh_frame is always marked as live now, but also it can reference to
241     // sections that contain personality. We preserve all non-text sections
242     // referred by .eh_frame here.
243     if (auto *EH = dyn_cast_or_null<EhInputSection<ELFT>>(Sec))
244       scanEhFrameSection<ELFT>(*EH, Enqueue);
245     if (isReserved<ELFT>(Sec) || Script<ELFT>::X->shouldKeep(Sec))
246       Enqueue({Sec, 0});
247   }
248 
249   // Mark all reachable sections.
250   while (!Q.empty())
251     forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
252 }
253 
254 template void elf::markLive<ELF32LE>();
255 template void elf::markLive<ELF32BE>();
256 template void elf::markLive<ELF64LE>();
257 template void elf::markLive<ELF64BE>();
258