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"
26 #include "OutputSections.h"
28 #include "SymbolTable.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 // A resolved relocation. The Sec and Offset fields are set if the relocation
47 // was resolved to an offset within a section.
48 struct ResolvedReloc {
49 InputSectionBase *Sec;
52 } // end anonymous namespace
55 static typename ELFT::uint getAddend(InputSectionBase &Sec,
56 const typename ELFT::Rel &Rel) {
57 return Target->getImplicitAddend(Sec.Data.begin() + Rel.r_offset,
58 Rel.getType(Config->IsMips64EL));
62 static typename ELFT::uint getAddend(InputSectionBase &Sec,
63 const typename ELFT::Rela &Rel) {
67 // There are normally few input sections whose names are valid C
68 // identifiers, so we just store a std::vector instead of a multimap.
69 static DenseMap<StringRef, std::vector<InputSectionBase *>> CNamedSections;
71 template <class ELFT, class RelT>
72 static void resolveReloc(InputSectionBase &Sec, RelT &Rel,
73 std::function<void(ResolvedReloc)> Fn) {
74 SymbolBody &B = Sec.getFile<ELFT>()->getRelocTargetSym(Rel);
75 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
78 typename ELFT::uint Offset = D->Value;
80 Offset += getAddend<ELFT>(Sec, Rel);
81 Fn({cast<InputSectionBase>(D->Section)->Repl, Offset});
82 } else if (auto *U = dyn_cast<Undefined>(&B)) {
83 for (InputSectionBase *Sec : CNamedSections.lookup(U->getName()))
88 // Calls Fn for each section that Sec refers to via relocations.
90 static void forEachSuccessor(InputSection &Sec,
91 std::function<void(ResolvedReloc)> Fn) {
92 if (Sec.AreRelocsRela) {
93 for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
94 resolveReloc<ELFT>(Sec, Rel, Fn);
96 for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
97 resolveReloc<ELFT>(Sec, Rel, Fn);
99 for (InputSectionBase *IS : Sec.DependentSections)
103 // The .eh_frame section is an unfortunate special case.
104 // The section is divided in CIEs and FDEs and the relocations it can have are
105 // * CIEs can refer to a personality function.
106 // * FDEs can refer to a LSDA
107 // * FDEs refer to the function they contain information about
108 // The last kind of relocation cannot keep the referred section alive, or they
109 // would keep everything alive in a common object file. In fact, each FDE is
110 // alive if the section it refers to is alive.
111 // To keep things simple, in here we just ignore the last relocation kind. The
112 // other two keep the referred section alive.
114 // A possible improvement would be to fully process .eh_frame in the middle of
115 // the gc pass. With that we would be able to also gc some sections holding
116 // LSDAs and personality functions if we found that they were unused.
117 template <class ELFT, class RelTy>
118 static void scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels,
119 std::function<void(ResolvedReloc)> Enqueue) {
120 const endianness E = ELFT::TargetEndianness;
121 for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) {
122 EhSectionPiece &Piece = EH.Pieces[I];
123 unsigned FirstRelI = Piece.FirstRelocation;
124 if (FirstRelI == (unsigned)-1)
126 if (read32<E>(Piece.data().data() + 4) == 0) {
127 // This is a CIE, we only need to worry about the first relocation. It is
128 // known to point to the personality function.
129 resolveReloc<ELFT>(EH, Rels[FirstRelI], Enqueue);
132 // This is a FDE. The relocations point to the described function or to
133 // a LSDA. We only need to keep the LSDA alive, so ignore anything that
134 // points to executable sections.
135 typename ELFT::uint PieceEnd = Piece.InputOff + Piece.size();
136 for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) {
137 const RelTy &Rel = Rels[I2];
138 if (Rel.r_offset >= PieceEnd)
140 resolveReloc<ELFT>(EH, Rels[I2], [&](ResolvedReloc R) {
141 if (!R.Sec || R.Sec == &InputSection::Discarded)
143 if (R.Sec->Flags & SHF_EXECINSTR)
151 template <class ELFT>
152 static void scanEhFrameSection(EhInputSection &EH,
153 std::function<void(ResolvedReloc)> Enqueue) {
154 if (!EH.NumRelocations)
157 // Unfortunately we need to split .eh_frame early since some relocations in
158 // .eh_frame keep other section alive and some don't.
161 if (EH.AreRelocsRela)
162 scanEhFrameSection<ELFT>(EH, EH.template relas<ELFT>(), Enqueue);
164 scanEhFrameSection<ELFT>(EH, EH.template rels<ELFT>(), Enqueue);
167 // We do not garbage-collect two types of sections:
168 // 1) Sections used by the loader (.init, .fini, .ctors, .dtors or .jcr)
169 // 2) Non-allocatable sections which typically contain debugging information
170 template <class ELFT> static bool isReserved(InputSectionBase *Sec) {
175 case SHT_PREINIT_ARRAY:
178 if (!(Sec->Flags & SHF_ALLOC))
181 StringRef S = Sec->Name;
182 return S.startswith(".ctors") || S.startswith(".dtors") ||
183 S.startswith(".init") || S.startswith(".fini") ||
184 S.startswith(".jcr");
188 // This is the main function of the garbage collector.
189 // Starting from GC-root sections, this function visits all reachable
190 // sections to set their "Live" bits.
191 template <class ELFT> void elf::markLive() {
192 SmallVector<InputSection *, 256> Q;
193 CNamedSections.clear();
195 auto Enqueue = [&](ResolvedReloc R) {
196 // Skip over discarded sections. This in theory shouldn't happen, because
197 // the ELF spec doesn't allow a relocation to point to a deduplicated
198 // COMDAT section directly. Unfortunately this happens in practice (e.g.
199 // .eh_frame) so we need to add a check.
200 if (R.Sec == &InputSection::Discarded)
203 // We don't gc non alloc sections.
204 if (!(R.Sec->Flags & SHF_ALLOC))
207 // Usually, a whole section is marked as live or dead, but in mergeable
208 // (splittable) sections, each piece of data has independent liveness bit.
209 // So we explicitly tell it which offset is in use.
210 if (auto *MS = dyn_cast<MergeInputSection>(R.Sec))
211 MS->markLiveAt(R.Offset);
216 // Add input section to the queue.
217 if (InputSection *S = dyn_cast<InputSection>(R.Sec))
221 auto MarkSymbol = [&](const SymbolBody *Sym) {
222 if (auto *D = dyn_cast_or_null<DefinedRegular>(Sym))
223 Enqueue({cast<InputSectionBase>(D->Section), D->Value});
226 // Add GC root symbols.
227 MarkSymbol(Symtab<ELFT>::X->find(Config->Entry));
228 MarkSymbol(Symtab<ELFT>::X->find(Config->Init));
229 MarkSymbol(Symtab<ELFT>::X->find(Config->Fini));
230 for (StringRef S : Config->Undefined)
231 MarkSymbol(Symtab<ELFT>::X->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 (const Symbol *S : Symtab<ELFT>::X->getSymbols())
236 if (S->includeInDynsym())
237 MarkSymbol(S->body());
239 // Preserve special sections and those which are specified in linker
240 // script KEEP command.
241 for (InputSectionBase *Sec : InputSections) {
242 // .eh_frame is always marked as live now, but also it can reference to
243 // sections that contain personality. We preserve all non-text sections
244 // referred by .eh_frame here.
245 if (auto *EH = dyn_cast_or_null<EhInputSection>(Sec))
246 scanEhFrameSection<ELFT>(*EH, Enqueue);
247 if (Sec->Flags & SHF_LINK_ORDER)
249 if (isReserved<ELFT>(Sec) || Script->shouldKeep(Sec))
251 else if (isValidCIdentifier(Sec->Name)) {
252 CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec);
253 CNamedSections[Saver.save("__end_" + Sec->Name)].push_back(Sec);
257 // Mark all reachable sections.
259 forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
262 template void elf::markLive<ELF32LE>();
263 template void elf::markLive<ELF32BE>();
264 template void elf::markLive<ELF64LE>();
265 template void elf::markLive<ELF64BE>();