| 1 |
// SPDX-License-Identifier: Apache-2.0 |
| 2 |
// SPDX-FileCopyrightText: 2026 The Ebitengine Authors |
| 3 |
|
| 4 |
// 386/arm are excluded: the standalone fakecgo test binary resolves pthread |
| 5 |
// from libpthread.so.0, which fails the dynamic symbol lookup on 32-bit linux. |
| 6 |
//go:build !cgo && (linux || darwin || freebsd || netbsd) && !386 && !arm |
| 7 |
|
| 8 |
package fakecgo |
| 9 |
|
| 10 |
import ( |
| 11 |
"runtime" |
| 12 |
"sync" |
| 13 |
"testing" |
| 14 |
) |
| 15 |
|
| 16 |
// TestThreadEntryReturn exercises the fakecgo threadentry -> runtime.mstart |
| 17 |
// return path, i.e. that an M created by fakecgo can exit cleanly. |
| 18 |
// |
| 19 |
// When iscgo is forced true by fakecgo, the runtime creates every new OS |
| 20 |
// thread through _cgo_thread_start -> threadentry_trampoline -> threadentry, |
| 21 |
// which calls runtime.mstart. For a fakecgo thread the M's stack is |
| 22 |
// system-allocated, so when the M exits, mexit(osStack=true) returns from |
| 23 |
// mstart back into threadentry. This return path has been the source of |
| 24 |
// crashes (a frame-pointer LEAVE fault on amd64, a bad indirect call and race |
| 25 |
// instrumentation on other platforms), so it is worth exercising everywhere. |
| 26 |
// |
| 27 |
// Locking an OS thread and then letting the goroutine exit (without calling |
| 28 |
// UnlockOSThread) forces the locked fakecgo M to exit, driving mstart to return |
| 29 |
// into threadentry. A busy loop that never lets the goroutine exit does NOT |
| 30 |
// reproduce the crash, because the M never exits and mstart never returns. |
| 31 |
func TestThreadEntryReturn(t *testing.T) { |
| 32 |
// The M exits on the first goroutine return, so a modest amount of churn is |
| 33 |
// enough to catch a broken teardown while staying quick under emulation. |
| 34 |
const rounds = 10 |
| 35 |
const workers = 16 |
| 36 |
for range rounds { |
| 37 |
var wg sync.WaitGroup |
| 38 |
wg.Add(workers) |
| 39 |
for range workers { |
| 40 |
go func() { |
| 41 |
defer wg.Done() |
| 42 |
runtime.LockOSThread() |
| 43 |
// Intentionally do NOT call UnlockOSThread: returning here exits |
| 44 |
// the goroutine while its OS thread is locked, forcing the M to |
| 45 |
// exit and mstart to return into fakecgo.threadentry. |
| 46 |
}() |
| 47 |
} |
| 48 |
wg.Wait() |
| 49 |
} |
| 50 |
} |