Repository navigation
runtime: cap shell variable size with MaxVariableBytes - #861
Merged
Merged
Conversation
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
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.
Summary
Repeated string doubling could exhaust host memory under every existing limit.
x=a; for i in $(seq 27); do x=$x$x; donereached a 128 MB value and ~450 MB RSS, and a few more iterations reach GBs. This PR addspolicy.Limits.MaxVariableBytes, which defaults to 32 MiB (headroom over the 8 MiBMaxFileBytes).User-visible behavior
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:=...},forvariables, andeval. Arrays count element bytes plus 16 bytes per element, so arrays of many tiny elements are bounded too.$(yes)and$(while :; do echo; done)stop at once.${x//pattern/replacement}results, checked before the string is built.readandmapfilestop buffering input once a value would exceed the cap.printfoutput, in both the shell builtin and theprintfcommand. A padded field is checked before it is built, soprintf '%*s' 2000000000 xno longer allocates 2 GB.forloop's word list are sized like an indexed array and held to the same cap. This stops positional-parameter and argv doubling:set -- "$@" "$@", and recursivef "$@" "$@".$_,BASH_EXECUTION_STRINGandBASH_REMATCHare exempt, because the shell derives them from data that is already bounded.Performance fix needed for the cap to matter. Dense tail appends in compound array assignment (
a+=(...)) and inmapfileno longer copy the whole list for every element. Both were O(n²), soa+=("${a[@]}")doubling and large mapfiles were CPU-bound long before any memory cap applied.Wiring. The limit is plumbed like
MaxBraceExpansionWordsin #855: runtime defaults,mergedLimits,mergeLimitOverrides, the conformance runner (32 MiB) and fuzztest (256 KiB). It reaches the interpreter throughinterp.RunnerConfig.MaxVariableBytesandexpand.Config.MaxVariableBytes.limitOverridePolicynow has pointer receivers, the same change #855 made, because gocritic'shugeParamfires onceLimitsgrows. Expect a trivial conflict in theLimitsstruct, 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
a[i]=x) still copy the whole list, about 2.7 ms per write on a 1M-element array. The profile shows onlyslices.Cloneplus GC. In-place mutation is unsafe because lists are shared copy-on-write across forked environments, including concurrent pipeline subshells, and across analysis snapshots.MaxCommandCountandMaxLoopIterationsbound 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 inexpand.Variable.Testing
internal/runtime/variable_limits_test.go(now includes printf width and repeated fields, theprintfcommand, positional/function-argument/fordoubling, 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:MaxOutputBytesin 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 allbuiltin-*, allvar-op-*,word-split,loop,func*andpositional.make lint: 0 issues.