Skip to content

cmd/cgo: unaligned access warning with zig #62480

@egonelbre

Description

@egonelbre

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

$ go version
go version go1.21.0 windows/amd64

Does this issue reproduce with the latest release?

Yes.

What did you do?

This is the smallest repro

package main

/*
#include <stdint.h>

typedef struct Data {
	int32_t a;
	int64_t x;
} Data;
*/
import "C"

//export call
func call(v *C.int, p C.Data) {}

func main() {}

Then using zig 0.11 for CC and compiling for linux/arm:

$ CGO_ENABLED=1 \
   CC="/path/to/zig cc -target arm-linux-gnueabihf" \
   GOARCH=arm \
   GOOS=linux \
   go build -ldflags="-s -w" -buildmode c-shared -o out.so .

_cgo_export.c:29:8: warning: field p1 within '_cgo_argtype' is less aligned than 'Data' (aka 'struct Data')
and is usually due to '_cgo_argtype' being packed, which can lead to unaligned accesses [-Wunaligned-access]
                Data p1;
                     ^
1 warning generated.

Ideally there wouldn't be a warning.

I would guess the same warning will be shown with clang, however the setup for cross-compile is more annoying and I didn't get it to work at the moment.

Debugging

Using go tool cgo it shows that it ends up generating:

CGO_NO_SANITIZE_THREAD
void call(int* v, Data p)
{
	size_t _cgo_ctxt = _cgo_wait_runtime_init_done();
	typedef struct {
		int* p0;
		Data p1;
	} __attribute__((__packed__)) _cgo_argtype;
	static _cgo_argtype _cgo_zero;
	_cgo_argtype _cgo_a = _cgo_zero;
	_cgo_a.p0 = v;
	_cgo_a.p1 = p;
	_cgo_tsan_release();
	crosscall2(_cgoexp_bd29973577f7_call, &_cgo_a, 20, _cgo_ctxt);
	_cgo_tsan_acquire();
	_cgo_release_context(_cgo_ctxt);
}

It seems this warning was added in https://reviews.llvm.org/D116221

As far as I understand the warning is happening due to having __attribute__((__packed__)) and typedef struct Data not having it. After adding __attribute__((__packed__)) to the Data struct the warning disappears.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsFixThe path to resolution is known, but the work has not been done.compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions