Skip to content

Commit c444ec3

Browse files
vitaminniybradfitz
authored andcommitted
encoding/binary: make Read return an error when data is not a pointer
Make binary.Read return an error when passed `data` argument is not a pointer to a fixed-size value or a slice of fixed-size values. Fixes #32927 Change-Id: I04f48be55fe9b0cc66c983d152407d0e42cbcd95 Reviewed-on: https://go-review.googlesource.com/c/go/+/184957 Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent a84ac18 commit c444ec3

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/encoding/binary/binary.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,8 +219,12 @@ func Read(r io.Reader, order ByteOrder, data interface{}) error {
219219
for i := range data {
220220
data[i] = order.Uint64(bs[8*i:])
221221
}
222+
default:
223+
n = 0 // fast path doesn't apply
224+
}
225+
if n != 0 {
226+
return nil
222227
}
223-
return nil
224228
}
225229

226230
// Fallback to reflect-based decoding.

src/encoding/binary/binary_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package binary
66

77
import (
88
"bytes"
9+
"fmt"
910
"io"
1011
"io/ioutil"
1112
"math"
@@ -451,6 +452,35 @@ func TestEarlyBoundsChecks(t *testing.T) {
451452
}
452453
}
453454

455+
func TestReadInvalidDestination(t *testing.T) {
456+
testReadInvalidDestination(t, BigEndian)
457+
testReadInvalidDestination(t, LittleEndian)
458+
}
459+
460+
func testReadInvalidDestination(t *testing.T, order ByteOrder) {
461+
destinations := []interface{}{
462+
int8(0),
463+
int16(0),
464+
int32(0),
465+
int64(0),
466+
467+
uint8(0),
468+
uint16(0),
469+
uint32(0),
470+
uint64(0),
471+
472+
bool(false),
473+
}
474+
475+
for _, dst := range destinations {
476+
err := Read(bytes.NewReader([]byte{1, 2, 3, 4, 5, 6, 7, 8}), order, dst)
477+
want := fmt.Sprintf("binary.Read: invalid type %T", dst)
478+
if err == nil || err.Error() != want {
479+
t.Fatalf("for type %T: got %q; want %q", dst, err, want)
480+
}
481+
}
482+
}
483+
454484
type byteSliceReader struct {
455485
remain []byte
456486
}

0 commit comments

Comments
 (0)