diff --git a/stackframe.go b/stackframe.go index 006cce3..b91fe73 100644 --- a/stackframe.go +++ b/stackframe.go @@ -1,9 +1,15 @@ package vm -const functionMemoryEntries = 16 - type stackFrame struct { previousFunctionIndex int64 previousInstructionIndex int64 - functionMemory [functionMemoryEntries]uint64 + functionMemory *memory +} + +func newStackFrame(state *State) *stackFrame { + return &stackFrame{ + previousFunctionIndex: state.functionIndex, + previousInstructionIndex: state.instructionIndex, + functionMemory: newMemory(16), + } } diff --git a/state.go b/state.go index 944ab53..9bf4c57 100644 --- a/state.go +++ b/state.go @@ -4,8 +4,6 @@ import "fmt" import "github.com/pkg/errors" -const globalMemoryEntries = 16 - type State struct { running bool err error @@ -22,7 +20,7 @@ type State struct { func NewState(functions [][]*Instruction) (*State, error) { return &State{ functions: functions, - globalMemory: newMemory(globalMemoryEntries), + globalMemory: newMemory(16), }, nil } @@ -91,11 +89,11 @@ func (state *State) readUnsigned(op *Operand) uint64 { return op.Value case FunctionMemoryIndex: - if op.Value >= functionMemoryEntries { - state.setError(fmt.Errorf("Invalid function memory index: %016x", op.Value)) - return 0 + value, err := state.stackFrame().functionMemory.readUnsigned(op.Value) + if err != nil { + state.setError(err) } - return state.stackFrame().functionMemory[op.Value] + return value case GlobalMemoryIndex: value, err := state.globalMemory.readUnsigned(op.Value) @@ -120,11 +118,10 @@ func (state *State) writeUnsigned(op *Operand, value uint64) { state.setError(fmt.Errorf("Write to literal operand")) case FunctionMemoryIndex: - if op.Value >= functionMemoryEntries { - state.setError(fmt.Errorf("Invalid function memory index: %016x", op.Value)) - return + err := state.stackFrame().functionMemory.writeUnsigned(op.Value, value) + if err != nil { + state.setError(err) } - state.stackFrame().functionMemory[op.Value] = value case GlobalMemoryIndex: err := state.globalMemory.writeUnsigned(op.Value, value) @@ -147,10 +144,7 @@ func (state *State) call(functionOffset int64) { return } - stackFrame := &stackFrame{ - previousFunctionIndex: state.functionIndex, - previousInstructionIndex: state.instructionIndex, - } + stackFrame := newStackFrame(state) state.stack = append(state.stack, stackFrame) state.functionIndex += functionOffset state.instructionIndex = 0