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