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 "InputFiles.h"
24#include "InputSection.h"
25#include "LinkerScript.h"
26#include "SymbolTable.h"
27#include "Symbols.h"
28#include "SyntheticSections.h"
29#include "Target.h"
30#include "lld/Common/Strings.h"
31#include "llvm/ADT/DenseMapInfoVariant.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/Support/Parallel.h"
34#include "llvm/Support/TimeProfiler.h"
35#include <variant>
36#include <vector>
37
38using namespace llvm;
39using namespace llvm::ELF;
40using namespace llvm::object;
41using namespace llvm::support::endian;
42using namespace lld;
43using namespace lld::elf;
44
45namespace {
46using SecOffset = std::pair<InputSectionBase *, unsigned>;
47
48// Something that can have an independent reason for being live.
49using LiveItem = std::variant<InputSectionBase *, Symbol *, SecOffset>;
50
51// The most proximate reason that something is live.
52struct LiveReason {
53 std::optional<LiveItem> item;
54 StringRef desc;
55};
56
57template <class ELFT, bool TrackWhyLive> class MarkLive {
58public:
59 MarkLive(Ctx &ctx) : ctx(ctx) {}
60
61 void run();
62 void printWhyLive(Symbol *s) const;
63
64private:
65 void enqueue(InputSectionBase *sec, uint64_t offset, Symbol *sym,
66 LiveReason reason);
67 void markSymbol(Symbol *sym, StringRef reason);
68 void mark();
69 void markParallel();
70
71 template <class RelTy>
72 void resolveReloc(InputSectionBase &sec, const RelTy &rel, bool fromFDE);
73
74 void scanEhFrameSection(EhInputSection &eh);
75
76 Ctx &ctx;
77
78 // A list of sections to visit.
79 SmallVector<InputSection *, 0> queue;
80
81 // There are normally few input sections whose names are valid C
82 // identifiers, so we just store a SmallVector instead of a multimap.
83 DenseMap<StringRef, SmallVector<InputSectionBase *, 0>> cNamedSections;
84
85 // The most proximate reason that something is live. This forms a DAG between
86 // LiveItems. Acyclicality is maintained by only admitting the first
87 // discovered reason for each LiveItem; this captures the acyclic region of
88 // the liveness graph around the GC roots.
89 DenseMap<LiveItem, LiveReason> whyLive;
90};
91} // namespace
92
93template <class ELFT>
94static uint64_t getAddend(Ctx &ctx, InputSectionBase &sec,
95 const typename ELFT::Rel &rel) {
96 return ctx.target->getImplicitAddend(buf: sec.content().begin() + rel.r_offset,
97 type: rel.getType(ctx.arg.isMips64EL));
98}
99
100template <class ELFT>
101static uint64_t getAddend(Ctx &, InputSectionBase &sec,
102 const typename ELFT::Rela &rel) {
103 return rel.r_addend;
104}
105
106// Currently, we assume all input CREL relocations have an explicit addend.
107template <class ELFT>
108static uint64_t getAddend(Ctx &, InputSectionBase &sec,
109 const typename ELFT::Crel &rel) {
110 return rel.r_addend;
111}
112
113template <class ELFT, bool TrackWhyLive>
114template <class RelTy>
115void MarkLive<ELFT, TrackWhyLive>::resolveReloc(InputSectionBase &sec,
116 const RelTy &rel,
117 bool fromFDE) {
118 // If a symbol is referenced in a live section, it is used.
119 Symbol *sym;
120 if constexpr (std::is_same_v<RelTy, Relocation>) {
121 assert(isa<EhInputSection>(sec));
122 sym = rel.sym;
123 } else {
124 sym = &sec.file->getRelocTargetSym(rel);
125 }
126 sym->setFlags(USED);
127
128 LiveReason reason;
129 if (TrackWhyLive) {
130 if constexpr (std::is_same_v<RelTy, Relocation>)
131 reason = {.item: SecOffset(&sec, rel.offset), .desc: "referenced by"};
132 else
133 reason = {.item: SecOffset(&sec, rel.r_offset), .desc: "referenced by"};
134 }
135
136 if (auto *d = dyn_cast<Defined>(Val: sym)) {
137 auto *relSec = dyn_cast_or_null<InputSectionBase>(Val: d->section);
138 if (!relSec)
139 return;
140
141 uint64_t offset = d->value;
142 if (d->isSection()) {
143 if constexpr (std::is_same_v<RelTy, Relocation>)
144 offset += rel.addend;
145 else
146 offset += getAddend<ELFT>(ctx, sec, rel);
147 // Skip out-of-bounds offsets to avoid an assertion failure in
148 // getSectionPiece.
149 if (auto *ms = dyn_cast<MergeInputSection>(Val: relSec);
150 ms && offset >= ms->content().size())
151 return;
152 }
153
154 // fromFDE being true means this is referenced by a FDE in a .eh_frame
155 // piece. The relocation points to the described function or to a LSDA. We
156 // only need to keep the LSDA live, so ignore anything that points to
157 // executable sections. If the LSDA is in a section group or has the
158 // SHF_LINK_ORDER flag, we ignore the relocation as well because (a) if the
159 // associated text section is live, the LSDA will be retained due to section
160 // group/SHF_LINK_ORDER rules (b) if the associated text section should be
161 // discarded, marking the LSDA will unnecessarily retain the text section.
162 if (!(fromFDE && std::is_same_v<RelTy, Relocation> &&
163 ((relSec->flags & (SHF_EXECINSTR | SHF_LINK_ORDER)) ||
164 relSec->nextInSectionGroup))) {
165 Symbol *canonicalSym = d;
166 if (TrackWhyLive && d->isSection()) {
167 // This is expensive, so ideally this would be deferred until it's known
168 // whether this reference contributes to a printed whyLive chain, but
169 // that determination cannot be made without knowing the enclosing
170 // symbol.
171 if (Symbol *s = relSec->getEnclosingSymbol(offset))
172 canonicalSym = s;
173 else
174 canonicalSym = nullptr;
175 }
176 enqueue(sec: relSec, offset, sym: canonicalSym, reason);
177 }
178 return;
179 }
180
181 if (auto *ss = dyn_cast<SharedSymbol>(Val: sym))
182 if (!ss->isWeak() && TrackWhyLive)
183 whyLive.try_emplace(Key: sym, Args&: reason);
184
185 for (InputSectionBase *sec : cNamedSections.lookup(Val: sym->getName()))
186 enqueue(sec, /*offset=*/0, /*sym=*/nullptr, reason);
187}
188
189// The .eh_frame section is an unfortunate special case.
190// The section is divided in CIEs and FDEs and the relocations it can have are
191// * CIEs can refer to a personality function.
192// * FDEs can refer to a LSDA
193// * FDEs refer to the function they contain information about
194// The last kind of relocation cannot keep the referred section alive, or they
195// would keep everything alive in a common object file. In fact, each FDE is
196// alive if the section it refers to is alive.
197// To keep things simple, in here we just ignore the last relocation kind. The
198// other two keep the referred section alive.
199//
200// A possible improvement would be to fully process .eh_frame in the middle of
201// the gc pass. With that we would be able to also gc some sections holding
202// LSDAs and personality functions if we found that they were unused.
203template <class ELFT, bool TrackWhyLive>
204void MarkLive<ELFT, TrackWhyLive>::scanEhFrameSection(EhInputSection &eh) {
205 if (TrackWhyLive)
206 whyLive.try_emplace(Key: &eh,
207 Args: LiveReason{.item: std::nullopt, .desc: "exception handling frame"});
208 ArrayRef<Relocation> rels = eh.rels;
209 for (const EhSectionPiece &cie : eh.cies)
210 if (cie.firstRelocation != unsigned(-1))
211 resolveReloc(eh, rels[cie.firstRelocation], false);
212 for (const EhSectionPiece &fde : eh.fdes) {
213 size_t firstRelI = fde.firstRelocation;
214 if (firstRelI == (unsigned)-1)
215 continue;
216 uint64_t pieceEnd = fde.inputOff + fde.size;
217 for (size_t j = firstRelI, end2 = rels.size();
218 j < end2 && rels[j].offset < pieceEnd; ++j)
219 resolveReloc(eh, rels[j], true);
220 }
221}
222
223// Some sections are used directly by the loader, so they should never be
224// garbage-collected. This function returns true if a given section is such
225// section.
226static bool isReserved(InputSectionBase *sec) {
227 switch (sec->type) {
228 case SHT_FINI_ARRAY:
229 case SHT_INIT_ARRAY:
230 case SHT_PREINIT_ARRAY:
231 return true;
232 case SHT_NOTE:
233 // SHT_NOTE sections in a group are subject to garbage collection.
234 return !sec->nextInSectionGroup;
235 default:
236 // Support SHT_PROGBITS .init_array (https://golang.org/issue/50295) and
237 // .init_array.N (https://github.com/rust-lang/rust/issues/92181) for a
238 // while.
239 StringRef s = sec->name;
240 return s == ".init" || s == ".fini" || s.starts_with(Prefix: ".init_array") ||
241 s == ".jcr" || s.starts_with(Prefix: ".ctors") || s.starts_with(Prefix: ".dtors");
242 }
243}
244
245template <class ELFT, bool TrackWhyLive>
246void MarkLive<ELFT, TrackWhyLive>::enqueue(InputSectionBase *sec,
247 uint64_t offset, Symbol *sym,
248 LiveReason reason) {
249 // Usually, a whole section is marked as live or dead, but in mergeable
250 // (splittable) sections, each piece of data has independent liveness bit.
251 // So we explicitly tell it which offset is in use.
252 if (auto *ms = dyn_cast<MergeInputSection>(Val: sec))
253 ms->getSectionPiece(offset).live = true;
254
255 if (sec->partition)
256 return;
257 sec->partition = 1;
258
259 if (TrackWhyLive) {
260 if (sym) {
261 // If a specific symbol is referenced, that keeps it live. The symbol then
262 // keeps its section live.
263 whyLive.try_emplace(Key: sym, Args&: reason);
264 whyLive.try_emplace(Key: sec, Args: LiveReason{.item: sym, .desc: "contained live symbol"});
265 } else {
266 // Otherwise, the reference generically keeps the section live.
267 whyLive.try_emplace(Key: sec, Args&: reason);
268 }
269 }
270
271 // Add input section to the queue.
272 if (InputSection *s = dyn_cast<InputSection>(Val: sec))
273 queue.push_back(Elt: s);
274}
275
276// Print the stack of reasons that the given symbol is live.
277template <class ELFT, bool TrackWhyLive>
278void MarkLive<ELFT, TrackWhyLive>::printWhyLive(Symbol *s) const {
279 // Skip dead symbols. A symbol is dead if it belongs to a dead section.
280 if (auto *d = dyn_cast<Defined>(Val: s)) {
281 auto *sec = dyn_cast_or_null<InputSectionBase>(Val: d->section);
282 if (sec && !sec->isLive())
283 return;
284 }
285
286 auto msg = Msg(ctx);
287
288 const auto printSymbol = [&](Symbol *s) {
289 msg << s->file << ":(" << s << ')';
290 };
291
292 msg << "live symbol: ";
293 printSymbol(s);
294
295 LiveItem cur = s;
296 while (true) {
297 auto it = whyLive.find(Val: cur);
298 LiveReason reason;
299 // If there is a specific reason this item is live...
300 if (it != whyLive.end()) {
301 reason = it->second;
302 } else {
303 // This item is live, but it has no tracked reason. It must be an
304 // unreferenced symbol in a live section or a symbol with no section.
305 InputSectionBase *sec = nullptr;
306 if (auto *d = dyn_cast<Defined>(Val: std::get<Symbol *>(v&: cur)))
307 sec = dyn_cast_or_null<InputSectionBase>(Val: d->section);
308 reason = sec ? LiveReason{.item: sec, .desc: "in live section"}
309 : LiveReason{.item: std::nullopt, .desc: "no section"};
310 }
311
312 if (!reason.item) {
313 msg << " (" << reason.desc << ')';
314 break;
315 }
316
317 msg << "\n>>> " << reason.desc << ": ";
318 // The reason may not yet have been resolved to a symbol; do so now.
319 if (std::holds_alternative<SecOffset>(v: *reason.item)) {
320 const auto &so = std::get<SecOffset>(v&: *reason.item);
321 InputSectionBase *sec = so.first;
322 Defined *sym = sec->getEnclosingSymbol(offset: so.second);
323 cur = sym ? LiveItem(sym) : LiveItem(sec);
324 } else {
325 cur = *reason.item;
326 }
327
328 if (std::holds_alternative<Symbol *>(v: cur))
329 printSymbol(std::get<Symbol *>(v&: cur));
330 else
331 msg << std::get<InputSectionBase *>(v&: cur);
332 }
333}
334
335template <class ELFT, bool TrackWhyLive>
336void MarkLive<ELFT, TrackWhyLive>::markSymbol(Symbol *sym, StringRef reason) {
337 if (auto *d = dyn_cast_or_null<Defined>(Val: sym))
338 if (auto *isec = dyn_cast_or_null<InputSectionBase>(Val: d->section))
339 enqueue(sec: isec, offset: d->value, sym, reason: {std::nullopt, reason});
340}
341
342// This is the main function of the garbage collector.
343// Starting from GC-root sections, this function visits all reachable
344// sections to set their "Live" bits.
345template <class ELFT, bool TrackWhyLive>
346void MarkLive<ELFT, TrackWhyLive>::run() {
347 // Add GC root symbols.
348
349 // Preserve externally-visible symbols if the symbols defined by this
350 // file can interpose other ELF file's symbols at runtime.
351 for (Symbol *sym : ctx.symtab->getSymbols())
352 if (sym->isExported)
353 markSymbol(sym, reason: "externally visible symbol");
354
355 markSymbol(sym: ctx.symtab->find(name: ctx.arg.entry), reason: "entry point");
356 markSymbol(sym: ctx.symtab->find(name: ctx.arg.init), reason: "initializer function");
357 markSymbol(sym: ctx.symtab->find(name: ctx.arg.fini), reason: "finalizer function");
358 for (StringRef s : ctx.arg.undefined)
359 markSymbol(sym: ctx.symtab->find(name: s), reason: "undefined command line flag");
360 for (StringRef s : ctx.script->referencedSymbols)
361 markSymbol(sym: ctx.symtab->find(name: s), reason: "referenced by linker script");
362 for (auto [symName, _] : ctx.symtab->cmseSymMap) {
363 markSymbol(sym: ctx.symtab->cmseSymMap[symName].sym, reason: "ARM CMSE symbol");
364 markSymbol(sym: ctx.symtab->cmseSymMap[symName].acleSeSym, reason: "ARM CMSE symbol");
365 }
366
367 // Mark .eh_frame sections as live because there are usually no relocations
368 // that point to .eh_frames. Otherwise, the garbage collector would drop
369 // all of them. We also want to preserve personality routines and LSDA
370 // referenced by .eh_frame sections, so we scan them for that here.
371 for (EhInputSection *eh : ctx.ehInputSections)
372 scanEhFrameSection(eh&: *eh);
373 for (InputSectionBase *sec : ctx.inputSections) {
374 if (sec->flags & SHF_GNU_RETAIN) {
375 enqueue(sec, /*offset=*/0, /*sym=*/nullptr, reason: {std::nullopt, "retained"});
376 continue;
377 }
378 if (sec->flags & SHF_LINK_ORDER)
379 continue;
380
381 // Usually, non-SHF_ALLOC sections are not removed even if they are
382 // unreachable through relocations because reachability is not a good signal
383 // whether they are garbage or not (e.g. there is usually no section
384 // referring to a .comment section, but we want to keep it.) When a
385 // non-SHF_ALLOC section is retained, we also retain sections dependent on
386 // it.
387 //
388 // Note on SHF_LINK_ORDER: Such sections contain metadata and they
389 // have a reverse dependency on the InputSection they are linked with.
390 // We are able to garbage collect them.
391 //
392 // Note on SHF_REL{,A}: Such sections reach here only when -r
393 // or --emit-reloc were given. And they are subject of garbage
394 // collection because, if we remove a text section, we also
395 // remove its relocation section.
396 //
397 // Note on nextInSectionGroup: The ELF spec says that group sections are
398 // included or omitted as a unit. We take the interpretation that:
399 //
400 // - Group members (nextInSectionGroup != nullptr) are subject to garbage
401 // collection.
402 // - Groups members are retained or discarded as a unit.
403 if (!(sec->flags & SHF_ALLOC)) {
404 if (!isStaticRelSecType(type: sec->type) && !sec->nextInSectionGroup) {
405 sec->markLive();
406 for (InputSection *isec : sec->dependentSections)
407 isec->markLive();
408 }
409 }
410
411 // Preserve special sections and those which are specified in linker
412 // script KEEP command.
413 if (isReserved(sec)) {
414 enqueue(sec, /*offset=*/0, /*sym=*/nullptr, reason: {std::nullopt, "reserved"});
415 } else if (ctx.script->shouldKeep(s: sec)) {
416 enqueue(sec, /*offset=*/0, /*sym=*/nullptr,
417 reason: {std::nullopt, "KEEP in linker script"});
418 } else if ((!ctx.arg.zStartStopGC || sec->name.starts_with(Prefix: "__libc_")) &&
419 isValidCIdentifier(s: sec->name)) {
420 // As a workaround for glibc libc.a before 2.34
421 // (https://sourceware.org/PR27492), retain __libc_atexit and similar
422 // sections regardless of zStartStopGC.
423 cNamedSections[ctx.saver.save(S: "__start_" + sec->name)].push_back(Elt: sec);
424 cNamedSections[ctx.saver.save(S: "__stop_" + sec->name)].push_back(Elt: sec);
425 }
426 }
427
428 mark();
429
430 if (TrackWhyLive) {
431 const auto handleSym = [&](Symbol *sym) {
432 if (llvm::any_of(ctx.arg.whyLive, [sym](const llvm::GlobPattern &pat) {
433 return pat.match(S: sym->getName());
434 }))
435 printWhyLive(s: sym);
436 };
437
438 for (Symbol *sym : ctx.symtab->getSymbols())
439 handleSym(sym);
440 // Handle local symbols, skipping the symbol at index 0 and section
441 // symbols, which usually have empty names and technically not live. Note:
442 // a live section may lack an associated section symbol, making them
443 // unreliable liveness indicators.
444 for (ELFFileBase *file : ctx.objectFiles)
445 for (Symbol *sym : file->getSymbols())
446 if (sym->isLocal() && sym->isDefined() && !sym->isSection())
447 handleSym(sym);
448 }
449}
450
451template <class ELFT, bool TrackWhyLive>
452void MarkLive<ELFT, TrackWhyLive>::mark() {
453 if constexpr (!TrackWhyLive) {
454 markParallel();
455 return;
456 }
457 while (!queue.empty()) {
458 InputSectionBase &sec = *queue.pop_back_val();
459
460 const RelsOrRelas<ELFT> rels = sec.template relsOrRelas<ELFT>();
461 for (const typename ELFT::Rel &rel : rels.rels)
462 resolveReloc(sec, rel, false);
463 for (const typename ELFT::Rela &rel : rels.relas)
464 resolveReloc(sec, rel, false);
465 for (const typename ELFT::Crel &rel : rels.crels)
466 resolveReloc(sec, rel, false);
467
468 for (InputSectionBase *isec : sec.dependentSections)
469 enqueue(sec: isec, /*offset=*/0, /*sym=*/nullptr,
470 reason: {&sec, "depended on by section"});
471
472 // Mark the next group member.
473 if (sec.nextInSectionGroup)
474 enqueue(sec: sec.nextInSectionGroup, /*offset=*/0, /*sym=*/nullptr,
475 reason: {&sec, "in section group with"});
476 }
477}
478
479// Helper function for markParallel. Walk all GC edges from sec, marking
480// everything that needs to be live. Call fn(target section, offset) for each
481// edge, which will mark the section live and handle further processing of edges
482// from that section.
483template <class ELFT, class Fn>
484static void processSectionEdges(
485 Ctx &ctx, InputSectionBase &sec,
486 const DenseMap<StringRef, SmallVector<InputSectionBase *, 0>>
487 &cNamedSections,
488 Fn fn) {
489 auto resolveEdge = [&](const auto &rel) {
490 Symbol &sym = sec.file->getRelocTargetSym(rel);
491 if (!sym.hasFlag(bit: USED))
492 sym.setFlags(USED);
493 if (auto *d = dyn_cast<Defined>(Val: &sym)) {
494 if (auto *relSec = dyn_cast_or_null<InputSectionBase>(Val: d->section)) {
495 uint64_t offset = d->value;
496 if (d->isSection()) {
497 offset += getAddend<ELFT>(ctx, sec, rel);
498 if (auto *ms = dyn_cast<MergeInputSection>(Val: relSec);
499 ms && offset >= ms->content().size())
500 return;
501 }
502 if (auto *ms = dyn_cast<MergeInputSection>(Val: relSec)) {
503 auto &piece = ms->getSectionPiece(offset);
504 auto *word =
505 reinterpret_cast<std::atomic<uint32_t> *>(&piece.inputOff + 1);
506 constexpr uint32_t liveBit = sys::IsBigEndianHost ? (1U << 31) : 1U;
507 word->fetch_or(i: liveBit, m: std::memory_order_relaxed);
508 }
509 fn(relSec, offset);
510 }
511 return;
512 }
513 for (InputSectionBase *csec : cNamedSections.lookup(Val: sym.getName()))
514 fn(csec, 0);
515 };
516 const RelsOrRelas<ELFT> rels = sec.template relsOrRelas<ELFT>();
517 for (const typename ELFT::Rel &rel : rels.rels)
518 resolveEdge(rel);
519 for (const typename ELFT::Rela &rel : rels.relas)
520 resolveEdge(rel);
521 for (const typename ELFT::Crel &rel : rels.crels)
522 resolveEdge(rel);
523 for (InputSectionBase *isec : sec.dependentSections)
524 fn(isec, 0);
525 if (sec.nextInSectionGroup)
526 fn(sec.nextInSectionGroup, 0);
527}
528
529// Parallel mark using level-synchronized BFS with depth-limited inline
530// recursion. Each parallelFor iteration processes a subtree up to depth 3
531// (DFS for cache locality), then queues deeper discoveries for the next level.
532template <class ELFT, bool TrackWhyLive>
533void MarkLive<ELFT, TrackWhyLive>::markParallel() {
534 const size_t numThreads = parallel::getThreadCount();
535 auto visit = [&](InputSection *sec, int depth,
536 SmallVector<InputSection *, 0> &localQueue,
537 auto &self) -> void {
538 processSectionEdges<ELFT>(
539 ctx, *sec, cNamedSections,
540 [&](InputSectionBase *target, uint64_t offset) {
541 auto &part =
542 reinterpret_cast<std::atomic<uint8_t> &>(target->partition);
543 // Optimistic load-then-exchange avoids expensive atomic
544 // RMW on already-visited sections.
545 if (part.load(m: std::memory_order_relaxed) != 0 ||
546 part.exchange(i: 1, m: std::memory_order_relaxed) != 0)
547 return;
548 if (auto *s = dyn_cast<InputSection>(Val: target)) {
549 if (depth < 3)
550 self(s, depth + 1, localQueue, self);
551 else
552 localQueue.push_back(Elt: s);
553 }
554 });
555 };
556
557 while (!queue.empty()) {
558 auto queues =
559 std::make_unique<SmallVector<InputSection *, 0>[]>(num: numThreads);
560 parallelFor(0, queue.size(), [&](size_t i) {
561 const unsigned tid = parallel::getThreadIndex();
562 visit(queue[i], 0, queues[tid], visit);
563 });
564 queue.clear();
565 for (size_t t = 0; t < numThreads; ++t)
566 queue.append(RHS: std::move(queues[t]));
567 }
568}
569
570// Before calling this function, Live bits are off for all
571// input sections. This function make some or all of them on
572// so that they are emitted to the output file.
573template <class ELFT> void elf::markLive(Ctx &ctx) {
574 llvm::TimeTraceScope timeScope("markLive");
575 // If --gc-sections is not given, retain all input sections.
576 if (!ctx.arg.gcSections) {
577 // If a DSO defines a symbol referenced in a regular object, it is needed.
578 for (Symbol *sym : ctx.symtab->getSymbols())
579 if (auto *s = dyn_cast<SharedSymbol>(Val: sym))
580 if (s->isUsedInRegularObj && !s->isWeak())
581 cast<SharedFile>(Val: s->file)->isNeeded = true;
582 return;
583 }
584
585 parallelForEach(ctx.inputSections,
586 [](InputSectionBase *sec) { sec->markDead(); });
587
588 // Follow the graph to mark all live sections.
589 if (ctx.arg.whyLive.empty())
590 MarkLive<ELFT, false>(ctx).run();
591 else
592 MarkLive<ELFT, true>(ctx).run();
593
594 // Determine which DSOs are needed. A DSO is needed if a non-weak SharedSymbol
595 // is used from a live section.
596 parallelForEach(ctx.symtab->getSymbols(), [](Symbol *sym) {
597 if (auto *ss = dyn_cast<SharedSymbol>(Val: sym))
598 if (ss->hasFlag(bit: USED) && !ss->isWeak())
599 cast<SharedFile>(Val: ss->file)->isNeeded = true;
600 });
601
602 // Report garbage-collected sections.
603 if (ctx.arg.printGcSections.empty())
604 return;
605 std::error_code ec;
606 raw_fd_ostream os = ctx.openAuxiliaryFile(ctx.arg.printGcSections, ec);
607 if (ec) {
608 Err(ctx) << "cannot open --print-gc-sections= file "
609 << ctx.arg.printGcSections << ": " << ec.message();
610 return;
611 }
612 for (InputSectionBase *sec : ctx.inputSections)
613 if (!sec->isLive())
614 os << "removing unused section " << toStr(ctx, sec) << '\n';
615}
616
617template void elf::markLive<ELF32LE>(Ctx &);
618template void elf::markLive<ELF32BE>(Ctx &);
619template void elf::markLive<ELF64LE>(Ctx &);
620template void elf::markLive<ELF64BE>(Ctx &);
621