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
Trust: Ian Lance Taylor <>
Reviewed-by: Keith Randall <>
Reviewed-by: Cherry Mui <>
4 files changed
tree: b3e27a617fa1b6d191dac8a40c99142b96f1eb50
  1. .gitattributes
  2. .github/
  3. .gitignore
  11. api/
  12. codereview.cfg
  13. doc/
  14. lib/
  15. misc/
  16. src/
  17. test/

The Go Programming Language

Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.

Gopher image Gopher image by Renee French, licensed under Creative Commons 3.0 Attributions license.

Our canonical Git repository is located at There is a mirror of the repository at

Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file.

Download and Install

Binary Distributions

Official binary distributions are available at

After downloading a binary release, visit for installation instructions.

Install From Source

If a binary distribution is not available for your combination of operating system and architecture, visit for source installation instructions.


Go is the work of thousands of contributors. We appreciate your help!

To contribute, please read the contribution guidelines at

Note that the Go project uses the issue tracker for bug reports and proposals only. See for a list of places to ask questions about the Go language.