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

unsupported use of reflect headers could lead to memory corruption #4

Open
martisch opened this issue Jun 10, 2020 · 0 comments
Open

Comments

@martisch
Copy link

martisch commented Jun 10, 2020

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

@martisch martisch changed the title unsupported use of reflect headers unsupported use of reflect headers could lead to memory corruption Jun 10, 2020
akalin added a commit to akalin/gopar that referenced this issue Feb 21, 2021
akalin added a commit to akalin/gopar that referenced this issue Feb 21, 2021
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

No branches or pull requests

1 participant