1 //===- MarkLive.cpp -------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
21 //===----------------------------------------------------------------------===//
23 #include "InputSection.h"
24 #include "LinkerScript.h"
25 #include "OutputSections.h"
27 #include "SymbolTable.h"
31 #include "lld/Common/Memory.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Object/ELF.h"
38 using namespace llvm::ELF;
39 using namespace llvm::object;
40 using namespace llvm::support::endian;
43 using namespace lld::elf;
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));
53 static typename ELFT::uint getAddend(InputSectionBase &Sec,
54 const typename ELFT::Rela &Rel) {
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;
62 template <class ELFT, class RelT>
63 static void resolveReloc(InputSectionBase &Sec, RelT &Rel,
64 std::function<void(InputSectionBase *, uint64_t)> Fn) {
65 Symbol &B = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
67 // If a symbol is referenced in a live section, it is used.
69 if (auto *SS = dyn_cast<SharedSymbol>(&B))
71 SS->getFile<ELFT>().IsNeeded = true;
73 if (auto *D = dyn_cast<Defined>(&B)) {
74 auto *RelSec = dyn_cast_or_null<InputSectionBase>(D->Section);
77 uint64_t Offset = D->Value;
79 Offset += getAddend<ELFT>(Sec, Rel);
85 for (InputSectionBase *Sec : CNamedSections.lookup(B.getName()))
89 // Calls Fn for each section that Sec refers to via relocations.
92 forEachSuccessor(InputSection &Sec,
93 std::function<void(InputSectionBase *, uint64_t)> Fn) {
94 if (Sec.AreRelocsRela) {
95 for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
96 resolveReloc<ELFT>(Sec, Rel, Fn);
98 for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
99 resolveReloc<ELFT>(Sec, Rel, Fn);
102 for (InputSectionBase *IS : Sec.DependentSections)
106 // The .eh_frame section is an unfortunate special case.
107 // The section is divided in CIEs and FDEs and the relocations it can have are
108 // * CIEs can refer to a personality function.
109 // * FDEs can refer to a LSDA
110 // * FDEs refer to the function they contain information about
111 // The last kind of relocation cannot keep the referred section alive, or they
112 // would keep everything alive in a common object file. In fact, each FDE is
113 // alive if the section it refers to is alive.
114 // To keep things simple, in here we just ignore the last relocation kind. The
115 // other two keep the referred section alive.
117 // A possible improvement would be to fully process .eh_frame in the middle of
118 // the gc pass. With that we would be able to also gc some sections holding
119 // LSDAs and personality functions if we found that they were unused.
120 template <class ELFT, class RelTy>
122 scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels,
123 std::function<void(InputSectionBase *, uint64_t)> Fn) {
124 const endianness E = ELFT::TargetEndianness;
126 for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) {
127 EhSectionPiece &Piece = EH.Pieces[I];
128 unsigned FirstRelI = Piece.FirstRelocation;
129 if (FirstRelI == (unsigned)-1)
131 if (read32<E>(Piece.data().data() + 4) == 0) {
132 // This is a CIE, we only need to worry about the first relocation. It is
133 // known to point to the personality function.
134 resolveReloc<ELFT>(EH, Rels[FirstRelI], Fn);
137 // This is a FDE. The relocations point to the described function or to
138 // a LSDA. We only need to keep the LSDA alive, so ignore anything that
139 // points to executable sections.
140 typename ELFT::uint PieceEnd = Piece.InputOff + Piece.Size;
141 for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) {
142 const RelTy &Rel = Rels[I2];
143 if (Rel.r_offset >= PieceEnd)
145 resolveReloc<ELFT>(EH, Rels[I2],
146 [&](InputSectionBase *Sec, uint64_t Offset) {
147 if (Sec && Sec != &InputSection::Discarded &&
148 !(Sec->Flags & SHF_EXECINSTR))
155 template <class ELFT>
157 scanEhFrameSection(EhInputSection &EH,
158 std::function<void(InputSectionBase *, uint64_t)> Fn) {
159 if (!EH.NumRelocations)
162 // Unfortunately we need to split .eh_frame early since some relocations in
163 // .eh_frame keep other section alive and some don't.
166 if (EH.AreRelocsRela)
167 scanEhFrameSection<ELFT>(EH, EH.template relas<ELFT>(), Fn);
169 scanEhFrameSection<ELFT>(EH, EH.template rels<ELFT>(), Fn);
172 // Some sections are used directly by the loader, so they should never be
173 // garbage-collected. This function returns true if a given section is such
175 template <class ELFT> static bool isReserved(InputSectionBase *Sec) {
180 case SHT_PREINIT_ARRAY:
183 StringRef S = Sec->Name;
184 return S.startswith(".ctors") || S.startswith(".dtors") ||
185 S.startswith(".init") || S.startswith(".fini") ||
186 S.startswith(".jcr");
190 // This is the main function of the garbage collector.
191 // Starting from GC-root sections, this function visits all reachable
192 // sections to set their "Live" bits.
193 template <class ELFT> static void doGcSections() {
194 SmallVector<InputSection *, 256> Q;
195 CNamedSections.clear();
197 auto Enqueue = [&](InputSectionBase *Sec, uint64_t Offset) {
198 // Skip over discarded sections. This in theory shouldn't happen, because
199 // the ELF spec doesn't allow a relocation to point to a deduplicated
200 // COMDAT section directly. Unfortunately this happens in practice (e.g.
201 // .eh_frame) so we need to add a check.
202 if (Sec == &InputSection::Discarded)
206 // Usually, a whole section is marked as live or dead, but in mergeable
207 // (splittable) sections, each piece of data has independent liveness bit.
208 // So we explicitly tell it which offset is in use.
209 if (auto *MS = dyn_cast<MergeInputSection>(Sec))
210 MS->markLiveAt(Offset);
216 // Add input section to the queue.
217 if (InputSection *S = dyn_cast<InputSection>(Sec))
221 auto MarkSymbol = [&](Symbol *Sym) {
222 if (auto *D = dyn_cast_or_null<Defined>(Sym))
223 if (auto *IS = dyn_cast_or_null<InputSectionBase>(D->Section))
224 Enqueue(IS, D->Value);
227 // Add GC root symbols.
228 MarkSymbol(Symtab->find(Config->Entry));
229 MarkSymbol(Symtab->find(Config->Init));
230 MarkSymbol(Symtab->find(Config->Fini));
231 for (StringRef S : Config->Undefined)
232 MarkSymbol(Symtab->find(S));
233 for (StringRef S : Script->ReferencedSymbols)
234 MarkSymbol(Symtab->find(S));
236 // Preserve externally-visible symbols if the symbols defined by this
237 // file can interrupt other ELF file's symbols at runtime.
238 for (Symbol *S : Symtab->getSymbols())
239 if (S->includeInDynsym())
242 // Preserve special sections and those which are specified in linker
243 // script KEEP command.
244 for (InputSectionBase *Sec : InputSections) {
245 // Mark .eh_frame sections as live because there are usually no relocations
246 // that point to .eh_frames. Otherwise, the garbage collector would drop
247 // all of them. We also want to preserve personality routines and LSDA
248 // referenced by .eh_frame sections, so we scan them for that here.
249 if (auto *EH = dyn_cast<EhInputSection>(Sec)) {
251 scanEhFrameSection<ELFT>(*EH, Enqueue);
254 if (Sec->Flags & SHF_LINK_ORDER)
256 if (isReserved<ELFT>(Sec) || Script->shouldKeep(Sec))
258 else if (isValidCIdentifier(Sec->Name)) {
259 CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec);
260 CNamedSections[Saver.save("__stop_" + Sec->Name)].push_back(Sec);
264 // Mark all reachable sections.
266 forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
269 // Before calling this function, Live bits are off for all
270 // input sections. This function make some or all of them on
271 // so that they are emitted to the output file.
272 template <class ELFT> void elf::markLive() {
273 // If -gc-sections is missing, no sections are removed.
274 if (!Config->GcSections) {
275 for (InputSectionBase *Sec : InputSections)
280 // The -gc-sections option works only for SHF_ALLOC sections
281 // (sections that are memory-mapped at runtime). So we can
282 // unconditionally make non-SHF_ALLOC sections alive.
284 // Non SHF_ALLOC sections are not removed even if they are
285 // unreachable through relocations because reachability is not
286 // a good signal whether they are garbage or not (e.g. there is
287 // usually no section referring to a .comment section, but we
290 // Note on SHF_REL{,A}: Such sections reach here only when -r
291 // or -emit-reloc were given. And they are subject of garbage
292 // collection because, if we remove a text section, we also
293 // remove its relocation section.
294 for (InputSectionBase *Sec : InputSections) {
295 bool IsAlloc = (Sec->Flags & SHF_ALLOC);
296 bool IsRel = (Sec->Type == SHT_REL || Sec->Type == SHT_RELA);
297 if (!IsAlloc && !IsRel)
301 // Follow the graph to mark all live sections.
302 doGcSections<ELFT>();
304 // Report garbage-collected sections.
305 if (Config->PrintGcSections)
306 for (InputSectionBase *Sec : InputSections)
308 message("removing unused section from '" + Sec->Name + "' in file '" +
309 Sec->File->getName() + "'");
312 template void elf::markLive<ELF32LE>();
313 template void elf::markLive<ELF32BE>();
314 template void elf::markLive<ELF64LE>();
315 template void elf::markLive<ELF64BE>();