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