Debian Codegraph @

src/cmd/link/internal/ld/deadcode.go

raw
1 // Copyright 2019 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/goobj"
9 "cmd/internal/objabi"
10 "cmd/internal/sys"
11 "cmd/link/internal/loader"
12 "cmd/link/internal/sym"
13 "fmt"
14 "internal/abi"
15 "internal/buildcfg"
16 "strings"
17 "unicode"
18 )
19
20 var _ = fmt.Print
21
22 type deadcodePass struct {
23 ctxt *Link
24 ldr *loader.Loader
25 wq heap // work queue, using min-heap for better locality
26
27 ifaceMethod map[methodsig]bool // methods called from reached interface call sites
28 genericIfaceMethod map[string]bool // names of methods called from reached generic interface call sites
29 markableMethods []methodref // methods of reached types
30 reflectSeen bool // whether we have seen a reflect method call
31 dynlink bool
32
33 methodsigstmp []methodsig // scratch buffer for decoding method signatures
34 pkginits []loader.Sym
35 mapinitnoop loader.Sym
36 }
37
38 func (d *deadcodePass) init() {
39 d.ldr.InitReachable()
40 d.ifaceMethod = make(map[methodsig]bool)
41 d.genericIfaceMethod = make(map[string]bool)
42 if buildcfg.Experiment.FieldTrack {
43 d.ldr.Reachparent = make([]loader.Sym, d.ldr.NSym())
44 }
45 d.dynlink = d.ctxt.DynlinkingGo()
46
47 if d.ctxt.BuildMode == BuildModeShared {
48 // Mark all symbols defined in this library as reachable when
49 // building a shared library.
50 n := d.ldr.NDef()
51 for i := 1; i < n; i++ {
52 s := loader.Sym(i)
53 if d.ldr.SymType(s).IsText() && d.ldr.SymSize(s) == 0 {
54 // Zero-sized text symbol is a function deadcoded by the
55 // compiler. It doesn't really get compiled, and its
56 // metadata may be missing.
57 continue
58 }
59 d.mark(s, 0)
60 }
61 d.mark(d.ctxt.mainInittasks, 0)
62 return
63 }
64
65 var names []string
66
67 // In a normal binary, start at main.main and the init
68 // functions and mark what is reachable from there.
69 if d.ctxt.linkShared && (d.ctxt.BuildMode == BuildModeExe || d.ctxt.BuildMode == BuildModePIE) {
70 names = append(names, "main.main", "main..inittask")
71 } else {
72 // The external linker refers main symbol directly.
73 if d.ctxt.LinkMode == LinkExternal && (d.ctxt.BuildMode == BuildModeExe || d.ctxt.BuildMode == BuildModePIE) {
74 if d.ctxt.HeadType == objabi.Hwindows && d.ctxt.Arch.Family == sys.I386 {
75 *flagEntrySymbol = "_main"
76 } else {
77 *flagEntrySymbol = "main"
78 }
79 }
80 names = append(names, *flagEntrySymbol)
81 }
82 // runtime.unreachableMethod is a function that will throw if called.
83 // We redirect unreachable methods to it.
84 names = append(names, "runtime.unreachableMethod")
85 if d.ctxt.BuildMode == BuildModePlugin {
86 names = append(names, objabi.PathToPrefix(*flagPluginPath)+"..inittask", objabi.PathToPrefix(*flagPluginPath)+".main", "go:plugin.tabs")
87
88 // We don't keep the go.plugin.exports symbol,
89 // but we do keep the symbols it refers to.
90 exportsIdx := d.ldr.Lookup("go:plugin.exports", 0)
91 if exportsIdx != 0 {
92 relocs := d.ldr.Relocs(exportsIdx)
93 for i := 0; i < relocs.Count(); i++ {
94 d.mark(relocs.At(i).Sym(), 0)
95 }
96 }
97 }
98
99 if d.ctxt.Debugvlog > 1 {
100 d.ctxt.Logf("deadcode start names: %v\n", names)
101 }
102
103 for _, name := range names {
104 // Mark symbol as a data/ABI0 symbol.
105 d.mark(d.ldr.Lookup(name, 0), 0)
106 if abiInternalVer != 0 {
107 // Also mark any Go functions (internal ABI).
108 d.mark(d.ldr.Lookup(name, abiInternalVer), 0)
109 }
110 }
111
112 // All dynamic exports are roots.
113 for _, s := range d.ctxt.dynexp {
114 if d.ctxt.Debugvlog > 1 {
115 d.ctxt.Logf("deadcode start dynexp: %s<%d>\n", d.ldr.SymName(s), d.ldr.SymVersion(s))
116 }
117 d.mark(s, 0)
118 }
119 // So are wasmexports.
120 for _, s := range d.ldr.WasmExports {
121 if d.ctxt.Debugvlog > 1 {
122 d.ctxt.Logf("deadcode start wasmexport: %s<%d>\n", d.ldr.SymName(s), d.ldr.SymVersion(s))
123 }
124 d.mark(s, 0)
125 }
126
127 d.mapinitnoop = d.ldr.Lookup("runtime.mapinitnoop", abiInternalVer)
128 if d.mapinitnoop == 0 {
129 panic("could not look up runtime.mapinitnoop")
130 }
131 if d.ctxt.mainInittasks != 0 {
132 d.mark(d.ctxt.mainInittasks, 0)
133 }
134 }
135
136 func (d *deadcodePass) flood() {
137 var methods []methodref
138 for !d.wq.empty() {
139 symIdx := d.wq.pop()
140
141 // Methods may be called via reflection. Give up on static analysis,
142 // and mark all exported methods of all reachable types as reachable.
143 d.reflectSeen = d.reflectSeen || d.ldr.IsReflectMethod(symIdx)
144
145 isgotype := d.ldr.IsGoType(symIdx)
146 relocs := d.ldr.Relocs(symIdx)
147 var usedInIface bool
148
149 if isgotype {
150 if d.dynlink {
151 // When dynamic linking, a type may be passed across DSO
152 // boundary and get converted to interface at the other side.
153 d.ldr.SetAttrUsedInIface(symIdx, true)
154 }
155 usedInIface = d.ldr.AttrUsedInIface(symIdx)
156 }
157
158 methods = methods[:0]
159 for i := 0; i < relocs.Count(); i++ {
160 r := relocs.At(i)
161 if r.Weak() {
162 convertWeakToStrong := false
163 // When build with "-linkshared", we can't tell if the
164 // interface method in itab will be used or not.
165 // Ignore the weak attribute.
166 if d.ctxt.linkShared && d.ldr.IsItab(symIdx) {
167 convertWeakToStrong = true
168 }
169 // If the program uses plugins, we can no longer treat
170 // relocs from pkg init functions to outlined map init
171 // fragments as weak, since doing so can cause package
172 // init clashes between the main program and the
173 // plugin. See #62430 for more details.
174 if d.ctxt.canUsePlugins && r.Type().IsDirectCall() {
175 convertWeakToStrong = true
176 }
177 if !convertWeakToStrong {
178 // skip this reloc
179 continue
180 }
181 }
182 t := r.Type()
183 switch t {
184 case objabi.R_METHODOFF:
185 if i+2 >= relocs.Count() {
186 panic("expect three consecutive R_METHODOFF relocs")
187 }
188 if usedInIface {
189 methods = append(methods, methodref{src: symIdx, r: i})
190 // The method descriptor is itself a type descriptor, and
191 // it can be used to reach other types, e.g. by using
192 // reflect.Type.Method(i).Type.In(j). We need to traverse
193 // its child types with UsedInIface set. (See also the
194 // comment below.)
195 rs := r.Sym()
196 if !d.ldr.AttrUsedInIface(rs) {
197 d.ldr.SetAttrUsedInIface(rs, true)
198 if d.ldr.AttrReachable(rs) {
199 d.ldr.SetAttrReachable(rs, false)
200 d.mark(rs, symIdx)
201 }
202 }
203 }
204 i += 2
205 continue
206 case objabi.R_USETYPE:
207 // type symbol used for DWARF. we need to load the symbol but it may not
208 // be otherwise reachable in the program.
209 // do nothing for now as we still load all type symbols.
210 continue
211 case objabi.R_USEIFACE:
212 // R_USEIFACE is a marker relocation that tells the linker the type is
213 // converted to an interface, i.e. should have UsedInIface set. See the
214 // comment below for why we need to unset the Reachable bit and re-mark it.
215 rs := r.Sym()
216 if d.ldr.IsItab(rs) {
217 // This relocation can also point at an itab, in which case it
218 // means "the Type field of that itab".
219 rs = decodeItabType(d.ldr, d.ctxt.Arch, rs)
220 }
221 if !d.ldr.IsGoType(rs) && !d.ctxt.linkShared {
222 panic(fmt.Sprintf("R_USEIFACE in %s references %s which is not a type or itab", d.ldr.SymName(symIdx), d.ldr.SymName(rs)))
223 }
224 if !d.ldr.AttrUsedInIface(rs) {
225 d.ldr.SetAttrUsedInIface(rs, true)
226 if d.ldr.AttrReachable(rs) {
227 d.ldr.SetAttrReachable(rs, false)
228 d.mark(rs, symIdx)
229 }
230 }
231 continue
232 case objabi.R_USEIFACEMETHOD:
233 // R_USEIFACEMETHOD is a marker relocation that marks an interface
234 // method as used.
235 rs := r.Sym()
236 if d.ctxt.linkShared && (d.ldr.SymType(rs) == sym.SDYNIMPORT || d.ldr.SymType(rs) == sym.Sxxx) {
237 // Don't decode symbol from shared library (we'll mark all exported methods anyway).
238 // We check for both SDYNIMPORT and Sxxx because name-mangled symbols haven't
239 // been resolved at this point.
240 continue
241 }
242 m := d.decodeIfaceMethod(d.ldr, d.ctxt.Arch, rs, r.Add())
243 if d.ctxt.Debugvlog > 1 {
244 d.ctxt.Logf("reached iface method: %v\n", m)
245 }
246 d.ifaceMethod[m] = true
247 continue
248 case objabi.R_USENAMEDMETHOD:
249 name := d.decodeGenericIfaceMethod(d.ldr, r.Sym())
250 if d.ctxt.Debugvlog > 1 {
251 d.ctxt.Logf("reached generic iface method: %s\n", name)
252 }
253 d.genericIfaceMethod[name] = true
254 continue // don't mark referenced symbol - it is not needed in the final binary.
255 case objabi.R_INITORDER:
256 // inittasks has already run, so any R_INITORDER links are now
257 // superfluous - the only live inittask records are those which are
258 // in a scheduled list somewhere (e.g. runtime.moduledata.inittasks).
259 continue
260 }
261 rs := r.Sym()
262 if isgotype && usedInIface && d.ldr.IsGoType(rs) && !d.ldr.AttrUsedInIface(rs) {
263 // If a type is converted to an interface, it is possible to obtain an
264 // interface with a "child" type of it using reflection (e.g. obtain an
265 // interface of T from []chan T). We need to traverse its "child" types
266 // with UsedInIface attribute set.
267 // When visiting the child type (chan T in the example above), it will
268 // have UsedInIface set, so it in turn will mark and (re)visit its children
269 // (e.g. T above).
270 // We unset the reachable bit here, so if the child type is already visited,
271 // it will be visited again.
272 // Note that a type symbol can be visited at most twice, one without
273 // UsedInIface and one with. So termination is still guaranteed.
274 d.ldr.SetAttrUsedInIface(rs, true)
275 d.ldr.SetAttrReachable(rs, false)
276 }
277 d.mark(rs, symIdx)
278 }
279 naux := d.ldr.NAux(symIdx)
280 for i := 0; i < naux; i++ {
281 a := d.ldr.Aux(symIdx, i)
282 if a.Type() == goobj.AuxGotype {
283 // A symbol being reachable doesn't imply we need its
284 // type descriptor. Don't mark it.
285 continue
286 }
287 d.mark(a.Sym(), symIdx)
288 }
289 // Record sym if package init func (here naux != 0 is a cheap way
290 // to check first if it is a function symbol).
291 if naux != 0 && d.ldr.IsPkgInit(symIdx) {
292
293 d.pkginits = append(d.pkginits, symIdx)
294 }
295 // Some host object symbols have an outer object, which acts like a
296 // "carrier" symbol, or it holds all the symbols for a particular
297 // section. We need to mark all "referenced" symbols from that carrier,
298 // so we make sure we're pulling in all outer symbols, and their sub
299 // symbols. This is not ideal, and these carrier/section symbols could
300 // be removed.
301 if d.ldr.IsExternal(symIdx) {
302 d.mark(d.ldr.OuterSym(symIdx), symIdx)
303 d.mark(d.ldr.SubSym(symIdx), symIdx)
304 }
305
306 if len(methods) != 0 {
307 if !isgotype {
308 panic("method found on non-type symbol")
309 }
310 // Decode runtime type information for type methods
311 // to help work out which methods can be called
312 // dynamically via interfaces.
313 methodsigs := d.decodetypeMethods(d.ldr, d.ctxt.Arch, symIdx, &relocs)
314 if len(methods) != len(methodsigs) {
315 panic(fmt.Sprintf("%q has %d method relocations for %d methods", d.ldr.SymName(symIdx), len(methods), len(methodsigs)))
316 }
317 for i, m := range methodsigs {
318 methods[i].m = m
319 if d.ctxt.Debugvlog > 1 {
320 d.ctxt.Logf("markable method: %v of sym %v %s\n", m, symIdx, d.ldr.SymName(symIdx))
321 }
322 }
323 d.markableMethods = append(d.markableMethods, methods...)
324 }
325 }
326 }
327
328 // mapinitcleanup walks all pkg init functions and looks for weak relocations
329 // to mapinit symbols that are no longer reachable. It rewrites
330 // the relocs to target a new no-op routine in the runtime.
331 func (d *deadcodePass) mapinitcleanup() {
332 for _, idx := range d.pkginits {
333 relocs := d.ldr.Relocs(idx)
334 var su *loader.SymbolBuilder
335 for i := 0; i < relocs.Count(); i++ {
336 r := relocs.At(i)
337 rs := r.Sym()
338 if r.Weak() && r.Type().IsDirectCall() && !d.ldr.AttrReachable(rs) {
339 // double check to make sure target is indeed map.init
340 rsn := d.ldr.SymName(rs)
341 if !strings.Contains(rsn, "map.init") {
342 panic(fmt.Sprintf("internal error: expected map.init sym for weak call reloc, got %s -> %s", d.ldr.SymName(idx), rsn))
343 }
344 d.ldr.SetAttrReachable(d.mapinitnoop, true)
345 if d.ctxt.Debugvlog > 1 {
346 d.ctxt.Logf("deadcode: %s rewrite %s ref to %s\n",
347 d.ldr.SymName(idx), rsn,
348 d.ldr.SymName(d.mapinitnoop))
349 }
350 if su == nil {
351 su = d.ldr.MakeSymbolUpdater(idx)
352 }
353 su.SetRelocSym(i, d.mapinitnoop)
354 }
355 }
356 }
357 }
358
359 func (d *deadcodePass) mark(symIdx, parent loader.Sym) {
360 if symIdx != 0 && !d.ldr.AttrReachable(symIdx) {
361 d.wq.push(symIdx)
362 d.ldr.SetAttrReachable(symIdx, true)
363 if buildcfg.Experiment.FieldTrack && d.ldr.Reachparent[symIdx] == 0 {
364 d.ldr.Reachparent[symIdx] = parent
365 }
366 if *flagDumpDep {
367 to := d.ldr.SymName(symIdx)
368 if to != "" {
369 to = d.dumpDepAddFlags(to, symIdx)
370 from := "_"
371 if parent != 0 {
372 from = d.ldr.SymName(parent)
373 from = d.dumpDepAddFlags(from, parent)
374 }
375 fmt.Printf("%s -> %s\n", from, to)
376 }
377 }
378 }
379 }
380
381 func (d *deadcodePass) dumpDepAddFlags(name string, symIdx loader.Sym) string {
382 var flags strings.Builder
383 if d.ldr.AttrUsedInIface(symIdx) {
384 flags.WriteString("<UsedInIface>")
385 }
386 if d.ldr.IsReflectMethod(symIdx) {
387 flags.WriteString("<ReflectMethod>")
388 }
389 if flags.Len() > 0 {
390 return name + " " + flags.String()
391 }
392 return name
393 }
394
395 func (d *deadcodePass) markMethod(m methodref) {
396 relocs := d.ldr.Relocs(m.src)
397 d.mark(relocs.At(m.r).Sym(), m.src)
398 d.mark(relocs.At(m.r+1).Sym(), m.src)
399 d.mark(relocs.At(m.r+2).Sym(), m.src)
400 }
401
402 // deadcode marks all reachable symbols.
403 //
404 // The basis of the dead code elimination is a flood fill of symbols,
405 // following their relocations, beginning at *flagEntrySymbol.
406 //
407 // This flood fill is wrapped in logic for pruning unused methods.
408 // All methods are mentioned by relocations on their receiver's *rtype.
409 // These relocations are specially defined as R_METHODOFF by the compiler
410 // so we can detect and manipulated them here.
411 //
412 // There are three ways a method of a reachable type can be invoked:
413 //
414 // 1. direct call
415 // 2. through a reachable interface type
416 // 3. reflect.Value.Method (or MethodByName), or reflect.Type.Method
417 // (or MethodByName)
418 //
419 // The first case is handled by the flood fill, a directly called method
420 // is marked as reachable.
421 //
422 // The second case is handled by decomposing all reachable interface
423 // types into method signatures. Each encountered method is compared
424 // against the interface method signatures, if it matches it is marked
425 // as reachable. This is extremely conservative, but easy and correct.
426 //
427 // The third case is handled by looking for functions that compiler flagged
428 // as REFLECTMETHOD. REFLECTMETHOD on a function F means that F does a method
429 // lookup with reflection, but the compiler was not able to statically determine
430 // the method name.
431 //
432 // All functions that call reflect.Value.Method or reflect.Type.Method are REFLECTMETHODs.
433 // Functions that call reflect.Value.MethodByName or reflect.Type.MethodByName with
434 // a non-constant argument are REFLECTMETHODs, too. If we find a REFLECTMETHOD,
435 // we give up on static analysis, and mark all exported methods of all reachable
436 // types as reachable.
437 //
438 // If the argument to MethodByName is a compile-time constant, the compiler
439 // emits a relocation with the method name. Matching methods are kept in all
440 // reachable types.
441 //
442 // Any unreached text symbols are removed from ctxt.Textp.
443 func deadcode(ctxt *Link) {
444 ldr := ctxt.loader
445 d := deadcodePass{ctxt: ctxt, ldr: ldr}
446 d.init()
447 d.flood()
448
449 if ctxt.DynlinkingGo() {
450 // Exported methods may satisfy interfaces we don't know
451 // about yet when dynamically linking.
452 d.reflectSeen = true
453 }
454
455 for {
456 // Mark all methods that could satisfy a discovered
457 // interface as reachable. We recheck old marked interfaces
458 // as new types (with new methods) may have been discovered
459 // in the last pass.
460 rem := d.markableMethods[:0]
461 for _, m := range d.markableMethods {
462 if (d.reflectSeen && (m.isExported() || d.dynlink)) || d.ifaceMethod[m.m] || d.genericIfaceMethod[m.m.name] {
463 d.markMethod(m)
464 } else {
465 rem = append(rem, m)
466 }
467 }
468 d.markableMethods = rem
469
470 if d.wq.empty() {
471 // No new work was discovered. Done.
472 break
473 }
474 d.flood()
475 }
476 if *flagPruneWeakMap {
477 d.mapinitcleanup()
478 }
479 }
480
481 // methodsig is a typed method signature (name + type).
482 type methodsig struct {
483 name string
484 typ loader.Sym // type descriptor symbol of the function
485 }
486
487 // methodref holds the relocations from a receiver type symbol to its
488 // method. There are three relocations, one for each of the fields in
489 // the reflect.method struct: mtyp, ifn, and tfn.
490 type methodref struct {
491 m methodsig
492 src loader.Sym // receiver type symbol
493 r int // the index of R_METHODOFF relocations
494 }
495
496 func (m methodref) isExported() bool {
497 for _, r := range m.m.name {
498 return unicode.IsUpper(r)
499 }
500 panic("methodref has no signature")
501 }
502
503 // decodeMethodSig decodes an array of method signature information.
504 // Each element of the array is size bytes. The first 4 bytes is a
505 // nameOff for the method name, and the next 4 bytes is a typeOff for
506 // the function type.
507 //
508 // Conveniently this is the layout of both runtime.method and runtime.imethod.
509 func (d *deadcodePass) decodeMethodSig(ldr *loader.Loader, arch *sys.Arch, symIdx loader.Sym, relocs *loader.Relocs, off, size, count int) []methodsig {
510 if cap(d.methodsigstmp) < count {
511 d.methodsigstmp = append(d.methodsigstmp[:0], make([]methodsig, count)...)
512 }
513 var methods = d.methodsigstmp[:count]
514 for i := 0; i < count; i++ {
515 methods[i].name = decodetypeName(ldr, symIdx, relocs, off)
516 methods[i].typ = decodeRelocSym(ldr, symIdx, relocs, int32(off+4))
517 off += size
518 }
519 return methods
520 }
521
522 // Decode the method of interface type symbol symIdx at offset off.
523 func (d *deadcodePass) decodeIfaceMethod(ldr *loader.Loader, arch *sys.Arch, symIdx loader.Sym, off int64) methodsig {
524 p := ldr.Data(symIdx)
525 if p == nil {
526 panic(fmt.Sprintf("missing symbol %q", ldr.SymName(symIdx)))
527 }
528 if decodetypeKind(arch, p) != abi.Interface {
529 panic(fmt.Sprintf("symbol %q is not an interface", ldr.SymName(symIdx)))
530 }
531 relocs := ldr.Relocs(symIdx)
532 var m methodsig
533 m.name = decodetypeName(ldr, symIdx, &relocs, int(off))
534 m.typ = decodeRelocSym(ldr, symIdx, &relocs, int32(off+4))
535 return m
536 }
537
538 // Decode the method name stored in symbol symIdx. The symbol should contain just the bytes of a method name.
539 func (d *deadcodePass) decodeGenericIfaceMethod(ldr *loader.Loader, symIdx loader.Sym) string {
540 return ldr.DataString(symIdx)
541 }
542
543 func (d *deadcodePass) decodetypeMethods(ldr *loader.Loader, arch *sys.Arch, symIdx loader.Sym, relocs *loader.Relocs) []methodsig {
544 p := ldr.Data(symIdx)
545 if !decodetypeHasUncommon(arch, p) {
546 panic(fmt.Sprintf("no methods on %q", ldr.SymName(symIdx)))
547 }
548 off := commonsize(arch) // reflect.rtype
549 switch decodetypeKind(arch, p) {
550 case abi.Struct: // reflect.structType
551 off += 4 * arch.PtrSize
552 case abi.Pointer: // reflect.ptrType
553 off += arch.PtrSize
554 case abi.Func: // reflect.funcType
555 off += arch.PtrSize // 4 bytes, pointer aligned
556 case abi.Slice: // reflect.sliceType
557 off += arch.PtrSize
558 case abi.Array: // reflect.arrayType
559 off += 3 * arch.PtrSize
560 case abi.Chan: // reflect.chanType
561 off += 2 * arch.PtrSize
562 case abi.Map:
563 off += 7*arch.PtrSize + 4 // internal/abi.MapType
564 if arch.PtrSize == 8 {
565 off += 4 // padding for final uint32 field (Flags).
566 }
567 case abi.Interface: // reflect.interfaceType
568 off += 3 * arch.PtrSize
569 default:
570 // just Sizeof(rtype)
571 }
572
573 mcount := int(decodeInuxi(arch, p[off+4:], 2))
574 moff := int(decodeInuxi(arch, p[off+4+2+2:], 4))
575 off += moff // offset to array of reflect.method values
576 const sizeofMethod = 4 * 4 // sizeof reflect.method in program
577 return d.decodeMethodSig(ldr, arch, symIdx, relocs, off, sizeofMethod, mcount)
578 }