Skip to content

cmd/compile: compiler assumes [2]T does not alias with struct{a, b T} which might be allowed by the unsafe package #65535

@Jorropo

Description

@Jorropo

Go version

go version devel go1.23-6076edc55c Mon Feb 5 20:59:15 2024 +0000 linux/amd64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/home/hugo/.cache/go-build'
GOENV='/home/hugo/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/home/hugo/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/hugo/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/home/hugo/k/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/home/hugo/k/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='devel go1.23-6076edc55c Mon Feb 5 20:59:15 2024 +0000'
GCCGO='/usr/bin/gccgo'
GOAMD64='v3'
AR='ar'
CC='gcc'
CXX='g++'
CGO_ENABLED='1'
GOMOD='/dev/null'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=/tmp/go-build1276548902=/tmp/go-build -gno-record-gcc-switches'

What did you do?

While investing #65495 I noticed that the compiler makes assumptions about aliasing of structs which are not documented in unsafe.

See this piece of code:

package main

import "unsafe"
import "fmt"

type S0 struct{ a, b S1 }
type S1 struct{ a, b S2 }
type S2 struct{ a, b S3 }
type S3 struct{ a, b S4 }
type S4 struct{ a, b S5 }
type S5 struct{ a, b S6 }
type S6 struct{ a, b S7 }
type S7 struct{ a, b S8 }
type S8 struct{ a, b int }

//go:noinline
func Copy(a, b *S0) {
	*a = *b
}

func main() {
	var arr [3]S1
	arr[0].a.a.a.a.a.a.a.a = 42
	arr[1].a.a.a.a.a.a.a.a = 43
	arr[2].a.a.a.a.a.a.a.a = 44
	Copy((*S0)(unsafe.Pointer(&arr[1])), (*S0)(unsafe.Pointer(&arr[0])))
	fmt.Println(arr[2].a.a.a.a.a.a.a.a)
}

What did you see happen?

42

What did you expect to see?

43

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationIssues describing a change to documentation.NeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    Status

    Todo

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions