lean4 icon indicating copy to clipboard operation
lean4 copied to clipboard

`IO.Process.spawn` with `inheritEnv := false` crashes the child on macOS when `env` sets a variable

Open rbeauchamp opened this issue 1 month ago • 0 comments

Prerequisites

Please put an X between the brackets as you perform the following steps:

  • [X] Check that your issue is not already filed: https://github.com/leanprover/lean4/issues
  • [X] Reduce the issue to a minimal, self-contained, reproducible test case. Avoid dependencies to Mathlib or Batteries.
  • [X] Test your test case against the latest nightly release, for example on https://live.lean-lang.org/#project=lean-nightly (You can also use the settings there to switch to “Lean nightly”)

Description

On macOS, a process started by IO.Process.spawn or IO.Process.output with inheritEnv := false and an env that sets a variable crashes with a segmentation fault before it runs. The parent sees exit code 139 and no output. With inheritEnv := true, or when env only removes variables, the child runs normally.

Context

Found while running git with a controlled environment. The same command started through env -i with the same variables runs.

Steps to Reproduce

  1. Repro.lean:
def test (env : Array (String × Option String)) : IO (UInt32 × String) := do
  let out ← IO.Process.output { cmd := "printenv", args := #["FOO"], env, inheritEnv := false }
  return (out.exitCode, out.stdout)

#eval test #[("FOO", some "1")]
#eval test #[("FOO", none)]
  1. lean Repro.lean on macOS.

Expected behavior: (0, "1\n"), then (1, ""), as env -i FOO=1 printenv FOO prints 1.

Actual behavior:

(139, "")
(1, "")

Versions

Lean (version 4.36.0-nightly-2026-10-13, arm64-apple-darwin24.6.0, commit b7725c34da98e6e2f6323d7f382448ddf31477fb, Release) macOS 27.0.1 (arm64)

Lean 4.34.1 gives the same output.

Additional Information

A compiled program crashes in the same way. The macOS crash report of the child shows a null pointer dereference in __setenv_locked, called from setenv in lean_io_process_spawn.

After fork, the child sets environ = NULL on macOS when inheritEnv is false, and then calls setenv or unsetenv for each entry of env (src/runtime/process.cpp). Apple's setenv counts the entries of environ before it adds a variable, without a check for NULL (Libc setenv.c); unsetenv does nothing when environ is NULL, which is why removals work. On Linux the child calls clearenv, and glibc's setenv accepts a NULL environ, so Linux is not affected.

#15613 and #13898 would replace this code path (with posix_spawn and uv_spawn), which would also remove the crash.

Impact

Add :+1: to issues you consider important. If others are impacted by this issue, please ask them to add :+1: to it.

rbeauchamp avatar Oct 13 '26 17:10 rbeauchamp