Skip to content

fix(gnovm): correct GotoJump stmt-stack truncation for goto out of nested loops#5963

Open
omarsy wants to merge 2 commits into
gnolang:masterfrom
omarsy:claude/nifty-easley-589646
Open

fix(gnovm): correct GotoJump stmt-stack truncation for goto out of nested loops#5963
omarsy wants to merge 2 commits into
gnolang:masterfrom
omarsy:claude/nifty-easley-589646

Conversation

@omarsy

@omarsy omarsy commented Jul 15, 2026

Copy link
Copy Markdown
Member

Summary

Fixes a pre-existing interpreter crash: a backward goto that jumps out of three or more nested for/range loops panics with

runtime error: slice bounds out of range [:-1]

in Machine.GotoJump (gnovm/pkg/gnolang/machine.go). The crash is independent of any gas/profiler work — it reproduces on a clean tree.

Reproduction

package main

func main() {
	i := 0
top:
	println("i =", i)
	for a := 0; a < 2; a++ {
		for b := 0; b < 2; b++ {
			for c := 0; c < 2; c++ {
				i++
				if i < 3 {
					goto top
				}
			}
		}
	}
	println("done", i)
}

Before this PR the program panics on the first goto; go run on the equivalent Go program prints i = 0 / i = 1 / i = 2 / done 10.

Root cause

For a GOTO, the preprocessor records FrameDepth (loop/switch-clause frames crossed to reach the label). At runtime GotoJump reset the statement stack to the outermost popped frame's NumStmts:

m.Stmts = m.Stmts[:fr.NumStmts]              // (1) baseline reset
m.Stmts = m.Stmts[:len(m.Stmts)-depthFrames] // (2) extra pop — BUG

fr.NumStmts is captured before that frame pushes its own bodyStmt, and every inner loop pushes later, so line (1) already drops all depthFrames loop bodyStmts (plus any transient block bodyStmts) in one shot. Line (2) then subtracts depthFrames a second time:

  • When fr.NumStmts >= depthFrames: silently over-truncates, but the GOTO handler in op_exec.go immediately re-truncates m.Stmts to the target block's bodyStmt.NumStmts (re-growing the slice via retained capacity), masking the bug.
  • When fr.NumStmts < depthFrames (e.g. three loops directly under the function body → fr.NumStmts == 2, depthFrames == 3): the index underflows to [:-1] and panics.

The m.Blocks handling is not symmetric — after resetting to fr.NumBlocks it pops an additional depthBlocks, which is correct because BlockDepth counts scopes within the target frame. Statements have no equivalent second component.

The line was introduced in #4219 (which created GotoJump to pop loop frames), modeled on PopFrameAndReset's "reset then pop one sticky stmt". That extra pop is valid for a single-frame pop, but wrong when generalized to - depthFrames because fr there is the outermost of many popped frames.

Fix

Remove the redundant second truncation. m.Stmts[:fr.NumStmts] is the correct baseline (consistent with the neighboring Ops/Values/Exprs/Blocks resets), and op_exec.go authoritatively sets the final m.Stmts length afterward — so previously-working gotos are unchanged; this is a pure crash fix.

Testing

  • New regression filetest gnovm/tests/files/goto10.gno — panics before the fix, passes after (output verified against go run).
  • go test ./gnovm/pkg/gnolang/ -run Files -test.short — 0 failures.
  • Whole goto* / heap_alloc_gotoloop* / loopvar_goto* families pass.
  • Cross-checked semantics against real go run for 3- and 4-deep nesting, nested range loops, and gotos additionally crossing block scopes — all match.

Files

  • gnovm/pkg/gnolang/machine.go — remove the erroneous stmt-stack truncation (net one line of logic), with an explanatory comment.
  • gnovm/tests/files/goto10.gno — regression test.
  • gnovm/adr/pr5963_gotojump_nested_loop_stmt_underflow.md — ADR documenting the accounting bug.

Developed with AI assistance (Claude Code); all changes were reviewed by the author.

…sted loops

A backward `goto` that jumps out of three or more nested for/range loops
panicked with "slice bounds out of range [:-1]" in Machine.GotoJump.

GotoJump reset the statement stack to the outermost popped frame's NumStmts
(which already excludes every crossed loop's bodyStmt) and then subtracted
depthFrames from it a second time. Once depthFrames exceeded fr.NumStmts —
e.g. three loops directly under the function body, where fr.NumStmts == 2 but
depthFrames == 3 — the slice index underflowed to [:-1] and panicked. In
shallower cases it silently over-truncated, but the GOTO handler in op_exec.go
re-truncates m.Stmts to the target block's bodyStmt.NumStmts right after,
which masked the bug.

Remove the redundant second truncation. Add a regression filetest
(goto10.gno) covering a backward goto out of three nested loops, and an ADR.
@github-actions github-actions Bot added the 📦 🤖 gnovm Issues or PRs gnovm related label Jul 15, 2026
@Gno2D2 Gno2D2 added the review/triage-pending PRs opened by external contributors that are waiting for the 1st review label Jul 15, 2026
@Gno2D2

Gno2D2 commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

🛠 PR Checks Summary

All Automated Checks passed. ✅

Manual Checks (for Reviewers):
  • IGNORE the bot requirements for this PR (force green CI check)
Read More

🤖 This bot helps streamline PR reviews by verifying automated checks and providing guidance for contributors and reviewers.

✅ Automated Checks (for Contributors):

🟢 Maintainers must be able to edit this pull request (more info)
🟢 Pending initial approval by a review team member, or review from tech-staff

☑️ Contributor Actions:
  1. Fix any issues flagged by automated checks.
  2. Follow the Contributor Checklist to ensure your PR is ready for review.
    • Add new tests, or document why they are unnecessary.
    • Provide clear examples/screenshots, if necessary.
    • Update documentation, if required.
    • Ensure no breaking changes, or include BREAKING CHANGE notes.
    • Link related issues/PRs, where applicable.
☑️ Reviewer Actions:
  1. Complete manual checks for the PR, including the guidelines and additional checks if applicable.
📚 Resources:
Debug
Automated Checks
Maintainers must be able to edit this pull request (more info)

If

🟢 Condition met
└── 🟢 And
    ├── 🟢 The base branch matches this pattern: ^master$
    └── 🟢 The pull request was created from a fork (head branch repo: omarsy/gno)

Then

🟢 Requirement satisfied
└── 🟢 Maintainer can modify this pull request

Pending initial approval by a review team member, or review from tech-staff

If

🟢 Condition met
└── 🟢 And
    ├── 🟢 The base branch matches this pattern: ^master$
    └── 🟢 Not (🔴 Pull request author is a member of the team: tech-staff)

Then

🟢 Requirement satisfied
└── 🟢 If
    ├── 🟢 Condition
    │   └── 🟢 Or
    │       ├── 🟢 User davd-gzl already reviewed PR 5963 with state APPROVED
    │       ├── 🔴 At least 1 user(s) of the team tech-staff reviewed pull request
    │       └── 🔴 This pull request is a draft
    └── 🟢 Then
        └── 🟢 Not (🔴 This label is applied to pull request: review/triage-pending)

Manual Checks
**IGNORE** the bot requirements for this PR (force green CI check)

If

🟢 Condition met
└── 🟢 On every pull request

Can be checked by

  • Any user with comment edit permission

@davd-gzl
davd-gzl self-requested a review July 15, 2026 13:58
@omarsy
omarsy requested review from a team, ltzmaxwell and thehowl July 15, 2026 14:08

@davd-gzl davd-gzl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified on a94c909. Re-adding the deleted second truncation reproduces the slice bounds out of range [:-1] crash. Output matches go run byte-for-byte across for, range, and switch-clause frame crossings for 3- to 6-deep nesting.

@Gno2D2 Gno2D2 removed the review/triage-pending PRs opened by external contributors that are waiting for the 1st review label Jul 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

📦 🤖 gnovm Issues or PRs gnovm related

Projects

Development

Successfully merging this pull request may close these issues.

4 participants