Repository navigation
WIP: FFI prototype — winuxcore.dll ABI v2 shell + host harness - #1426
Closed
caomengxuan666 wants to merge 15 commits into
Closed
caomengxuan666 wants to merge 15 commits into
caomengxuan666 wants to merge 15 commits into
Conversation
All presets forced BUILD_FFI=ON while option(BUILD_FFI) defaults OFF and src/ffi was absent, so every preset configure emitted the missing-sources warning and silently forced the cache OFF (drift recorded in ffi-route AUDIT 2.3). Non-FFI presets now set OFF; ffi-only keeps ON as its purpose. Also refresh the stale option and warning comments that claimed the FFI sources are not distributed. Refs unixwin/niubash#567
…type Resurrect the DLL shell from the public baseline d62be40^ with a new ABI (the v1 winux_execute shape is deliberately not revived: no env, no stdin, buffer copy-back, no cancellation - AUDIT 2). ABI v2: winux_ffi_abi_version / winux_ffi_init(explicit install root + locale snapshot) / winux_ffi_call(ctx) carrying wide argv (byte-exact), the full env block, an absolute cwd, raw stdin/stdout/stderr HANDLEs (handle pass-through, no capture layer), the ABI version and a cancellation callback. Exports via explicit winuxcore.def only; entries are exception-proof at the DLL boundary. The shell is thin: it borrows cwd/env/std-handles under the process FFI lock and calls the unchanged CommandRegistry::dispatch, so Tier-1 (cp rm rmdir mkdir touch chmod cat sed mkfifo tty) is reachable in-process. tiers.tsv is generated at build time from the audited tiers-manifest.tsv (incl. the rm -i/-I per-call shape fallback). examples/ffi-harness: standalone host implementing the DESIGN 3.2/4.1 loader - versioned side-by-side layout + current.txt pointer, pre-load SHA-256 pinning, LoadLibraryExW with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32, never CWD/PATH, load-once; NIU_WINUXCMD_FFI off declines everything to the spawn form, every failure is fail-closed with a reason code. Demo doubles (demo/) exercise the loader where the real DLL is unbuilt. .github/workflows/ffi-prototype.yml: dedicated Windows MSVC build + smoke matrix + artifact provenance for this surface. Refs unixwin/niubash#567
CMake's import-std synthesis rejects targets whose compile features resolve to cxx_std_17 once module targets exist in the tree (CI generate error on @cmake_cxx_std@synth_*). The harness and demo sources are C++17-shaped but compile cleanly as C++23; align the property with winuxcmd-commands instead of fighting the machinery.
_CRT_DISABLE_PERFCRIT_LOCKS (active via the shared PCH) macro-rewrites the fflush token to _fflush_nolock, which the imported std module does not export (MSVC C2039). The exe form does not flush around dispatch either - applets own their stream flushing - so the calls were not load-bearing; remove them and record why.
…n pwsh) [Linq.Enumerable]::SequenceEqual has no resolvable overload from PowerShell for byte[] arguments; compare SHA-256 of the captured output file against the payload file instead.
rm reads its invocation arguments through __argc/__wargv. In the exe form those globals are the applet's own arguments; in winuxcore.dll they belong to the DLL's own CRT instance, which never ran an exe startup for the applet. Observed under validation: __argc >= 2 with __wargv == NULL, so rm's --no-preserve-root abbreviation scan read __wargv[1] at address 0x8 and took an access violation before doing any work (every rm FFI call returned WINUX_FFI_ERR_EXCEPTION and was rescued by the spawn fallback). ArgvBorrow installs the ctx argv for the duration of the call: __wargv[0] is the applet name (consumers scan from index 1, exactly like the exe form), ctx.argv follows verbatim, NULL entries borrow as empty strings. Saved values are restored on scope exit, alongside the existing cwd/env/std borrows. The narrow __argv is not synthesized: no consumer in the tree reads it and the ctx carries wide strings.
/EHa is load-bearing. ffi.cpp's borrow/lock guards are RAII objects in winux_ffi_call's frame; under /EHsc an SEH fault raised inside dispatch (the rm access violation) is caught by the boundary catch(...) but unwinds WITHOUT running those destructors, leaving the process FFI mutex locked for the life of the process — every later call in the process failed 'resource deadlock would occur'. /EHa makes SEH unwinds run the destructors, so a contained fault restores all borrowed process state and releases the lock. Also stage winuxcore.sha256 next to the staged DLL (write_pin.cmake, bare lowercase hex): the per-version file is the loader's pinned-hash source; the package-root SHA256SUMS remains the zip-level manifest written by packaging. The pin is installed with the layout as well.
shape_matches judged argv by substring: any token containing the shape letter anywhere counted as a flag cluster, so 'rm -- -weird.txt' (a filename) was misjudged as an interactive -i call and declined. The judgment is structural now: '--' ends option territory (later tokens are operands, never shapes), exact tokens match before it, and a short shape matches a cluster only when the token is a pure cluster (one leading '-', ASCII letters only). Add 'sequence' mode: one process, one DLL load, N rotations of in-process calls (touch/cat/cp/rm/chmod; subset for the demo doubles) with per-call tier/shape eligibility checks, applet-success and file-state assertions, and no spawn fallback. The one-call-per-process form cannot see a fault that wedges the DLL's serialization lock — this mode exists to catch exactly that class.
The harness prints route=ffi BEFORE the call, so a call that faults in-process and is rescued by the spawn fallback still satisfied the old '-match route=ffi' assertions (the ffi-rm case passed while every rm call was throwing). FFI cases now also require the absence of the ffi-call-failed line and of any DLL boundary diagnostic. New sequence-multi-call case runs the harness sequence mode (25 rotations in one process, no fallback) against the real layout; the demo-doubles run passes its cat/cp/rm subset. A lock-wedging fault now fails CI instead of passing silently.
Start-Process -PassThru with redirected streams can leave ExitCode unpopulated ($null) even after -Wait, which failed the sequence-multi-call case despite 'SEQUENCE OK reps=25 calls=125' in its own output. WaitForExit() before reading ExitCode makes the observation reliable.
Second Start-Process -PassThru gotcha: with redirected streams, ExitCode also stays $null unless the process Handle is accessed before WaitForExit. Do both, and include the observed exit code in the case detail so a failure here is self-diagnosing.
The combined -and chain failed on the runner although exit=0, the output contained 'SEQUENCE OK' and stderr was empty. Evaluate each term separately (guarding the possibly-$null Get-Content results) and print all three in the case detail.
This was referenced Oct 31, 2026
…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.
fix(ffi): rebind CRT std fds to ctx handles and poll cancel mid-dispatch (#1487)
Member
Author
|
FFI prototype deferred per the #1487 verdict (0/7 prerequisites; host module removed). Dossier: DOCS/ffi-1487/REVIVAL-DOSSIER.md. |
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.
WIP: FFI prototype (P1 of the FFI route design,
ffi-route/DESIGN.md§7.3) — WinuxCmd-sidewinuxcore.dllshell + standalone host harness. Prototype only: the niubash-side provider lands in a separate line after the AGENTS.md ban supersede is merged.Refs unixwin/niubash#567
Scope (this branch only):
CMakePresets.json: clear theBUILD_FFI: "ON"drift — presets now align withoption(BUILD_FFI ... OFF); onlyffi-onlykeeps ON.src/ffi/**: resurrect the DLL shell from the public git baselined62be40^with a new ABI v2 (the oldwinux_executeABI is deliberately NOT revived: no env, no stdin, buffer copy-back, no cancellation — seeffi-route/AUDIT.md§2). New surface:winux_ffi_abi_version(),winux_ffi_init(explicit install root + locale snapshot),winux_ffi_call(ctx)with wide argv, full env block, absolute cwd, stdin/stdout/stderr HANDLE pass-through (no capture layer), ABI version and a cancellation callback. Exports via explicit.def. Entry points are exception-proof (try/catch → rc + stderr).CommandRegistry::dispatch;tiers.tsvgenerated at build time (incl. per-call shape fallbackrm -i/-I).examples/ffi-harness/**: host harness implementing the DESIGN §3.2/§4.1 loader — versioned side-by-side layout,current.txtpointer, pre-load SHA-256 verification against a pinned manifest,LoadLibraryExWwithLOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|LOAD_LIBRARY_SEARCH_SYSTEM32, never CWD/PATH, load-once;NIU_WINUXCMD_FFIunset/0 declines everything to the spawn path,=1enables in-process calls; every failure is fail-closed with a distinguishable reason code (dll-missing / hash-mismatch / abi-mismatch / ...).Do not merge yet — prototype evidence (Wine matrix + CI MSVC build) is being collected on this branch.