Skip to content

fix(ffi): rebind CRT std fds to ctx handles and poll cancel mid-dispatch (#1487) - #1599

Merged
caomengxuan666 merged 2 commits into
feat/ffi-prototypefrom
ai-fix/WinuxCmd-1487
Nov 13, 2026
Merged

caomengxuan666 merged 2 commits into
feat/ffi-prototypefrom
ai-fix/WinuxCmd-1487

Conversation

@arookieofc-ai

Copy link
Copy Markdown
Contributor

Fixes #1487 (defects A and B; fact C is out of scope — see below).

Base-branch note: this PR targets feat/ffi-prototype, not main.
src/ffi/ is not tracked on main (main's CMakeLists.txt says the FFI
sources are not in git and disables FFI when absent); the FFI shell lives
only on feat/ffi-prototype (PR #1426, head d589562f). This is a stacked
fix on top of #1426. The landing path — merge #1426 first then this, or
rebase this onto main after #1426 lands — is the maintainer's call.

Feasibility assessment

Defect A — host stdio redirects never reach the applets (P0, data loss)

Root cause — three independent missing bindings, all in the FFI shell:

  • A2 (primary): CRT fds never rebound. StdBorrow::apply
    (src/ffi/ffi.cpp) did only SetStdHandle() + _setmode(fd, _O_BINARY).
    A CRT fd stays bound to the OS handle it had at CRT startup; SetStdHandle
    does not change the fd→HANDLE mapping. Applets go through the CRT fds:
    sort reads std::cin (src/commands/sort.cpp:203,250,272) and writes
    std::cout directly in the merge path (sort.cpp:1935); wc reads
    std::cin (wc.cpp:183,438); tee uses fwrite(..., stdout)
    (tee.cpp:147); tr uses ::fwrite(..., stdout) (tr.cpp:580). So
    sort < words.txt read the host's console stdin (EOF → wc printed 0)
    and sort words.txt > o.txt wrote to the host's console stdout (36 MB
    sprayed to the terminal, o.txt empty). The 23 no-redirect cases were
    byte-identical because the applets are correct — only the wiring was
    missing.
  • A1: stale console-layer cache. getStdOut()/getStdErr() in
    src/utils/console.cppm cache GetStdHandle() in thread_locals, and
    isStdoutConsole() caches the console-ness verdict. invalidateCachedHandles()
    exists ("call after SetStdHandle") but ffi.cpp never called it, so a
    long-lived host thread poisons the cache with the console handle on its
    first call and every later safePrint writes there. This is why the
    prototype's own smoke tests stayed green: one call per fresh process
    (cold cache, already pointing at the redirect), and the sequence case
    never changes handles between calls.
  • A3: no flush across the DLL boundary + sticky flags. C stdio output
    is buffered in the DLL CRT and there is no process exit to flush it, so
    unflushed bytes land on whatever handle fd 1 points at later. And
    clear_pipe_closed_flags() had zero call sites — the sticky
    g_stdout_pipe_closed / g_stdout_write_error thread_locals persisted
    across calls, so one broken pipe made later calls silently drop stdout.

Fix (src/ffi/ffi.cpp, src/ffi/winux_ffi.h):
StdBorrow now rebinds fds 0/1/2 to duplicates of the ctx handles
(_close(fd) + _open_osfhandle(dup)), calls invalidateCachedHandles()
and clear_pipe_closed_flags() per call, and flushes C stdio with
_flushall() before the swap and before restore (draining to the
borrowed handles on exit; also discards any bytes a previous call
prefetched from a different stdin handle). fflush is unspellable here —
this TU builds with _CRT_DISABLE_PERFCRIT_LOCKS, which macro-rewrites the
token to _fflush_nolock (see commit cc8335c3) — so _flushall is
declared manually as extern "C" int _flushall(void);.

Handle ownership is the sharp edge: _close also closes the underlying OS
handle (_open_osfhandle transfers ownership to the fd), so both sides
are duplicated first
— the fd's original handle is duplicated before
_close, and the ctx handle is duplicated before _open_osfhandle. The
DLL never closes a handle the host owns. Restore rebinds the fd to the
saved original duplicate and restores the Win32 slot to that duplicate —
same kernel object, different numeric value.

Host contract change (documented in winux_ffi.h): after each FFI call
the Win32 std slot may hold a duplicate of the previous handle. Hosts
must re-query std handles via GetStdHandle after each call and never
cache a raw HANDLE value across calls. The in-tree hosts (harness,
niubash) build the ctx per call from GetStdHandle, so this holds — but
niubash-side confirmation is still outstanding (see "Not verified").

Empirical evidence: a CRT experiment (mingw-w64 + wine64) reproduced
the bug and confirmed the fix: SetStdHandle-only leaves
_get_osfhandle(1) unchanged and std::cout misses the redirect file;
after _close(1) + _open_osfhandle(dup), std::cout reaches the file
and restore returns the original stdout, with the host's redirect handle
untouched; same for stdin/fd 0 (std::getline(std::cin) EOF → reads
"hello-stdin" after rebind). Caveat: wine's CRT is mingw UCRT, not MSVC's;
semantics match documented MSVC behavior, but the real MSVC build still
needs Windows CI.

Defect B — no cancel polling during dispatch (P1)

Root cause: winux_ffi_call checked the cancel callback once, before
dispatch (src/ffi/ffi.cpp:327-329 at the time of the report); a 12.61 s
sort then ran a further 9.01 s after ^C. CommandRegistry::dispatch is
noexcept, so checkpoints cannot throw — they must bail out through
normal return paths.

Alternatives rejected: worker-thread + abandon (borrowed process-global
state — cwd/env/std/argv + g_ffi_lock — would be restored while the
abandoned thread still runs); TerminateThread (can leave g_ffi_lock
held forever); CancelSynchronousIo (cancels blocked I/O only, not the
sort phase); closing borrowed handles from a watchdog (handle-recycling
race + closes host-owned handles).

Fix: a CancelWatchdog thread in winux_ffi_call polls the host's
cancel callback every 20 ms while dispatch runs and raises a shared atomic
flag (request_ffi_cancel() / ffi_cancel_requested() /
clear_ffi_cancel() in src/utils/console.cppm, never set in the exe form,
so the checks are dead code there). sort checks the flag at loop
boundaries — after each 1 MB flush in write_records_to_file /
write_records_to_stdout, every 4096 lines in external_sort::consume,
per iteration in the merge loop, and on the run() error paths — and stops
silently; winux_ffi_call then reports WINUX_FFI_ERR_CANCELLED (-1006)
regardless of the applet's return code. A TempCleanup RAII guard removes
chunk temp files on every exit path (no-op on the normal path). The
watchdog is joined before the call returns, so it never outlives the
borrowed ctx; thread-creation failure degrades to no mid-dispatch polling
for that call; a throwing host callback is caught and treated as cancel
(it must not std::terminate the host). Worst-case latency for the
reported case is one 8 MB chunk sort (~0.2–0.5 s), because external_sort
sorts per 8 MB chunk — the in-sort phase is bounded by chunk size, not the
whole input. (A throwing comparator for mid-sort abort was considered and
rejected: noexcept dispatch boundary, no exception-cancellation
precedent in the tree, and no Windows box to debug it on.)

The "cancelled" string used internally is provably never user-visible —
every propagation point intercepts when the flag is set — so no i18n key
or catalog sync is needed. No other user-visible messages were added.

Scope: checkpoints cover sort only (the reported B case). Other
commands' checkpoints are follow-ups; tier admission already restricts
FFI to short-lived commands.

Change surface

7 files, fix commit d4a1a9f8 (+943/−26) + style commit fd31e05b
(clang-format 20 on the changed lines only; the tree is not clean under
clang-format 20 as a whole, so no whole-file reformat):

  • src/ffi/ffi.cpp — StdBorrow rebind + flush, CancelWatchdog, cancel
    translation in winux_ffi_call
  • src/ffi/winux_ffi.h — docs only, no ABI change (rebind + host
    re-query contract, watchdog polling requirements)
  • src/utils/console.cppm — cancel flag accessors
  • src/commands/sort.cpp — B checkpoints + TempCleanup
  • examples/ffi-harness/harness.cpp — redirect and cancel modes
  • examples/ffi-harness/smoke.ps1 — cases 3c/3d (real-DLL matrix only)
  • examples/ffi-harness/README.md — DLL-face test modes docs

Not touched: tiers-manifest.tsv, tier/claim logic, DEFAULT_ENABLED
(still false, per the 2026-11-01 ruling), .github/workflows/*.
Note: sort's manifest blocker ("writes std::cout directly") is now
addressed by the CRT rebind, but tier promotion needs the separate R1–R7
tier audit, not this PR. Fact C (no tier2 rows in the shipped tiers.tsv)
is a release-shape issue and is out of scope here.

Regression tests

Verification done

  • harness.cpp compiles with mingw-w64 (x86_64-w64-mingw32-g++,
    -std=c++17, object produced; only pre-existing GetProcAddress
    cast warnings, same pattern as the existing code).
  • CRT rebind experiment under wine64: ALL PASS (see Defect A above).
  • clang-format 20 dry-run: no violations on the changed lines
    (remaining violations in these files are pre-existing baseline lines).

Not verified — needs CI / real machine

  • MSVC compile of ffi.cpp (C++23 modules, manual _flushall
    declaration, std::thread), console.cppm, sort.cpp — only
    Windows CI can check this.
  • smoke.ps1 3c/3d against the real DLL (Windows runner).
  • The original 2026-11-01 evidence cases end-to-end through niubash,
    including the host re-query contract (host must not cache raw HANDLE
    values across calls).

CI note

ffi-prototype.yml triggers only on PRs to main/master and pushes to
feat/ffi-prototype — a PR targeting feat/ffi-prototype triggers no
workflow automatically
, so this PR is expected to show no checks. That
is not a green signal; merging needs a maintainer decision (stacked on
#1426; also note main's build-winuxcmd.yml x64-default is itself red
at baseline). Do not merge on CI signal alone.

…tch (#1487)

Defect A: applets read stdin via std::cin and write stdout via
std::cout/fwrite(stdout), i.e. through the DLL CRT fds, which stayed
bound to the host's console handles no matter what SetStdHandle did.
StdBorrow now rebinds fds 0/1/2 to duplicates of the ctx handles
(_close + _open_osfhandle), invalidates the console layer's cached
handles, resets the sticky pipe-closed flags, and flushes C stdio with
_flushall across the borrow boundary so buffered output lands on the
borrowed handles.

Defect B: the host cancel callback was only checked before dispatch.
A watchdog thread now polls it every 20ms while dispatch runs and
raises a shared flag; sort checks the flag at loop boundaries and
stops silently, and winux_ffi_call reports WINUX_FFI_ERR_CANCELLED.

Regression tests: harness redirect mode (6 calls, one process, ctx
handles changing between calls, incl. a 12MB multi-run merge case)
and cancel mode (3M-line sort, cancel at 300ms), wired into
smoke.ps1 cases 3c/3d (real-DLL matrix only).
clang-format 20 with the repo .clang-format, limited to the lines
this fix added (the tree is not clean under clang-format 20 as a
whole, so no whole-file reformat). One #define comment shortened
to a single line instead of clang-format's line continuation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants