avoid panic on funcs that almost look like tests (#235)

The added test case used to crash garble:

	panic: runtime error: invalid memory address or nil pointer dereference [recovered]
		panic: runtime error: invalid memory address or nil pointer dereference
	[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x8fe71b]

	goroutine 1 [running]:
	golang.org/x/tools/go/ast/astutil.Apply.func1(0xc0001e8880, 0xc000221570)
		/go/pkg/mod/golang.org/x/tools@v0.0.0-20210115202250-e0d201561e39/go/ast/astutil/rewrite.go:47 +0x97
	panic(0x975bc0, 0xd6c610)
		/sdk/go1.15.8/src/runtime/panic.go:969 +0x1b9
	go/types.(*Named).Obj(...)
		/sdk/go1.15.8/src/go/types/type.go:473
	mvdan.cc/garble.isTestSignature(0xc0001e7080, 0xa02e84)
		/src/garble/main.go:1170 +0x7b
	mvdan.cc/garble.(*transformer).transformGo.func2(0xc000122df0, 0xaac301)
		/src/garble/main.go:1028 +0xff1

We were assuming that the first parameter was a named type, but that
might not be the case.

This crash was found out in the wild, from which a minimal repro was
written. We add two variants of it to the test data, just in case.
pull/236/head
Daniel Martí 3 years ago committed by GitHub
parent e64fccd367
commit 2fa5697189
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1159,13 +1159,17 @@ func namedType(t types.Type) *types.Named {
// isTestSignature returns true if the signature matches "func _(*testing.T)".
func isTestSignature(sign *types.Signature) bool {
if sign.Recv() != nil {
return false
return false // test funcs don't have receivers
}
params := sign.Params()
if params.Len() != 1 {
return false
return false // too many parameters for a test func
}
named := namedType(params.At(0).Type())
if named == nil {
return false // the only parameter isn't named, like "string"
}
obj := namedType(params.At(0).Type()).Obj()
obj := named.Obj()
return obj != nil && obj.Pkg().Path() == "testing" && obj.Name() == "T"
}

@ -149,6 +149,13 @@ func Test() {
}
func noop(...interface{}) {}
// Funcs that almost look like test funcs used to make garble panic.
func TestFoo(s string) {}
func TestBar(*struct{}) {}
-- main.stderr --
nil case
{"Foo":3}

Loading…
Cancel
Save