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 "InputSection.h" 24 #include "LinkerScript.h" 25 #include "OutputSections.h" 26 #include "SymbolTable.h" 27 #include "Symbols.h" 28 #include "Target.h" 29 #include "lld/Common/Memory.h" 30 #include "lld/Common/Strings.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/Object/ELF.h" 33 #include <functional> 34 #include <vector> 35 36 using namespace llvm; 37 using namespace llvm::ELF; 38 using namespace llvm::object; 39 using namespace llvm::support::endian; 40 41 using namespace lld; 42 using namespace lld::elf; 43 44 namespace { 45 template <class ELFT> class MarkLive { 46 public: 47 void run(); 48 49 private: 50 void enqueue(InputSectionBase *Sec, uint64_t Offset, bool IsLSDA); 51 void markSymbol(Symbol *Sym); 52 53 template <class RelTy> 54 void resolveReloc(InputSectionBase &Sec, RelTy &Rel, bool IsLSDA); 55 56 template <class RelTy> 57 void scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels); 58 59 // A list of sections to visit. 60 SmallVector<InputSection *, 256> Queue; 61 62 // There are normally few input sections whose names are valid C 63 // identifiers, so we just store a std::vector instead of a multimap. 64 DenseMap<StringRef, std::vector<InputSectionBase *>> CNamedSections; 65 }; 66 } // namespace 67 68 template <class ELFT> 69 static uint64_t getAddend(InputSectionBase &Sec, 70 const typename ELFT::Rel &Rel) { 71 return Target->getImplicitAddend(Sec.data().begin() + Rel.r_offset, 72 Rel.getType(Config->IsMips64EL)); 73 } 74 75 template <class ELFT> 76 static uint64_t getAddend(InputSectionBase &Sec, 77 const typename ELFT::Rela &Rel) { 78 return Rel.r_addend; 79 } 80 81 template <class ELFT> 82 template <class RelTy> 83 void MarkLive<ELFT>::resolveReloc(InputSectionBase &Sec, RelTy &Rel, 84 bool IsLSDA) { 85 Symbol &Sym = Sec.getFile<ELFT>()->getRelocTargetSym(Rel); 86 87 // If a symbol is referenced in a live section, it is used. 88 Sym.Used = true; 89 90 if (auto *D = dyn_cast<Defined>(&Sym)) { 91 auto *RelSec = dyn_cast_or_null<InputSectionBase>(D->Section); 92 if (!RelSec) 93 return; 94 95 uint64_t Offset = D->Value; 96 if (D->isSection()) 97 Offset += getAddend<ELFT>(Sec, Rel); 98 99 if (!IsLSDA || !(RelSec->Flags & SHF_EXECINSTR)) 100 enqueue(RelSec, Offset, IsLSDA); 101 return; 102 } 103 104 if (auto *SS = dyn_cast<SharedSymbol>(&Sym)) 105 if (!SS->isWeak()) 106 SS->getFile().IsNeeded = true; 107 108 for (InputSectionBase *Sec : CNamedSections.lookup(Sym.getName())) 109 enqueue(Sec, 0, IsLSDA); 110 } 111 112 // The .eh_frame section is an unfortunate special case. 113 // The section is divided in CIEs and FDEs and the relocations it can have are 114 // * CIEs can refer to a personality function. 115 // * FDEs can refer to a LSDA 116 // * FDEs refer to the function they contain information about 117 // The last kind of relocation cannot keep the referred section alive, or they 118 // would keep everything alive in a common object file. In fact, each FDE is 119 // alive if the section it refers to is alive. 120 // To keep things simple, in here we just ignore the last relocation kind. The 121 // other two keep the referred section alive. 122 // 123 // A possible improvement would be to fully process .eh_frame in the middle of 124 // the gc pass. With that we would be able to also gc some sections holding 125 // LSDAs and personality functions if we found that they were unused. 126 template <class ELFT> 127 template <class RelTy> 128 void MarkLive<ELFT>::scanEhFrameSection(EhInputSection &EH, 129 ArrayRef<RelTy> Rels) { 130 for (size_t I = 0, End = EH.Pieces.size(); I < End; ++I) { 131 EhSectionPiece &Piece = EH.Pieces[I]; 132 size_t FirstRelI = Piece.FirstRelocation; 133 if (FirstRelI == (unsigned)-1) 134 continue; 135 136 if (read32<ELFT::TargetEndianness>(Piece.data().data() + 4) == 0) { 137 // This is a CIE, we only need to worry about the first relocation. It is 138 // known to point to the personality function. 139 resolveReloc(EH, Rels[FirstRelI], false); 140 continue; 141 } 142 143 // This is a FDE. The relocations point to the described function or to 144 // a LSDA. We only need to keep the LSDA alive, so ignore anything that 145 // points to executable sections. 146 uint64_t PieceEnd = Piece.InputOff + Piece.Size; 147 for (size_t J = FirstRelI, End2 = Rels.size(); J < End2; ++J) 148 if (Rels[J].r_offset < PieceEnd) 149 resolveReloc(EH, Rels[J], true); 150 } 151 } 152 153 // Some sections are used directly by the loader, so they should never be 154 // garbage-collected. This function returns true if a given section is such 155 // section. 156 static bool isReserved(InputSectionBase *Sec) { 157 switch (Sec->Type) { 158 case SHT_FINI_ARRAY: 159 case SHT_INIT_ARRAY: 160 case SHT_NOTE: 161 case SHT_PREINIT_ARRAY: 162 return true; 163 default: 164 StringRef S = Sec->Name; 165 return S.startswith(".ctors") || S.startswith(".dtors") || 166 S.startswith(".init") || S.startswith(".fini") || 167 S.startswith(".jcr"); 168 } 169 } 170 171 template <class ELFT> 172 void MarkLive<ELFT>::enqueue(InputSectionBase *Sec, uint64_t Offset, 173 bool IsLSDA) { 174 // Skip over discarded sections. This in theory shouldn't happen, because 175 // the ELF spec doesn't allow a relocation to point to a deduplicated 176 // COMDAT section directly. Unfortunately this happens in practice (e.g. 177 // .eh_frame) so we need to add a check. 178 if (Sec == &InputSection::Discarded) 179 return; 180 181 // Usually, a whole section is marked as live or dead, but in mergeable 182 // (splittable) sections, each piece of data has independent liveness bit. 183 // So we explicitly tell it which offset is in use. 184 if (auto *MS = dyn_cast<MergeInputSection>(Sec)) 185 MS->getSectionPiece(Offset)->Live = true; 186 187 InputSection *S = dyn_cast<InputSection>(Sec); 188 // LSDA does not count as "live code or data" in the object file. 189 // The section may already have been marked live for LSDA in which 190 // case we still need to mark the file. 191 if (S && !IsLSDA && Sec->File) 192 Sec->getFile<ELFT>()->HasLiveCodeOrData = true; 193 194 if (Sec->Live) 195 return; 196 197 Sec->Live = true; 198 // Add input section to the queue. 199 if (S) 200 Queue.push_back(S); 201 } 202 203 template <class ELFT> void MarkLive<ELFT>::markSymbol(Symbol *Sym) { 204 if (auto *D = dyn_cast_or_null<Defined>(Sym)) 205 if (auto *IS = dyn_cast_or_null<InputSectionBase>(D->Section)) 206 enqueue(IS, D->Value, false); 207 } 208 209 // This is the main function of the garbage collector. 210 // Starting from GC-root sections, this function visits all reachable 211 // sections to set their "Live" bits. 212 template <class ELFT> void MarkLive<ELFT>::run() { 213 // Add GC root symbols. 214 markSymbol(Symtab->find(Config->Entry)); 215 markSymbol(Symtab->find(Config->Init)); 216 markSymbol(Symtab->find(Config->Fini)); 217 for (StringRef S : Config->Undefined) 218 markSymbol(Symtab->find(S)); 219 for (StringRef S : Script->ReferencedSymbols) 220 markSymbol(Symtab->find(S)); 221 222 // Preserve externally-visible symbols if the symbols defined by this 223 // file can interrupt other ELF file's symbols at runtime. 224 for (Symbol *S : Symtab->getSymbols()) 225 if (S->includeInDynsym()) 226 markSymbol(S); 227 228 // Preserve special sections and those which are specified in linker 229 // script KEEP command. 230 for (InputSectionBase *Sec : InputSections) { 231 // Mark .eh_frame sections as live because there are usually no relocations 232 // that point to .eh_frames. Otherwise, the garbage collector would drop 233 // all of them. We also want to preserve personality routines and LSDA 234 // referenced by .eh_frame sections, so we scan them for that here. 235 if (auto *EH = dyn_cast<EhInputSection>(Sec)) { 236 EH->Live = true; 237 if (!EH->NumRelocations) 238 continue; 239 240 if (EH->AreRelocsRela) 241 scanEhFrameSection(*EH, EH->template relas<ELFT>()); 242 else 243 scanEhFrameSection(*EH, EH->template rels<ELFT>()); 244 } 245 246 if (Sec->Flags & SHF_LINK_ORDER) 247 continue; 248 249 if (isReserved(Sec) || Script->shouldKeep(Sec)) { 250 enqueue(Sec, 0, false); 251 } else if (isValidCIdentifier(Sec->Name)) { 252 CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec); 253 CNamedSections[Saver.save("__stop_" + Sec->Name)].push_back(Sec); 254 } 255 } 256 257 // Mark all reachable sections. 258 while (!Queue.empty()) { 259 InputSectionBase &Sec = *Queue.pop_back_val(); 260 261 if (Sec.AreRelocsRela) { 262 for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>()) 263 resolveReloc(Sec, Rel, false); 264 } else { 265 for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>()) 266 resolveReloc(Sec, Rel, false); 267 } 268 269 for (InputSectionBase *IS : Sec.DependentSections) 270 enqueue(IS, 0, false); 271 } 272 } 273 274 // Before calling this function, Live bits are off for all 275 // input sections. This function make some or all of them on 276 // so that they are emitted to the output file. 277 template <class ELFT> void elf::markLive() { 278 // If -gc-sections is not given, no sections are removed. 279 if (!Config->GcSections) { 280 for (InputSectionBase *Sec : InputSections) 281 Sec->Live = true; 282 283 // If a DSO defines a symbol referenced in a regular object, it is needed. 284 for (Symbol *Sym : Symtab->getSymbols()) 285 if (auto *S = dyn_cast<SharedSymbol>(Sym)) 286 if (S->IsUsedInRegularObj && !S->isWeak()) 287 S->getFile().IsNeeded = true; 288 return; 289 } 290 291 // Otheriwse, do mark-sweep GC. 292 // 293 // The -gc-sections option works only for SHF_ALLOC sections 294 // (sections that are memory-mapped at runtime). So we can 295 // unconditionally make non-SHF_ALLOC sections alive except 296 // SHF_LINK_ORDER and SHT_REL/SHT_RELA sections and .debug sections. 297 // 298 // Usually, SHF_ALLOC sections are not removed even if they are 299 // unreachable through relocations because reachability is not 300 // a good signal whether they are garbage or not (e.g. there is 301 // usually no section referring to a .comment section, but we 302 // want to keep it.). 303 // 304 // Note on SHF_LINK_ORDER: Such sections contain metadata and they 305 // have a reverse dependency on the InputSection they are linked with. 306 // We are able to garbage collect them. 307 // 308 // Note on SHF_REL{,A}: Such sections reach here only when -r 309 // or -emit-reloc were given. And they are subject of garbage 310 // collection because, if we remove a text section, we also 311 // remove its relocation section. 312 for (InputSectionBase *Sec : InputSections) { 313 bool IsAlloc = (Sec->Flags & SHF_ALLOC); 314 bool IsLinkOrder = (Sec->Flags & SHF_LINK_ORDER); 315 bool IsRel = (Sec->Type == SHT_REL || Sec->Type == SHT_RELA); 316 317 if (!IsAlloc && !IsLinkOrder && !IsRel && !Sec->Debug) 318 Sec->Live = true; 319 } 320 321 // Follow the graph to mark all live sections. 322 MarkLive<ELFT>().run(); 323 324 // Mark debug sections as live in any object file that has a live 325 // Regular or Merge section. 326 for (InputSectionBase *Sec : InputSections) 327 if (Sec->Debug && Sec->getFile<ELFT>()->HasLiveCodeOrData) 328 Sec->Live = true; 329 330 // Report garbage-collected sections. 331 if (Config->PrintGcSections) 332 for (InputSectionBase *Sec : InputSections) 333 if (!Sec->Live) 334 message("removing unused section " + toString(Sec)); 335 } 336 337 template void elf::markLive<ELF32LE>(); 338 template void elf::markLive<ELF32BE>(); 339 template void elf::markLive<ELF64LE>(); 340 template void elf::markLive<ELF64BE>(); 341