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 template <class ELFT> 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)); 50 } 51 52 template <class ELFT> 53 static typename ELFT::uint getAddend(InputSectionBase &Sec, 54 const typename ELFT::Rela &Rel) { 55 return Rel.r_addend; 56 } 57 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; 61 62 template <class ELFT, class RelT> 63 static void resolveReloc(InputSectionBase &Sec, RelT &Rel, 64 std::function<void(InputSectionBase *, uint64_t)> Fn) { 65 SymbolBody &B = Sec.getFile<ELFT>()->getRelocTargetSym(Rel); 66 67 if (auto *D = dyn_cast<DefinedRegular>(&B)) { 68 if (!D->Section) 69 return; 70 uint64_t Offset = D->Value; 71 if (D->isSection()) 72 Offset += getAddend<ELFT>(Sec, Rel); 73 Fn(cast<InputSectionBase>(D->Section), Offset); 74 return; 75 } 76 77 if (auto *U = dyn_cast<Undefined>(&B)) 78 for (InputSectionBase *Sec : CNamedSections.lookup(U->getName())) 79 Fn(Sec, 0); 80 } 81 82 // Calls Fn for each section that Sec refers to via relocations. 83 template <class ELFT> 84 static void 85 forEachSuccessor(InputSection &Sec, 86 std::function<void(InputSectionBase *, uint64_t)> Fn) { 87 if (Sec.AreRelocsRela) { 88 for (const typename ELFT::Rela &Rel : Sec.template relas<ELFT>()) 89 resolveReloc<ELFT>(Sec, Rel, Fn); 90 } else { 91 for (const typename ELFT::Rel &Rel : Sec.template rels<ELFT>()) 92 resolveReloc<ELFT>(Sec, Rel, Fn); 93 } 94 95 for (InputSectionBase *IS : Sec.DependentSections) 96 Fn(IS, 0); 97 } 98 99 // The .eh_frame section is an unfortunate special case. 100 // The section is divided in CIEs and FDEs and the relocations it can have are 101 // * CIEs can refer to a personality function. 102 // * FDEs can refer to a LSDA 103 // * FDEs refer to the function they contain information about 104 // The last kind of relocation cannot keep the referred section alive, or they 105 // would keep everything alive in a common object file. In fact, each FDE is 106 // alive if the section it refers to is alive. 107 // To keep things simple, in here we just ignore the last relocation kind. The 108 // other two keep the referred section alive. 109 // 110 // A possible improvement would be to fully process .eh_frame in the middle of 111 // the gc pass. With that we would be able to also gc some sections holding 112 // LSDAs and personality functions if we found that they were unused. 113 template <class ELFT, class RelTy> 114 static void 115 scanEhFrameSection(EhInputSection &EH, ArrayRef<RelTy> Rels, 116 std::function<void(InputSectionBase *, uint64_t)> Fn) { 117 const endianness E = ELFT::TargetEndianness; 118 119 for (unsigned I = 0, N = EH.Pieces.size(); I < N; ++I) { 120 EhSectionPiece &Piece = EH.Pieces[I]; 121 unsigned FirstRelI = Piece.FirstRelocation; 122 if (FirstRelI == (unsigned)-1) 123 continue; 124 if (read32<E>(Piece.data().data() + 4) == 0) { 125 // This is a CIE, we only need to worry about the first relocation. It is 126 // known to point to the personality function. 127 resolveReloc<ELFT>(EH, Rels[FirstRelI], Fn); 128 continue; 129 } 130 // This is a FDE. The relocations point to the described function or to 131 // a LSDA. We only need to keep the LSDA alive, so ignore anything that 132 // points to executable sections. 133 typename ELFT::uint PieceEnd = Piece.InputOff + Piece.Size; 134 for (unsigned I2 = FirstRelI, N2 = Rels.size(); I2 < N2; ++I2) { 135 const RelTy &Rel = Rels[I2]; 136 if (Rel.r_offset >= PieceEnd) 137 break; 138 resolveReloc<ELFT>(EH, Rels[I2], 139 [&](InputSectionBase *Sec, uint64_t Offset) { 140 if (Sec && Sec != &InputSection::Discarded && 141 !(Sec->Flags & SHF_EXECINSTR)) 142 Fn(Sec, 0); 143 }); 144 } 145 } 146 } 147 148 template <class ELFT> 149 static void 150 scanEhFrameSection(EhInputSection &EH, 151 std::function<void(InputSectionBase *, uint64_t)> Fn) { 152 if (!EH.NumRelocations) 153 return; 154 155 // Unfortunately we need to split .eh_frame early since some relocations in 156 // .eh_frame keep other section alive and some don't. 157 EH.split<ELFT>(); 158 159 if (EH.AreRelocsRela) 160 scanEhFrameSection<ELFT>(EH, EH.template relas<ELFT>(), Fn); 161 else 162 scanEhFrameSection<ELFT>(EH, EH.template rels<ELFT>(), Fn); 163 } 164 165 // We do not garbage-collect two types of sections: 166 // 1) Sections used by the loader (.init, .fini, .ctors, .dtors or .jcr) 167 // 2) Non-allocatable sections which typically contain debugging information 168 template <class ELFT> static bool isReserved(InputSectionBase *Sec) { 169 switch (Sec->Type) { 170 case SHT_FINI_ARRAY: 171 case SHT_INIT_ARRAY: 172 case SHT_NOTE: 173 case SHT_PREINIT_ARRAY: 174 return true; 175 default: 176 if (!(Sec->Flags & SHF_ALLOC)) 177 return true; 178 179 StringRef S = Sec->Name; 180 return S.startswith(".ctors") || S.startswith(".dtors") || 181 S.startswith(".init") || S.startswith(".fini") || 182 S.startswith(".jcr"); 183 } 184 } 185 186 // This is the main function of the garbage collector. 187 // Starting from GC-root sections, this function visits all reachable 188 // sections to set their "Live" bits. 189 template <class ELFT> static void doGcSections() { 190 SmallVector<InputSection *, 256> Q; 191 CNamedSections.clear(); 192 193 auto Enqueue = [&](InputSectionBase *Sec, uint64_t Offset) { 194 // Skip over discarded sections. This in theory shouldn't happen, because 195 // the ELF spec doesn't allow a relocation to point to a deduplicated 196 // COMDAT section directly. Unfortunately this happens in practice (e.g. 197 // .eh_frame) so we need to add a check. 198 if (Sec == &InputSection::Discarded) 199 return; 200 201 // We don't gc non alloc sections. 202 if (!(Sec->Flags & SHF_ALLOC)) 203 return; 204 205 // Usually, a whole section is marked as live or dead, but in mergeable 206 // (splittable) sections, each piece of data has independent liveness bit. 207 // So we explicitly tell it which offset is in use. 208 if (auto *MS = dyn_cast<MergeInputSection>(Sec)) 209 MS->markLiveAt(Offset); 210 211 if (Sec->Live) 212 return; 213 Sec->Live = true; 214 215 // Add input section to the queue. 216 if (InputSection *S = dyn_cast<InputSection>(Sec)) 217 Q.push_back(S); 218 }; 219 220 auto MarkSymbol = [&](SymbolBody *Sym) { 221 if (auto *D = dyn_cast_or_null<DefinedRegular>(Sym)) 222 if (auto *IS = cast_or_null<InputSectionBase>(D->Section)) 223 Enqueue(IS, D->Value); 224 }; 225 226 // Add GC root symbols. 227 MarkSymbol(Symtab->find(Config->Entry)); 228 MarkSymbol(Symtab->find(Config->Init)); 229 MarkSymbol(Symtab->find(Config->Fini)); 230 for (StringRef S : Config->Undefined) 231 MarkSymbol(Symtab->find(S)); 232 for (StringRef S : Script->ReferencedSymbols) 233 MarkSymbol(Symtab->find(S)); 234 235 // Preserve externally-visible symbols if the symbols defined by this 236 // file can interrupt other ELF file's symbols at runtime. 237 for (Symbol *S : Symtab->getSymbols()) 238 if (S->includeInDynsym()) 239 MarkSymbol(S->body()); 240 241 // Preserve special sections and those which are specified in linker 242 // script KEEP command. 243 for (InputSectionBase *Sec : InputSections) { 244 // .eh_frame is always marked as live now, but also it can reference to 245 // sections that contain personality. We preserve all non-text sections 246 // referred by .eh_frame here. 247 if (auto *EH = dyn_cast_or_null<EhInputSection>(Sec)) 248 scanEhFrameSection<ELFT>(*EH, Enqueue); 249 if (Sec->Flags & SHF_LINK_ORDER) 250 continue; 251 if (isReserved<ELFT>(Sec) || Script->shouldKeep(Sec)) 252 Enqueue(Sec, 0); 253 else if (isValidCIdentifier(Sec->Name)) { 254 CNamedSections[Saver.save("__start_" + Sec->Name)].push_back(Sec); 255 CNamedSections[Saver.save("__stop_" + Sec->Name)].push_back(Sec); 256 } 257 } 258 259 // Mark all reachable sections. 260 while (!Q.empty()) 261 forEachSuccessor<ELFT>(*Q.pop_back_val(), Enqueue); 262 } 263 264 // Before calling this function, Live bits are off for all 265 // input sections. This function make some or all of them on 266 // so that they are emitted to the output file. 267 template <class ELFT> void elf::markLive() { 268 // If -gc-sections is missing, no sections are removed. 269 if (!Config->GcSections) { 270 for (InputSectionBase *Sec : InputSections) 271 Sec->Live = true; 272 return; 273 } 274 275 // The -gc-sections option works only for SHF_ALLOC sections 276 // (sections that are memory-mapped at runtime). So we can 277 // unconditionally make non-SHF_ALLOC sections alive. 278 // 279 // Non SHF_ALLOC sections are not removed even if they are 280 // unreachable through relocations because reachability is not 281 // a good signal whether they are garbage or not (e.g. there is 282 // usually no section referring to a .comment section, but we 283 // want to keep it.) 284 // 285 // Note on SHF_REL{,A}: Such sections reach here only when -r 286 // or -emit-reloc were given. And they are subject of garbage 287 // collection because, if we remove a text section, we also 288 // remove its relocation section. 289 for (InputSectionBase *Sec : InputSections) { 290 bool IsAlloc = (Sec->Flags & SHF_ALLOC); 291 bool IsRel = (Sec->Type == SHT_REL || Sec->Type == SHT_RELA); 292 if (!IsAlloc && !IsRel) 293 Sec->Live = true; 294 } 295 296 // Follow the graph to mark all live sections. 297 doGcSections<ELFT>(); 298 } 299 300 template void elf::markLive<ELF32LE>(); 301 template void elf::markLive<ELF32BE>(); 302 template void elf::markLive<ELF64LE>(); 303 template void elf::markLive<ELF64BE>(); 304