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: []byte argument has Go pointer to Go pointer #28606

Open
crawshaw opened this Issue Nov 6, 2018 · 1 comment

Comments

Projects
None yet
2 participants
@crawshaw
Contributor

crawshaw commented Nov 6, 2018

With Go 1.11 and HEAD: go version devel +a2a3dd00c9 Thu Sep 13 09:52:57 2018 +0000 darwin/amd64, the following program:

package main

// void f(void* ptr) {}
import "C"

import (
	"compress/gzip"
	"unsafe"
)

type cgoWriter struct{}

func (cgoWriter) Write(p []byte) (int, error) {
	ptr := unsafe.Pointer(&p[0])
	C.f(ptr)
	return 0, nil
}

func main() {
	w := cgoWriter{}
	gzw := gzip.NewWriter(w)
	gzw.Close() // calls cgoWriter.Write
}

Panics:

panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
main.cgoWriter.Write.func1(0xc00015e020)
	/Users/crawshaw/junk.go:15 +0x48
main.cgoWriter.Write(0xc00015e020, 0x1, 0xf8, 0xc0000b1e50, 0x4027ff1, 0x40dad60)
	/Users/crawshaw/junk.go:15 +0x35
compress/flate.(*huffmanBitWriter).write(0xc00015e000, 0xc00015e020, 0x1, 0xf8)
	/Users/crawshaw/go/go/src/compress/flate/huffman_bit_writer.go:136 +0x5f
compress/flate.(*huffmanBitWriter).flush(0xc00015e000)
	/Users/crawshaw/go/go/src/compress/flate/huffman_bit_writer.go:128 +0xb7
compress/flate.(*huffmanBitWriter).writeStoredHeader(0xc00015e000, 0x0, 0x1)
	/Users/crawshaw/go/go/src/compress/flate/huffman_bit_writer.go:412 +0x63
compress/flate.(*compressor).close(0xc0000ba000, 0x0, 0xc0000a62b0)
	/Users/crawshaw/go/go/src/compress/flate/deflate.go:647 +0x83
compress/flate.(*Writer).Close(0xc0000ba000, 0x0, 0x0)
	/Users/crawshaw/go/go/src/compress/flate/deflate.go:729 +0x2d
compress/gzip.(*Writer).Close(0xc0000a6210, 0x419bf30, 0xc0000a6210)
	/Users/crawshaw/go/go/src/compress/gzip/gzip.go:242 +0x6e
main.main()
	/Users/crawshaw/junk.go:22 +0x47

I suspect (but cannot yet show that) this is related to the fact that gzip.Writer is passing a []byte to the Write method made out of an array field of the gzip.Writer struct.

@ianlancetaylor ianlancetaylor changed the title from runtime/cgo: []byte argument has Go pointer to Go pointer to cmd/cgo: []byte argument has Go pointer to Go pointer Nov 6, 2018

@ianlancetaylor

This comment has been minimized.

Contributor

ianlancetaylor commented Nov 6, 2018

cgo isn't clever enough to look at where the arguments are coming from. It should work if you write it as

	C.f(unsafe.Pointer(&p[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment