diff options
author | Keith Randall <khr@golang.org> | 2016-02-04 13:38:38 -0800 |
---|---|---|
committer | Keith Randall <khr@golang.org> | 2016-02-04 23:57:10 +0000 |
commit | 4d02b1241738a5bd06201455a4f74a013f6c9437 (patch) | |
tree | 1aa3d0d40a1d62ae81b788d40f88926324e81686 | |
parent | 39304eb69d7f6117e60630452c0e037dbb555f5e (diff) | |
download | go-4d02b1241738a5bd06201455a4f74a013f6c9437.tar.gz go-4d02b1241738a5bd06201455a4f74a013f6c9437.zip |
runtime: don't expose stack buffer in stringto{byte,rune}slice
When using a stack-allocated buffer for the result, don't
expose the uninitialized portion of it by restricting its
capacity to its length.
The other option is to zero the portion between len and cap.
That seems like more work, but might be worth it if the caller
then appends some stuff to the result. But this close to 1.6,
I'm inclined to do the simplest fix possible.
Fixes #14232
Change-Id: I21c50d3cda02fd2df4d60ba5e2cfe2efe272f333
Reviewed-on: https://go-review.googlesource.com/19231
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
-rw-r--r-- | src/runtime/string.go | 4 | ||||
-rw-r--r-- | src/runtime/string_test.go | 15 |
2 files changed, 17 insertions, 2 deletions
diff --git a/src/runtime/string.go b/src/runtime/string.go index f8ccd41b1d..dd04bda04b 100644 --- a/src/runtime/string.go +++ b/src/runtime/string.go @@ -139,7 +139,7 @@ func slicebytetostringtmp(b []byte) string { func stringtoslicebyte(buf *tmpBuf, s string) []byte { var b []byte if buf != nil && len(s) <= len(buf) { - b = buf[:len(s)] + b = buf[:len(s):len(s)] } else { b = rawbyteslice(len(s)) } @@ -171,7 +171,7 @@ func stringtoslicerune(buf *[tmpStringBufSize]rune, s string) []rune { } var a []rune if buf != nil && n <= len(buf) { - a = buf[:n] + a = buf[:n:n] } else { a = rawruneslice(n) } diff --git a/src/runtime/string_test.go b/src/runtime/string_test.go index 318a5532e5..150a25520a 100644 --- a/src/runtime/string_test.go +++ b/src/runtime/string_test.go @@ -222,3 +222,18 @@ func TestRangeStringCast(t *testing.T) { t.Fatalf("want 0 allocs, got %v", n) } } + +func TestString2Slice(t *testing.T) { + // Make sure we don't return slices that expose + // an unzeroed section of stack-allocated temp buf + // between len and cap. See issue 14232. + s := "foož" + b := ([]byte)(s) + if cap(b) != 5 { + t.Errorf("want cap of 5, got %d", cap(b)) + } + r := ([]rune)(s) + if cap(r) != 4 { + t.Errorf("want cap of 4, got %d", cap(r)) + } +} |