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

Add a function to reuse a terminated VM. #107

Closed
wants to merge 2 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
15 changes: 15 additions & 0 deletions exec/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,21 @@ func (vm *VirtualMachine) AddAndCheckGas(delta uint64) bool {
return true
}

// Reset makes de VM ready for a new call to Execute if the previous interruption
// has been interrupted.
func (vm *VirtualMachine) Reset() {
vm.CurrentFrame = -1
vm.Exited = false
vm.ExitError = nil
// The current depth of the callstack is a good indication of
// how deep it can go, clear all the current frames but leave
// it at its current allocation level.
for frame := range vm.CallStack {
vm.CallStack[frame] = Frame{}
}
vm.Delegate = nil
}

// Execute starts the virtual machines main instruction processing loop.
// This function may return at any point and is guaranteed to return
// at least once every 10000 instructions. Caller is responsible for
Expand Down
45 changes: 45 additions & 0 deletions exec/vm_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package exec

import "testing"

var testCode = []byte{
0, 97, 115, 109, 1, 0, 0, 0, 1, 14, 3, 96, 2, 127, 127, 0, 96, 0, 0, 96, 2, 127, 127, 0, 2, 12, 1, 3, 109, 111, 100, 4, 116, 101, 115, 116, 0, 2, 3, 2, 1, 1, 5, 3, 1, 0, 17, 7, 17, 2, 6, 109, 101, 109, 111, 114, 121, 2, 0, 4, 109, 97, 105, 110, 0, 1, 10, 11, 1, 9, 0, 65, 0, 65, 247, 0, 16, 0, 11,
}

type MyResolver struct{}

func (mr *MyResolver) ResolveFunc(module, field string) FunctionImport {
return func(vm *VirtualMachine) int64 {
panic("panic in order to trigger the VM's termination")
return 0
}
}
func (mr *MyResolver) ResolveGlobal(module, field string) int64 {
panic("not implemented")
}

func TestVMReset(t *testing.T) {
vm, err := NewVirtualMachine(testCode, VMConfig{}, &MyResolver{}, nil)
if err != nil {
t.Fatalf("Error creating VM: %v", err)
}
x := func() {
defer func() {
if err := recover(); err == nil {
t.Fatalf("an error should have been triggered")
}
}()
vm.Run(0, 0, 0)
}
x()
vm.Reset()
y := func() {
defer func() {
if err := recover(); err != nil && err != "panic in order to trigger the VM's termination" {
t.Fatalf("no panic or wrong type: %v", err)
}
}()
vm.Run(0, 1, 0)
}
y()
}