From 70fd4e47d73b92fe90e44ac785e2f98f9df0ab67 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Wed, 28 Jul 2021 21:09:31 -0700 Subject: runtime: avoid possible preemption when returning from Go to C When returning from Go to C, it was possible for the goroutine to be preempted after calling unlockOSThread. This could happen when there a context function installed by SetCgoTraceback set a non-zero context, leading to a defer call in cgocallbackg1. The defer function wrapper, introduced in 1.17 as part of the regabi support, was not nosplit, and hence was a potential preemption point. If it did get preempted, the G would move to a new M. It would then attempt to return to C code on a different stack, typically leading to a SIGSEGV. Fix this in a simple way by postponing the unlockOSThread until after the other defer. Also check for the failure condition and fail early, rather than waiting for a SIGSEGV. Without the fix to cgocall.go, the test case fails about 50% of the time on my laptop. Fixes #47441 Change-Id: Ib8ca13215bd36cddc2a49e86698824a29c6a68ba Reviewed-on: https://go-review.googlesource.com/c/go/+/338197 Trust: Ian Lance Taylor Reviewed-by: Keith Randall Reviewed-by: Cherry Mui --- src/runtime/testdata/testprogcgo/tracebackctxt_c.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'src/runtime/testdata/testprogcgo/tracebackctxt_c.c') diff --git a/src/runtime/testdata/testprogcgo/tracebackctxt_c.c b/src/runtime/testdata/testprogcgo/tracebackctxt_c.c index 900cada0d3..910cb7b899 100644 --- a/src/runtime/testdata/testprogcgo/tracebackctxt_c.c +++ b/src/runtime/testdata/testprogcgo/tracebackctxt_c.c @@ -11,6 +11,7 @@ // Functions exported from Go. extern void G1(void); extern void G2(void); +extern void TracebackContextPreemptionGoFunction(int); void C1() { G1(); @@ -62,10 +63,17 @@ void tcContext(void* parg) { } } +void tcContextSimple(void* parg) { + struct cgoContextArg* arg = (struct cgoContextArg*)(parg); + if (arg->context == 0) { + arg->context = 1; + } +} + void tcTraceback(void* parg) { int base, i; struct cgoTracebackArg* arg = (struct cgoTracebackArg*)(parg); - if (arg->context == 0) { + if (arg->context == 0 && arg->sigContext == 0) { // This shouldn't happen in this program. abort(); } @@ -89,3 +97,7 @@ void tcSymbolizer(void *parg) { arg->func = "cFunction"; arg->lineno = arg->pc + (arg->more << 16); } + +void TracebackContextPreemptionCallGo(int i) { + TracebackContextPreemptionGoFunction(i); +} -- cgit v1.2.3-54-g00ecf