github.com/euank/go@v0.0.0-20160829210321-495514729181/src/cmd/vet/copylock.go (about)

     1  // Copyright 2013 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  // This file contains the code to check that locks are not passed by value.
     6  
     7  package main
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  	"go/ast"
    13  	"go/token"
    14  	"go/types"
    15  )
    16  
    17  func init() {
    18  	register("copylocks",
    19  		"check that locks are not passed by value",
    20  		checkCopyLocks,
    21  		funcDecl, rangeStmt, funcLit, callExpr, assignStmt, genDecl, compositeLit, returnStmt)
    22  }
    23  
    24  // checkCopyLocks checks whether node might
    25  // inadvertently copy a lock.
    26  func checkCopyLocks(f *File, node ast.Node) {
    27  	switch node := node.(type) {
    28  	case *ast.RangeStmt:
    29  		checkCopyLocksRange(f, node)
    30  	case *ast.FuncDecl:
    31  		checkCopyLocksFunc(f, node.Name.Name, node.Recv, node.Type)
    32  	case *ast.FuncLit:
    33  		checkCopyLocksFunc(f, "func", nil, node.Type)
    34  	case *ast.CallExpr:
    35  		checkCopyLocksCallExpr(f, node)
    36  	case *ast.AssignStmt:
    37  		checkCopyLocksAssign(f, node)
    38  	case *ast.GenDecl:
    39  		checkCopyLocksGenDecl(f, node)
    40  	case *ast.CompositeLit:
    41  		checkCopyLocksCompositeLit(f, node)
    42  	case *ast.ReturnStmt:
    43  		checkCopyLocksReturnStmt(f, node)
    44  	}
    45  }
    46  
    47  // checkCopyLocksAssign checks whether an assignment
    48  // copies a lock.
    49  func checkCopyLocksAssign(f *File, as *ast.AssignStmt) {
    50  	for i, x := range as.Rhs {
    51  		if path := lockPathRhs(f, x); path != nil {
    52  			f.Badf(x.Pos(), "assignment copies lock value to %v: %v", f.gofmt(as.Lhs[i]), path)
    53  		}
    54  	}
    55  }
    56  
    57  // checkCopyLocksGenDecl checks whether lock is copied
    58  // in variable declaration.
    59  func checkCopyLocksGenDecl(f *File, gd *ast.GenDecl) {
    60  	if gd.Tok != token.VAR {
    61  		return
    62  	}
    63  	for _, spec := range gd.Specs {
    64  		valueSpec := spec.(*ast.ValueSpec)
    65  		for i, x := range valueSpec.Values {
    66  			if path := lockPathRhs(f, x); path != nil {
    67  				f.Badf(x.Pos(), "variable declaration copies lock value to %v: %v", valueSpec.Names[i].Name, path)
    68  			}
    69  		}
    70  	}
    71  }
    72  
    73  // checkCopyLocksCompositeLit detects lock copy inside a composite literal
    74  func checkCopyLocksCompositeLit(f *File, cl *ast.CompositeLit) {
    75  	for _, x := range cl.Elts {
    76  		if node, ok := x.(*ast.KeyValueExpr); ok {
    77  			x = node.Value
    78  		}
    79  		if path := lockPathRhs(f, x); path != nil {
    80  			f.Badf(x.Pos(), "literal copies lock value from %v: %v", f.gofmt(x), path)
    81  		}
    82  	}
    83  }
    84  
    85  // checkCopyLocksReturnStmt detects lock copy in return statement
    86  func checkCopyLocksReturnStmt(f *File, rs *ast.ReturnStmt) {
    87  	for _, x := range rs.Results {
    88  		if path := lockPathRhs(f, x); path != nil {
    89  			f.Badf(x.Pos(), "return copies lock value: %v", path)
    90  		}
    91  	}
    92  }
    93  
    94  // checkCopyLocksCallExpr detects lock copy in the arguments to a function call
    95  func checkCopyLocksCallExpr(f *File, ce *ast.CallExpr) {
    96  	if id, ok := ce.Fun.(*ast.Ident); ok && id.Name == "new" && f.pkg.types[id].IsBuiltin() {
    97  		// Skip 'new(Type)' for built-in 'new'
    98  		return
    99  	}
   100  	for _, x := range ce.Args {
   101  		if path := lockPathRhs(f, x); path != nil {
   102  			f.Badf(x.Pos(), "function call copies lock value: %v", path)
   103  		}
   104  	}
   105  }
   106  
   107  // checkCopyLocksFunc checks whether a function might
   108  // inadvertently copy a lock, by checking whether
   109  // its receiver, parameters, or return values
   110  // are locks.
   111  func checkCopyLocksFunc(f *File, name string, recv *ast.FieldList, typ *ast.FuncType) {
   112  	if recv != nil && len(recv.List) > 0 {
   113  		expr := recv.List[0].Type
   114  		if path := lockPath(f.pkg.typesPkg, f.pkg.types[expr].Type); path != nil {
   115  			f.Badf(expr.Pos(), "%s passes lock by value: %v", name, path)
   116  		}
   117  	}
   118  
   119  	if typ.Params != nil {
   120  		for _, field := range typ.Params.List {
   121  			expr := field.Type
   122  			if path := lockPath(f.pkg.typesPkg, f.pkg.types[expr].Type); path != nil {
   123  				f.Badf(expr.Pos(), "%s passes lock by value: %v", name, path)
   124  			}
   125  		}
   126  	}
   127  
   128  	// Don't check typ.Results. If T has a Lock field it's OK to write
   129  	//     return T{}
   130  	// because that is returning the zero value. Leave result checking
   131  	// to the return statement.
   132  }
   133  
   134  // checkCopyLocksRange checks whether a range statement
   135  // might inadvertently copy a lock by checking whether
   136  // any of the range variables are locks.
   137  func checkCopyLocksRange(f *File, r *ast.RangeStmt) {
   138  	checkCopyLocksRangeVar(f, r.Tok, r.Key)
   139  	checkCopyLocksRangeVar(f, r.Tok, r.Value)
   140  }
   141  
   142  func checkCopyLocksRangeVar(f *File, rtok token.Token, e ast.Expr) {
   143  	if e == nil {
   144  		return
   145  	}
   146  	id, isId := e.(*ast.Ident)
   147  	if isId && id.Name == "_" {
   148  		return
   149  	}
   150  
   151  	var typ types.Type
   152  	if rtok == token.DEFINE {
   153  		if !isId {
   154  			return
   155  		}
   156  		obj := f.pkg.defs[id]
   157  		if obj == nil {
   158  			return
   159  		}
   160  		typ = obj.Type()
   161  	} else {
   162  		typ = f.pkg.types[e].Type
   163  	}
   164  
   165  	if typ == nil {
   166  		return
   167  	}
   168  	if path := lockPath(f.pkg.typesPkg, typ); path != nil {
   169  		f.Badf(e.Pos(), "range var %s copies lock: %v", f.gofmt(e), path)
   170  	}
   171  }
   172  
   173  type typePath []types.Type
   174  
   175  // String pretty-prints a typePath.
   176  func (path typePath) String() string {
   177  	n := len(path)
   178  	var buf bytes.Buffer
   179  	for i := range path {
   180  		if i > 0 {
   181  			fmt.Fprint(&buf, " contains ")
   182  		}
   183  		// The human-readable path is in reverse order, outermost to innermost.
   184  		fmt.Fprint(&buf, path[n-i-1].String())
   185  	}
   186  	return buf.String()
   187  }
   188  
   189  func lockPathRhs(f *File, x ast.Expr) typePath {
   190  	if _, ok := x.(*ast.CompositeLit); ok {
   191  		return nil
   192  	}
   193  	if _, ok := x.(*ast.CallExpr); ok {
   194  		// A call may return a zero value.
   195  		return nil
   196  	}
   197  	if star, ok := x.(*ast.StarExpr); ok {
   198  		if _, ok := star.X.(*ast.CallExpr); ok {
   199  			// A call may return a pointer to a zero value.
   200  			return nil
   201  		}
   202  	}
   203  	return lockPath(f.pkg.typesPkg, f.pkg.types[x].Type)
   204  }
   205  
   206  // lockPath returns a typePath describing the location of a lock value
   207  // contained in typ. If there is no contained lock, it returns nil.
   208  func lockPath(tpkg *types.Package, typ types.Type) typePath {
   209  	if typ == nil {
   210  		return nil
   211  	}
   212  
   213  	// We're only interested in the case in which the underlying
   214  	// type is a struct. (Interfaces and pointers are safe to copy.)
   215  	styp, ok := typ.Underlying().(*types.Struct)
   216  	if !ok {
   217  		return nil
   218  	}
   219  
   220  	// We're looking for cases in which a reference to this type
   221  	// can be locked, but a value cannot. This differentiates
   222  	// embedded interfaces from embedded values.
   223  	if plock := types.NewMethodSet(types.NewPointer(typ)).Lookup(tpkg, "Lock"); plock != nil {
   224  		if lock := types.NewMethodSet(typ).Lookup(tpkg, "Lock"); lock == nil {
   225  			return []types.Type{typ}
   226  		}
   227  	}
   228  
   229  	nfields := styp.NumFields()
   230  	for i := 0; i < nfields; i++ {
   231  		ftyp := styp.Field(i).Type()
   232  		subpath := lockPath(tpkg, ftyp)
   233  		if subpath != nil {
   234  			return append(subpath, typ)
   235  		}
   236  	}
   237  
   238  	return nil
   239  }