xref: /llvm-project-15.0.7/lld/ELF/MarkLive.cpp (revision 1cb0256a)
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 struct ResolvedReloc {
48   InputSectionBase *Sec;
49   uint64_t 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 void resolveReloc(InputSectionBase &Sec, RelT &Rel,
68                          std::function<void(ResolvedReloc)> Fn) {
69   SymbolBody &B = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
70   auto *D = dyn_cast<DefinedRegular>(&B);
71   if (!D || !D->Section)
72     return;
73   typename ELFT::uint Offset = D->Value;
74   if (D->isSection())
75     Offset += getAddend<ELFT>(Sec, Rel);
76   Fn({D->Section->Repl, Offset});
77 }
78 
79 // Calls Fn for each section that Sec refers to via relocations.
80 template <class ELFT>
81 static void forEachSuccessor(InputSection &Sec,
82                              std::function<void(ResolvedReloc)> Fn) {
83   if (Sec.AreRelocsRela) {
84     for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
85       resolveReloc<ELFT>(Sec, Rel, Fn);
86   } else {
87     for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
88       resolveReloc<ELFT>(Sec, Rel, Fn);
89   }
90   for (InputSectionBase *IS : Sec.DependentSections)
91     Fn({IS, 0});
92 }
93 
94 // The .eh_frame section is an unfortunate special case.
95 // The section is divided in CIEs and FDEs and the relocations it can have are
96 // * CIEs can refer to a personality function.
97 // * FDEs can refer to a LSDA
98 // * FDEs refer to the function they contain information about
99 // The last kind of relocation cannot keep the referred section alive, or they
100 // would keep everything alive in a common object file. In fact, each FDE is
101 // alive if the section it refers to is alive.
102 // To keep things simple, in here we just ignore the last relocation kind. The
103 // other two keep the referred section alive.
104 //
105 // A possible improvement would be to fully process .eh_frame in the middle of
106 // the gc pass. With that we would be able to also gc some sections holding
107 // LSDAs and personality functions if we found that they were unused.
108 template <class ELFT, class RelTy>
109 static void scanEhFrameSection(EhInputSection<ELFT> &EH, ArrayRef<RelTy> Rels,
110                                std::function<void(ResolvedReloc)> 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       resolveReloc<ELFT>(EH, Rels[FirstRelI], Enqueue);
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       resolveReloc<ELFT>(EH, Rels[I2], [&](ResolvedReloc R) {
132         if (!R.Sec || R.Sec == &InputSection::Discarded)
133           return;
134         if (R.Sec->Flags & SHF_EXECINSTR)
135           return;
136         Enqueue({R.Sec, 0});
137       });
138     }
139   }
140 }
141 
142 template <class ELFT>
143 static void scanEhFrameSection(EhInputSection<ELFT> &EH,
144                                std::function<void(ResolvedReloc)> 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     StringRef S = Sec->Name;
176     return S.startswith(".ctors") || S.startswith(".dtors") ||
177            S.startswith(".init") || S.startswith(".fini") ||
178            S.startswith(".jcr");
179   }
180 }
181 
182 // This is the main function of the garbage collector.
183 // Starting from GC-root sections, this function visits all reachable
184 // sections to set their "Live" bits.
185 template <class ELFT> void elf::markLive() {
186   SmallVector<InputSection *, 256> Q;
187 
188   auto Enqueue = [&](ResolvedReloc R) {
189     // Skip over discarded sections. This in theory shouldn't happen, because
190     // the ELF spec doesn't allow a relocation to point to a deduplicated
191     // COMDAT section directly. Unfortunately this happens in practice (e.g.
192     // .eh_frame) so we need to add a check.
193     if (R.Sec == &InputSection::Discarded)
194       return;
195 
196     // We don't gc non alloc sections.
197     if (!(R.Sec->Flags & SHF_ALLOC))
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     // Add input section to the queue.
210     if (InputSection *S = dyn_cast<InputSection>(R.Sec))
211       Q.push_back(S);
212   };
213 
214   auto MarkSymbol = [&](const SymbolBody *Sym) {
215     if (auto *D = dyn_cast_or_null<DefinedRegular>(Sym))
216       Enqueue({D->Section, D->Value});
217   };
218 
219   // Add GC root symbols.
220   MarkSymbol(Symtab<ELFT>::X->find(Config->Entry));
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   // Remember which __start_* or __stop_* symbols are used so that we don't gc
227   // those sections.
228   DenseSet<StringRef> UsedStartStopNames;
229 
230   // Preserve externally-visible symbols if the symbols defined by this
231   // file can interrupt other ELF file's symbols at runtime.
232   for (const Symbol *S : Symtab<ELFT>::X->getSymbols()) {
233     if (auto *U = dyn_cast_or_null<Undefined>(S->body())) {
234       StringRef Name = U->getName();
235       for (StringRef Prefix : {"__start_", "__stop_"})
236         if (Name.startswith(Prefix))
237           UsedStartStopNames.insert(Name.substr(Prefix.size()));
238     } else if (S->includeInDynsym()) {
239       MarkSymbol(S->body());
240     }
241   }
242 
243   // Preserve special sections and those which are specified in linker
244   // script KEEP command.
245   for (InputSectionBase *Sec : InputSections) {
246     // .eh_frame is always marked as live now, but also it can reference to
247     // sections that contain personality. We preserve all non-text sections
248     // referred by .eh_frame here.
249     if (auto *EH = dyn_cast_or_null<EhInputSection<ELFT>>(Sec))
250       scanEhFrameSection<ELFT>(*EH, Enqueue);
251     if (isReserved<ELFT>(Sec) || Script<ELFT>::X->shouldKeep(Sec) ||
252         UsedStartStopNames.count(Sec->Name))
253       Enqueue({Sec, 0});
254   }
255 
256   // Mark all reachable sections.
257   while (!Q.empty())
258     forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
259 }
260 
261 template void elf::markLive<ELF32LE>();
262 template void elf::markLive<ELF32BE>();
263 template void elf::markLive<ELF64LE>();
264 template void elf::markLive<ELF64BE>();
265