Skip to content

Commit

Permalink
fix(gnovm): protect TypedValue stringer against deep recursivity (#3790)
Browse files Browse the repository at this point in the history
The protectedStringer is improved by limiting the successive number of
nested calls when constructing the string representation of a deeply
recursive value.

Fixes #3471.

---------

Co-authored-by: ltzmaxwell <ltz.maxwell@gmail.com>
  • Loading branch information
mvertes and ltzmaxwell authored Feb 21, 2025
1 parent 2c2c018 commit 85b3c0b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
16 changes: 13 additions & 3 deletions gnovm/pkg/gnolang/values_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@ type protectedStringer interface {
ProtectedString(*seenValues) string
}

// This indicates the maximum anticipated depth of the stack when printing a Value type.
const defaultSeenValuesSize = 32
const (
// defaultSeenValuesSize indicates the maximum anticipated depth of the stack when printing a Value type.
defaultSeenValuesSize = 32

// nestedLimit indicates the maximum nested level when printing a deeply recursive value.
nestedLimit = 10
)

type seenValues struct {
values []Value
nc int // nested counter, to limit recursivity
}

func (sv *seenValues) Put(v Value) {
Expand Down Expand Up @@ -46,7 +52,7 @@ func (sv *seenValues) Pop() {
}

func newSeenValues() *seenValues {
return &seenValues{values: make([]Value, 0, defaultSeenValuesSize)}
return &seenValues{values: make([]Value, 0, defaultSeenValuesSize), nc: nestedLimit}
}

func (v StringValue) String() string {
Expand Down Expand Up @@ -74,6 +80,10 @@ func (av *ArrayValue) ProtectedString(seen *seenValues) string {
return fmt.Sprintf("%p", av)
}

seen.nc--
if seen.nc < 0 {
return "..."
}
seen.Put(av)
defer seen.Pop()

Expand Down
12 changes: 12 additions & 0 deletions gnovm/tests/files/recurse1.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package main

func main() {
var x interface{}
for i := 0; i < 10000; i++ {
x = [1]interface{}{x}
}
println(x)
}

// Output:
// array[(array[(array[(array[(array[(array[(array[(array[(array[(array[(... [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})] [1]interface{})]

0 comments on commit 85b3c0b

Please sign in to comment.