Skip to content

Commit

Permalink
internal/gocore/test: split run into runCrasher and doRunCrasher
Browse files Browse the repository at this point in the history
Refactors the run function by splitting it in two, making it easier to
reuse for more involved tests that need to set different parameters
(flags, other environment variables).

This commit also makes the otherwise unrelated change of setting
GOMAXPROCS=2 in the child binary. This can reduce the size of the crash
stack (fewer GC workers).

Change-Id: I4edd5c51fdfed6b8bb57f2e682cb98dc084e50a5
Reviewed-on: https://go-review.googlesource.com/c/debug/+/632296
LUCI-TryBot-Result: Go LUCI <[email protected]>
Auto-Submit: Nicolas Hillegeer <[email protected]>
Reviewed-by: Michael Knyszek <[email protected]>
  • Loading branch information
aktau authored and gopherbot committed Dec 2, 2024
1 parent 885ca4e commit af4ac2c
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions internal/gocore/gocore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,20 +187,23 @@ func adjustCoreRlimit(t *testing.T) error {
return nil
}

// run spawns the supplied exe with wd as working directory.
//
// - The parent environment is amended with GOTRACEBACK=crash to provoke a
// core dump on (e.g.) segfaults.
// - Thread/process state (like resource limits) are propagated.
//
// If the binary fails to crash, an error is returned.
func run(exe, wd string) (pid int, output []byte, err error) {
// runCrasher spawns exe via [doRunCrasher] with wd as working directory.
// GOTRACEBACK=crash is set.
func runCrasher(exe, wd string) (pid int, output []byte, err error) {
cmd := exec.Command(exe)
cmd.Env = append(os.Environ(), "GOTRACEBACK=crash")
cmd.Env = append(os.Environ(), "GOMAXPROCS=2", "GOTRACEBACK=crash")
cmd.Dir = wd
return doRunCrasher(cmd)
}

// doRunCrasher spawns the supplied cmd, propagating parent state (see
// [exec.Cmd.Run]), and returns an error if the process failed to start or did
// *NOT* crash.
func doRunCrasher(cmd *exec.Cmd) (pid int, output []byte, err error) {
var b bytes.Buffer
cmd.Stdout = &b
cmd.Stderr = &b

runtime.LockOSThread() // Propagate parent state, see [exec.Cmd.Run].
err = cmd.Run()
runtime.UnlockOSThread()
Expand Down Expand Up @@ -237,7 +240,7 @@ func generateCore(dir string, buildFlags ...string) (string, []byte, error) {
return "", nil, fmt.Errorf("error building crasher: %w\n%s", err, string(b))
}

_, b, err = run("./test.exe", dir)
_, b, err = runCrasher("./test.exe", dir)
if err != nil {
return "", b, err
}
Expand Down

0 comments on commit af4ac2c

Please sign in to comment.