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

Closed
ianlancetaylor opened this issue Jul 4, 2018 · 1 comment
Closed
Labels
FrozenDueToAge NeedsFix The path to resolution is known, but the work has not been done. release-blocker
Milestone

Comments

@ianlancetaylor
Copy link
Contributor

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.
//go:noinline
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.
//go:noinline
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.
//go:noinline
func F2() interface{} {
	return C.S{}
}

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

func main() {
	allocateStack(16384)
	poisonStack(128)
}
@ianlancetaylor ianlancetaylor added NeedsFix The path to resolution is known, but the work has not been done. release-blocker labels Jul 4, 2018
@ianlancetaylor ianlancetaylor added this to the Go1.11 milestone Jul 4, 2018
@gopherbot
Copy link

Change https://golang.org/cl/122196 mentions this issue: cmd/cgo: mark C result as written for msan

@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.
Labels
FrozenDueToAge NeedsFix The path to resolution is known, but the work has not been done. release-blocker
Projects
None yet
Development

No branches or pull requests

2 participants