Skip to content

Commit 554d2c4

Browse files
reflect: panic on New of go:notinheap type
For #42076 Fixes #45451 Change-Id: I69646226d3480d5403205412ddd13c0cfc2c8a53 Reviewed-on: https://go-review.googlesource.com/c/go/+/308970 Trust: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Keith Randall <[email protected]>
1 parent 5305bde commit 554d2c4

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

misc/cgo/test/cgo_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ func Test28896(t *testing.T) { test28896(t) }
5959
func Test30065(t *testing.T) { test30065(t) }
6060
func Test32579(t *testing.T) { test32579(t) }
6161
func Test31891(t *testing.T) { test31891(t) }
62+
func Test45451(t *testing.T) { test45451(t) }
6263
func TestAlign(t *testing.T) { testAlign(t) }
6364
func TestAtol(t *testing.T) { testAtol(t) }
6465
func TestBlocking(t *testing.T) { testBlocking(t) }

misc/cgo/test/test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,9 @@ void cFunc37033(uintptr_t handle) { GoFunc37033(handle); }
912912
enum Enum40494 { X_40494 };
913913
union Union40494 { int x; };
914914
void issue40494(enum Enum40494 e, union Union40494* up) {}
915+
916+
// Issue 45451, bad handling of go:notinheap types.
917+
typedef struct issue45451Undefined issue45451;
915918
*/
916919
import "C"
917920

@@ -2266,3 +2269,19 @@ var issue39877 *C.void = nil
22662269
func Issue40494() {
22672270
C.issue40494(C.enum_Enum40494(C.X_40494), (*C.union_Union40494)(nil))
22682271
}
2272+
2273+
// Issue 45451.
2274+
func test45451(t *testing.T) {
2275+
var u *C.issue45451
2276+
typ := reflect.ValueOf(u).Type().Elem()
2277+
2278+
// The type is undefined in C so allocating it should panic.
2279+
defer func() {
2280+
if r := recover(); r == nil {
2281+
t.Error("expected panic")
2282+
}
2283+
}()
2284+
2285+
_ = reflect.New(typ)
2286+
t.Errorf("reflect.New(%v) should have panicked", typ)
2287+
}

src/reflect/value.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2702,9 +2702,14 @@ func New(typ Type) Value {
27022702
panic("reflect: New(nil)")
27032703
}
27042704
t := typ.(*rtype)
2705+
pt := t.ptrTo()
2706+
if ifaceIndir(pt) {
2707+
// This is a pointer to a go:notinheap type.
2708+
panic("reflect: New of type that may not be allocated in heap (possibly undefined cgo C type)")
2709+
}
27052710
ptr := unsafe_New(t)
27062711
fl := flag(Ptr)
2707-
return Value{t.ptrTo(), ptr, fl}
2712+
return Value{pt, ptr, fl}
27082713
}
27092714

27102715
// NewAt returns a Value representing a pointer to a value of the

0 commit comments

Comments
 (0)