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