You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I wrote unsupported but I meant unsafe as really unsafe leading the compiler to potentially miscompile or the runtime to garbage collect leading to "use after free bugs" and not just as in unsafe in that one can alter the contents of a string.
See https://golang.org/pkg/unsafe/#Pointer (6):
"In general, reflect.SliceHeader and reflect.StringHeader should be used only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual slices or strings, never as plain structs."
Example from the codebase:
func StringFromByteSlice(b []byte) string {
h := &reflect.StringHeader{
Data: uintptr(unsafe.Pointer(&b[0])),
Len: len(b),
}
return *(*string)(unsafe.Pointer(h)) // At this point b might have been garbage collected already because h might be the only reference to b contents
}
to avoid this we first need to create a real string and then interpret it as reflect header:
func StringFromByteSlice(b []byte) string {
p := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&b)).Data)
var s string
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(p)
hdr.Len = len(b)
return s
}
I wrote unsupported but I meant unsafe as really unsafe leading the compiler to potentially miscompile or the runtime to garbage collect leading to "use after free bugs" and not just as in unsafe in that one can alter the contents of a string.
See https://golang.org/pkg/unsafe/#Pointer (6):
"In general, reflect.SliceHeader and reflect.StringHeader should be used only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual slices or strings, never as plain structs."
Example from the codebase:
to avoid this we first need to create a real string and then interpret it as reflect header:
@alecthomas
The text was updated successfully, but these errors were encountered: