`IO.currentDir`, `IO.Process.getCurrentDir` and `Std.Internal.UV.System.cwd` fail when the working directory is longer than `PATH_MAX`

Đang mở
#16,802 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
56/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Lĩnh vực
backend, operating-systems

Hướng nghiên cứu

Read src/runtime/io.cpp around lean_io_current_dir, src/runtime/process.cpp around lean_io_process_get_current_dir, and src/runtime/uv/system.cpp around get_uv_string and lean_uv_cwd. Reproduce with the provided deep-directory example, then check each API against the expected path and the /bin/pwd -P result. Done means all three APIs return the full path when it exceeds PATH_MAX.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

bug
Prerequisites
  • Check that your issue is not already filed:
    https://github.com/leanprover/lean4/issues
  • Reduce the issue to a minimal, self-contained, reproducible test case.
    Avoid dependencies to Mathlib or Batteries.
  • 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”)
  • When reporting a perceived soundness bug: Does it affect lake check --paranoid?
    If in doubt, please reach out on [email protected] for responsible disclosure.
    (Not a soundness bug.)
Description

All three runtime functions that return the current working directory read it into a fixed PATH_MAX buffer and give up when the path does not fit, instead of retrying with a larger buffer:

  • lean_io_current_dir (IO.currentDir) calls getcwd(buffer, PATH_MAX) on a stack buffer (io.cpp:1490-1491) and returns an error on ERANGE (io.cpp:1495).
  • lean_io_process_get_current_dir (IO.Process.getCurrentDir) calls getcwd with a fixed char[PATH_MAX] buffer (process.cpp:59-65) and returns the ERANGE error.
  • get_uv_string (used by lean_uv_cwd, Std.Internal.UV.System.cwd) starts with a PATH_MAX buffer and retries only on UV_ENOBUFS (src/runtime/uv/system.cpp:119-139). libuv's uv_cwd returns UV_ENOBUFS with a size only when the path fits in its own PATH_MAX scratch buffer; for a longer path it returns UV_ERANGE, so the retry never happens.

A working directory longer than PATH_MAX can be reached by relative chdirs, the OS can report it (getcwd(NULL, 0) or a large enough buffer returns it), and the docstrings promise the current directory and state no limit. So the error is wrong. Many tools have this limit, so it is low priority; a single fix (grow and retry on ERANGE, or getcwd(NULL, 0)) would cover all three. The same fixed-buffer pattern is also in realpath (io.cpp:1084).

Each program below moves the process into a working directory whose absolute path is over 8000 bytes long (40 components of 200 bytes, entered one short relative IO.Process.setCurrentDir at a time, none of which the OS rejects), then reads that directory through the API under test. In the same run it runs /bin/pwd -P in that directory from a child process and checks that the printed path equals the path the program built, which shows that the value is obtainable and not an OS limit.

IO.currentDir (lean_io_current_dir)

The call fails with "failed to retrieve current working directory", a userError, so the Lean program never sees its working directory. The cause is char buffer[PATH_MAX]; char* cwd = getcwd(buffer, sizeof(buffer));: when the path does not fit, getcwd sets ERANGE and the function returns io_result_mk_error("failed to retrieve current working directory") instead of growing the buffer.

Documented behavior it contradicts (IO.currentDir docstring, src/Init/System/IO.lean:964):

Returns the current working directory of the executing process.

IO.Process.getCurrentDir (lean_io_process_get_current_dir)

The call fails with unsupported operation (error code: 34, result too large), an IO.Error carrying ERANGE, instead of returning the directory. The cause is char path[PATH_MAX]; if (getcwd(path, PATH_MAX)) ... else return io_result_mk_error(decode_io_error(errno, nullptr));: when the path does not fit the fixed buffer, getcwd sets ERANGE and the function reports the error rather than retrying with a buffer of the size the path needs.

Documented behavior it contradicts (IO.Process.getCurrentDir docstring, src/Init/System/IO.lean:1389):

Returns the current working directory of the calling process.

Std.Internal.UV.System.cwd (lean_uv_cwd / get_uv_string)

The call fails with unsupported operation (error code: 34, result too large), an IO.Error carrying libuv's UV_ERANGE. The shared helper get_uv_string only handles a too-small buffer reported as UV_ENOBUFS with a size. libuv's uv_cwd reports it as UV_ERANGE with no size, so the retry never happens. That contradicts the helper's own comment ("retrying with the size it asks for when the buffer is too small"). Its sibling lean_uv_get_process_title in the same file doubles the buffer until it fits precisely because "libuv does not report the size the title needs". libuv documents only the ENOBUFS path, so this is partly a libuv limit that Lean passes through, but Lean could double the buffer on ERANGE in the same way.

Documented behavior it contradicts (src/Std/Internal/UV/System.lean:140):

Gets the current working directory.

Context
  • Affected functions: lean_io_current_dir (src/runtime/io.cpp), lean_io_process_get_current_dir (src/runtime/process.cpp), get_uv_string / lean_uv_cwd (src/runtime/uv/system.cpp)
  • Upstream: no existing issue found; the cited code is identical in nightly-2026-11-26.
Steps to Reproduce
  1. Save the following as input.lean (imports only Init/Std). This is the IO.currentDir version. For the other two functions, replace the IO.currentDir call inside runtime (and the label) with IO.Process.getCurrentDir or Std.Internal.UV.System.cwd (for the latter, compare cwd == expected directly, since it returns a String):
import Std

/-
The process moves into a working directory whose absolute path is longer than `PATH_MAX` (such a
directory is reached one component at a time, as a deeply nested build tree or cache is), and then
reads that directory with `IO.currentDir`, and with the operating system itself, by running
`/bin/pwd -P` in the same directory from a child process.
-/

def component : String := String.ofList (List.replicate 200 'd')

def sh (script : String) : IO Unit := do
  let child ← IO.Process.spawn { cmd := "/bin/sh", args := #["-c", script], stdin := .null }
  discard child.wait

def main : IO Unit := do
  let base := (← IO.currentDir).toString
  -- 40 components in total; `mkdir -p` is given 4 at a time so each argument stays below
  -- macOS's PATH_MAX of 1024 (on Linux 4 rounds of 10 work as well)
  let rounds := 10
  let perRound := 4
  let chunk := String.intercalate "/" (List.replicate perRound component)
  for _ in List.range rounds do
    sh s!"mkdir -p {chunk}"
    for _ in List.range perRound do
      IO.Process.setCurrentDir component
  let expected := base ++ String.join (List.replicate (rounds * perRound) ("/" ++ component))

  let runtime ← try
      let cwd ← IO.currentDir
      pure (if cwd.toString == expected then "ok" else "wrong value")
    catch e => pure s!"error: {e}"
  IO.println s!"IO.currentDir: {runtime}"

  sh "/bin/pwd -P > pwd.txt"
  let osSays ← try
      let out ← IO.FS.readFile "pwd.txt"
      pure (out.startsWith expected && out.length == expected.length + 1)
    catch _ => pure false
  IO.println s!"operating system reports the directory: {osSays}"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog (it creates the deep ddd… tree in the current directory)

Expected behavior:

IO.currentDir: ok
operating system reports the directory: true

(and likewise IO.Process.getCurrentDir: ok / System.cwd: ok)

Actual behavior:

IO.currentDir: error: failed to retrieve current working directory
operating system reports the directory: true
IO.Process.getCurrentDir: error: unsupported operation (error code: 34, result too large)
operating system reports the directory: true
System.cwd: error: unsupported operation (error code: 34, result too large)
operating system reports the directory: true
Versions

Lean (version 4.38.0-nightly-2026-11-26, arm64-apple-darwin24.6.0, commit e1228b8b45918ece1a00d68e5fc5e6a685ca59ee, Release)
macOS 26.6.2 (arm64)

Additional Information

Root cause analysis. In each case the process is in a real working directory: it entered the directory with the runtime's own IO.Process.setCurrentDir (uv_chdir) one 200-byte component at a time, and a child process prints exactly that path. No callee hands back a wrong value. getcwd correctly reports ERANGE because the fixed PATH_MAX buffer is too small, and uv_cwd returns UV_ERANGE for the PATH_MAX-sized buffer. io_result_mk_error/decode_io_error/io_result_mk_uv_error encode exactly what they are given. The decision to stop instead of retrying with a larger buffer is each function's own: io.cpp:1495, process.cpp:63-64, and the UV_ENOBUFS-only retry in get_uv_string. On macOS, a C probe in the same 8102-byte directory shows that getcwd(NULL, 0) and getcwd with a 64 KiB buffer both succeed and return the full 8102-byte path.

Suggested fix: retry with a larger buffer on ERANGE in all three places: getcwd(NULL, 0) (supported by glibc and macOS) or doubling, as lean_uv_get_process_title does in system.cpp:36-49. For get_uv_string, also double the buffer when uv_cwd returns UV_ERANGE.

Impact

Only processes whose working directory is longer than PATH_MAX (4096 bytes on Linux, 1024 on macOS), for example inside a very deep generated tree, are affected: they get an error from IO.currentDir, IO.Process.getCurrentDir and System.cwd instead of the path. This is very rare.

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

Ngôn ngữ chính
Lean
Star
10.3k
Fork
1.1k
Merge trung bình
16 giờ 45 phút
Pull request đã merge (30 ngày)
361

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của leanprover/lean4

Tất cả issue của leanprover/lean4

Issue tương tự

Thêm issue về Backend & API Design

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.