1 //===- MarkLive.cpp -------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
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.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "InputSection.h"
24 #include "LinkerScript.h"
25 #include "Memory.h"
26 #include "OutputSections.h"
27 #include "Strings.h"
28 #include "SymbolTable.h"
29 #include "Symbols.h"
30 #include "Target.h"
31 #include "Writer.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Object/ELF.h"
34 #include <functional>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace llvm::ELF;
39 using namespace llvm::object;
40 using namespace llvm::support::endian;
41 
42 using namespace lld;
43 using namespace lld::elf;
44 
45 namespace {
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;
50   uint64_t Offset;
51 };
52 } // end anonymous namespace
53 
54 template <class ELFT>
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));
59 }
60 
61 template <class ELFT>
62 static typename ELFT::uint getAddend(InputSectionBase &Sec,
63                                      const typename ELFT::Rela &Rel) {
64   return Rel.r_addend;
65 }
66 
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;
70 
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)) {
76     auto *RelSec = dyn_cast_or_null<InputSectionBase>(D->Section);
77     if (!RelSec)
78       return;
79     typename ELFT::uint Offset = D->Value;
80     if (D->isSection())
81       Offset += getAddend<ELFT>(Sec, Rel);
82     Fn({RelSec, Offset});
83   } else if (auto *U = dyn_cast<Undefined>(&B)) {
84     for (InputSectionBase *Sec : CNamedSections.lookup(U->getName()))
85       Fn({Sec, 0});
86   }
87 }
88 
89 // Calls Fn for each section that Sec refers to via relocations.
90 template <class ELFT>
91 static void forEachSuccessor(InputSection &Sec,
92                              std::function<void(ResolvedReloc)> Fn) {
93   if (Sec.AreRelocsRela) {
94     for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>())
95       resolveReloc<ELFT>(Sec, Rel, Fn);
96   } else {
97     for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>())
98       resolveReloc<ELFT>(Sec, Rel, Fn);
99   }
100   for (InputSectionBase *IS : Sec.DependentSections)
101     Fn({IS, 0});
102 }
103 
104 // The .eh_frame section is an unfortunate special case.
105 // The section is divided in CIEs and FDEs and the relocations it can have are
106 // * CIEs can refer to a personality function.
107 // * FDEs can refer to a LSDA
108 // * FDEs refer to the function they contain information about
109 // The last kind of relocation cannot keep the referred section alive, or they
110 // would keep everything alive in a common object file. In fact, each FDE is
111 // alive if the section it refers to is alive.
112 // To keep things simple, in here we just ignore the last relocation kind. The
113 // other two keep the referred section alive.
114 //
115 // A possible improvement would be to fully process .eh_frame in the middle of
116 // the gc pass. With that we would be able to also gc some sections holding
117 // LSDAs and personality functions if we found that they were unused.
118 template <class ELFT, class RelTy>
119 static void scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels,
120                                std::function<void(ResolvedReloc)> Enqueue) {
121   const endianness E = ELFT::TargetEndianness;
122   for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) {
123     EhSectionPiece &Piece = EH.Pieces[I];
124     unsigned FirstRelI = Piece.FirstRelocation;
125     if (FirstRelI == (unsigned)-1)
126       continue;
127     if (read32<E>(Piece.data().data() + 4) == 0) {
128       // This is a CIE, we only need to worry about the first relocation. It is
129       // known to point to the personality function.
130       resolveReloc<ELFT>(EH, Rels[FirstRelI], Enqueue);
131       continue;
132     }
133     // This is a FDE. The relocations point to the described function or to
134     // a LSDA. We only need to keep the LSDA alive, so ignore anything that
135     // points to executable sections.
136     typename ELFT::uint PieceEnd = Piece.InputOff + Piece.size();
137     for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) {
138       const RelTy &Rel = Rels[I2];
139       if (Rel.r_offset >= PieceEnd)
140         break;
141       resolveReloc<ELFT>(EH, Rels[I2], [&](ResolvedReloc R) {
142         if (!R.Sec || R.Sec == &InputSection::Discarded)
143           return;
144         if (R.Sec->Flags & SHF_EXECINSTR)
145           return;
146         Enqueue({R.Sec, 0});
147       });
148     }
149   }
150 }
151 
152 template <class ELFT>
153 static void scanEhFrameSection(EhInputSection &EH,
154                                std::function<void(ResolvedReloc)> Enqueue) {
155   if (!EH.NumRelocations)
156     return;
157 
158   // Unfortunately we need to split .eh_frame early since some relocations in
159   // .eh_frame keep other section alive and some don't.
160   EH.split<ELFT>();
161 
162   if (EH.AreRelocsRela)
163     scanEhFrameSection<ELFT>(EH, EH.template relas<ELFT>(), Enqueue);
164   else
165     scanEhFrameSection<ELFT>(EH, EH.template rels<ELFT>(), Enqueue);
166 }
167 
168 // We do not garbage-collect two types of sections:
169 // 1) Sections used by the loader (.init, .fini, .ctors, .dtors or .jcr)
170 // 2) Non-allocatable sections which typically contain debugging information
171 template <class ELFT> static bool isReserved(InputSectionBase *Sec) {
172   switch (Sec->Type) {
173   case SHT_FINI_ARRAY:
174   case SHT_INIT_ARRAY:
175   case SHT_NOTE:
176   case SHT_PREINIT_ARRAY:
177     return true;
178   default:
179     if (!(Sec->Flags & SHF_ALLOC))
180       return true;
181 
182     StringRef S = Sec->Name;
183     return S.startswith(".ctors") || S.startswith(".dtors") ||
184            S.startswith(".init") || S.startswith(".fini") ||
185            S.startswith(".jcr");
186   }
187 }
188 
189 // This is the main function of the garbage collector.
190 // Starting from GC-root sections, this function visits all reachable
191 // sections to set their "Live" bits.
192 template <class ELFT> void elf::markLive() {
193   SmallVector<InputSection *, 256> Q;
194   CNamedSections.clear();
195 
196   auto Enqueue = [&](ResolvedReloc R) {
197     // Skip over discarded sections. This in theory shouldn't happen, because
198     // the ELF spec doesn't allow a relocation to point to a deduplicated
199     // COMDAT section directly. Unfortunately this happens in practice (e.g.
200     // .eh_frame) so we need to add a check.
201     if (R.Sec == &InputSection::Discarded)
202       return;
203 
204     // We don't gc non alloc sections.
205     if (!(R.Sec->Flags & SHF_ALLOC))
206       return;
207 
208     // Usually, a whole section is marked as live or dead, but in mergeable
209     // (splittable) sections, each piece of data has independent liveness bit.
210     // So we explicitly tell it which offset is in use.
211     if (auto *MS = dyn_cast<MergeInputSection>(R.Sec))
212       MS->markLiveAt(R.Offset);
213 
214     if (R.Sec->Live)
215       return;
216     R.Sec->Live = true;
217     // Add input section to the queue.
218     if (InputSection *S = dyn_cast<InputSection>(R.Sec))
219       Q.push_back(S);
220   };
221 
222   auto MarkSymbol = [&](const SymbolBody *Sym) {
223     if (auto *D = dyn_cast_or_null<DefinedRegular>(Sym))
224       if (auto *IS = dyn_cast_or_null<InputSectionBase>(D->Section))
225         Enqueue({IS, D->Value});
226   };
227 
228   // Add GC root symbols.
229   MarkSymbol(Symtab<ELFT>::X->find(Config->Entry));
230   MarkSymbol(Symtab<ELFT>::X->find(Config->Init));
231   MarkSymbol(Symtab<ELFT>::X->find(Config->Fini));
232   for (StringRef S : Config->Undefined)
233     MarkSymbol(Symtab<ELFT>::X->find(S));
234   for (StringRef S : Script->Opt.ReferencedSymbols)
235     MarkSymbol(Symtab<ELFT>::X->find(S));
236 
237   // Preserve externally-visible symbols if the symbols defined by this
238   // file can interrupt other ELF file's symbols at runtime.
239   for (const Symbol *S : Symtab<ELFT>::X->getSymbols())
240     if (S->includeInDynsym())
241       MarkSymbol(S->body());
242 
243   // Preserve special sections and those which are specified in linker
244   // script KEEP command.
245   for (InputSectionBase *Sec : InputSections) {
246     // .eh_frame is always marked as live now, but also it can reference to
247     // sections that contain personality. We preserve all non-text sections
248     // referred by .eh_frame here.
249     if (auto *EH = dyn_cast_or_null<EhInputSection>(Sec))
250       scanEhFrameSection<ELFT>(*EH, Enqueue);
251     if (Sec->Flags & SHF_LINK_ORDER)
252       continue;
253     if (isReserved<ELFT>(Sec) || Script->shouldKeep(Sec))
254       Enqueue({Sec, 0});
255     else if (isValidCIdentifier(Sec->Name)) {
256       CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec);
257       CNamedSections[Saver.save("__end_" + Sec->Name)].push_back(Sec);
258     }
259   }
260 
261   // Mark all reachable sections.
262   while (!Q.empty())
263     forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue);
264 }
265 
266 template void elf::markLive<ELF32LE>();
267 template void elf::markLive<ELF32BE>();
268 template void elf::markLive<ELF64LE>();
269 template void elf::markLive<ELF64BE>();
270