Skip to content

Commit 9c258c6

Browse files
dspeziaianlancetaylor
authored andcommitted
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 <[email protected]>
1 parent 4a6326e commit 9c258c6

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

misc/cgo/errors/issue11097a.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2015 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 main
6+
7+
/*
8+
//enum test { foo, bar };
9+
*/
10+
import "C"
11+
12+
func main() {
13+
var a = C.enum_test(1) // ERROR HERE
14+
_ = a
15+
}

misc/cgo/errors/issue11097b.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2015 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 main
6+
7+
/*
8+
//enum test { foo, bar };
9+
*/
10+
import "C"
11+
12+
func main() {
13+
p := new(C.enum_test) // ERROR HERE
14+
_ = p
15+
}

misc/cgo/errors/test.bash

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ check err2.go
3131
check err3.go
3232
check issue7757.go
3333
check issue8442.go
34+
check issue11097a.go
35+
check issue11097b.go
3436

3537
rm -rf errs _obj
3638
exit 0

src/cmd/cgo/gcc.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,10 @@ func (p *Package) rewriteRef(f *File) {
607607
if r.Name.Kind != "func" {
608608
if r.Name.Kind == "type" {
609609
r.Context = "type"
610+
if r.Name.Type == nil {
611+
error_(r.Pos(), "invalid conversion to C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
612+
break
613+
}
610614
expr = r.Name.Type.Go
611615
break
612616
}
@@ -658,6 +662,10 @@ func (p *Package) rewriteRef(f *File) {
658662
}
659663
} else if r.Name.Kind == "type" {
660664
// Okay - might be new(T)
665+
if r.Name.Type == nil {
666+
error_(r.Pos(), "expression C.%s: undefined C type '%s'", fixGo(r.Name.Go), r.Name.C)
667+
break
668+
}
661669
expr = r.Name.Type.Go
662670
} else if r.Name.Kind == "var" {
663671
expr = &ast.StarExpr{Star: (*r.Expr).Pos(), X: expr}

0 commit comments

Comments
 (0)