]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: panic on New of go:notinheap type
authorIan Lance Taylor <iant@golang.org>
Fri, 9 Apr 2021 18:20:35 +0000 (11:20 -0700)
committerIan Lance Taylor <iant@golang.org>
Fri, 9 Apr 2021 23:54:31 +0000 (23:54 +0000)
For #42076
Fixes #45451

Change-Id: I69646226d3480d5403205412ddd13c0cfc2c8a53
Reviewed-on: https://go-review.googlesource.com/c/go/+/308970
Trust: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
misc/cgo/test/cgo_test.go
misc/cgo/test/test.go
src/reflect/value.go

index 837307263a139bcb4fb8f024db480b4a7001c159..143f23f0e0cc36983ad44595469b5b7f55ff0d56 100644 (file)
@@ -59,6 +59,7 @@ func Test28896(t *testing.T)                 { test28896(t) }
 func Test30065(t *testing.T)                 { test30065(t) }
 func Test32579(t *testing.T)                 { test32579(t) }
 func Test31891(t *testing.T)                 { test31891(t) }
+func Test45451(t *testing.T)                 { test45451(t) }
 func TestAlign(t *testing.T)                 { testAlign(t) }
 func TestAtol(t *testing.T)                  { testAtol(t) }
 func TestBlocking(t *testing.T)              { testBlocking(t) }
index 76afa524c351d38f84e105ced0bb3367ad68045b..3b8f548b13dd206fedd0653d8472c5b8d9958d12 100644 (file)
@@ -912,6 +912,9 @@ void cFunc37033(uintptr_t handle) { GoFunc37033(handle); }
 enum Enum40494 { X_40494 };
 union Union40494 { int x; };
 void issue40494(enum Enum40494 e, union Union40494* up) {}
+
+// Issue 45451, bad handling of go:notinheap types.
+typedef struct issue45451Undefined issue45451;
 */
 import "C"
 
@@ -2266,3 +2269,19 @@ var issue39877 *C.void = nil
 func Issue40494() {
        C.issue40494(C.enum_Enum40494(C.X_40494), (*C.union_Union40494)(nil))
 }
+
+// Issue 45451.
+func test45451(t *testing.T) {
+       var u *C.issue45451
+       typ := reflect.ValueOf(u).Type().Elem()
+
+       // The type is undefined in C so allocating it should panic.
+       defer func() {
+               if r := recover(); r == nil {
+                       t.Error("expected panic")
+               }
+       }()
+
+       _ = reflect.New(typ)
+       t.Errorf("reflect.New(%v) should have panicked", typ)
+}
index 9670d4656b187eafd2463ac7a97525149e5316f3..7890c125d81b0f5e75d3b9b1ea6b764fa8dc6189 100644 (file)
@@ -2702,9 +2702,14 @@ func New(typ Type) Value {
                panic("reflect: New(nil)")
        }
        t := typ.(*rtype)
+       pt := t.ptrTo()
+       if ifaceIndir(pt) {
+               // This is a pointer to a go:notinheap type.
+               panic("reflect: New of type that may not be allocated in heap (possibly undefined cgo C type)")
+       }
        ptr := unsafe_New(t)
        fl := flag(Ptr)
-       return Value{t.ptrTo(), ptr, fl}
+       return Value{pt, ptr, fl}
 }
 
 // NewAt returns a Value representing a pointer to a value of the