Skip to content

runtime: cap shell variable size with MaxVariableBytes - #861

Merged
ewhauser merged 4 commits into
mainfrom
claude/keen-faraday-a282f1
Oct 19, 2026
Merged

ewhauser merged 4 commits into
mainfrom
claude/keen-faraday-a282f1

Conversation

@ewhauser

@ewhauser ewhauser commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Repeated string doubling could exhaust host memory under every existing limit. x=a; for i in $(seq 27); do x=$x$x; done reached a 128 MB value and ~450 MB RSS, and a few more iterations reach GBs. This PR adds policy.Limits.MaxVariableBytes, which defaults to 32 MiB (headroom over the 8 MiB MaxFileBytes).

User-visible behavior

  • Every shell variable write is checked in the interpreter's single write path (setVarObserved). That covers plain and += assignments, array and associative element writes, array literals and appends, declare/local/export/readonly, read, printf -v, mapfile/readarray, ${x:=...}, for variables, and eval. Arrays count element bytes plus 16 bytes per element, so arrays of many tiny elements are bounded too.
  • Intermediate values that one expansion step can grow without bound are also capped:
    • command substitution output, measured before trailing newlines are stripped. The substitution is cancelled as soon as it overflows, so $(yes) and $(while :; do echo; done) stop at once.
    • ${x//pattern/replacement} results, checked before the string is built.
    • read and mapfile stop buffering input once a value would exceed the cap.
    • printf output, in both the shell builtin and the printf command. A padded field is checked before it is built, so printf '%*s' 2000000000 x no longer allocates 2 GB.
  • A command's expanded argument list and a for loop's word list are sized like an indexed array and held to the same cap. This stops positional-parameter and argv doubling: set -- "$@" "$@", and recursive f "$@" "$@".
  • Going over the cap prints a message, leaves the variable unchanged, and exits the current shell with status 126, like the other budgets. Interactive shells abort only the command.
  • $_, BASH_EXECUTION_STRING and BASH_REMATCH are exempt, because the shell derives them from data that is already bounded.
$ gbash -c 'x=a; for i in $(seq 40); do x=$x$x; done; echo ${#x}'
x: value too large (limit 33554432 bytes), increase policy.Limits.MaxVariableBytes
$ echo $?
126
$ gbash -c 'x=$(yes); echo unreachable'
command substitution: value too large (limit 33554432 bytes), increase policy.Limits.MaxVariableBytes

Performance fix needed for the cap to matter. Dense tail appends in compound array assignment (a+=(...)) and in mapfile no longer copy the whole list for every element. Both were O(n²), so a+=("${a[@]}") doubling and large mapfiles were CPU-bound long before any memory cap applied.

Wiring. The limit is plumbed like MaxBraceExpansionWords in #855: runtime defaults, mergedLimits, mergeLimitOverrides, the conformance runner (32 MiB) and fuzztest (256 KiB). It reaches the interpreter through interp.RunnerConfig.MaxVariableBytes and expand.Config.MaxVariableBytes. limitOverridePolicy now has pointer receivers, the same change #855 made, because gocritic's hugeParam fires once Limits grows. Expect a trivial conflict in the Limits struct, defaults and merge functions when #855 lands.

SPEC. The default-limits list in SPEC.md §9 documents the cap, what it covers, the 126 behavior, the exemptions, and the gaps. The implementation note in §9.5 is updated, and the website security budget tables are updated.

Not changed

  • Keyed element writes (a[i]=x) still copy the whole list, about 2.7 ms per write on a 1M-element array. The profile shows only slices.Clone plus GC. In-place mutation is unsafe because lists are shared copy-on-write across forked environments, including concurrent pipeline subshells, and across analysis snapshots. MaxCommandCount and MaxLoopIterations bound the total number of writes, so the worst case is about (commands × one capped-size copy). That is comparable to other per-command work at the cap, such as ${x//a/b} on a 32 MB value. Removing it would need a persistent array representation in expand.Variable.
  • The argv check runs after expansion. At the 32 MiB default, peak RSS can reach roughly 400–550 MB on a list that overflows, because the expander's per-field overhead is larger than the 16 bytes the cap charges. It is still bounded.

Testing

  • internal/runtime/variable_limits_test.go (now includes printf width and repeated fields, the printf command, positional/function-argument/for doubling, and the argv boundary): the default stops doubling; 8 MiB values still work; overrides; a table of 28 assignment and expansion paths, each checking exit 126, the single message and empty stdout; the variable is left unchanged (seen from an EXIT trap); subshell, $(...) and pipeline status; an unbounded producer inside $(...) stops quickly; values exactly at the limit pass; array doubling now reaches the cap in under 0.5 s.
  • internal/printfutil: MaxOutputBytes in both dialects.
  • shell/expand/limits_test.go: the replacer size check in UTF-8 and byte locales, and the capped writer.
  • go test ./shell/... ./internal/shell/... ./internal/runtime/... ./internal/printfutil/... ./internal/fuzztest/... . passes. In ./internal/builtins, only the diff and ripgrep oracle tests fail, because their Nix binaries are not set locally.
  • make conformance-test CONFORMANCE_RUN='TestConformance/bash/oils/(append|array.*|assign.*|builtin-(read|printf|vars|bash)|command-sub|var-op-(patsub|bash)|var-sub.*|vars-special|nameref|ble-.*)\.test\.sh' passes. A wider slice also passes, adding all builtin-*, all var-op-*, word-split, loop, func* and positional.
  • make lint: 0 issues.

Add policy.Limits.MaxVariableBytes (default 32 MiB) so repeated string
or array doubling cannot exhaust host memory. The interpreter checks it
in its single variable-write path, covering every assignment form, and
also caps command substitution output, ${x//p/r} results, and the input
read and mapfile buffer. Going over prints a message naming the limit
and exits the current shell with status 126.

Dense array appends in compound assignments and mapfile no longer copy
the list per element, which kept those paths quadratic and CPU-bound
long before any memory cap applied.
printf built a whole padded field before writing it, so
printf '%*s' 2000000000 x allocated 2 GB. printfutil now stops once a
field or the running output would pass Options.MaxOutputBytes, and both
the builtin and the printf command pass MaxVariableBytes.

Expanded argument lists and for word lists are now sized like indexed
arrays and held to the same cap, so set -- "$@" "$@" and recursive
f "$@" "$@" doubling stop with status 126.
File-descriptor duplication compares writers with ==, and comparing a
struct value that holds a func panics, so $(script 2>&1) failed with
"shell execution failed".
# Conflicts:
#	SPEC.md
#	internal/conformance/runner.go
#	internal/fuzztest/fuzztest.go
#	internal/runtime/runtime.go
#	internal/shell/core.go
#	internal/shell/interp/api.go
#	internal/shell/interp/runner.go
#	policy/policy.go
@ewhauser
ewhauser enabled auto-merge (squash) October 19, 2026 06:37
@ewhauser
ewhauser merged commit 609b310 into main Oct 19, 2026
16 checks passed
@ewhauser
ewhauser deleted the claude/keen-faraday-a282f1 branch October 19, 2026 06:44
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