Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: catch runtime panic #2484

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions gnovm/pkg/gnolang/machine.go
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,20 @@ const (
// main run loop.

func (m *Machine) Run() {
defer func() {
if r := recover(); r != nil {
switch r := r.(type) {
case []Exception:
panic(m.buildPanicString(r))
case error:
m.Panic(typedString(r.Error()))
default:
m.Panic(typedString(fmt.Sprintf("%v", r)))
}
m.Run()
}
}()

for {
if m.Debugger.enabled {
m.Debug()
Expand Down Expand Up @@ -2081,6 +2095,15 @@ func (m *Machine) CheckEmpty() error {
}
}

func (m *Machine) buildPanicString(exceptions []Exception) string {
// Build exception string just as go, separated by \n\t.
exs := make([]string, len(exceptions))
for i, ex := range exceptions {
exs[i] = ex.Sprint(m)
}
return strings.Join(exs, "\n\t")
}

func (m *Machine) Panic(ex TypedValue) {
m.Exceptions = append(
m.Exceptions,
Expand Down
8 changes: 1 addition & 7 deletions gnovm/pkg/gnolang/op_call.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package gnolang
import (
"fmt"
"reflect"
"strings"
)

func (m *Machine) doOpPrecall() {
Expand Down Expand Up @@ -422,12 +421,7 @@ func (m *Machine) doOpPanic2() {
// Keep panicking
last := m.PopUntilLastCallFrame()
if last == nil {
// Build exception string just as go, separated by \n\t.
exs := make([]string, len(m.Exceptions))
for i, ex := range m.Exceptions {
exs[i] = ex.Sprint(m)
}
panic(strings.Join(exs, "\n\t"))
panic(m.Exceptions)
}
m.PushOp(OpPanic2)
m.PushOp(OpReturnCallDefers) // XXX rename, not return?
Expand Down
18 changes: 18 additions & 0 deletions gnovm/tests/files/recover13a.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

func p() {
defer func() {
if r := recover(); r != nil {
println(r)
}
}()
i := 0
i = 1 / i
}

func main() {
p()
}

// Output:
// runtime error: integer divide by zero
22 changes: 22 additions & 0 deletions gnovm/tests/files/recover13b.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

type s struct {
el func()
}

func p() {
var el *s
defer func() {
if r := recover(); r != nil {
println(r)
}
}()
el.el()
}

func main() {
p()
}

// Output:
// interface conversion: gnolang.Value is nil, not gnolang.PointerValue
Loading