xref: /llvm-project-15.0.7/lld/ELF/MarkLive.cpp (revision 64f5f6d7)
1 //===- MarkLive.cpp -------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements --gc-sections, which is a feature to remove unused
10 // sections from output. Unused sections are sections that are not reachable
11 // from known GC-root symbols or sections. Naturally the feature is
12 // implemented as a mark-sweep garbage collector.
13 //
14 // Here's how it works. Each InputSectionBase has a "Live" bit. The bit is off
15 // by default. Starting with GC-root symbols or sections, markLive function
16 // defined in this file visits all reachable sections to set their Live
17 // bits. Writer will then ignore sections whose Live bits are off, so that
18 // such sections are not included into output.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "MarkLive.h"
23 #include "InputSection.h"
24 #include "LinkerScript.h"
25 #include "SymbolTable.h"
26 #include "Symbols.h"
27 #include "SyntheticSections.h"
28 #include "Target.h"
29 #include "lld/Common/CommonLinkerContext.h"
30 #include "lld/Common/Strings.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Object/ELF.h"
33 #include "llvm/Support/TimeProfiler.h"
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 using namespace lld;
41 using namespace lld::elf;
42 
43 namespace {
44 template <class ELFT> class MarkLive {
45 public:
46   MarkLive(unsigned partition) : partition(partition) {}
47 
48   void run();
49   void moveToMain();
50 
51 private:
52   void enqueue(InputSectionBase *sec, uint64_t offset);
53   void markSymbol(Symbol *sym);
54   void mark();
55 
56   template <class RelTy>
57   void resolveReloc(InputSectionBase &sec, RelTy &rel, bool fromFDE);
58 
59   template <class RelTy>
60   void scanEhFrameSection(EhInputSection &eh, ArrayRef<RelTy> rels);
61 
62   // The index of the partition that we are currently processing.
63   unsigned partition;
64 
65   // A list of sections to visit.
66   SmallVector<InputSection *, 0> queue;
67 
68   // There are normally few input sections whose names are valid C
69   // identifiers, so we just store a SmallVector instead of a multimap.
70   DenseMap<StringRef, SmallVector<InputSectionBase *, 0>> cNamedSections;
71 };
72 } // namespace
73 
74 template <class ELFT>
75 static uint64_t getAddend(InputSectionBase &sec,
76                           const typename ELFT::Rel &rel) {
77   return target->getImplicitAddend(sec.data().begin() + rel.r_offset,
78                                    rel.getType(config->isMips64EL));
79 }
80 
81 template <class ELFT>
82 static uint64_t getAddend(InputSectionBase &sec,
83                           const typename ELFT::Rela &rel) {
84   return rel.r_addend;
85 }
86 
87 template <class ELFT>
88 template <class RelTy>
89 void MarkLive<ELFT>::resolveReloc(InputSectionBase &sec, RelTy &rel,
90                                   bool fromFDE) {
91   Symbol &sym = sec.getFile<ELFT>()->getRelocTargetSym(rel);
92 
93   // If a symbol is referenced in a live section, it is used.
94   sym.used = true;
95 
96   if (auto *d = dyn_cast<Defined>(&sym)) {
97     auto *relSec = dyn_cast_or_null<InputSectionBase>(d->section);
98     if (!relSec)
99       return;
100 
101     uint64_t offset = d->value;
102     if (d->isSection())
103       offset += getAddend<ELFT>(sec, rel);
104 
105     // fromFDE being true means this is referenced by a FDE in a .eh_frame
106     // piece. The relocation points to the described function or to a LSDA. We
107     // only need to keep the LSDA live, so ignore anything that points to
108     // executable sections. If the LSDA is in a section group or has the
109     // SHF_LINK_ORDER flag, we ignore the relocation as well because (a) if the
110     // associated text section is live, the LSDA will be retained due to section
111     // group/SHF_LINK_ORDER rules (b) if the associated text section should be
112     // discarded, marking the LSDA will unnecessarily retain the text section.
113     if (!(fromFDE && ((relSec->flags & (SHF_EXECINSTR | SHF_LINK_ORDER)) ||
114                       relSec->nextInSectionGroup)))
115       enqueue(relSec, offset);
116     return;
117   }
118 
119   if (auto *ss = dyn_cast<SharedSymbol>(&sym))
120     if (!ss->isWeak())
121       ss->getFile().isNeeded = true;
122 
123   for (InputSectionBase *sec : cNamedSections.lookup(sym.getName()))
124     enqueue(sec, 0);
125 }
126 
127 // The .eh_frame section is an unfortunate special case.
128 // The section is divided in CIEs and FDEs and the relocations it can have are
129 // * CIEs can refer to a personality function.
130 // * FDEs can refer to a LSDA
131 // * FDEs refer to the function they contain information about
132 // The last kind of relocation cannot keep the referred section alive, or they
133 // would keep everything alive in a common object file. In fact, each FDE is
134 // alive if the section it refers to is alive.
135 // To keep things simple, in here we just ignore the last relocation kind. The
136 // other two keep the referred section alive.
137 //
138 // A possible improvement would be to fully process .eh_frame in the middle of
139 // the gc pass. With that we would be able to also gc some sections holding
140 // LSDAs and personality functions if we found that they were unused.
141 template <class ELFT>
142 template <class RelTy>
143 void MarkLive<ELFT>::scanEhFrameSection(EhInputSection &eh,
144                                         ArrayRef<RelTy> rels) {
145   for (size_t i = 0, end = eh.pieces.size(); i < end; ++i) {
146     EhSectionPiece &piece = eh.pieces[i];
147     size_t firstRelI = piece.firstRelocation;
148     if (firstRelI == (unsigned)-1)
149       continue;
150 
151     if (read32<ELFT::TargetEndianness>(piece.data().data() + 4) == 0) {
152       // This is a CIE, we only need to worry about the first relocation. It is
153       // known to point to the personality function.
154       resolveReloc(eh, rels[firstRelI], false);
155       continue;
156     }
157 
158     uint64_t pieceEnd = piece.inputOff + piece.size;
159     for (size_t j = firstRelI, end2 = rels.size();
160          j < end2 && rels[j].r_offset < pieceEnd; ++j)
161       resolveReloc(eh, rels[j], true);
162   }
163 }
164 
165 // Some sections are used directly by the loader, so they should never be
166 // garbage-collected. This function returns true if a given section is such
167 // section.
168 static bool isReserved(InputSectionBase *sec) {
169   switch (sec->type) {
170   case SHT_FINI_ARRAY:
171   case SHT_INIT_ARRAY:
172   case SHT_PREINIT_ARRAY:
173     return true;
174   case SHT_NOTE:
175     // SHT_NOTE sections in a group are subject to garbage collection.
176     return !sec->nextInSectionGroup;
177   default:
178     // Support SHT_PROGBITS .init_array (https://golang.org/issue/50295) and
179     // .init_array.N (https://github.com/rust-lang/rust/issues/92181) for a
180     // while.
181     StringRef s = sec->name;
182     return s == ".init" || s == ".fini" || s.startswith(".init_array") ||
183            s == ".jcr" || s.startswith(".ctors") || s.startswith(".dtors");
184   }
185 }
186 
187 template <class ELFT>
188 void MarkLive<ELFT>::enqueue(InputSectionBase *sec, uint64_t offset) {
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 (sec == &InputSection::discarded)
194     return;
195 
196   // Usually, a whole section is marked as live or dead, but in mergeable
197   // (splittable) sections, each piece of data has independent liveness bit.
198   // So we explicitly tell it which offset is in use.
199   if (auto *ms = dyn_cast<MergeInputSection>(sec))
200     ms->getSectionPiece(offset)->live = true;
201 
202   // Set Sec->Partition to the meet (i.e. the "minimum") of Partition and
203   // Sec->Partition in the following lattice: 1 < other < 0. If Sec->Partition
204   // doesn't change, we don't need to do anything.
205   if (sec->partition == 1 || sec->partition == partition)
206     return;
207   sec->partition = sec->partition ? 1 : partition;
208 
209   // Add input section to the queue.
210   if (InputSection *s = dyn_cast<InputSection>(sec))
211     queue.push_back(s);
212 }
213 
214 template <class ELFT> void MarkLive<ELFT>::markSymbol(Symbol *sym) {
215   if (auto *d = dyn_cast_or_null<Defined>(sym))
216     if (auto *isec = dyn_cast_or_null<InputSectionBase>(d->section))
217       enqueue(isec, d->value);
218 }
219 
220 // This is the main function of the garbage collector.
221 // Starting from GC-root sections, this function visits all reachable
222 // sections to set their "Live" bits.
223 template <class ELFT> void MarkLive<ELFT>::run() {
224   // Add GC root symbols.
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 (Symbol *sym : symtab->symbols())
229     if (sym->includeInDynsym() && sym->partition == partition)
230       markSymbol(sym);
231 
232   // If this isn't the main partition, that's all that we need to preserve.
233   if (partition != 1) {
234     mark();
235     return;
236   }
237 
238   markSymbol(symtab->find(config->entry));
239   markSymbol(symtab->find(config->init));
240   markSymbol(symtab->find(config->fini));
241   for (StringRef s : config->undefined)
242     markSymbol(symtab->find(s));
243   for (StringRef s : script->referencedSymbols)
244     markSymbol(symtab->find(s));
245 
246   for (InputSectionBase *sec : inputSections) {
247     // Mark .eh_frame sections as live because there are usually no relocations
248     // that point to .eh_frames. Otherwise, the garbage collector would drop
249     // all of them. We also want to preserve personality routines and LSDA
250     // referenced by .eh_frame sections, so we scan them for that here.
251     if (auto *eh = dyn_cast<EhInputSection>(sec)) {
252       eh->markLive();
253 
254       const RelsOrRelas<ELFT> rels = eh->template relsOrRelas<ELFT>();
255       if (rels.areRelocsRel())
256         scanEhFrameSection(*eh, rels.rels);
257       else if (rels.relas.size())
258         scanEhFrameSection(*eh, rels.relas);
259       continue;
260     }
261 
262     if (sec->flags & SHF_GNU_RETAIN) {
263       enqueue(sec, 0);
264       continue;
265     }
266     if (sec->flags & SHF_LINK_ORDER)
267       continue;
268 
269     // Usually, non-SHF_ALLOC sections are not removed even if they are
270     // unreachable through relocations because reachability is not a good signal
271     // whether they are garbage or not (e.g. there is usually no section
272     // referring to a .comment section, but we want to keep it.) When a
273     // non-SHF_ALLOC section is retained, we also retain sections dependent on
274     // it.
275     //
276     // Note on SHF_LINK_ORDER: Such sections contain metadata and they
277     // have a reverse dependency on the InputSection they are linked with.
278     // We are able to garbage collect them.
279     //
280     // Note on SHF_REL{,A}: Such sections reach here only when -r
281     // or --emit-reloc were given. And they are subject of garbage
282     // collection because, if we remove a text section, we also
283     // remove its relocation section.
284     //
285     // Note on nextInSectionGroup: The ELF spec says that group sections are
286     // included or omitted as a unit. We take the interpretation that:
287     //
288     // - Group members (nextInSectionGroup != nullptr) are subject to garbage
289     //   collection.
290     // - Groups members are retained or discarded as a unit.
291     if (!(sec->flags & SHF_ALLOC)) {
292       bool isRel = sec->type == SHT_REL || sec->type == SHT_RELA;
293       if (!isRel && !sec->nextInSectionGroup) {
294         sec->markLive();
295         for (InputSection *isec : sec->dependentSections)
296           isec->markLive();
297       }
298     }
299 
300     // Preserve special sections and those which are specified in linker
301     // script KEEP command.
302     if (isReserved(sec) || script->shouldKeep(sec)) {
303       enqueue(sec, 0);
304     } else if ((!config->zStartStopGC || sec->name.startswith("__libc_")) &&
305                isValidCIdentifier(sec->name)) {
306       // As a workaround for glibc libc.a before 2.34
307       // (https://sourceware.org/PR27492), retain __libc_atexit and similar
308       // sections regardless of zStartStopGC.
309       cNamedSections[saver().save("__start_" + sec->name)].push_back(sec);
310       cNamedSections[saver().save("__stop_" + sec->name)].push_back(sec);
311     }
312   }
313 
314   mark();
315 }
316 
317 template <class ELFT> void MarkLive<ELFT>::mark() {
318   // Mark all reachable sections.
319   while (!queue.empty()) {
320     InputSectionBase &sec = *queue.pop_back_val();
321 
322     const RelsOrRelas<ELFT> rels = sec.template relsOrRelas<ELFT>();
323     for (const typename ELFT::Rel &rel : rels.rels)
324       resolveReloc(sec, rel, false);
325     for (const typename ELFT::Rela &rel : rels.relas)
326       resolveReloc(sec, rel, false);
327 
328     for (InputSectionBase *isec : sec.dependentSections)
329       enqueue(isec, 0);
330 
331     // Mark the next group member.
332     if (sec.nextInSectionGroup)
333       enqueue(sec.nextInSectionGroup, 0);
334   }
335 }
336 
337 // Move the sections for some symbols to the main partition, specifically ifuncs
338 // (because they can result in an IRELATIVE being added to the main partition's
339 // GOT, which means that the ifunc must be available when the main partition is
340 // loaded) and TLS symbols (because we only know how to correctly process TLS
341 // relocations for the main partition).
342 //
343 // We also need to move sections whose names are C identifiers that are referred
344 // to from __start_/__stop_ symbols because there will only be one set of
345 // symbols for the whole program.
346 template <class ELFT> void MarkLive<ELFT>::moveToMain() {
347   for (ELFFileBase *file : objectFiles)
348     for (Symbol *s : file->getSymbols())
349       if (auto *d = dyn_cast<Defined>(s))
350         if ((d->type == STT_GNU_IFUNC || d->type == STT_TLS) && d->section &&
351             d->section->isLive())
352           markSymbol(s);
353 
354   for (InputSectionBase *sec : inputSections) {
355     if (!sec->isLive() || !isValidCIdentifier(sec->name))
356       continue;
357     if (symtab->find(("__start_" + sec->name).str()) ||
358         symtab->find(("__stop_" + sec->name).str()))
359       enqueue(sec, 0);
360   }
361 
362   mark();
363 }
364 
365 // Before calling this function, Live bits are off for all
366 // input sections. This function make some or all of them on
367 // so that they are emitted to the output file.
368 template <class ELFT> void elf::markLive() {
369   llvm::TimeTraceScope timeScope("markLive");
370   // If --gc-sections is not given, retain all input sections.
371   if (!config->gcSections) {
372     // If a DSO defines a symbol referenced in a regular object, it is needed.
373     for (Symbol *sym : symtab->symbols())
374       if (auto *s = dyn_cast<SharedSymbol>(sym))
375         if (s->isUsedInRegularObj && !s->isWeak())
376           s->getFile().isNeeded = true;
377     return;
378   }
379 
380   for (InputSectionBase *sec : inputSections)
381     sec->markDead();
382 
383   // Follow the graph to mark all live sections.
384   for (unsigned curPart = 1; curPart <= partitions.size(); ++curPart)
385     MarkLive<ELFT>(curPart).run();
386 
387   // If we have multiple partitions, some sections need to live in the main
388   // partition even if they were allocated to a loadable partition. Move them
389   // there now.
390   if (partitions.size() != 1)
391     MarkLive<ELFT>(1).moveToMain();
392 
393   // Report garbage-collected sections.
394   if (config->printGcSections)
395     for (InputSectionBase *sec : inputSections)
396       if (!sec->isLive())
397         message("removing unused section " + toString(sec));
398 }
399 
400 template void elf::markLive<ELF32LE>();
401 template void elf::markLive<ELF32BE>();
402 template void elf::markLive<ELF64LE>();
403 template void elf::markLive<ELF64BE>();
404