fix possible memory confusion in unsafe slice cast

This commit is contained in:
Johannes Lauinger 2020-05-31 21:32:17 +02:00 committed by GitHub
parent 3d78558cf2
commit 813d953eeb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,6 +4,7 @@ package util
import ( import (
"reflect" "reflect"
"runtime"
"unsafe" "unsafe"
) )
@ -14,7 +15,12 @@ func BytesToReadOnlyString(b []byte) string {
// StringToReadOnlyBytes returns bytes converted from given string. // StringToReadOnlyBytes returns bytes converted from given string.
func StringToReadOnlyBytes(s string) []byte { func StringToReadOnlyBytes(s string) []byte {
b := make([]byte, 0)
sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len} bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
return *(*[]byte)(unsafe.Pointer(&bh)) bh.Data = sh.Data
bh.Cap = sh.Len
bh.Len = sh.Len
runtime.KeepAlive(s)
return b
} }