Skip to content

fix(spawn): unified GNU execvp child resolution for Windows spawners (PATH-only, POSIX PATH normalization) - #1169

Merged
caomengxuan666 merged 5 commits into
mainfrom
fix/unified-child-path-resolution
Oct 12, 2026
Merged

caomengxuan666 merged 5 commits into
mainfrom
fix/unified-child-path-resolution

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Problem

Every WinuxCmd command that spawns a child process handed a bare command name to CreateProcessW with lpApplicationName == nullptr. Two systematic bugs follow (both reproduced on Windows 10/11):

  1. Win32 default search order shadows PATH. With lpApplicationName == nullptr the image is resolved as application 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.
  2. POSIX PATH spellings are unparseable. rubash exports PATH verbatim (rubash#149/[gap] install: with piped input fails if target file exists (uutils#12407) #331): /c/... drive spellings mixed with : separators inside the ;-separated Windows form. Win32 SearchPathW/CreateProcessW cannot split or open those entries, so resolution either failed (false ENOENT) or fell back to System32.

GNU reference (coreutils 9.4 in WSL): execvp searches 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 (the execvp _CS_PATH analog). Resolution failures distinguish NotFound (127), NotExecutable (126), NotADirectory (126).
  • plan_child_launch — builds the (lpApplicationName, lpCommandLine) pair for CreateProcessW: native image = resolved path + command line keeping the caller's spelling for argv[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

Command Spawn site Child Resolution before After
env env.cpp run_command user command private resolver; cwd-first scan (GNU deviation); ;-only PATH split (root cause 2) helper; PATH= overrides honored via path_override; dead resolver deleted
nice nice.cpp user command none (Win32 default order) helper (+ PATHEXT batch discovery)
nohup nohup.cpp user command none helper (+ batch discovery)
stdbuf stdbuf.cpp user command none helper (+ batch discovery)
time time.cpp user command SearchPathW batch finder; native → Win32 default helper; SearchPath wrapper deleted
timeout timeout.cpp user command SearchPathW batch finder; native → Win32 default helper; SearchPath wrapper deleted; gains the missing GNU diagnostic (timeout: failed to run command ..., 127)
xargs xargs.cpp launch_process user command none helper, keeping xargs' cmd /C-aware quoting via command_line_override
find find.cpp run_child (-exec/-execdir/-ok/-okdir) user command none helper
diff --diff-program=PROGRAM user program none (CreateProcessA, naive quoting) helper (CreateProcessW, resolved image)
diff3 --diff-program (read_diff_via_program) user program none helper (stdout pipe unchanged)
dir / vdir external ls fallback (only when ls is not registered in-process) fixed bare name none helper resolve
install -s / --strip-program strip none helper resolve
watch _popen (shell-mediated) command string cmd.exe resolution first shell word substituted from PATH
split --filter (shell-mediated) command string cmd.exe resolution first shell word substituted from PATH

Reviewed, intentionally NOT converted

Site Why
ldd.cpp resolve_dll emulates the Windows loader DLL search order (SearchPathW with Win32 defaults) — that is the semantic being reported, not a GNU child spawn
wpm.cpp run_process (tar.exe), launch_apply_update (staged exe) package-manager internals: fixed tool (System32 bsdtar is the intended target), not a user-command operand; update relaunch uses an explicit path
Main/main.cpp shim relaunch payload discovered by explicit directory walk, passed as lpApplicationName
which.cpp lookup-only, spawns nothing; PATH parsing there still splits on ; only — candidate to reuse normalize_path_entries in a follow-up
getconf.cpp comment mentions CreateProcess limits only

Everything else among the 178 command sources (src/commands/*.cpp) never spawns a child.

Before / after (fake bin directory shadows System32 where.exe; where is not a WinuxCmd command, so pre-fix the wrong hit was always System32's)

Scenario env timeout time nice nohup stdbuf xargs find split --filter
clean fakebin PATH, before ok System32 System32 System32 System32 System32 System32 System32 shell/System32
clean fakebin PATH, after PATH PATH PATH PATH PATH PATH PATH PATH PATH
POSIX-mixed PATH, before System32 System32 System32 System32 System32 System32 System32 System32 not found
POSIX-mixed PATH, after PATH PATH PATH PATH PATH PATH PATH PATH PATH
POSIX-only PATH, before 127 (false ENOENT) System32 — — — — — — —
POSIX-only PATH, after PATH PATH — — — — — — —
missing child 127 + msg 127 (silent) → now 127 + GNU msg 127 + msg

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.

  • Consumer side (this PR) is now self-sufficient: every WinuxCmd spawner normalizes PATH before resolution, and env normalizes 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.
  • rubash side: the exporter should keep its POSIX PATH internally, but when spawning a native child it should export a Windows-normalized PATH (translate /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".
  • Risk note: normalizing at export changes what env, set, and child scripts observe as $PATH; gate it behind the same behavior rubash already uses for PATH conversion on native exec, and keep WINUX_...-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

  • New 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/env and tests/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).
  • Full suite: 2826 / 2828 (the 2 failures are pre-existing non-admin symlink-privilege tests in grep, identical on main).
  • Manually verified against WSL GNU coreutils 9.4 (PATH-order resolution, missing-child diagnostics) and live 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 fresh i18n_sync.py prepare extract is key-identical to the published catalog (3 release keys); no winuxcmd-i18n change or VERSION bump required. (The main.*/sdiff.* key drift visible in a full validate predates this PR and is unrelated.)

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.
@caomengxuan666

Copy link
Copy Markdown
Member Author

CI x64 lane red test disposition (nohup.nohup_wrapped_command_own_version_is_not_intercepted, fixed in 6d58a5c):

Diagnosed as option (a) -- the test had baked in the old accidental resolution order. CI's own log proves the resolver behaved correctly: nohup printf.exe --version printed printf (GNU coreutils) 8.32 with exit code 0, i.e. the new PATH-only execvp resolution correctly picked the GNU printf available on the runner's PATH (Strawberry/Git), and only the binary-identity assertion (printf (WinuxCmd)) failed. Pre-#1169 the test passed because the Win32 default search hit nohup.exe's application directory (the WinuxCmd hardlink sibling) before ever consulting PATH.

Fix: the test now pins PATH to WINUXCMD_BIN_DIR (the activated-winuxcmd-shell scenario it intends) with a comment documenting the accident and the design; the 'nohup must not intercept the wrapped --version' invariant is unchanged. Sibling tests that spawn bare echo/printf children assert output shape only, which GNU coreutils satisfy identically, so they needed no change. Full suite 2826/2828 locally (the 2 reds are the pre-existing non-admin symlink-privilege grep tests, also red on main).

@caomengxuan666
caomengxuan666 merged commit 0ee66d3 into main Oct 12, 2026
8 checks passed
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
…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.
@caomengxuan666
caomengxuan666 deleted the fix/unified-child-path-resolution branch October 13, 2026 02:09
caomengxuan666 added a commit that referenced this pull request Oct 13, 2026
…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.
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.

1 participant