Skip to content

Commit

Permalink
interp: recover in Eval and EvalPath
Browse files Browse the repository at this point in the history
Now Eval() and EvalPath() recover from internal panic and
return it as error with call stacks.

This fixes the case where user code calls os.Exit(1), which is
converted to panic() and breaks down the program.
  • Loading branch information
Bai-Yingjie committed Oct 8, 2023
1 parent da27c4f commit 48f8875
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions interp/interp.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,13 +498,29 @@ func (interp *Interpreter) resizeFrame() {
// Eval evaluates Go code represented as a string. Eval returns the last result
// computed by the interpreter, and a non nil error in case of failure.
func (interp *Interpreter) Eval(src string) (res reflect.Value, err error) {
defer func() {
if r := recover(); r != nil {
var pc [64]uintptr
n := runtime.Callers(1, pc[:])
err = Panic{Value: r, Callers: pc[:n], Stack: debug.Stack()}
}
}()

return interp.eval(src, "", true)
}

// EvalPath evaluates Go code located at path and returns the last result computed
// by the interpreter, and a non nil error in case of failure.
// The main function of the main package is executed if present.
func (interp *Interpreter) EvalPath(path string) (res reflect.Value, err error) {
defer func() {
if r := recover(); r != nil {
var pc [64]uintptr
n := runtime.Callers(1, pc[:])
err = Panic{Value: r, Callers: pc[:n], Stack: debug.Stack()}
}
}()

if !isFile(interp.opt.filesystem, path) {
_, err := interp.importSrc(mainID, path, NoTest)
return res, err
Expand Down Expand Up @@ -581,14 +597,7 @@ func (interp *Interpreter) EvalWithContext(ctx context.Context, src string) (ref

done := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
var pc [64]uintptr
n := runtime.Callers(1, pc[:])
err = Panic{Value: r, Callers: pc[:n], Stack: debug.Stack()}
}
close(done)
}()
defer close(done)
v, err = interp.Eval(src)
}()

Expand Down

0 comments on commit 48f8875

Please sign in to comment.