Skip to content

Commit

Permalink
go/analysis/passes/copylock: find locks via type parameters
Browse files Browse the repository at this point in the history
Add support for finding incorrect usage of locks via type parameters. It
would probably be fine not to do this, since using locks explicitly via
type parameters should be exceedingly rare. However, it was
straightforward to add, and is consistent with other analyzers.

Updates golang/go#48704

Change-Id: I329a2fa9f11c6bbb491d49afde7fabce8299cbdf
Reviewed-on: https://go-review.googlesource.com/c/tools/+/360234
Trust: Robert Findley <rfindley@google.com>
Run-TryBot: Robert Findley <rfindley@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Tim King <taking@google.com>
  • Loading branch information
findleyr committed Nov 2, 2021
1 parent ebc40b3 commit 058ed05
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 6 deletions.
40 changes: 35 additions & 5 deletions go/analysis/passes/copylock/copylock.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/analysis/passes/internal/analysisutil"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/internal/typeparams"
)

const Doc = `check for locks erroneously passed by value
Expand Down Expand Up @@ -204,7 +205,7 @@ func checkCopyLocksRangeVar(pass *analysis.Pass, rtok token.Token, e ast.Expr) {
}
}

type typePath []types.Type
type typePath []string

// String pretty-prints a typePath.
func (path typePath) String() string {
Expand All @@ -215,7 +216,7 @@ func (path typePath) String() string {
fmt.Fprint(&buf, " contains ")
}
// The human-readable path is in reverse order, outermost to innermost.
fmt.Fprint(&buf, path[n-i-1].String())
fmt.Fprint(&buf, path[n-i-1])
}
return buf.String()
}
Expand Down Expand Up @@ -244,6 +245,35 @@ func lockPath(tpkg *types.Package, typ types.Type) typePath {
return nil
}

if tpar, ok := typ.(*typeparams.TypeParam); ok {
terms, err := typeparams.StructuralTerms(tpar)
if err != nil {
return nil // invalid type
}
for _, term := range terms {
subpath := lockPath(tpkg, term.Type())
if len(subpath) > 0 {
if term.Tilde() {
// Prepend a tilde to our lock path entry to clarify the resulting
// diagnostic message. Consider the following example:
//
// func _[Mutex interface{ ~sync.Mutex; M() }](m Mutex) {}
//
// Here the naive error message will be something like "passes lock
// by value: Mutex contains sync.Mutex". This is misleading because
// the local type parameter doesn't actually contain sync.Mutex,
// which lacks the M method.
//
// With tilde, it is clearer that the containment is via an
// approximation element.
subpath[len(subpath)-1] = "~" + subpath[len(subpath)-1]
}
return append(subpath, typ.String())
}
}
return nil
}

for {
atyp, ok := typ.Underlying().(*types.Array)
if !ok {
Expand All @@ -263,7 +293,7 @@ func lockPath(tpkg *types.Package, typ types.Type) typePath {
// is a sync.Locker, but a value is not. This differentiates
// embedded interfaces from embedded values.
if types.Implements(types.NewPointer(typ), lockerType) && !types.Implements(typ, lockerType) {
return []types.Type{typ}
return []string{typ.String()}
}

// In go1.10, sync.noCopy did not implement Locker.
Expand All @@ -272,15 +302,15 @@ func lockPath(tpkg *types.Package, typ types.Type) typePath {
if named, ok := typ.(*types.Named); ok &&
named.Obj().Name() == "noCopy" &&
named.Obj().Pkg().Path() == "sync" {
return []types.Type{typ}
return []string{typ.String()}
}

nfields := styp.NumFields()
for i := 0; i < nfields; i++ {
ftyp := styp.Field(i).Type()
subpath := lockPath(tpkg, ftyp)
if subpath != nil {
return append(subpath, typ)
return append(subpath, typ.String())
}
}

Expand Down
7 changes: 6 additions & 1 deletion go/analysis/passes/copylock/copylock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import (

"golang.org/x/tools/go/analysis/analysistest"
"golang.org/x/tools/go/analysis/passes/copylock"
"golang.org/x/tools/internal/typeparams"
)

func Test(t *testing.T) {
testdata := analysistest.TestData()
analysistest.Run(t, testdata, copylock.Analyzer, "a")
pkgs := []string{"a"}
if typeparams.Enabled {
pkgs = append(pkgs, "typeparams")
}
analysistest.Run(t, testdata, copylock.Analyzer, pkgs...)
}
45 changes: 45 additions & 0 deletions go/analysis/passes/copylock/testdata/src/typeparams/typeparams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package typeparams

import "sync"

func OkFunc1[Struct ~*struct{ mu sync.Mutex }](s Struct) {
}

func BadFunc1[Struct ~struct{ mu sync.Mutex }](s Struct) { // want `passes lock by value: .*Struct contains ~struct{mu sync.Mutex}`
}

func OkFunc2[MutexPtr *sync.Mutex](m MutexPtr) {
var x *MutexPtr
p := x
var y MutexPtr
p = &y
*p = *x

var mus []MutexPtr

for _, _ = range mus {
}
}

func BadFunc2[Mutex sync.Mutex](m Mutex) { // want `passes lock by value: .*Mutex contains sync.Mutex`
var x *Mutex
p := x
var y Mutex
p = &y
*p = *x // want `assignment copies lock value to \*p: .*Mutex contains sync.Mutex`

var mus []Mutex

for _, _ = range mus {
}
}

func ApproximationError[Mutex interface {
~sync.Mutex
M()
}](m Mutex) { // want `passes lock by value: .*Mutex contains ~sync.Mutex`
}

0 comments on commit 058ed05

Please sign in to comment.