win: correctness bugs introduced by cancellation PR
@Keno Cancellation introduced a couple regressions into Windows IO paths, which can result in lost data or crashes. But Claude also wrote some detailed instructions on how to fix it.
win,pipe: a write issued from a write_cb on a non-overlapped pipe is never dispatched (regression in #4966)
Version: v1.53.0 (regression from v1.52.1, introduced by 6ea389cf "stream: Implement cancellation support for uv_write_t (#4966)")
Platform: Windows, non-overlapped pipes only (UV_HANDLE_NON_OVERLAPPED_PIPE). For example, an inherited stdio pipe or a uv_pipe() end opened with uv_pipe_open().
What happens
For non-overlapped pipes, uv__pipe_write_data() sends a new write to the thread pool only when stream.conn.write_reqs_pending == 0 (src/win/pipe.c:1848). Otherwise it leaves the write in the non_overlapped_writes_tail list and expects a later completion to dispatch it.
#4966 moved that "dispatch the next write" step in uv__process_pipe_write_req() so that it now runs before the user callback and before write_reqs_pending-- (src/win/pipe.c:2410-2431). It also made the step conditional on the completing request being non_overlapped_write_active. Two things follow from that:
Writing from inside
write_cb. While request A's callback runs, A is still counted inwrite_reqs_pending(the count is 1), but A is no longer active. Auv_write()of C made from that callback sees a non-zero count, so C only goes into the list. After the callback returns, the count drops back to 1 (now counting C), and nothing dispatches C. C never completes. Every later write goes into the list behind it, so the stream hangs for good.In v1.52.1 this worked, because the dispatch ran after the decrement and checked
non_overlapped_writes_tail.Cancelled writes still counted. A write that is cancelled while still in the list is removed from it and posted with
ERROR_OPERATION_ABORTED. It stays inwrite_reqs_pendinguntil its completion is processed. Take this sequence: A is active and B is in the list.uv_cancel(B)is called (say, from another handle's callback earlier in the sameuv__process_reqsbatch). A then completes before B's completion is processed. A's completion finds the list empty, andnon_overlapped_write_activebecomes NULL. Anyuv_write()issued before B's completion is processed now seeswrite_reqs_pending > 0and is only added to the list. B's completion does not dispatch it either, because B was never active. The same hang follows.
Repro sketch
static void write_cb(uv_write_t* req, int status) {
if (++count < 2)
uv_write(&req2, (uv_stream_t*) &writer, &buf, 1, write_cb); /* never completes */
}
...
uv_file fds[2];
uv_pipe(fds, 0, 0); /* no flags -> non-overlapped */
uv_pipe_open(&writer, fds[1]);
uv_pipe_open(&reader, fds[0]);
uv_read_start((uv_stream_t*) &reader, alloc_cb, read_cb);
uv_write(&req1, (uv_stream_t*) &writer, &buf, 1, write_cb);
uv_run(loop, UV_RUN_DEFAULT); /* hangs: req2 stays in the list */Suggested fix
Decide whether to dispatch based on whether a write is actually in flight, not on how many are counted as pending:
} else if (handle->flags & UV_HANDLE_NON_OVERLAPPED_PIPE) {
req->write_buffer = write_buf;
uv__insert_non_overlapped_write_req(handle, req);
- if (handle->stream.conn.write_reqs_pending == 0) {
+ if (handle->pipe.conn.non_overlapped_write_active == NULL) {
uv__queue_non_overlapped_write(handle);This holds because non_overlapped_write_active == NULL implies the list is empty. Whenever the active slot is cleared, the next queued write is dispatched straight away. uv__pipe_flush_non_overlapped_writes() also empties the list. So the existing assert(non_overlapped_writes_tail == NULL) after the dispatch stays valid. With this change, the dispatch in uv__process_pipe_write_req() can stay before the callback.
We made this change while merging v1.53.0 into the Julia fork (julia-uv2). That fork tracks writes with a per-stream write_queue instead of write_reqs_pending. Its version avoids case 1, because the request is taken off the queue before the callback runs. It still hits case 2 with an empty-queue check.
win,tty: read error paths mishandle cancellation state and the active count
Version: v1.53.0 (the code is older than that). Platform: Windows console TTYs.
The completion handlers for TTY reads have error paths (including EOF-like errors such as ERROR_BROKEN_PIPE -> UV_EOF, or ReadConsoleW failing) that don't keep UV_HANDLE_READ_CANCELLATION_PENDING and activecnt in step with the success paths and with uv__tty_read_stop().
1. Line mode: the error path never clears UV_HANDLE_READ_CANCELLATION_PENDING
uv_process_tty_read_line_req() (src/win/tty.c:990-1008):
if (!REQ_SUCCESS(req)) {
if (handle->flags & UV_HANDLE_READING) {
/* Real error */
handle->flags &= ~UV_HANDLE_READING;
DECREASE_ACTIVE_COUNT(loop, handle);
handle->read_cb(..., uv_translate_sys_error(GET_REQ_ERROR(req)), &buf);
}
} else {
if (!(handle->flags & UV_HANDLE_READ_CANCELLATION_PENDING) && InternalHigh != 0)
handle->read_cb(...);
handle->flags &= ~UV_HANDLE_READ_CANCELLATION_PENDING; /* only cleared here */
}uv__tty_read_stop() sets UV_HANDLE_READ_CANCELLATION_PENDING after injecting the VK_RETURN trap (tty.c:1090-1096). If the cancelled ReadConsoleW then fails instead of returning the injected line, the flag is never cleared. That can happen when the console is closed or detached, or when the error is an EOF. The consequences:
- Lost input. After a later
uv_read_start(), the first line that is read successfully is dropped silently. The success branch sees the stale flag, discards the data, and only then clears the flag. - A read that
uv_read_stop()can't cancel. The stale flag makesuv__tty_read_stop()skipuv__cancel_read_console(). The worker thread stays blocked inReadConsoleWafter the user stopped reading. It swallows the next line of console input, which may have been meant for someone else, such as a child process that shares the console. - An error from the cancelled read reported against the new read. Suppose the user calls
uv_read_stop()and thenuv_read_start()before the cancelled request completes.UV_HANDLE_READINGis set again, so the old read's error isreported as a "real error" of the new read. That clearsUV_HANDLE_READINGand decrements the active count. The decrement matches the restart's increment, but the read was never meant to be reported. The result is only correct if the error really applies to the stream as a whole, such as EOF.
Suggested fix: clear UV_HANDLE_READ_CANCELLATION_PENDING on both branches, and don't report an error for a read that was cancelled unless it is sticky (EOF):
int cancelled = handle->flags & UV_HANDLE_READ_CANCELLATION_PENDING;
handle->flags &= ~UV_HANDLE_READ_CANCELLATION_PENDING;
if (!REQ_SUCCESS(req)) {
err = GET_REQ_ERROR(req);
if ((handle->flags & UV_HANDLE_READING) &&
!(cancelled && err == ERROR_OPERATION_ABORTED)) {
...
}
} else if (!cancelled && InternalHigh != 0) {
...
}2. Raw mode: the error path clears UV_HANDLE_READING without decrementing the active count
uv_process_tty_read_raw_req() (src/win/tty.c:738-746):
if (!REQ_SUCCESS(req)) {
if ((handle->flags & UV_HANDLE_READING)) {
handle->flags &= ~UV_HANDLE_READING;
/* missing: DECREASE_ACTIVE_COUNT(loop, handle); */
handle->read_cb(..., uv_translate_sys_error(GET_REQ_ERROR(req)), &uv_null_buf_);
}
goto out;
}Every other error path in this function, and the matching one in line mode, pairs clearing UV_HANDLE_READING with DECREASE_ACTIVE_COUNT(). uv_read_stop() returns early when UV_HANDLE_READING is clear (src/win/stream.c:97), so theuser has no way to get the count back. After a raw-mode read error (for example, RegisterWaitForSingleObject failing in uv__tty_queue_read_raw()), the handle keeps activecnt >= 1. It then keeps uv_run(UV_RUN_DEFAULT) alive until the handle is closed. Each later uv_read_start() / uv_read_stop() cycle leaves one more stray increment.
Fix: add DECREASE_ACTIVE_COUNT(loop, handle); there.
Source: libuv/libuv