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 //===----------------------------------------------------------------------===//
24 #include "InputSection.h"
25 #include "LinkerScript.h"
26 #include "OutputSections.h"
27 #include "SymbolTable.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"
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>
64 resolveReloc(InputSectionBase &Sec, RelT &Rel,
65 llvm::function_ref<void(InputSectionBase *, uint64_t)> Fn) {
66 Symbol &B = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
68 // If a symbol is referenced in a live section, it is used.
70 if (auto *SS = dyn_cast<SharedSymbol>(&B))
72 SS->getFile<ELFT>().IsNeeded = true;
74 if (auto *D = dyn_cast<Defined>(&B)) {
75 auto *RelSec = dyn_cast_or_null<InputSectionBase>(D->Section);
78 uint64_t Offset = D->Value;
80 Offset += getAddend<ELFT>(Sec, Rel);
86 for (InputSectionBase *Sec : CNamedSections.lookup(B.getName()))
90 // Calls Fn for each section that Sec refers to via relocations.
93 forEachSuccessor(InputSection &Sec,
94 llvm::function_ref<void(InputSectionBase *, uint64_t)> Fn) {
95 if (Sec.AreRelocsRela) {
96 for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
97 resolveReloc<ELFT>(Sec, Rel, Fn);
99 for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
100 resolveReloc<ELFT>(Sec, Rel, Fn);
103 for (InputSectionBase *IS : Sec.DependentSections)
107 // The .eh_frame section is an unfortunate special case.
108 // The section is divided in CIEs and FDEs and the relocations it can have are
109 // * CIEs can refer to a personality function.
110 // * FDEs can refer to a LSDA
111 // * FDEs refer to the function they contain information about
112 // The last kind of relocation cannot keep the referred section alive, or they
113 // would keep everything alive in a common object file. In fact, each FDE is
114 // alive if the section it refers to is alive.
115 // To keep things simple, in here we just ignore the last relocation kind. The
116 // other two keep the referred section alive.
118 // A possible improvement would be to fully process .eh_frame in the middle of
119 // the gc pass. With that we would be able to also gc some sections holding
120 // LSDAs and personality functions if we found that they were unused.
121 template <class ELFT, class RelTy>
123 scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels,
124 llvm::function_ref<void(InputSectionBase *, uint64_t)> Fn) {
125 const endianness E = ELFT::TargetEndianness;
127 for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) {
128 EhSectionPiece &Piece = EH.Pieces[I];
129 unsigned FirstRelI = Piece.FirstRelocation;
130 if (FirstRelI == (unsigned)-1)
132 if (read32<E>(Piece.data().data() + 4) == 0) {
133 // This is a CIE, we only need to worry about the first relocation. It is
134 // known to point to the personality function.
135 resolveReloc<ELFT>(EH, Rels[FirstRelI], Fn);
138 // This is a FDE. The relocations point to the described function or to
139 // a LSDA. We only need to keep the LSDA alive, so ignore anything that
140 // points to executable sections.
141 typename ELFT::uint PieceEnd = Piece.InputOff + Piece.Size;
142 for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) {
143 const RelTy &Rel = Rels[I2];
144 if (Rel.r_offset >= PieceEnd)
146 resolveReloc<ELFT>(EH, Rels[I2],
147 [&](InputSectionBase *Sec, uint64_t Offset) {
148 if (Sec && Sec != &InputSection::Discarded &&
149 !(Sec->Flags & SHF_EXECINSTR))
156 template <class ELFT>
158 scanEhFrameSection(EhInputSection &EH,
159 llvm::function_ref<void(InputSectionBase *, uint64_t)> Fn) {
160 if (!EH.NumRelocations)
163 if (EH.AreRelocsRela)
164 scanEhFrameSection<ELFT>(EH, EH.template relas<ELFT>(), Fn);
166 scanEhFrameSection<ELFT>(EH, EH.template rels<ELFT>(), Fn);
169 // Some sections are used directly by the loader, so they should never be
170 // garbage-collected. This function returns true if a given section is such
172 template <class ELFT> static bool isReserved(InputSectionBase *Sec) {
177 case SHT_PREINIT_ARRAY:
180 StringRef S = Sec->Name;
181 return S.startswith(".ctors") || S.startswith(".dtors") ||
182 S.startswith(".init") || S.startswith(".fini") ||
183 S.startswith(".jcr");
187 // This is the main function of the garbage collector.
188 // Starting from GC-root sections, this function visits all reachable
189 // sections to set their "Live" bits.
190 template <class ELFT> static void doGcSections() {
191 SmallVector<InputSection *, 256> Q;
192 CNamedSections.clear();
194 auto Enqueue = [&](InputSectionBase *Sec, uint64_t Offset) {
195 // Skip over discarded sections. This in theory shouldn't happen, because
196 // the ELF spec doesn't allow a relocation to point to a deduplicated
197 // COMDAT section directly. Unfortunately this happens in practice (e.g.
198 // .eh_frame) so we need to add a check.
199 if (Sec == &InputSection::Discarded)
203 // Usually, a whole section is marked as live or dead, but in mergeable
204 // (splittable) sections, each piece of data has independent liveness bit.
205 // So we explicitly tell it which offset is in use.
206 if (auto *MS = dyn_cast<MergeInputSection>(Sec))
207 MS->getSectionPiece(Offset)->Live = true;
213 // Add input section to the queue.
214 if (InputSection *S = dyn_cast<InputSection>(Sec))
218 auto MarkSymbol = [&](Symbol *Sym) {
219 if (auto *D = dyn_cast_or_null<Defined>(Sym))
220 if (auto *IS = dyn_cast_or_null<InputSectionBase>(D->Section))
221 Enqueue(IS, D->Value);
224 // Add GC root symbols.
225 MarkSymbol(Symtab->find(Config->Entry));
226 MarkSymbol(Symtab->find(Config->Init));
227 MarkSymbol(Symtab->find(Config->Fini));
228 for (StringRef S : Config->Undefined)
229 MarkSymbol(Symtab->find(S));
230 for (StringRef S : Script->ReferencedSymbols)
231 MarkSymbol(Symtab->find(S));
233 // Preserve externally-visible symbols if the symbols defined by this
234 // file can interrupt other ELF file's symbols at runtime.
235 for (Symbol *S : Symtab->getSymbols())
236 if (S->includeInDynsym())
239 // Preserve special sections and those which are specified in linker
240 // script KEEP command.
241 for (InputSectionBase *Sec : InputSections) {
242 // Mark .eh_frame sections as live because there are usually no relocations
243 // that point to .eh_frames. Otherwise, the garbage collector would drop
244 // all of them. We also want to preserve personality routines and LSDA
245 // referenced by .eh_frame sections, so we scan them for that here.
246 if (auto *EH = dyn_cast<EhInputSection>(Sec)) {
248 scanEhFrameSection<ELFT>(*EH, Enqueue);
251 if (Sec->Flags & SHF_LINK_ORDER)
253 if (isReserved<ELFT>(Sec) || Script->shouldKeep(Sec))
255 else if (isValidCIdentifier(Sec->Name)) {
256 CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec);
257 CNamedSections[Saver.save("__stop_" + Sec->Name)].push_back(Sec);
261 // Mark all reachable sections.
263 forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
266 // Before calling this function, Live bits are off for all
267 // input sections. This function make some or all of them on
268 // so that they are emitted to the output file.
269 template <class ELFT> void elf::markLive() {
270 // If -gc-sections is missing, no sections are removed.
271 if (!Config->GcSections) {
272 for (InputSectionBase *Sec : InputSections)
277 // The -gc-sections option works only for SHF_ALLOC sections
278 // (sections that are memory-mapped at runtime). So we can
279 // unconditionally make non-SHF_ALLOC sections alive except
280 // SHF_LINK_ORDER and SHT_REL/SHT_RELA sections.
282 // Usually, SHF_ALLOC sections are not removed even if they are
283 // unreachable through relocations because reachability is not
284 // a good signal whether they are garbage or not (e.g. there is
285 // usually no section referring to a .comment section, but we
286 // want to keep it.).
288 // Note on SHF_LINK_ORDER: Such sections contain metadata and they
289 // have a reverse dependency on the InputSection they are linked with.
290 // We are able to garbage collect them.
292 // Note on SHF_REL{,A}: Such sections reach here only when -r
293 // or -emit-reloc were given. And they are subject of garbage
294 // collection because, if we remove a text section, we also
295 // remove its relocation section.
296 for (InputSectionBase *Sec : InputSections) {
297 bool IsAlloc = (Sec->Flags & SHF_ALLOC);
298 bool IsLinkOrder = (Sec->Flags & SHF_LINK_ORDER);
299 bool IsRel = (Sec->Type == SHT_REL || Sec->Type == SHT_RELA);
300 if (!IsAlloc && !IsLinkOrder && !IsRel)
304 // Follow the graph to mark all live sections.
305 doGcSections<ELFT>();
307 // Report garbage-collected sections.
308 if (Config->PrintGcSections)
309 for (InputSectionBase *Sec : InputSections)
311 message("removing unused section " + toString(Sec));
314 template void elf::markLive<ELF32LE>();
315 template void elf::markLive<ELF32BE>();
316 template void elf::markLive<ELF64LE>();
317 template void elf::markLive<ELF64BE>();