alecthomas / alecthomas/unsafeslice
unsupported use of reflect headers could lead to memory corruption
- 主要語言
- Go
- 星號
- 37
- 分支
- 6
- PR 合併指標
- 30 天內沒有已合併 PR
描述
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
}
```
@alecthomas
貢獻指南
這個儲存庫沒有索引到貢獻指南
評估
這個 Issue 還沒有評估資料。