Skip to content

fix(path): /tmp and /var/tmp resolve to per-user temp even with shell root - #103

Merged
caomengxuan666 merged 18 commits into
masterfrom
fix/tmp-prefers-tmpdir
Sep 14, 2026
Merged

caomengxuan666 merged 18 commits into
masterfrom
fix/tmp-prefers-tmpdir

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Fixes the rubash half of unixwin/niubash#94.

Problem

When a shell root is configured (niubash sets __RUBASH_SHELL_ROOT/WINUXSH_ROOT to the winuxcmd install tree), /tmp and /var/tmp resolved to <shell_root>\tmp and <shell_root>\var\tmp. For installs into non-user-writable directories such as C:\Program Files\Niubash, every /tmp redirection failed with permission errors.

Change

  • shell_path_to_windows on Windows resolves /tmp and /tmp/... to a per-user host temp dir: TMPDIR, then TEMP, then TMP. A TMPDIR that is itself the virtual /tmp (or nested under it) is ignored to avoid recursion; a TMPDIR under /var/tmp resolves against the temp-backed var/tmp base.
  • /var/tmp and /var/tmp/... resolve under a dedicated var\tmp child of the same temp source, so they stay writable and cannot collide with /tmp or unrelated %TEMP% contents.
  • ensure_var_tmp_dir creates that temp-backed directory instead of <shell_root>\var\tmp.
  • pwd's reverse logical-PWD mapping uses the resolved /tmp location rather than <shell_root>\tmp.

Regression tests

  • windows_tmp_prefers_tmpdir_even_with_shell_root
  • windows_var_tmp_stays_in_user_temp_even_with_shell_root
  • existing pwd test updated for the new /tmp mapping

Verification

  • cargo build clean.
  • cargo test path tests: 42 passed; pwd tests: 5 passed.
  • Script-file comparison vs WSL GNU Bash 5.3.0 (MSYS_NO_PATHCONV=1 wsl bash <file>): echo > /tmp/x; cat /tmp/x; echo > /var/tmp/x; cat /var/tmp/x produces identical output in both shells; on Windows the files land under %TEMP% and %TEMP%\var\tmp, not under the shell root.

caomengxuan666 and others added 18 commits September 14, 2026 11:24
…diagnostic

Two GNU expr.c-aligned arithmetic fixes:

1. Deferred array subscript evaluation in assignments (expr.c:1395-1401):
   When the lvalue has an array subscript and the next token is `=`, GNU
   skips expr_streval and saves the raw token string. The subscript is
   re-evaluated at bind time (after the RHS), so side effects in the RHS
   are visible to the subscript. For example, `a[n]=++n` with n=0 stores
   at a[1] (not a[0]) because ++n increments n before the subscript bind.

   Adds ArithLValue::IndexedRaw variant that captures the raw subscript
   text, resolved to Indexed in assign_lvalue after RHS evaluation.

2. Trailing-input diagnostic (expr.c:484-485):
   `curtok != 0` after EXP_LOWEST() reports "arithmetic syntax error in
   expression" with the unparsed remainder as the error token. For
   `(( x=9 y=41 ))` the error token is "y=41 " (trailing blank kept).
   Uses the raw expression display so trailing blanks survive.

   Adds ArithmeticErrorCategory::TrailingInput and trailing_input_token()
   helper that re-parses to find the unparsed remainder. Numeric
   assignment expressions (e.g. `7 = 43`) are excluded so they keep the
   "attempted assignment to non-variable" diagnostic.

arith suite: 57 → 48 diff lines
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
In remove_double_quoted_into, `\"` was emitted as a bare `"`, but the
expansion walker (expand_embedded_parameters_inner) treats bare `"` as a
quote delimiter and toggles in_double, silently dropping it. This made
`echo "a\"b"` print `ab` instead of `a"b`, and `recho $"hello, \"world\""`
print `hello, world` instead of `hello, "world"`.

Emit the data-double-quote marker (\x18) for `\"` inside double quotes,
matching the convention already used for `\"` outside quotes. The
expansion walker restores \x18 to `"` on output.

GNU source: subst.c string_extract_double_quoted keeps `\"` as a literal
quote that survives quote removal.

nquote suite: 57 → 53 diff lines
quote suite: 0 diff lines (clean)
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
execute_arithmetic_for_command incremented loop_depth before evaluating
the init expression but only decremented it when init succeeded. When
init failed (e.g. `for ((j=;;))` with empty RHS), loop_depth stayed at 1,
so a following `break` was treated as in-loop and silently aborted the
rest of the script instead of printing the out-of-loop diagnostic.

GNU 5.3 execute_arith_for_command always decrements loop_level after
the loop, even on init failure. The previous code matched the Git Bash
5.2 bug; switch to the GNU 5.3 behavior.

arith-for suite: 2 → 0 diff lines (clean)
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…readonly errors

Three GNU-aligned fixes in execute_declare_functions:

1. `declare -Fr` (function names + readonly filter) now lists only
   readonly functions as `declare -fr NAME`, matching GNU declare.def.
   Previously it printed `declare -f NAME` for all functions.

2. `declare -f -a` / `declare -f -i` / `declare -f -A` / `declare -f -n`
   are invalid option combinations (GNU declare_invalid_opts rejects
   att_function combined with att_array/att_assoc/att_integer/att_nameref).
   Now prints `declare: -X: invalid option` and returns 1 instead of
   printing the function body.

3. `declare -f +r NAME` on a readonly function now prints
   `declare: NAME: readonly function` and returns 1 (GNU declare.def:497).

errors suite: 31 → 19 diff lines
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…bstitution

In decode_old_style_backtick_source, a backslash before `"` inside
backticks (outside double quotes) was preserved as `\"`, but GNU
parse.y parse_matched_pair consumes the backslash via LEX_PASSNEXT
and adds the next character verbatim. This made
  recho "`echo \"Hello world!\"`"
print `\Hello world!\` instead of `Hello world!`, because the inner
echo received `\"Hello world!\"` (escaped quotes) instead of
`"Hello world!"` (real quote delimiters).

Now `\"` inside backticks becomes `"` (backslash consumed), matching
GNU parse_matched_pair behavior.

exp suite: 73 → 69 diff lines
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
GNU setattr.def includes `n` in ATTROPTS ("aAfnp"). For `readonly`,
`-n` sets undo=1, but undoing att_readonly is silently disallowed
(setattr.def lines 174-176: `if (undo && (attribute & att_readonly))
attribute &= ~att_readonly;`). So `readonly -n NAME` is an accepted
no-op that leaves readonly status unchanged.

Rubash previously rejected `-n` as an invalid option, printing
`readonly: -n: invalid option` and returning EX_USAGE. Now `-n` is
accepted in both the variable path (setattr::readonly_with_io) and
the function path (readonly_functions), matching GNU.

errors suite stderr: 129 → 127 diff lines
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
GNU execute_cmd.c:4887-4888 sets `special_builtin_failed = 1` when a
POSIX special builtin returns an error status > EX_SHERRBASE (256).
After the command (execute_cmd.c:1004-1017), if `posixly_correct &&
interactive == 0 && special_builtin_failed`, the shell exits with the
converted status. Rubash previously continued after special builtin
errors in POSIX mode, producing extra "after ..." lines that GNU does
not emit.

This commit ports the `special_builtin_failed` mechanism:
- Add `special_builtin_failed: Cell<bool>` to the Executor, reset
  before each simple command (command_dispatch.rs), checked after
  dispatch to exit the non-interactive POSIX shell.
- `return` outside a function (return.def:74 returns EX_USAGE=258):
  set the flag in execute_return (pwd_loop_builtins.rs).
- `unset` on readonly/invalid-identifier/non-unsettable (set.def:1046
  returns EX_UTILERROR=263): return EX_UTILERROR from unset_name, set
  the flag in execute_unset_with_stderr after builtin_status conversion.
- `unset` invalid option (set.def:855 returns EX_USAGE=258): return
  EX_USAGE_ORIG=258 from parse_unset_options, convert in the executor.
- `set` invalid option/option-name (set.def returns EX_USAGE=258):
  set the flag in execute_set when set_with_io returns EX_USAGE=2.

Verified against WSL GNU Bash 5.3.0:
- `bash -o posix -c 'return; echo after'` → exit 2, no "after" (was: 0)
- `bash -o posix -c 'readonly a=a; unset -v a; echo after'` → exit 1 (was: 0)
- `bash -o posix -c 'unset -v a-b; echo after'` → exit 1 (was: 0)
- `bash -o posix -c 'set -z; echo after'` → exit 2, no "after" (was: 0)
- `bash -o posix -c 'trap "echo bad" SIGNOSIG; echo after'` → exit 0 (unchanged, trap is non-fatal)
- Non-POSIX mode: all cases continue as before (unchanged)

errors suite: stdout 16 → 13 diff lines; stderr 127 → 127 (formatting)
lib tests: 381 passed; 0 failed

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…tution

split_shell_words_with_quote_info bypassed lexer quote removal for command
substitution bodies, so `$(echo \a)` kept the backslash where GNU removes it.
Apply GNU slashify_in_quotes semantics: outside quotes a backslash escapes
any character and is removed; inside double quotes it only retains meaning
before \, $, `, ", and newline; inside single quotes it is literal.

more-exp: 38 -> 28 diff lines, nquote: 39 -> 37, no regressions in exp/rhs-exp/quote/comsub/new-exp/errors.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
expand_assignment_alternate_mut used expand_parameter_word_mut which always
expands with Unquoted context. Inside double quotes, single quotes are data
not delimiters, so `${fox='$foo'}` with foo=bar should expand $foo and keep
the single quotes, yielding 'bar'. Now uses DoubleQuoted context with
decode_double_quotes_in_quoted_parameter_word and unescape_parameter_operator_result,
matching the +/- operator path (subst.c expand_string_for_rhs).

more-exp: 28 -> 26 diff lines, new-exp: no regression (61), all suites stable.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
decode_double_quotes_in_quoted_parameter_word only handled backslash before
CBSDQUOTE chars ($ ` " \ newline). Backslash before ordinary chars like \p
or \' was preserved, but GNU expand_word_internal with Q_DOUBLE_QUOTES
removes it (subst.c ~11678). Added a fallback '\' arm that drops the
backslash and keeps only the char.

rhs-exp: 6 -> 0, more-exp: 21 -> 19, no regression in other suites.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
GNU only splits on IFS characters produced by expansion, not literal
characters in the word. With IFS=+, $x+$y produces one field a+b, not
two fields a and b. Marked literal non-whitespace IFS chars with \x1c
before expansion so the field splitter can distinguish them from
expansion-produced IFS chars (subst.c field splitting with CTLESC).

more-exp: 21 -> 19 (a+b vs a b fix), ifs: 0, no regression.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
copy_dollar_paren_word and related span scanners didn't track quote state
when matching closing ) of $(...). A ) inside double quotes incorrectly
closed the command substitution. Now skips nested $(...) inside double
quotes as a unit in command_substitution_spans_whole_word, scan_substitution_spans,
and dollar_command_substitution (parse.y xparse_dolparen quote tracking).

$(echo "foo$(echo ")")") now produces foo) instead of foo)).
more-exp: 21 -> 19, comsub: no regression.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Replaced incomplete safe-char set with faithful implementation of GNU's
sh_backslash_quote (flags=3) from lib/sh/shquote.c. Now correctly
handles @, =, %, +, # (at position 0), ~ (at position 0 or after :/=),
and non-ASCII printable chars.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ates

braced_alternate_word_values only recognized literal $@/$* but missed
braced modified forms like ${*/}, ${*,,}, ${@/}, ${@,,}. Updated the
narrow check and positional_at check to use ${@/${* prefixes, and added
PF_ASSIGNRHS join+split path for non-whitespace IFS.

exp: 46 -> 37, no regression.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…me pending

Three lexer fixes from GNU source:
- \c? in $'...' now produces 0x7f (DEL) per chartypes.h TOCTRL, and
  trailing \c with no operand passes through literally (strtrans.c)
- A " inside single quotes carries \x18 data-double-quote marker when
  the word has content outside single quotes (nquote.tests line 27:
  $"hello", $"world" quoting)
- $name pending_name tracking in remove_double_quoted_into fixed for
  escaped $ before name chars

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
${#:foo} should return $# (5) since $# is non-empty, not compute length
of parameter "foo". ${#-posparams} should return $# since # is always set.
${#?} (bare, no error word) should return length of $? (1). Added
hash_is_special_param_with_operator guard so ${#-word}/${#+word}/${#=word}/
${#?word} skip the length-prefix route and use operator semantics, while
${#?} (bare) stays as length of $?. Also fixed substring parse for special
parameter names (#, ?, $, !, -, 0).

more-exp: 19 -> 7, no regression.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…$@ scan

Three fixes for ${@}/${*} with operators:
- quoted_positional_at_segments now skips ${...} bodies so "$@" inside
  ${undef-"$@"} is not treated as top-level positional-at (x${undef-"$@"}
  produced x} instead of x)
- quoted_braced_alternate_positional_at_values handles ${@-}/${@:-} when
  @ is set: returns one field per positional (like "$@")
- quoted_positional_at_word_values handles -/:-/+/:+ operators for @ and *
  in the for-loop word expansion path

more-exp: 11 -> 7, no regression.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… root

A shell root below a non-user-writable install dir (e.g.
C:\Program Files\Niubash) previously left the virtual /tmp read-only
because shell_path_to_windows only consulted TMPDIR when no root was
configured (unixwin/niubash#94).

- /tmp and /tmp/* now resolve through windows_tmp_base() unconditionally:
  the executor TMPDIR wins, a TMPDIR that spells the virtual /tmp itself
  falls back to the process temp dir so resolution cannot recurse.
- /var/tmp and /var/tmp/* resolve to <safe-temp>/var/tmp unconditionally;
  other /var children still map below the shell root.
- ensure_var_tmp_dir() creates the temp-backed var/tmp dir regardless of
  shell root, so /var/tmp works on read-only install roots.
- logical_pwd_if_current() already reverse-resolves through
  shell_path_to_windows, so 'cd /tmp; pwd' keeps reporting /tmp.

Verified against WSL GNU Bash 5.3.0 script-file run: redirection,
input redirect, cd /tmp, and /var/tmp round-trip match.
@caomengxuan666
caomengxuan666 merged commit 242e2a6 into master Sep 14, 2026
2 of 3 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/tmp-prefers-tmpdir branch September 14, 2026 09:14
caomengxuan666 added a commit that referenced this pull request Sep 16, 2026
…-backslash sh_double_quote

Compound array elements ran quote removal twice. The raw token first had
its backslash escapes decoded (`\"` -> data `"`), and the partially_quoted
pass then ran remove_shell_quotes over the DECODED text, which re-parsed
the data quote as an operator pair and stripped it. The order is now the
GNU one: remove_shell_quotes over the raw token (leaving escaped quotes
as \x17/\x18 data carriers), restore the carriers, then unquote. This
matches the storage-side behavior of quote.tests array6.sub and fixes
niubash #103 side findings against GNU bash 5.3.0(1) (WSL oracle):

  x=(q\"q)      stored qq        now q"q   (71 22 71)
  x=("q\"q")    stored q\"q      now q"q
  x=('a"b')     read back a\"b   now a"b
  x=("a\"b")    read back a\"b   now a"b
  x[1]=c\"d     read back c\"d   now c"d

The read-back half came from quote_array_value / quote_assoc_display_key
escaping a bare `"` as `\\"` (two backslashes) where shquote.c
sh_double_quote emits `\"`; the doubled backslash survived the storage
round-trip as a spurious literal byte. The declare storage path already
used the single-backslash form (storage.rs quote_double) and was correct.

Known remaining gap (pre-existing, not addressed here): an ANSI-C `$'...'`
element whose decoded value contains a quote reaches the storage split
with a bare untagged `"` (the upstream decoder does not emit the E010/
E011 markers on this path), so remove_shell_quotes treats it as an
operator pair: x=($'a"b') stores ab instead of a"b.

Tests: 3 new cases in tests/assignment_quote_roundtrip_regressions.rs;
cargo test --lib 397 passed; cargo fmt --check and
scripts/check-utf8-boundary-hygiene.sh clean.
caomengxuan666 added a commit that referenced this pull request Sep 16, 2026
fix(assignment): restore \x18 escaped-quote carrier in quoted-assignment fast path (niubash #103)
caomengxuan666 added a commit that referenced this pull request Sep 16, 2026
fix: niubash #106/#107/#108 regressions + restore #103 array fix lost in rescue merge
caomengxuan666 added a commit that referenced this pull request Sep 16, 2026
…WIP) over #111

Content reconciled from the offline local master (30d42e61, based on 9ac6170)
plus its uncommitted gnu-compat WIP, three-way merged over the PR #111 merge
(82b0f6f). Overlapping files (arrays.rs, arrays/storage.rs, lexer/mod.rs)
carry BOTH sides: the #103/#109 quote-carrier handling and the local
intl/array/trap batch. Leftover [DEBUG] eprintln instrumentation from the WIP
was stripped before landing.

Highlights:
- intl: nested same-shell script output ordering, IFS isolation,
  /usr/bin/printf fixture (30d42e61)
- lexer/executor batch: ANSI-C carrier handling, assignment expansion,
  parameter decode, conditional patterns, prompt expansion,
  temporary assignments, printf escape/path builtins, shell options
- docs: COMPATIBILITY-STATUS ledger (43 zero-diff caliber), README refresh

Full release test suite green on the merged tree; gnu-compat run-83 check
PASS=34 / DIFF=48 / TIMEOUT=1 (unchanged caliber).
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