`Handle.read`/`Handle.getLine` mishandle sticky stdio EOF/error indicators: spurious empty read after partial EOF read, and `getLine` drops a line after an earlier failed operation

Aperta
#16,812 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
55/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Ambito
backend

Direzione di ricerca

Read src/runtime/io.cpp, focusing on lean_io_prim_handle_read and lean_io_prim_handle_get_line, then compare their behavior with the IO.FS.Handle.read and getLine contracts in src/Init/System/IO.lean. Reproduce both cases with the provided Lean programs. Done when reads after partial EOF return newly available bytes and getLine returns the line after an earlier failed operation without consuming it and throwing a stale error.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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

lean_io_prim_handle_read and lean_io_prim_handle_get_line (src/runtime/io.cpp) both work on a C FILE* whose end-of-file and error indicators are sticky, and neither clears them consistently. This shows up in two ways, one per function.

1. Handle.read: spurious empty read (EOF) after a partial read that met EOF

When fread returns some bytes and also hits EOF, lean_io_prim_handle_read returns them through the n > 0 branch (io.cpp:618-620) without clearerr. Only the n == 0 branch clears the EOF indicator (io.cpp:621-623). Because the C library's EOF indicator is sticky, the next read returns an empty array (the documented EOF marker) even though new data is available. That contradicts the docstring "Encountering an EOF does not close a handle. Subsequent reads may block and return more data" (src/Init/System/IO.lean:846). getLine already clears the indicator (io.cpp:674), and the read branch for n == 0 does too, which shows the intent (PR #1479 added clearerr to make EOF non-sticky for getLine).

The program opens /tmp/lean_sticky_eof_demo.txt read-only while it holds 3 bytes "abc", reads 16 bytes (first: [97, 98, 99], a read that runs into the end of the file), appends "def" through a second handle in .append mode and flushes it, then reads 16 bytes from the first handle again. It prints second: [] — the empty array that the docstring calls the end-of-file marker — although 3 unread bytes are at the handle's cursor; only the next read returns them (third: [100, 101, 102]). The second read therefore reports EOF while the file is not at EOF, and a caller such as IO.FS.Handle.readBinToEndInto (which stops at the first empty array) silently loses the appended bytes. With a 2-byte first read (which does not reach the end of the file and leaves no end-of-file indicator) the same program returns second: [99, 100, 101, 102], so the only difference is the stale end-of-file indicator.

Documented behavior it contradicts (IO.FS.Handle.read docstring):

Reads up to the given number of bytes from the handle. If the returned array is empty, an
end-of-file marker (EOF) has been reached.

Encountering an EOF does not close a handle. Subsequent reads may block and return more data.

2. Handle.getLine: stale error indicator makes it consume a line and throw

lean_io_prim_handle_get_line reads the line with getc_unlocked and then tests std::ferror(fp) (io.cpp:672). The error indicator is sticky and nothing clears it before the read. If an earlier operation on the handle failed, getLine consumes a complete line and still returns that old errno (EBADF here), so the line is lost. lean_io_prim_handle_read returns the bytes whenever n > 0 (io.cpp:618-620), so it does not have this problem. The trigger used below, a putStr on a read-only handle, is a misuse that returns a documented error; a transient read error such as EAGAIN or EINTR would also make every later getLine fail and drop data.

The program writes "abc\ndef\n" to a temp file, opens it read-only, attempts a write through that read-only handle (an operation the runtime itself documents and tests as failing with IO.Error.invalidArgument "bad file descriptor", see tests/elab/file_not_found.lean), catches that failure, and then calls getLine on the same handle. getLine throws instead of returning the line: the program prints "getLine failed: invalid argument (error code: 9, bad file descriptor) ; rest: def\n". That error is the stale EBADF of the earlier failed write: getLine's own getc loop had already read the complete first line, which is why the read of the same handle performed immediately after the failure returns exactly the remaining bytes "def\n" (the line "abc\n" was consumed and thrown away). The Handle.getLine contract says it reads UTF-8-encoded text up to and including the next line break from the handle, so this call had to return the String "abc\n" and the program had to print "abc\ndef\n" — which is what it does when the earlier failed write is left out.

Documented behavior it contradicts (IO.FS.Handle.getLine docstring):

Reads UTF-8-encoded text up to and including the next line break from the handle. If the returned string does not end with a line break, an end-of-file marker (EOF) has been reached.

Context
  • Affected functions: lean_io_prim_handle_read and lean_io_prim_handle_get_line (src/runtime/io.cpp)
  • Upstream: no existing issue found; the cited code is unchanged in nightly-2026-11-26. PR #1479 added clearerr to make EOF non-sticky for getLine, which is the intent violated by Handle.read.
Steps to Reproduce
1. Handle.read
  1. Save the following as input.lean (imports only Init):
/-
`Handle.read` on a regular file: the first read reaches the end of the file (3 bytes),
then more bytes are appended, and the same handle is read again. The docstring of
IO.FS.Handle.read says that an empty result means an EOF has been reached and that encountering
an EOF does not close the handle, so subsequent reads return the data that has become available.
-/
def main : IO Unit := do
  let path : System.FilePath := "/tmp/lean_sticky_eof_demo.txt"
  IO.FS.writeFile path "abc"
  let h ← IO.FS.Handle.mk path .read
  let b1 ← h.read 16
  IO.println s!"first: {b1.toList}"
  let w ← IO.FS.Handle.mk path .append
  w.putStr "def"
  w.flush
  let b2 ← h.read 16
  IO.println s!"second: {b2.toList}"
  let b3 ← h.read 16
  IO.println s!"third: {b3.toList}"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog

Expected behavior:

first: [97, 98, 99]
second: [100, 101, 102]
third: []

Actual behavior:

first: [97, 98, 99]
second: []
third: [100, 101, 102]

(With h.read 2 as the first read, which does not hit EOF, the output is first: [97, 98], second: [99, 100, 101, 102], third: [].)

2. Handle.getLine
  1. Save the following as input.lean (imports only Init):
def main : IO Unit := do
  IO.FS.writeFile "/tmp/getline_probe.txt" "abc\ndef\n"
  let h ← IO.FS.Handle.mk "/tmp/getline_probe.txt" .read
  try h.putStr "x" catch _ => pure ()
  try
    let l ← h.getLine
    let b ← h.read 64
    IO.print (l ++ String.fromUTF8! b)
  catch e =>
    let b ← h.read 64
    IO.print s!"getLine failed: {toString e} ; rest: {String.fromUTF8! b}"
  IO.FS.removeFile "/tmp/getline_probe.txt"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog

Expected behavior:

abc
def

Actual behavior:

getLine failed: invalid argument (error code: 9, bad file descriptor) ; rest: def

(Without the try h.putStr "x" catch _ => pure () line the program prints abc\ndef\n.)

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 (Handle.read). The call is Handle.read h 16 on a valid read-mode handle, and 3 unread bytes had just been appended and flushed, so at least one byte is readable at the cursor. It returns an ok result whose byte array is empty, and the next read of the same handle returns the data. No callee hands it a wrong value: the byte array is allocated by this function itself before reading (lean_alloc_sarray(1, 0, nbytes), io.cpp:612) and keeps size 0 because std::fread returns 0 without reading anything (io.cpp:617); fread returns 0 only because the stream's end-of-file indicator was still set by the immediately preceding call of this same function, whose if (n > 0) { lean_sarray_set_size(res, n); return io_result_mk_ok(res); } branch (io.cpp:618-620) returns without clearerr(fp) — the only branch that clears it is the feof branch at io.cpp:621-623, which is not reached when bytes were read.

Root cause analysis (Handle.getLine). The handle is an ordinary read-mode handle on a regular file holding "abc\ndef\n" with the cursor at offset 0; the only unusual part of the state is the stdio error indicator, which the preceding failed putStr on the same handle sets. getLine returns an IO error carrying IO.Error.invalidArgument with osCode 9 ("bad file descriptor"), the stale errno of that earlier failed write, although its own getc loop had already read the whole first line. io_get_handle returned the valid FILE*, the getc calls returned the correct bytes 'a','b','c','\n', and decode_io_error/io_result_mk_error only encode the decision; the wrong decision is this function's own if (std::ferror(fp)) test at io.cpp:672, taken although the while loop ended by finding the line break (io.cpp:664-669) and although nothing failed during this call. Since the flag is never cleared, every later getLine keeps dropping one line.

Suggested fix:

  • Handle.read: call clearerr(fp) before returning (e.g. at the start of the function or on the n > 0 path, as lean_io_prim_handle_get_line does at io.cpp:674-676). Then the second read returns the appended bytes.
  • Handle.getLine: only consult ferror when the getc loop ended because getc returned EOF (c == EOF), not when it broke on '\n' (and/or clearerr(fp) before reading, so that an error from an earlier operation is not reported again).
Impact
  • Handle.read: programs that follow a growing file, or read interactive stdin after a partial read that met EOF, get one spurious empty read, and loops like readBinToEnd stop early and miss data.
  • Handle.getLine: after any earlier failed operation on a handle, each later getLine silently consumes a line and throws a stale error, which mostly affects programs that catch an IO error and keep using the handle.

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

Lingua principale
Lean
Stelle
10.3k
Fork
1.1k
Merge medio
16h 45m
PR unite (30g)
361

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di leanprover/lean4

Tutte le issue di leanprover/lean4

Issue simili

Altre issue su Backend & API Design

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.