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