Skip to content

cmd/cgo: ptr type casts of struct fields cause the whole struct to be checked #32970

Closed
@notti

Description

@notti

What version of Go are you using (go version)?

$ go version
go version go1.12.6 linux/amd64
$ go version
go version devel +13327f219e Sat Jul 6 13:25:59 2019 +0000 linux/amd64

Does this issue reproduce with the latest release?

Yes. Tried also several older versions back to 1.10

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/hidden/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/hidden/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/lib/go"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build181091171=/tmp/go-build -gno-record-gcc-switches"

What did you do?

package main

/*
struct I {
    int i;
    int *p;
};

int f(struct I *x) {
	return x->i;
}

*/
import "C"

import (
	"fmt"
)

type x struct {
	p *int
	i C.struct_I
}

func main() {
	t1 := new(x)
	t1.p = new(int)
	t1.i.i = 2
	fmt.Println("1:", C.f(&t1.i)) // <- this works
	fmt.Println("2:", C.f((*C.struct_I)(&t1.i))) // <- this doesn't work
}

What did you expect to see?

1: 2
2: 2

What did you see instead?

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

goroutine 1 [running]:
main.main.func2(0xc000090020, 0xc00009a008)
	/home/notti/projects/cgocheck/main.go:30 +0x53
main.main()
	/home/notti/projects/cgocheck/main.go:30 +0x114

Why does this happen?

checkAddr in src/cmd/cgo/gcc.go doesn't recognize type conversions containing parenthesis, which are required for pointers (see https://golang.org/ref/spec#Conversions), and, therefore emits a _cgoCheckPointer without true as second argument, causing the check to look at the whole struct instead of just the element. Looks like pointer type conversions should be supported since ast.StarExpr is handled in isType.

This is the cause for google/gopacket#664

Possible fix: https://go-review.googlesource.com/c/go/+/185098

(updated with better demonstration program)

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions