From d1a986698c820415b2e0be12141091a3cbf6fde3 Mon Sep 17 00:00:00 2001 From: Johan Abildskov Date: Tue, 21 Mar 2023 19:59:28 +0000 Subject: [PATCH] encoding/gob: Extend partially allocated string slices There is a bug in the current implementation where very large `[]string` will not be extended, causing an index out of bounds panic. Fixes #59172 --- src/encoding/gob/codec_test.go | 14 ++++++++++++++ src/encoding/gob/dec_helpers.go | 3 +++ 2 files changed, 17 insertions(+) diff --git a/src/encoding/gob/codec_test.go b/src/encoding/gob/codec_test.go index 54c356c4644722..28cd6088af16ff 100644 --- a/src/encoding/gob/codec_test.go +++ b/src/encoding/gob/codec_test.go @@ -1544,6 +1544,10 @@ type LargeSliceStruct struct { S []StringPair } +type LargeSliceString struct { + S []string +} + func testEncodeDecode(t *testing.T, in, out any) { t.Helper() var b bytes.Buffer @@ -1592,4 +1596,14 @@ func TestLargeSlice(t *testing.T) { rt := &LargeSliceStruct{} testEncodeDecode(t, st, rt) }) + t.Run("string", func(t *testing.T) { + t.Parallel() + s := make([]string, 1<<21) + for i := range s { + s[i] = string(rune(i)) + } + st := &LargeSliceString{S: s} + rt := &LargeSliceString{} + testEncodeDecode(t, st, rt) + }) } diff --git a/src/encoding/gob/dec_helpers.go b/src/encoding/gob/dec_helpers.go index a09ac8fc1afd93..098ba7254a21ed 100644 --- a/src/encoding/gob/dec_helpers.go +++ b/src/encoding/gob/dec_helpers.go @@ -358,6 +358,9 @@ func decStringSlice(state *decoderState, v reflect.Value, length int, ovfl error if state.b.Len() == 0 { errorf("decoding string array or slice: length exceeds input size (%d elements)", length) } + if i >= len(slice) { + growSlice(v, &slice, length) + } u := state.decodeUint() n := int(u) if n < 0 || uint64(n) != u || n > state.b.Len() {