Skip to content

Commit b41185a

Browse files
committed
rlp: fix nil pointer decoding
The generic pointer decoder did not advance the input position for empty values. This can lead to strange issues and even infinite loops.
1 parent 28ddc16 commit b41185a

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎rlp/decode.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,12 @@ func makePtrDecoder(typ reflect.Type) (decoder, error) {
367367
dec := func(s *Stream, val reflect.Value) (err error) {
368368
_, size, err := s.Kind()
369369
if err != nil || size == 0 && s.byteval == 0 {
370-
val.Set(reflect.Zero(typ)) // set to nil
370+
// rearm s.Kind. This is important because the input
371+
// position must advance to the next value even though
372+
// we don't read anything.
373+
s.kind = -1
374+
// set the pointer to nil.
375+
val.Set(reflect.Zero(typ))
371376
return err
372377
}
373378
newval := val

‎rlp/decode_test.go‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func TestStreamKind(t *testing.T) {
3939
s := NewStream(bytes.NewReader(unhex(test.input)))
4040
kind, len, err := s.Kind()
4141
if err != nil {
42-
t.Errorf("test %d: Type returned error: %v", i, err)
42+
t.Errorf("test %d: Kind returned error: %v", i, err)
4343
continue
4444
}
4545
if kind != test.wantKind {
@@ -93,6 +93,23 @@ func TestStreamErrors(t *testing.T) {
9393
{"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, EOL},
9494
{"00", calls{"ListEnd"}, errNotInList},
9595
{"C40102", calls{"List", "Uint", "ListEnd"}, errNotAtEOL},
96+
97+
// This test verifies that the input position is advanced
98+
// correctly when calling Bytes for empty strings. Kind can be called
99+
// any number of times in between and doesn't advance.
100+
{"C3808080", calls{
101+
"List", // enter the list
102+
"Bytes", // past first element
103+
104+
"Kind", "Kind", "Kind", // this shouldn't advance
105+
106+
"Bytes", // past second element
107+
108+
"Kind", "Kind", // can't hurt to try
109+
110+
"Bytes", // past final element
111+
"Bytes", // this one should fail
112+
}, EOL},
96113
}
97114

98115
testfor:
@@ -314,6 +331,9 @@ var decodeTests = []decodeTest{
314331
{input: "C109", ptr: new(*[]uint), value: &[]uint{9}},
315332
{input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}},
316333

334+
// check that input position is advanced also empty values.
335+
{input: "C3808005", ptr: new([]*uint), value: []*uint{nil, nil, uintp(5)}},
336+
317337
// pointer should be reset to nil
318338
{input: "05", ptr: sharedPtr, value: uintp(5)},
319339
{input: "80", ptr: sharedPtr, value: (*uint)(nil)},

0 commit comments

Comments
 (0)