Repository navigation
fix(spawn): unified GNU execvp child resolution for Windows spawners (PATH-only, POSIX PATH normalization) - #1169
Conversation
WinuxCmd commands that spawn subprocesses handed a bare command name to CreateProcessW with lpApplicationName == NULL, so the Win32 fallback order (application directory -> cwd -> System32 -> Windows -> PATH) decided the image. Any child name colliding with a System32 binary (timeout, sort, find, more, tree, hostname, choice, ...) silently resolved to the Windows binary, and PATH values exported by POSIX shells (rubash#149/#331: '/c/...' drive spellings mixed with ':' separators) are unparseable for Win32 SearchPath. utils:childproc implements GNU execvp semantics for Windows: - normalize_path_entries: splits mixed ':'/';' PATH strings and converts '/c/...' (and /cygdrive/) entries to Windows form; - resolve_child_command[_in_path]: explicit relative/absolute operands are used as given, bare names are searched ONLY in PATH entries -- no application directory, no cwd, no implicit System32/Windows fallback (an unset PATH falls back to the system directories, the execvp _CS_PATH analog); - plan_child_launch: builds the CreateProcessW (application name, command line) pair, routing .cmd/.bat candidates through COMSPEC; - resolve_shell_command_first_word: rewrites the first word of a shell-mediated command string (watch, split --filter) to its PATH-resolved absolute form; - child_spawn_exit_status / child_status_to_win32_error: shared 127/126 mapping and diagnostics.
Commands that spawn a user-specified child now resolve it through
winux::childproc::plan_child_launch instead of the Win32 default search
or per-command SearchPath wrappers:
- env: replaces the private resolve_executable (cwd-first scan,
semicolon-only PATH split) with the helper; the modified PATH from
NAME=VALUE assignments is honored via path_override. GNU deviation
removed: a bare operand no longer resolves from the current
directory.
- nice/nohup/stdbuf: previously passed the bare name to CreateProcessW
(System32 shadows PATH); also gain PATHEXT batch discovery.
- time/timeout: SearchPathW batch wrappers deleted; resolution now
PATH-only. timeout gains the missing GNU diagnostic on resolution
failure ('timeout: failed to run command ...', exit 127).
- xargs: resolution through the helper while keeping its cmd /C-aware
command-line quoting (command_line_override).
- find: -exec/-execdir children resolve from PATH; the System32
shadow for colliding names is gone.
Verified against GNU coreutils 9.4 in WSL: with a fake bin directory
shadowing System32's where.exe, all eight spawners now pick the PATH
entry under clean, POSIX-mixed, and POSIX-only PATH values (pre-fix
they ran System32's binary or failed), and missing children report the
GNU-shaped 127 diagnostic.
- diff --diff-program / diff3 --diff-program: the subsidiary program is resolved from PATH (CreateProcessW now also takes the resolved image as lpApplicationName; diff3 pipes stdout as before). - dir/vdir: the external AGENTS.md CHANGELOG.md CMakeLists.txt CMakePresets.json CONTRIBUTING.md CONTRIBUTING_ZH.MD DOCS LICENSE PROJECT_VERSION README-zh.md README.md TemplateLicense.lict build-vs cmake examples packaging resources scripts src tests fallback resolves from PATH. - install -s / --strip-program: strip resolves from PATH. - watch / split --filter: the command string is mediated by cmd.exe, whose own search cannot parse POSIX PATH entries; the first shell word is rewritten to its PATH-resolved absolute form before the spawn (unresolved words are left for the shell to report verbatim). Intentionally NOT converted (documented in the spawner inventory on the PR): ldd emulates the Windows loader search order (SearchPath with the Win32 defaults is the semantic there), wpm spawns a fixed internal tool (System32 bsdtar) rather than a user command, and Main�s shim relaunch uses an explicitly discovered path.
tests/unit/childproc pins the GNU execvp contract for every converted
spawner: a fake bin directory shadows System32's where.exe and must
win under a clean Windows PATH, a POSIX-mixed PATH ('/c/...' + ';'
tails), and a POSIX-only PATH; extensionless operands must discover
.cmd scripts through PATHEXT; explicit relative paths keep working;
missing children exit 127 with the GNU diagnostic shape.
tests/unit/env and tests/unit/timeout children that were addressed by
bare name from the current directory now use an explicit relative
path -- matching execvp, which never searches the cwd for a bare
operand.
…antics nohup_wrapped_command_own_version_is_not_intercepted asserted that 'nohup printf.exe --version' prints 'printf (WinuxCmd)'. That expectation was an accident of the pre-#1169 resolution order: the Win32 default search (application directory first) resolved the bare 'printf.exe' to the WinuxCmd hardlink sitting next to nohup.exe regardless of PATH. Under the unified GNU execvp semantics a bare operand is searched in PATH only, so a machine whose PATH carries a GNU printf (CI runners see coreutils 8.32 through Strawberry/Git) correctly resolves the wrapped command to that binary and the identity assertion fails while the option-parsing invariant still holds. Pin the pipeline PATH to WINUXCMD_BIN_DIR -- the activated-winuxcmd- shell scenario the test intends -- so the bare-name resolution lands on the WinuxCmd printf deterministically on every machine. The 'nohup does not intercept the wrapped --version' invariant is unchanged.
|
CI x64 lane red test disposition ( Diagnosed as option (a) -- the test had baked in the old accidental resolution order. CI's own log proves the resolver behaved correctly: Fix: the test now pins |
…y, tput stdin-preservation contract pinned, junction tests privilege-skip (#1171) * fix(find): resolve POSIX drive-form start points via the shared operand boundary (#1170) find was the only tool-layer exception to the boundary contract B2 audit: touch/ls/env/timeout/xargs/rm all accept explicit POSIX path operands, but find's start-point operands went straight into std::filesystem, so "find /c/Windows/System32/attrib.exe -maxdepth 0" failed with "No such file or directory" while the native "C:/..." spelling worked (-exec child lookup was already unified by #1169). Route every start point through winux::native_path::normalize_api_operand, the same helper the other tools use for their operands: command-line roots (parse_roots), -files0-from entries, and the -files0-from source operand. Native and relative forms pass through unchanged; POSIX drive forms (/c/..., /d/..., /cygdrive/c/...) fold to their native spellings. GNU attestation: findutils 4.9.0 under WSL takes POSIX absolute start points verbatim (rc=0). RED->GREEN covered by find.find_accepts_posix_drive_form_start_points, which drives a /c/... directory root, a /c/... regular-file root (-maxdepth 0), and traversal below a POSIX-form root. * test(grep): skip junction symlink cases without symlink privilege (#1168) grep_r_skips_cross_junction_trees_without_crashing and grep_R_warns_and_terminates_on_junction_cycle called the throwing std::filesystem::create_directory_symlink directly, so on hosts without symlink-creation privilege (non-admin, no Developer Mode) both tests died with an unhandled filesystem_error (Win32 error 1314, "A required privilege is not held by the client") instead of skipping. The exists() guard after the call was unreachable because the throwing call never returned. Add the same create_directory_symlink_or_skip helper the other unit test files carry (ls/readlink/touch/unlink/find): raw CreateSymbolicLinkW with SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE, printing a SKIPPED line with the GetLastError() code and returning false on failure. Non-admin full-suite runs go back to all-green (the 2811-run legacy of 2809 passed / 2 failed). * test(tput): pin the GNU stdin-preservation contract across all tput paths (#1166) GNU tput answers capability queries from the terminfo database alone and never consumes stdin -- success or failure -- so scripts like "printf 'aq' | { tput lines; IFS= read -rsn1 k; ... }" keep their data. The issue reports WinuxCmd's tput draining the pipe on the terminfo-less failure path. Analysis at this tree's HEAD: tput.cpp is byte-identical to v1.1.5 (47 lines, a fixed capability table, no terminfo lookup) and no shared startup layer (main/console/pager/dispatcher) reads stdin; in a pure-Win32 cleanroom (CreateProcess with pipe stdin, write end held open until child exit, leftover measured via PeekNamedPipe) the failure path (unknown capability, rc=1), the success path (clear, rc=0), and the missing-operand path all leave the piped "aq" fully intact. The drain reported against the NiuBash 1.4.0 bundle could not be reproduced from this tree; its terminfo lookup does not exist here. Deliverable per the issue's own fix list is the GNU differential test: the test framework gains an opt-in Pipeline::probe_stdin_leftover mode (keeps the stdin write end open until the child exits, reports unconsumed bytes in CommandResult::stdin_leftover), and three tput tests pin the contract so any future stdin read on any tput path fails the suite. WSL ncurses 6.4 attestation: GNU tput preserves the pipe on success and failure.
…u/sed, CHANGELOG #1167/#1169 (#1178) * fix(seq): batch stdout into 64 KiB chunks + integral to_chars fast path (issue #1173) safePrint issues one WriteFile per call, so per-line emission paid a kernel transition two-three times per line (~30us/line piped; 100k lines ~332ms while GNU needs ~5ms). Lines now assemble into a 64 KiB buffer flushed in large chunks, integral first/increment sequences (default fixed format, precision 0, no --format/-w, |operands| <= 2^52) emit through std::to_chars like GNU seq.c's integer bypass, and the floating path drops the per-line size-query snprintf round trip. 100k lines, release build: seq 332ms -> ~45ms, seq | wc 903ms -> ~45ms (GNU/WSL oracle: 7-10ms; residual is the ~40ms Windows process spawn). Byte stream unchanged: new seq_large_range_buffered_output_matches_gnu_bytes pins 588895 bytes/100000 lines across several flush rounds. * fix(du,sed): POSIX drive-form operands resolve through the shared boundary (issue #1174) du rejected '/d/...' operands with ENOENT while accepting 'D:/...' and sed could not read them either — the L2 self-parse contract (tools resolve POSIX operands themselves) was unevenly applied. Both now route operands through native_path::make_api_path_operand_w/normalize_api_operand, the same boundary grep/wc/head/find already use: - du: traversal operands (and -X exclude files, --files0-from sources) fold '/d/src', '/cygdrive/d/src' and /dev pseudo-paths to their Win32 form; operand line and child entries agree on the resolved forward-slashed spelling (Savannah #13956) while the #1159 trailing-separator collapse and error messages keep the operand text as typed. - sed: input operands (glob patterns included) fold before expansion/open, and with -i the folded path is what gets replaced; -f script files and the r/w/W script-embedded paths resolve the same way. Diagnostics and the '='/F filename display keep the operand text as typed. GNU oracle (WSL coreutils): du -sh /usr -> '8.5G /usr' rc=0. New tests cover the dual forms: du -sh '/d/...' vs 'D:/...', sed -n 1p, sed -i and sed -f through '/d/...' paths. * docs(changelog): record the #1167 ntfs-noise docs round and #1169 spawn resolver in [Unreleased] (issue #1175) #1169 (GNU execvp-style child resolution: PATH-only bare-name search with no cwd/System32 shadowing, POSIX PATH spellings normalized) and #1167 (touch NTFS literal-glob platform deviation documented, test exemption registered) were merged without a CHANGELOG entry. PR #1171's own fixes (#1170/#1168/ #1166) were already recorded at merge time (d4210c7), so no duplicate entry is added for it.
Problem
Every WinuxCmd command that spawns a child process handed a bare command name to
CreateProcessWwithlpApplicationName == nullptr. Two systematic bugs follow (both reproduced on Windows 10/11):lpApplicationName == nullptrthe image is resolved asapplication directory -> current directory -> System32 -> Windows -> PATH. Any child name that collides with a System32 image (sort,find,timeout,more,tree,hostname,choice,where, ...) silently resolved to the Windows binary even when the caller's PATH pointed at the GNU-compatible one first./c/...drive spellings mixed with:separators inside the;-separated Windows form. Win32SearchPathW/CreateProcessWcannot split or open those entries, so resolution either failed (false ENOENT) or fell back to System32.GNU reference (coreutils 9.4 in WSL):
execvpsearches PATH only — no application directory, no cwd, no implicit System32 fallback.Fix:
utils:childproc(new shared helper)normalize_path_entries— splits mixed:/;PATH strings; converts/c/...and/cygdrive/c/...entries to Windows form; a:is a drive separator only right after a single drive letter.resolve_child_command[_in_path]— explicit relative/absolute operands are used as given (with PATHEXT completion); bare names are searched only in normalized PATH entries. An unset PATH falls back to the system directories (theexecvp_CS_PATHanalog). Resolution failures distinguishNotFound(127),NotExecutable(126),NotADirectory(126).plan_child_launch— builds the(lpApplicationName, lpCommandLine)pair forCreateProcessW: native image = resolved path + command line keeping the caller's spelling forargv[0](execvp parity);.cmd/.bat= routed through%COMSPEC%with/d /s /c.resolve_shell_command_first_word— for shell-mediated spawners (watch,split --filter): rewrites the first shell word to its PATH-resolved absolute form before_popen(cmd.exe searches cwd/System32 ahead of unparseable PATH entries; unresolved words are left for the shell to report verbatim).child_spawn_exit_status/child_status_to_win32_error— shared 127/126 mapping and diagnostics.Spawner inventory (all spawn sites in
src/)Converted — user-visible child resolution
envrun_command;-only PATH split (root cause 2)PATH=overrides honored viapath_override; dead resolver deletednicenohupstdbuftimeSearchPathWbatch finder; native → Win32 defaulttimeoutSearchPathWbatch finder; native → Win32 defaulttimeout: failed to run command ..., 127)xargslaunch_processcmd /C-aware quoting viacommand_line_overridefindrun_child(-exec/-execdir/-ok/-okdir)diff--diff-program=PROGRAMCreateProcessA, naive quoting)CreateProcessW, resolved image)diff3--diff-program(read_diff_via_program)dir/vdirlsfallback (only whenlsis not registered in-process)install-s/--strip-programstripwatch_popen(shell-mediated)split--filter(shell-mediated)Reviewed, intentionally NOT converted
ldd.cppresolve_dllSearchPathWwith Win32 defaults) — that is the semantic being reported, not a GNU child spawnwpm.cpprun_process(tar.exe),launch_apply_update(staged exe)Main/main.cppshim relaunchlpApplicationNamewhich.cpp;only — candidate to reusenormalize_path_entriesin a follow-upgetconf.cppEverything else among the 178 command sources (
src/commands/*.cpp) never spawns a child.Before / after (fake bin directory shadows System32
where.exe;whereis not a WinuxCmd command, so pre-fix the wrong hit was always System32's)Batch children (
.cmd) now resolve through PATHEXT from PATH for all spawners (pre-fix only env/time/timeout handled them; nice/nohup/stdbuf/xargs/find reported ENOENT). Explicit relative/absolute operands keep working, including POSIX spellings (/c/...), which env previously rejected with a false ENOENT.rubash linkage assessment (normalize at the consumer or at the exporter?)
Recommendation: normalize at both, with different responsibilities.
envnormalizes per-invocation overrides (env PATH=/c/bin ...). This is the load-bearing half: WinuxCmd children are also spawned by arbitrary parents (CI, cmd.exe, other shells) whose PATH we do not control, and users can set PATH per invocation./c/...→C:\...and:→;at the exec boundary, the same split MSYS2 performs at process creation). Pure consumer-side normalization cannot fix non-WinuxCmd native children (git, editors, installers), which still see the raw POSIX PATH and misbehave in the same two ways. If rubash normalizes only at export, POSIX-facing consumers inside the shell must keep reading the internal POSIX value — hence "both, at the boundary".env,set, and child scripts observe as$PATH; gate it behind the same behavior rubash already uses forPATHconversion on native exec, and keepWINUX_...-style opt-outs consistent with existing rubash conventions (fix: execute timeout commands on Windows #149/[gap] install: with piped input fails if target file exists (uutils#12407) #331).Tests
tests/unit/childproc/childproc_unit_test.cpp: 17 cases — System32-name collision via clean/POSIX-mixed/POSIX-only PATH for env, timeout, xargs,find -exec, nice, nohup, stdbuf; PATHEXT batch discovery from PATH; explicit relative paths; GNU-shaped 127 diagnostics.tests/unit/envandtests/unit/timeout: children that were addressed by bare name from the cwd now use explicit relative paths (execvp never searches the cwd for a bare operand).main).watch.I18N
No keyed user-visible text changed: the new diagnostics reuse each command's existing raw-literal message shape (
win32_posix_error_text), matching the surrounding code. A freshi18n_sync.py prepareextract is key-identical to the published catalog (3 release keys); nowinuxcmd-i18nchange or VERSION bump required. (Themain.*/sdiff.*key drift visible in a fullvalidatepredates this PR and is unrelated.)