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

cmd/cgo: pointer check is too aggressive with bytes.Buffer #22788

Closed
bcmills opened this issue Nov 17, 2017 · 2 comments
Closed

cmd/cgo: pointer check is too aggressive with bytes.Buffer #22788

bcmills opened this issue Nov 17, 2017 · 2 comments

Comments

@bcmills
Copy link
Contributor

bcmills commented Nov 17, 2017

According to the current cgo pointer-passing rules:

When passing a pointer to an element in an array or slice, the Go memory in question is the entire array or the entire backing array of the slice.

However, when we pass such a pointer as type unsafe.Pointer (rather than a concrete pointer type) and the slice is backed by some field of a larger struct type (such as a bytes.Buffer) cgo ends up checking the entire struct instead of just the backing array, producing false positives.

(Passing a slice as unsafe.Pointer can occasionally occur naturally when using SWIG, for example when wrapping a []byte to a std::string_view.)

We should either document the type-based caveat or weaken the check to avoid reporting this as an error.


src/cgobuf/main.go:

package main

/*
#include <stdio.h>

static void print(const void* s) {
	printf("%s\n", (const char*)s);
}
*/
import "C"

import (
	"bytes"
	"unsafe"
)

func main() {
	var buf bytes.Buffer
	buf.WriteString("Hello, World!")
	buf.WriteByte(0)

	C.print(unsafe.Pointer(&buf.Bytes()[0]))
}
~$ go version
go version devel +3a395e2283 Fri Nov 17 19:00:41 2017 +0000 linux/amd64
~$ go run src/cgobuf/main.go
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
main.main.func1(0xc42009e020)
        /home/bcmills/src/cgobuf/main.go:22 +0x48
main.main()
        /home/bcmills/src/cgobuf/main.go:22 +0xa6
exit status 2

(CC @ianlancetaylor )

@ianlancetaylor
Copy link
Contributor

Dup of #14210?

@bcmills
Copy link
Contributor Author

bcmills commented Nov 17, 2017

Yep, looks like it.

@bcmills bcmills closed this as completed Nov 17, 2017
@golang golang locked and limited conversation to collaborators Nov 17, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants