cmd/cgo: fix panic on references to non-existing C types

cgo panics in Package.rewriteRef for:

var a = C.enum_test(1)
or
p := new(C.enum_test)

when the corresponding enum type is not defined.

Check nil values for Type fields and issue a proper
error instead.

Fixes #11097
Updates #12160

Change-Id: I5821d29097ef0a36076ec5273125b09846c7d832
Reviewed-on: https://go-review.googlesource.com/15264
Reviewed-by: Ian Lance Taylor <iant@golang.org>
This commit is contained in:
Didier Spezia 2015-10-03 15:50:45 +00:00 committed by Ian Lance Taylor
parent 4a6326e7b5
commit 9c258c6aa6
4 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,15 @@
// Copyright 2015 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 main
/*
//enum test { foo, bar };
*/
import "C"
func main() {
var a = C.enum_test(1) // ERROR HERE
_ = a
}

View File

@ -0,0 +1,15 @@
// Copyright 2015 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 main
/*
//enum test { foo, bar };
*/
import "C"
func main() {
p := new(C.enum_test) // ERROR HERE
_ = p
}

View File

@ -31,6 +31,8 @@ check err2.go
check err3.go
check issue7757.go
check issue8442.go
check issue11097a.go
check issue11097b.go
rm -rf errs _obj
exit 0

View File

@ -607,6 +607,10 @@ func (p *Package) rewriteRef(f *File) {
if r.Name.Kind != "func" {
if r.Name.Kind == "type" {
r.Context = "type"
if r.Name.Type == nil {
error_(r.Pos(), "invalid conversion to C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
break
}
expr = r.Name.Type.Go
break
}
@ -658,6 +662,10 @@ func (p *Package) rewriteRef(f *File) {
}
} else if r.Name.Kind == "type" {
// Okay - might be new(T)
if r.Name.Type == nil {
error_(r.Pos(), "expression C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
break
}
expr = r.Name.Type.Go
} else if r.Name.Kind == "var" {
expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}