github.com/Filosottile/go@v0.0.0-20170906193555-dbed9972d994/src/cmd/link/internal/ld/deadcode.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package ld 6 7 import ( 8 "cmd/internal/objabi" 9 "cmd/internal/sys" 10 "fmt" 11 "strings" 12 "unicode" 13 ) 14 15 // deadcode marks all reachable symbols. 16 // 17 // The basis of the dead code elimination is a flood fill of symbols, 18 // following their relocations, beginning at *flagEntrySymbol. 19 // 20 // This flood fill is wrapped in logic for pruning unused methods. 21 // All methods are mentioned by relocations on their receiver's *rtype. 22 // These relocations are specially defined as R_METHODOFF by the compiler 23 // so we can detect and manipulated them here. 24 // 25 // There are three ways a method of a reachable type can be invoked: 26 // 27 // 1. direct call 28 // 2. through a reachable interface type 29 // 3. reflect.Value.Call, .Method, or reflect.Method.Func 30 // 31 // The first case is handled by the flood fill, a directly called method 32 // is marked as reachable. 33 // 34 // The second case is handled by decomposing all reachable interface 35 // types into method signatures. Each encountered method is compared 36 // against the interface method signatures, if it matches it is marked 37 // as reachable. This is extremely conservative, but easy and correct. 38 // 39 // The third case is handled by looking to see if any of: 40 // - reflect.Value.Call is reachable 41 // - reflect.Value.Method is reachable 42 // - reflect.Type.Method or MethodByName is called. 43 // If any of these happen, all bets are off and all exported methods 44 // of reachable types are marked reachable. 45 // 46 // Any unreached text symbols are removed from ctxt.Textp. 47 func deadcode(ctxt *Link) { 48 if ctxt.Debugvlog != 0 { 49 ctxt.Logf("%5.2f deadcode\n", Cputime()) 50 } 51 52 d := &deadcodepass{ 53 ctxt: ctxt, 54 ifaceMethod: make(map[methodsig]bool), 55 } 56 57 // First, flood fill any symbols directly reachable in the call 58 // graph from *flagEntrySymbol. Ignore all methods not directly called. 59 d.init() 60 d.flood() 61 62 callSym := ctxt.Syms.ROLookup("reflect.Value.Call", 0) 63 methSym := ctxt.Syms.ROLookup("reflect.Value.Method", 0) 64 reflectSeen := false 65 66 if ctxt.DynlinkingGo() { 67 // Exported methods may satisfy interfaces we don't know 68 // about yet when dynamically linking. 69 reflectSeen = true 70 } 71 72 for { 73 if !reflectSeen { 74 if d.reflectMethod || (callSym != nil && callSym.Attr.Reachable()) || (methSym != nil && methSym.Attr.Reachable()) { 75 // Methods might be called via reflection. Give up on 76 // static analysis, mark all exported methods of 77 // all reachable types as reachable. 78 reflectSeen = true 79 } 80 } 81 82 // Mark all methods that could satisfy a discovered 83 // interface as reachable. We recheck old marked interfaces 84 // as new types (with new methods) may have been discovered 85 // in the last pass. 86 var rem []methodref 87 for _, m := range d.markableMethods { 88 if (reflectSeen && m.isExported()) || d.ifaceMethod[m.m] { 89 d.markMethod(m) 90 } else { 91 rem = append(rem, m) 92 } 93 } 94 d.markableMethods = rem 95 96 if len(d.markQueue) == 0 { 97 // No new work was discovered. Done. 98 break 99 } 100 d.flood() 101 } 102 103 // Remove all remaining unreached R_METHODOFF relocations. 104 for _, m := range d.markableMethods { 105 for _, r := range m.r { 106 d.cleanupReloc(r) 107 } 108 } 109 110 if Buildmode != BuildmodeShared { 111 // Keep a itablink if the symbol it points at is being kept. 112 // (When BuildmodeShared, always keep itablinks.) 113 for _, s := range ctxt.Syms.Allsym { 114 if strings.HasPrefix(s.Name, "go.itablink.") { 115 s.Attr.Set(AttrReachable, len(s.R) == 1 && s.R[0].Sym.Attr.Reachable()) 116 } 117 } 118 } 119 120 // Remove dead text but keep file information (z symbols). 121 textp := make([]*Symbol, 0, len(ctxt.Textp)) 122 for _, s := range ctxt.Textp { 123 if s.Attr.Reachable() { 124 textp = append(textp, s) 125 } 126 } 127 ctxt.Textp = textp 128 } 129 130 // methodref holds the relocations from a receiver type symbol to its 131 // method. There are three relocations, one for each of the fields in 132 // the reflect.method struct: mtyp, ifn, and tfn. 133 type methodref struct { 134 m methodsig 135 src *Symbol // receiver type symbol 136 r [3]*Reloc // R_METHODOFF relocations to fields of runtime.method 137 } 138 139 func (m methodref) ifn() *Symbol { return m.r[1].Sym } 140 141 func (m methodref) isExported() bool { 142 for _, r := range m.m { 143 return unicode.IsUpper(r) 144 } 145 panic("methodref has no signature") 146 } 147 148 // deadcodepass holds state for the deadcode flood fill. 149 type deadcodepass struct { 150 ctxt *Link 151 markQueue []*Symbol // symbols to flood fill in next pass 152 ifaceMethod map[methodsig]bool // methods declared in reached interfaces 153 markableMethods []methodref // methods of reached types 154 reflectMethod bool 155 } 156 157 func (d *deadcodepass) cleanupReloc(r *Reloc) { 158 if r.Sym.Attr.Reachable() { 159 r.Type = objabi.R_ADDROFF 160 } else { 161 if d.ctxt.Debugvlog > 1 { 162 d.ctxt.Logf("removing method %s\n", r.Sym.Name) 163 } 164 r.Sym = nil 165 r.Siz = 0 166 } 167 } 168 169 // mark appends a symbol to the mark queue for flood filling. 170 func (d *deadcodepass) mark(s, parent *Symbol) { 171 if s == nil || s.Attr.Reachable() { 172 return 173 } 174 if s.Attr.ReflectMethod() { 175 d.reflectMethod = true 176 } 177 if *flagDumpDep { 178 p := "_" 179 if parent != nil { 180 p = parent.Name 181 } 182 fmt.Printf("%s -> %s\n", p, s.Name) 183 } 184 s.Attr |= AttrReachable 185 s.Reachparent = parent 186 d.markQueue = append(d.markQueue, s) 187 } 188 189 // markMethod marks a method as reachable. 190 func (d *deadcodepass) markMethod(m methodref) { 191 for _, r := range m.r { 192 d.mark(r.Sym, m.src) 193 r.Type = objabi.R_ADDROFF 194 } 195 } 196 197 // init marks all initial symbols as reachable. 198 // In a typical binary, this is *flagEntrySymbol. 199 func (d *deadcodepass) init() { 200 var names []string 201 202 if SysArch.Family == sys.ARM { 203 // mark some functions that are only referenced after linker code editing 204 names = append(names, "runtime.read_tls_fallback") 205 } 206 207 if Buildmode == BuildmodeShared { 208 // Mark all symbols defined in this library as reachable when 209 // building a shared library. 210 for _, s := range d.ctxt.Syms.Allsym { 211 if s.Type != 0 && s.Type != SDYNIMPORT { 212 d.mark(s, nil) 213 } 214 } 215 } else { 216 // In a normal binary, start at main.main and the init 217 // functions and mark what is reachable from there. 218 219 if *FlagLinkshared && (Buildmode == BuildmodeExe || Buildmode == BuildmodePIE) { 220 names = append(names, "main.main", "main.init") 221 } else { 222 // The external linker refers main symbol directly. 223 if Linkmode == LinkExternal && (Buildmode == BuildmodeExe || Buildmode == BuildmodePIE) { 224 if Headtype == objabi.Hwindows && SysArch.Family == sys.I386 { 225 *flagEntrySymbol = "_main" 226 } else { 227 *flagEntrySymbol = "main" 228 } 229 } 230 names = append(names, *flagEntrySymbol) 231 if Buildmode == BuildmodePlugin { 232 names = append(names, *flagPluginPath+".init", *flagPluginPath+".main", "go.plugin.tabs") 233 234 // We don't keep the go.plugin.exports symbol, 235 // but we do keep the symbols it refers to. 236 exports := d.ctxt.Syms.ROLookup("go.plugin.exports", 0) 237 if exports != nil { 238 for _, r := range exports.R { 239 d.mark(r.Sym, nil) 240 } 241 } 242 } 243 } 244 for _, s := range dynexp { 245 d.mark(s, nil) 246 } 247 } 248 249 for _, name := range names { 250 d.mark(d.ctxt.Syms.ROLookup(name, 0), nil) 251 } 252 } 253 254 // flood fills symbols reachable from the markQueue symbols. 255 // As it goes, it collects methodref and interface method declarations. 256 func (d *deadcodepass) flood() { 257 for len(d.markQueue) > 0 { 258 s := d.markQueue[0] 259 d.markQueue = d.markQueue[1:] 260 if s.Type == STEXT { 261 if d.ctxt.Debugvlog > 1 { 262 d.ctxt.Logf("marktext %s\n", s.Name) 263 } 264 if s.FuncInfo != nil { 265 for _, a := range s.FuncInfo.Autom { 266 d.mark(a.Gotype, s) 267 } 268 } 269 270 } 271 272 if strings.HasPrefix(s.Name, "type.") && s.Name[5] != '.' { 273 if len(s.P) == 0 { 274 // Probably a bug. The undefined symbol check 275 // later will give a better error than deadcode. 276 continue 277 } 278 if decodetypeKind(s)&kindMask == kindInterface { 279 for _, sig := range decodeIfaceMethods(d.ctxt.Arch, s) { 280 if d.ctxt.Debugvlog > 1 { 281 d.ctxt.Logf("reached iface method: %s\n", sig) 282 } 283 d.ifaceMethod[sig] = true 284 } 285 } 286 } 287 288 mpos := 0 // 0-3, the R_METHODOFF relocs of runtime.uncommontype 289 var methods []methodref 290 for i := 0; i < len(s.R); i++ { 291 r := &s.R[i] 292 if r.Sym == nil { 293 continue 294 } 295 if r.Type == objabi.R_WEAKADDROFF { 296 // An R_WEAKADDROFF relocation is not reason 297 // enough to mark the pointed-to symbol as 298 // reachable. 299 continue 300 } 301 if r.Type != objabi.R_METHODOFF { 302 d.mark(r.Sym, s) 303 continue 304 } 305 // Collect rtype pointers to methods for 306 // later processing in deadcode. 307 if mpos == 0 { 308 m := methodref{src: s} 309 m.r[0] = r 310 methods = append(methods, m) 311 } else { 312 methods[len(methods)-1].r[mpos] = r 313 } 314 mpos++ 315 if mpos == len(methodref{}.r) { 316 mpos = 0 317 } 318 } 319 if len(methods) > 0 { 320 // Decode runtime type information for type methods 321 // to help work out which methods can be called 322 // dynamically via interfaces. 323 methodsigs := decodetypeMethods(d.ctxt.Arch, s) 324 if len(methods) != len(methodsigs) { 325 panic(fmt.Sprintf("%q has %d method relocations for %d methods", s.Name, len(methods), len(methodsigs))) 326 } 327 for i, m := range methodsigs { 328 name := string(m) 329 name = name[:strings.Index(name, "(")] 330 if !strings.HasSuffix(methods[i].ifn().Name, name) { 331 panic(fmt.Sprintf("%q relocation for %q does not match method %q", s.Name, methods[i].ifn().Name, name)) 332 } 333 methods[i].m = m 334 } 335 d.markableMethods = append(d.markableMethods, methods...) 336 } 337 338 if s.FuncInfo != nil { 339 for i := range s.FuncInfo.Funcdata { 340 d.mark(s.FuncInfo.Funcdata[i], s) 341 } 342 } 343 d.mark(s.Gotype, s) 344 d.mark(s.Sub, s) 345 d.mark(s.Outer, s) 346 } 347 }