From 9bced47706f605c3d1b75d694dd3c9fb771ce7ba Mon Sep 17 00:00:00 2001 From: =?utf8?q?Daniel=20Mart=C3=AD?= Date: Wed, 10 May 2017 13:53:39 +0200 Subject: [PATCH] reflect: don't panic in ArrayOf if elem size is 0 MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit We do a division by the elem type size to check if the array size would be too large for the virtual address space. This is a silly check if the size is 0, but the problem is that it means a division by zero and a panic. Since arrays of empty structs are valid in a regular program, make them also work in reflect. Use a separate, explicit test with struct{}{} to make sure the test for a zero-sized type is not confused with the rest. Fixes #20313. Change-Id: I47b8b87e6541631280b79227bdea6a0f6035c9e0 Reviewed-on: https://go-review.googlesource.com/43131 Run-TryBot: Daniel Martí Reviewed-by: Brad Fitzpatrick --- src/reflect/all_test.go | 1 + src/reflect/type.go | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/reflect/all_test.go b/src/reflect/all_test.go index b3b82f8b2a..4953e4ff83 100644 --- a/src/reflect/all_test.go +++ b/src/reflect/all_test.go @@ -6016,6 +6016,7 @@ func TestTypeStrings(t *testing.T) { {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"}, {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"}, {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"}, + {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"}, } for i, test := range stringTests { diff --git a/src/reflect/type.go b/src/reflect/type.go index 637392f4e7..1849c4b8d4 100644 --- a/src/reflect/type.go +++ b/src/reflect/type.go @@ -2814,9 +2814,11 @@ func ArrayOf(count int, elem Type) Type { array.hash = fnv1(array.hash, ']') array.elem = typ array.ptrToThis = 0 - max := ^uintptr(0) / typ.size - if uintptr(count) > max { - panic("reflect.ArrayOf: array size would exceed virtual address space") + if typ.size > 0 { + max := ^uintptr(0) / typ.size + if uintptr(count) > max { + panic("reflect.ArrayOf: array size would exceed virtual address space") + } } array.size = typ.size * uintptr(count) if count > 0 && typ.ptrdata != 0 { -- 2.48.1