Skip to content

fix(shift): throw ExecutionLimitError when $# exceeds maxArrayElements - #734

Open
abhiramshaji-cyber wants to merge 25 commits into
vercel-labs:mainfrom
abhiramshaji-cyber:fix/shift-bounded
Open

abhiramshaji-cyber wants to merge 25 commits into
vercel-labs:mainfrom
abhiramshaji-cyber:fix/shift-bounded

Conversation

@abhiramshaji-cyber

@abhiramshaji-cyber abhiramshaji-cyber commented Nov 4, 2026 •

Copy link
Copy Markdown

A host that passed a huge $# in env could make shift, function calls or $* hang or crash, and now they stop at once with ExecutionLimitError.

This is the follow up to the shift loop from #729 (thanks again @jamalkamaladdin for spotting it), reworked the way @privatenumber decided in review: a bounded positional count instead of BigInt and two shift paths.

What this code is for

$# is the number of positional parameters ($1, $2, ...). Scripts set it through set --, function calls and source, but a host can also pass "#" in env when it calls new Bash(...). shift, function calls, getopts and every positional expansion ($*, "$@", ${#@}, ${@:n}, ${!#}) read $# and then loop from 1 to $#.

Before this PR

A host calls new Bash({ env: { "#": "1000000000", "1": "a", "2": "b" } }) and runs shift; echo "$*".

  1. handleShift reads $# with Number.parseInt(ctx.state.env.get("#") || "0", 10): 1000000000.
  2. It loops from 1 to $#, calling env.get and pushing one value per slot into an array.
  3. $* and the other positional readers in expansion/ read $# the same way and loop over the same range.
  4. The script hangs, or crashes with Invalid array length once the array cannot grow.

After this PR

Same host, same script.

  1. handleShift reads $# through positionalCount(ctx).
  2. positionalCount parses it exactly as before, then compares it with ctx.limits.maxArrayElements (1000000 by default).
  3. 1000000000 is above that, so it throws ExecutionLimitError("positional parameter limit exceeded (1000000)", "array_elements").
  4. The script stops with exit code 126 in about 55 ms, and the same error comes from $*, "$@", a function call or any other reader. That includes $# inside an array subscript, so ${a[$#]}, a[$#]=z, a=(['a[$#]']=x), unset 'a[$#]' and [[ $# -gt 0 ]] stop too instead of falling back to a[0] or an ordinary exit 1 or 2.

A script whose $# is at or below the limit takes the same path as on main.

The diagram

flowchart LR

classDef box fill:#eef1ff,stroke:#4c5bd4,color:#111827
classDef bad fill:#ffd6d6,stroke:#cc0000,color:#111827,stroke-width:3px
classDef good fill:#c8f0c8,stroke:#008800,color:#111827,stroke-width:3px

subgraph BEFORE["BEFORE: $# = 1000000000 hangs or crashes"]
direction TB
  B1["host seeds $#, script runs shift or $*"] --> B2["handleShift or a $* reader"]
  B2 --> B3["Number.parseInt reads $#"]
  B3 --> B4{"loop from 1 to $#"}
  B4 -->|"$# is huge"| B5["hang or Invalid array length"]
  B4 -->|"$# is small"| B6["works"]
end

subgraph AFTER["AFTER: exit 126 in about 55 ms"]
direction TB
  A1["host seeds $#, script runs shift or $*"] --> A2["handleShift or a $* reader"]
  A2 --> A3["positionalCount reads $#"]
  A3 --> A4{"THE CHANGE: $# above maxArrayElements?"}
  A4 -->|"yes"| A5["ExecutionLimitError, exit 126"]
  A4 -->|"no"| A6["same loop as main, works"]
end

B1 ~~~ A1

class B1,B2,B3,B6 box
class A1,A2,A3,A6 box
class B4,B5 bad
class A4,A5 good

linkStyle 3 stroke:#cc0000,stroke-width:5px
linkStyle 8 stroke:#008800,stroke-width:5px

style BEFORE fill:#fff5f5,stroke:#cc0000,color:#111827
style AFTER fill:#f3fff3,stroke:#008800,color:#111827
Loading

The change

The fix is positionalCount(ctx) in the new helpers/positional-count.ts. It replaces all 17 inline Number.parseInt(ctx.state.env.get("#") ...) reads in shift, getopts, callFunction, expansion.ts and the files under expansion/. The if that throws is count > ctx.limits.maxArrayElements.

Three readers did not parse $# but follow it: the bare $# and the stored $@ in getVariable, and a bare for x; do in executeFor. They call positionalCount(ctx) first, so every path gives the same answer for the same $#.

$# is read only where positional work happens. computeIsEmpty calls positionalCount(ctx) only in its $* and $@ branches, so ${foo:-bar} never reads $#. hasQuotedMultiValueAt looks for a quoted plain "$@" in the redirect target first and reads $# only when it finds one, so echo ok > file never reads it either.

A bare for x; do also walks the stored $@ with matchAll(/[^ ]+/g) and appendBoundedElements, instead of split(" "). A host can seed a small $# next to a $@ with any number of words, and the loop now throws for-loop expansion element limit exceeded (N) once it passes maxArrayElements instead of building the whole list. Below the limit it gives the same words as split(" ").filter(Boolean) on main.

set --, function calls and source set $# from their own arguments, and the existing expanded argument check already rejects more than maxArrayElements of those, so they cannot write a $# above the limit. The new tests check that too.

Several catch blocks fall back when an array subscript or an arithmetic value fails to evaluate: getVariable and isVariableSet in expansion/variable.ts, the subscript, integer and nameref fallbacks in simple-command-assignments.ts, declare, readonly, unset, test -v, the [[ ]] arithmetic operand in conditionals.ts, let, and the [[ ]] and (( )) handlers in interpreter.ts. The index fallbacks for a compound array assignment like a=(['a[$#]']=x), ${a[i]:=v} and local a[i]=v work the same way. Each of these catch blocks now starts with rethrowFatalExecutionError(error) from fatal-execution-error.ts, as @jamalkamaladdin suggested, so the limit error from positionalCount, an abort and a security violation are no longer turned into a[0], 0 or a plain exit 1 or 2. Other errors still take the same fallback as on main.

The earlier BigInt, sparse shift and set -u / set -- changes on this branch are reverted, so those files match main.

What changes for a user

  • Scripts, functions, source and set -- behave exactly as on main whenever $# is at or below maxArrayElements, including a host seeded $# exactly at the limit.
  • A host seeded $# above the limit makes the first command that reads it stop with exit code 126 and positional parameter limit exceeded (N), instead of hanging or crashing.
  • A host seeded $# above the limit does not touch commands that never read it: ${foo:-bar}, ${HOME:+set} and echo ok > file work as on main.
  • A bare for x; do over a host seeded $@ with more than maxArrayElements words stops with exit code 126, even when $# is small.
  • $# inside an array subscript (including a compound array assignment), [[ ]], (( )) or let stops the same way when it is above the limit, instead of reading a[0] or carrying on after an error message.
  • A non numeric $# from the host behaves as on main.
  • Below the limit, shift still walks 1 to $# on every call, as on main. That is the same cost as a script that ran set -- $(seq 1000000) itself, and was accepted in review.
  • Tests: helpers/positional-count.test.ts covers each reader above the limit, a count exactly at the limit, a huge count with default limits, a non numeric $#, set -- and function arguments past the limit, ${foo:-bar}, ${HOME:+set} and a plain redirect with $# above the limit, a bare for over a $@ with too many words, and $# inside a subscript, a compound array assignment, declare, readonly, a nameref write, unset, test -v, [[ ]], let and (( )) (each of those fails without the fix). The bash comparison suite passes, and the rest of the suite shows no new failures.

shift looped up to $# to read and clear parameters, so a $# seeded
through the environment made it build and rewrite that many slots
before any limit applied. It now stops at the first parameter that is
not set, capped at $#, so the work follows real state.
@vercel

vercel Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

@abhiramshaji-cyber is attempting to deploy a commit to the Vercel Labs Team on Vercel.

A member of the Team first needs to authorize it.

@auto-maintain

auto-maintain Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

🤖 auto-maintain review

Automated, advisory triage for @abhiramshaji-cyber's PR. Facts below are read from the GitHub API.

Check Result
Author's merged PRs (this repo) 0 — ⚠️ first-time contributor
Account established ✅ (age 445d · 30 followers · 146 public repos)
Commits signed/verified ✅ 25/25
Changeset included ✅ (.changeset/positional-count-limit.md)

Review panel: 🟡 medium highest severity

just-bash maintainer code review: 🟢 low

No actionable correctness or maintainability issues found in the complete diff.

General code review: 🟢 low

No actionable correctness issues found in the complete diff.

Adversarial security: 🟡 medium

The limit blocks the immediate exhaustion path, but function calls can permanently poison reusable interpreter state when it triggers.

  • packages/just-bash/src/interpreter/functions.ts:95 — `positionalCount()` can throw after function-call state has already been pushed but before the cleanup `try/finally` exists. A hostile oversized `$#` therefore leaves `callDepth`, call stacks, and local scopes corrupted across later `exec()` calls. Validate `$#` before mutating state or include setup in the cleanup region.

Adversarial security (second opinion): 🟢 low

Focused hardening change: a shared positionalCount() helper bounds host-seeded $# against maxArrayElements, the bare `for` loop over $@ is now bounded, and broad catch blocks rethrow fatal ExecutionLimit/Abort/SecurityViolation errors instead of swallowing them. I verified all $# reads are routed through the guard (only the save/restore sites in functions.ts and source.ts read it raw, which is safe), the hasQuotedMultiValueAt and computeIsEmpty rewrites are behavior-preserving, matchAll(/[^ ]+/g) is equivalent to the prior split(' ').filter(Boolean), and all rethrowFatalExecutionError import paths resolve correctly. No dependency, CI, build, network, process-execution, or install-script changes; no obfuscation; stated intent matches actual behavior. No actionable security findings.

Standard Bash and host portability: 🟢 low

No actionable Bash or host-portability issues found.

Posted by auto-maintain. This automated code review is advisory; a human maintainer makes the call.

The first version capped the count at the parameters it could walk, which
changed $# for sourced files with more than nine arguments, stopped
while [ $# -gt 0 ] loops from ending when $# was above the set
parameters, and left later parameters behind after a gap. The count, the
range check and the new $# now follow $# exactly as before, and only the
data move is limited to the numbered keys that exist.
@abhiramshaji-cyber abhiramshaji-cyber changed the title fix(shift): walk only the positional parameters that are set fix(shift): move only the positional parameters that are set Nov 4, 2026
The previous commit left slots without a stored value unset, while main
sets every slot up to the new $# (empty when missing), which set -u,
${N-x} and [ -v N ] can tell apart. Main's walk now runs unchanged
whenever $# is within the environment size or maxArrayElements, and only
a $# beyond both moves the stored keys alone.
@abhiramshaji-cyber abhiramshaji-cyber changed the title fix(shift): move only the positional parameters that are set fix(shift): stop a seeded $# from crashing shift Nov 4, 2026
…rflows

The previous bound used the environment size and maxArrayElements, but
main's walk succeeds far above both. The switch now sits exactly where
the full walk would exceed the JavaScript limits measured on Node 24:
2 ** 27 array elements, or 2 ** 24 Map entries counting the new slots and
$@. Below that, shift runs main's code unchanged. Above it, $# is counted
down with BigInt so loops past 2 ** 53 still end.
The engine measured caps made the switch depend on V8 and still let a
seeded $# drive millions of slots per shift. The switch is back at
max(env.size, maxArrayElements), so the work is bounded by real entries
or the host's own limit on every engine. Above it, slots with nothing
stored behind them stay unset, which only a host seeded $# can reach,
and $# still counts down with BigInt past 2 ** 53.
Above the bound, the range check and the subtraction now use BigInt on
the digits of $# and the shift count, and stored keys are matched with
BigInt, so large values no longer round. $# is read once and the out of
range error is shared by both paths. Tests pin the existing walk below
the bound and the exact results past 2 ** 53.
…size

The walk used to switch on count > max(env.size, maxArrayElements), so
${2-U} and [ -v 2 ] changed with the number of unrelated variables, and a
$# just under maxArrayElements still built and walked a 1,000,000 slot
array on every shift. Now there is one behavior: each stored $1..$# key
moves down by n and slots with nothing behind them stay unset. The keys
are found by walking 1..$# when $# <= env.size and by scanning env
otherwise, so both give the same keys and the work is bounded by
min($#, env.size).
BigInt parsed $# and every numeric env key on each shift with no length
limit, so a host seeded value of a million digits made every shift slow.
Numbers now keep at most 19 significant digits, the width bash reads as
intmax_t. A longer shift count is always out of range, a longer $# stops
with an ExecutionLimitError, and stored keys longer than $# are skipped
before any parsing.
Gaps now stay unset after shift, so a set -u script that read one of
them (source with more than nine arguments before vercel-labs#729, or a host seeded
$# above the stored keys) died with "unbound variable" where main printed
an empty line. getVariable now raises the nounset error for $N only when
N is above $#, which is what bash means by $#. The sourced file test also
checks the moved values.
The common walk used BigInt counters and was about 2.4x slower than main.
When $# is at most env.size it now walks with plain numbers and moves
each stored key in place, which is a little faster than main; BigInt is
only used for the env scan. shift 0 and the out of range check run
before the $# bound again, so shift 0 keeps returning 0. A $# above
intmax_t max now fails with status 1 instead of throwing an
ExecutionLimitError, and the tests use maxExecutionTimeMs instead of
wall clock asserts and cover both sides of 2 ** 63 - 1.
The parser and the stored key move now live in helpers/stored-params.ts.
shift checks the $# bound before the range check, so every shift other
than shift 0 on a $# above 2 ** 63 - 1 gives the same error. set -u reads
$# with the same bounded parser instead of parseInt, which rounded above
2 ** 53 and reparsed a long $# on every reference. set -- now removes the
stored keys up to the old $# before its existing walk, so a gap left by
shift no longer keeps later keys alive. The host limit tests no longer
set maxArrayElements, which shift does not read, and the sourced file
test checks exact values with and without vercel-labs#729.
After moveStoredParams removed $1 to $#, the existing walk still started
at 1, found nothing and stopped, so keys above the old $# (the caller's
$10 and $11 inside a sourced file, or a stored key past a seeded $#)
survived where main cleared them. The walk now starts at $# + 1. The
sourced set -u test pins the output without vercel-labs#729 instead of probing for
it.
The sourced set -u test pinned output that changes once vercel-labs#729 stores $10
and later, so it now uses a seeded gap that does not depend on vercel-labs#729. New
tests cover set -u with a non numeric or too large $#, where every $N
past the stored keys still errors, and set -- with a seeded $# above
env.size, which takes the scan path. The changeset now says shift 0
still returns 0 above 2 ** 63 - 1 and describes the set -- clearing.
@abhiramshaji-cyber

Copy link
Copy Markdown
Author

Thanks so much for the careful review, all three points were spot on and the repros made them easy to confirm.

2bfa05b: shift now moves only the $1..$# keys that are actually stored, so the work no longer grows with a seeded $#. It walks 1..$# when $# is at most env.size and scans env once otherwise, and both find the same keys, so ${2-U} and [ -v 2 ] no longer change with unrelated variables. A seeded $# of 1000000 with 2000 shifts went from about 215 s to under 100 ms.

76a0e37, d1d5d5f and ba8e700: $# is read from at most 20 digits and exactly up to 2 ** 63 - 1, and stored keys longer than $# are skipped before any parsing. Above that bound, shift 0 still returns 0 like main and every other shift fails with status 1. The walk uses plain numbers, so draining 20000 arguments is a little faster than main (10.3 s against 12.8 s).

22e0607, ba8e700 and a2df117: since gaps now stay unset after a shift, set -u treats $1 to $# as set, reading $# with the same bounded parser, and set -- removes every stored key up to the old $# and keeps clearing the keys right above it, so scripts that ran on main keep running.

ac23d5c adds tests for the seeded gap under set -u, set -u with an unusable $#, and set -- with a large seeded $#. Every test passes with and without #729 applied, and the PR description lists every behaviour change from main.

Hey @jamalkamaladdin, hope you're doing well! Does keeping gaps unset sound right to you, or would you rather shift throw an ExecutionLimitError when $# is above maxArrayElements, the way "$@" does? Happy to switch, and I'd really love any tips.

@abhiramshaji-cyber

Copy link
Copy Markdown
Author

Hi @jamalkamaladdin, hope you're doing well, and I know you have a lot on your plate, so no rush at all! Just checking in: the review feedback is addressed in 2bfa05b and the commits after it, and I'm happy to change anything, including having shift throw an ExecutionLimitError instead if you'd prefer. Would anything else help on my side?

@privatenumber privatenumber added awaiting-review Maintainer review or re-review is next. Does not imply approval or merge readiness. bug Something isn't working p1 Prompt action for substantial impact. Priority is not acceptance or a delivery promise. shell Parsing, quoting, expansion, pipelines, redirection, and shell execution labels Nov 20, 2026
@abhiramshaji-cyber

Copy link
Copy Markdown
Author

Hi @privatenumber, hope you're doing well! I know there's a lot on your plate, so please take your time. I left a note here on the 16th and wanted to check in with you directly, since I think you're the right person to ask. The auto-maintain points are addressed in 2bfa05b and the commits after it. Is there anything else that would help, or anything you'd like done differently? I'm glad to rework it however suits you best, including having shift throw an ExecutionLimitError instead, and I can bring the branch up to date with main too. The two Vercel checks are just waiting on someone from the team to authorize the deploy, whenever it's convenient. Thanks so much!

@privatenumber

Copy link
Copy Markdown
Collaborator

To answer your question on sparse gaps vs ExecutionLimitError: let's throw ExecutionLimitError when $# exceeds a safe positional-count limit (such as maxArrayElements) rather than supporting sparse 64-bit counts via BigInt and two shift paths.

Reasons:

  1. CONTRIBUTING.md explicitly excludes 64-bit integers, so adding BigInt parsing up to 2^63 - 1 plus a separate sparse-scan shift path adds significant complexity for a synthetic host-seeded env edge case.
  2. Accepting huge $# values in shift still leaves $* (src/interpreter/expansion/variable.ts) synchronously iterating and allocating across 1..$#, which hangs on billion-scale counts.
  3. Keeping sparse gaps unset introduces inconsistent positional-parameter views: ${2-U} treats a gap as unset, set -u treats it as set, $@ skips gaps (b d), and $* includes them (b d).

If we enforce a bounded positional-count limit with ExecutionLimitError (covering both shift and positional expansion like $*), we fix the hang cleanly without BigInt or sparse-parameter semantics.

Restores shift, set --, set -u and the shift tests to main, per the review decision to bound $# with ExecutionLimitError instead.
Every reader of $# goes through positionalCount, so shift, function calls, getopts and every positional expansion share one bound.
@abhiramshaji-cyber abhiramshaji-cyber changed the title fix(shift): stop a seeded $# from crashing shift fix(shift): throw ExecutionLimitError when $# exceeds maxArrayElements Dec 2, 2026
@abhiramshaji-cyber

Copy link
Copy Markdown
Author

Hey @privatenumber, hope your week's going well, and thanks so much for taking the time to lay that out, the three reasons made the call really easy to follow. I reworked it the way you suggested.

  • f410917 drops the BigInt parsing, both shift paths and the set -u / set -- changes, so those files match main again.
  • 2827122 adds a small positionalCount(ctx) helper that every reader of $# now goes through. It parses $# the same way main does and throws ExecutionLimitError (array_elements) when the count is above maxArrayElements. That covers shift, function calls, getopts, $*, "$@", $@, $#, ${#@}, ${@:n}, ${!#} and a bare for x, so there are no gaps and every path sees the same count. A seeded $# of a billion now fails right away instead of hanging.
  • set --, function calls and source already can't grow $# past the limit, because the expanded argument check rejects those calls first. The new tests pin that down too.
  • a9adaaa replaces the old shift tests with one file covering each path above, plus a count exactly at the limit and a non numeric $#, which behaves as before.

I also merged main in. I reused maxArrayElements as you suggested, and I'm happy to switch to a dedicated limit if that ever reads better. Thanks again!

@auto-maintain

auto-maintain Bot commented Dec 2, 2026

Copy link
Copy Markdown

⚠️ auto-maintain: review severity raised to 🔴 high

A new push changed this PR and the review now contains a higher-severity finding. See the updated review comment above.

@abhiramshaji-cyber

Copy link
Copy Markdown
Author

Thanks for the careful review, all three points held up when I tried them, and the repros made them quick to confirm. 62aaeba fixes each one:

  • computeIsEmpty now reads $# only in the $* and $@ branches, so ${foo:-bar} and ${HOME:+set} work again when a host seeds a large $#.
  • hasQuotedMultiValueAt looks for a quoted "$@" first and reads the count only when it finds one, so echo ok > file no longer fails.
  • A bare for x now walks the stored $@ lazily and throws ExecutionLimitError (array_elements) once it passes maxArrayElements, so a small $# next to a huge $@ can't build an unbounded list anymore. Loops within the limit behave exactly as on main.

New tests in positional-count.test.ts cover all three and fail without the change. The full suite, typecheck and lint pass.

@privatenumber, for the bare for x I kept main's splitting of $@ here and only bounded it, since #729 switches it to read $1 to $# directly. Would you rather I fold that into this PR instead? Happy either way, and thanks again for your time!

…metic fallbacks

Catch blocks that fall back on a failed array subscript or arithmetic evaluation, plus the [[ ]] and (( )) error handlers, swallowed the positional limit error, so ${a[$#]} read a[0] and [[ $# -gt 0 ]] kept going instead of stopping.

@vercel vercel Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional findings

  1. packages/just-bash/src/interpreter/simple-command-assignments.ts:523-533 — When a compound array assignment evaluates an indirect subscript containing an over-limit $#, its fallback still swallows ExecutionLimitError and writes to index 0 instead of stopping.

    Fix on Vercel

@auto-maintain

auto-maintain Bot commented Dec 4, 2026

Copy link
Copy Markdown

⚠️ auto-maintain: review severity raised to 🟡 medium

A new push changed this PR and the review now contains a higher-severity finding. See the updated review comment above.

…hmetic fallbacks

Swap the hand written ExecutionLimitError rethrows for the shared helper, so aborts and security violations pass through too, and cover the compound array, ${a[i]:=v} and local a[i]=v index fallbacks, where a=(['a[$#]']=x) wrote to index 0 instead of stopping.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting-review Maintainer review or re-review is next. Does not imply approval or merge readiness. bug Something isn't working p1 Prompt action for substantial impact. Priority is not acceptance or a delivery promise. shell Parsing, quoting, expansion, pipelines, redirection, and shell execution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants