Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix possible misuse of reflect.SliceHeader vet error #465

Closed
robbertvanginkel opened this issue Feb 16, 2021 · 0 comments · Fixed by #466
Closed

Fix possible misuse of reflect.SliceHeader vet error #465

robbertvanginkel opened this issue Feb 16, 2021 · 0 comments · Fixed by #466

Comments

@robbertvanginkel
Copy link
Contributor

robbertvanginkel commented Feb 16, 2021

A new check was added to vet in go1.16 (golang/go#40701), lint now fails with:

wire/unsafe.go:38:35: possible misuse of reflect.SliceHeader

// unsafeStringToBytes converts a string into a byte slice without allocating
// new memory for it with the assumption that the resulting byte slice will not
// be mutated.
func unsafeStringToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
sliceHeader := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&sliceHeader))
}

Currently failing #464. Should fix and rebase.

robbertvanginkel added a commit that referenced this issue Feb 17, 2021
Fixes #465.

According to https://golang.org/pkg/unsafe/#Pointer (6), one of the only safe ways to use pointers:
> Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer.
...
> 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. A program should not declare or allocate variables of these struct types.

This rewrites the unsafe to only modify to not allocate a `reflect.SliceHeader ` manually making the vet check happy.
r-hang pushed a commit that referenced this issue Feb 18, 2021
Fixes #465.

According to https://golang.org/pkg/unsafe/#Pointer (6), one of the only safe ways to use pointers:
> Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer.
...
> 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. A program should not declare or allocate variables of these struct types.

This rewrites the unsafe to only modify to not allocate a `reflect.SliceHeader ` manually making the vet check happy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant