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