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: false msan reports when C function returns struct on stack #26209

ianlancetaylor opened this issue Jul 4, 2018 · 1 comment


Copy link

commented Jul 4, 2018

When using -msan with the C compiler option -fsanitize=memory, when a C function returns a struct on the Go stack, the memory sanitizer code can mark a portion of the Go stack as uninitialized. If that portion of the Go stack is later passed to msanread, perhaps in a different function, the memory sanitizer will report an error.

Test case, which shows the problem when built with go build -msan.

package main

#cgo LDFLAGS: -fsanitize=memory
#cgo CPPFLAGS: -fsanitize=memory

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
	uintptr_t a[20];
} S;

S f() {
	S *p;

	p = (S *)(malloc(sizeof(S)));
	p->a[0] = 0;
	return *p;
import "C"

// allocateStack extends the stack so that stack copying doesn't
// confuse the msan data structures.
func allocateStack(i int) int {
	if i == 0 {
		return i
	return allocateStack(i - 1)

// F1 marks a chunk of stack as uninitialized.
// C.f returns an uninitialized struct on the stack, so msan will mark
// the stack as uninitialized.
func F1() uintptr {
	s := C.f()
	return uintptr(s.a[0])

// F2 allocates a struct on the stack and converts it to an empty interface,
// which will call msanread and see that the data appears uninitialized.
func F2() interface{} {
	return C.S{}

func poisonStack(i int) int {
	if i == 0 {
		return int(F1())
	r := poisonStack(i - 1)
	return r

func main() {

This comment has been minimized.

Copy link

commented Jul 4, 2018

Change mentions this issue: cmd/cgo: mark C result as written for msan

@gopherbot gopherbot closed this in e2f8766 Jul 5, 2018

@golang golang locked and limited conversation to collaborators Jul 5, 2019

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
None yet
2 participants
You can’t perform that action at this time.