Repository navigation
fix(ffi): rebind CRT std fds to ctx handles and poll cancel mid-dispatch (#1487) - #1599
Merged
Merged
Conversation
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1487 (defects A and B; fact C is out of scope — see below).
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:
StdBorrow::apply(
src/ffi/ffi.cpp) did onlySetStdHandle()+_setmode(fd, _O_BINARY).A CRT fd stays bound to the OS handle it had at CRT startup;
SetStdHandledoes not change the fd→HANDLE mapping. Applets go through the CRT fds:
sortreadsstd::cin(src/commands/sort.cpp:203,250,272) and writesstd::coutdirectly in the merge path (sort.cpp:1935);wcreadsstd::cin(wc.cpp:183,438);teeusesfwrite(..., stdout)(
tee.cpp:147);truses::fwrite(..., stdout)(tr.cpp:580). Sosort < words.txtread the host's console stdin (EOF →wcprinted 0)and
sort words.txt > o.txtwrote to the host's console stdout (36 MBsprayed to the terminal,
o.txtempty). The 23 no-redirect cases werebyte-identical because the applets are correct — only the wiring was
missing.
getStdOut()/getStdErr()insrc/utils/console.cppmcacheGetStdHandle()in thread_locals, andisStdoutConsole()caches the console-ness verdict.invalidateCachedHandles()exists ("call after SetStdHandle") but
ffi.cppnever called it, so along-lived host thread poisons the cache with the console handle on its
first call and every later
safePrintwrites there. This is why theprototype'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.
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 stickyg_stdout_pipe_closed/g_stdout_write_errorthread_locals persistedacross calls, so one broken pipe made later calls silently drop stdout.
Fix (
src/ffi/ffi.cpp,src/ffi/winux_ffi.h):StdBorrownow rebinds fds 0/1/2 to duplicates of the ctx handles(
_close(fd)+_open_osfhandle(dup)), callsinvalidateCachedHandles()and
clear_pipe_closed_flags()per call, and flushes C stdio with_flushall()before the swap and before restore (draining to theborrowed handles on exit; also discards any bytes a previous call
prefetched from a different stdin handle).
fflushis unspellable here —this TU builds with
_CRT_DISABLE_PERFCRIT_LOCKS, which macro-rewrites thetoken to
_fflush_nolock(see commitcc8335c3) — so_flushallisdeclared manually as
extern "C" int _flushall(void);.Handle ownership is the sharp edge:
_closealso closes the underlying OShandle (
_open_osfhandletransfers ownership to the fd), so both sidesare duplicated first — the fd's original handle is duplicated before
_close, and the ctx handle is duplicated before_open_osfhandle. TheDLL 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 callthe Win32 std slot may hold a duplicate of the previous handle. Hosts
must re-query std handles via
GetStdHandleafter each call and nevercache a raw
HANDLEvalue across calls. The in-tree hosts (harness,niubash) build the ctx per call from
GetStdHandle, so this holds — butniubash-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 andstd::coutmisses the redirect file;after
_close(1)+_open_osfhandle(dup),std::coutreaches the fileand 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_callchecked the cancel callback once, beforedispatch (
src/ffi/ffi.cpp:327-329at the time of the report); a 12.61 ssort then ran a further 9.01 s after ^C.
CommandRegistry::dispatchisnoexcept, so checkpoints cannot throw — they must bail out throughnormal return paths.
Alternatives rejected: worker-thread + abandon (borrowed process-global
state — cwd/env/std/argv +
g_ffi_lock— would be restored while theabandoned thread still runs);
TerminateThread(can leaveg_ffi_lockheld forever);
CancelSynchronousIo(cancels blocked I/O only, not thesort phase); closing borrowed handles from a watchdog (handle-recycling
race + closes host-owned handles).
Fix: a
CancelWatchdogthread inwinux_ffi_callpolls the host'scancel callback every 20 ms while dispatch runs and raises a shared atomic
flag (
request_ffi_cancel()/ffi_cancel_requested()/clear_ffi_cancel()insrc/utils/console.cppm, never set in the exe form,so the checks are dead code there).
sortchecks the flag at loopboundaries — after each 1 MB flush in
write_records_to_file/write_records_to_stdout, every 4096 lines inexternal_sort::consume,per iteration in the merge loop, and on the
run()error paths — and stopssilently;
winux_ffi_callthen reportsWINUX_FFI_ERR_CANCELLED(-1006)regardless of the applet's return code. A
TempCleanupRAII guard removeschunk 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::terminatethe host). Worst-case latency for thereported case is one 8 MB chunk sort (~0.2–0.5 s), because
external_sortsorts 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:
noexceptdispatch boundary, no exception-cancellationprecedent 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
sortonly (the reported B case). Othercommands' checkpoints are follow-ups; tier admission already restricts
FFI to short-lived commands.
Change surface
7 files, fix commit
d4a1a9f8(+943/−26) + style commitfd31e05b(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—StdBorrowrebind + flush,CancelWatchdog, canceltranslation in
winux_ffi_callsrc/ffi/winux_ffi.h— docs only, no ABI change (rebind + hostre-query contract, watchdog polling requirements)
src/utils/console.cppm— cancel flag accessorssrc/commands/sort.cpp— B checkpoints +TempCleanupexamples/ffi-harness/harness.cpp—redirectandcancelmodesexamples/ffi-harness/smoke.ps1— cases 3c/3d (real-DLL matrix only)examples/ffi-harness/README.md— DLL-face test modes docsNot touched:
tiers-manifest.tsv, tier/claim logic,DEFAULT_ENABLED(still
false, per the 2026-11-01 ruling),.github/workflows/*.Note:
sort's manifest blocker ("writesstd::coutdirectly") is nowaddressed 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
ffi-harness.exe redirect([ffi] winuxcore.dll 产品路径实证:调用不应用 shell 重定向(数据丢失)+ dispatch 期不轮询取消 + 出货认领面为空(niubash#727 门①③ 皆红) #1487-A): 6 calls in one process with ctxstd handles changing between calls — (1)
cat words.txtprimes theconsole cache, (2)
sort words.txtmust land insrt.out, (3)wc -lmust read 7 from stdin, (4)
sort words.txt words.txt, (5)sortfromstdin, (6)
sort ext.txt(12 MB, multi-run merge — the shape of the36 MB evidence case). All outputs content-asserted.
ffi-harness.exe cancel([ffi] winuxcore.dll 产品路径实证:调用不应用 shell 重定向(数据丢失)+ dispatch 期不轮询取消 + 出货认领面为空(niubash#727 门①③ 皆红) #1487-B): 3M-line sort (~39 MB), cancelcallback firing at 300 ms; requires rc == -1006,
cancel_ms < 0.75 × full_ms, and a short output file. Skips (CANCEL SKIP, exit 0) if theuncancelled baseline is under 1000 ms.
smoke.ps1cases 3c (redirect-multi-call) and 3d(
cancel-mid-dispatch), guarded to the real-DLL matrix (demo doublesimplement only cat/cp/rm); harness stdin is an empty file so the old DLL
reads EOF instead of blocking on a console.
Verification done
harness.cppcompiles with mingw-w64 (x86_64-w64-mingw32-g++,-std=c++17, object produced; only pre-existingGetProcAddresscast warnings, same pattern as the existing code).
(remaining violations in these files are pre-existing baseline lines).
Not verified — needs CI / real machine
ffi.cpp(C++23 modules, manual_flushalldeclaration,
std::thread),console.cppm,sort.cpp— onlyWindows CI can check this.
smoke.ps13c/3d against the real DLL (Windows runner).including the host re-query contract (host must not cache raw
HANDLEvalues across calls).
CI note
ffi-prototype.ymltriggers only on PRs tomain/masterand pushes tofeat/ffi-prototype— a PR targetingfeat/ffi-prototypetriggers noworkflow 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'sbuild-winuxcmd.ymlx64-default is itself redat baseline). Do not merge on CI signal alone.