interpreter.go 7.04 KB
Newer Older
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16

obscuren's avatar
obscuren committed
17
package vm
18

obscuren's avatar
obscuren committed
19 20
import (
	"fmt"
21
	"sync/atomic"
22
	"time"
23

obscuren's avatar
obscuren committed
24
	"github.com/ethereum/go-ethereum/common"
25
	"github.com/ethereum/go-ethereum/common/math"
obscuren's avatar
obscuren committed
26
	"github.com/ethereum/go-ethereum/crypto"
27
	"github.com/ethereum/go-ethereum/log"
28
	"github.com/ethereum/go-ethereum/params"
obscuren's avatar
obscuren committed
29
)
obscuren's avatar
obscuren committed
30

31
// Config are the configuration options for the Interpreter
32
type Config struct {
33
	// Debug enabled debugging Interpreter options
34 35
	Debug bool
	// EnableJit enabled the JIT VM
36
	EnableJit bool
37 38 39 40
	// ForceJit forces the JIT VM
	ForceJit bool
	// Tracer is the op code logger
	Tracer Tracer
41
	// NoRecursion disabled Interpreter call, callcode,
42 43
	// delegate call and create.
	NoRecursion bool
44 45
	// Disable gas metering
	DisableGasMetering bool
46 47
	// Enable recording of SHA3/keccak preimages
	EnablePreimageRecording bool
48
	// JumpTable contains the EVM instruction table. This
49 50 51
	// may me left uninitialised and will be set the default
	// table.
	JumpTable [256]operation
52 53
}

54
// Interpreter is used to run Ethereum based contracts and will utilise the
55
// passed evmironment to query external sources for state information.
56
// The Interpreter will run the byte code VM or JIT VM based on the passed
57
// configuration.
58
type Interpreter struct {
59
	evm      *EVM
60 61
	cfg      Config
	gasTable params.GasTable
62
	intPool  *intPool
63 64

	readonly bool
obscuren's avatar
obscuren committed
65 66
}

67
// NewInterpreter returns a new instance of the Interpreter.
68
func NewInterpreter(evm *EVM, cfg Config) *Interpreter {
69 70 71 72
	// We use the STOP instruction whether to see
	// the jump table was initialised. If it was not
	// we'll set the default jump table.
	if !cfg.JumpTable[STOP].valid {
73 74 75 76
		switch {
		case evm.ChainConfig().IsHomestead(evm.BlockNumber):
			cfg.JumpTable = homesteadInstructionSet
		default:
77
			cfg.JumpTable = frontierInstructionSet
78
		}
79 80 81
	}

	return &Interpreter{
82
		evm:      evm,
83
		cfg:      cfg,
84
		gasTable: evm.ChainConfig().GasTable(evm.BlockNumber),
85
		intPool:  newIntPool(),
86
	}
obscuren's avatar
obscuren committed
87 88
}

89 90 91
func (in *Interpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error {
	return nil
}
obscuren's avatar
obscuren committed
92

93
// Run loops and evaluates the contract's code with the given input data and returns
94
// the return byte-slice and an error if one occurred.
95 96 97 98 99 100 101
//
// It's important to note that any errors returned by the interpreter should be
// considered a revert-and-consume-all-gas operation. No error specific checks
// should be handled to reduce complexity and errors further down the in.
func (in *Interpreter) Run(snapshot int, contract *Contract, input []byte) (ret []byte, err error) {
	in.evm.depth++
	defer func() { in.evm.depth-- }()
102

103 104
	// Don't bother with the execution if there's no code.
	if len(contract.Code) == 0 {
105
		return nil, nil
106 107
	}

108 109 110 111
	codehash := contract.CodeHash // codehash is used when doing jump dest caching
	if codehash == (common.Hash{}) {
		codehash = crypto.Keccak256Hash(contract.Code)
	}
112

113
	var (
114 115 116
		op    OpCode        // current opcode
		mem   = NewMemory() // bound memory
		stack = newstack()  // local stack
117
		// For optimisation reason we're using uint64 as the program counter.
118 119
		// It's theoretically possible to go above 2^64. The YP defines the PC
		// to be uint256. Practically much less so feasible.
120
		pc   = uint64(0) // program counter
121
		cost uint64
122
	)
123
	contract.Input = input
obscuren's avatar
obscuren committed
124

obscuren's avatar
obscuren committed
125
	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
obscuren's avatar
obscuren committed
126
	defer func() {
127
		if err != nil && in.cfg.Debug {
128 129
			// XXX For debugging
			//fmt.Printf("%04d: %8v    cost = %-8d stack = %-8d ERR = %v\n", pc, op, cost, stack.len(), err)
130
			in.cfg.Tracer.CaptureState(in.evm, pc, op, contract.Gas, cost, mem, stack, contract, in.evm.depth, err)
obscuren's avatar
obscuren committed
131 132
		}
	}()
obscuren's avatar
obscuren committed
133

134
	log.Debug("interpreter running contract", "hash", codehash[:])
135
	tstart := time.Now()
136
	defer log.Debug("interpreter finished running contract", "hash", codehash[:], "elapsed", time.Since(tstart))
137

138
	// The Interpreter main run loop (contextual). This loop runs until either an
139
	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
140 141
	// the execution of one of the operations or until the done flag is set by the
	// parent context.
142
	for atomic.LoadInt32(&in.evm.abort) == 0 {
obscuren's avatar
obscuren committed
143
		// Get the memory location of pc
144
		op = contract.GetOp(pc)
obscuren's avatar
obscuren committed
145

146
		// get the operation from the jump table matching the opcode
147 148 149 150
		operation := in.cfg.JumpTable[op]
		if err := in.enforceRestrictions(op, operation, stack); err != nil {
			return nil, err
		}
151

152 153
		// if the op is invalid abort the process and return an error
		if !operation.valid {
154
			return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
155 156
		}

157 158 159 160
		// validate the stack and make sure there enough stack items available
		// to perform the operation
		if err := operation.validateStack(stack); err != nil {
			return nil, err
obscuren's avatar
obscuren committed
161 162
		}

163
		var memorySize uint64
164 165 166
		// calculate the new memory size and expand the memory to fit
		// the operation
		if operation.memorySize != nil {
167 168 169 170
			memSize, overflow := bigUint64(operation.memorySize(stack))
			if overflow {
				return nil, errGasUintOverflow
			}
171 172
			// memory is expanded in words of 32 bytes. Gas
			// is also calculated in words.
173 174 175
			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
				return nil, errGasUintOverflow
			}
176 177
		}

178
		if !in.cfg.DisableGasMetering {
179 180
			// consume the gas and return an error if not enough gas is available.
			// cost is explicitly set so that the capture state defer method cas get the proper cost
181
			cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize)
182
			if err != nil || !contract.UseGas(cost) {
183 184
				return nil, ErrOutOfGas
			}
obscuren's avatar
obscuren committed
185
		}
186 187
		if memorySize > 0 {
			mem.Resize(memorySize)
obscuren's avatar
obscuren committed
188
		}
obscuren's avatar
obscuren committed
189

190 191
		if in.cfg.Debug {
			in.cfg.Tracer.CaptureState(in.evm, pc, op, contract.Gas, cost, mem, stack, contract, in.evm.depth, err)
obscuren's avatar
obscuren committed
192
		}
193 194
		// XXX For debugging
		//fmt.Printf("%04d: %8v    cost = %-8d stack = %-8d\n", pc, op, cost, stack.len())
195

196
		// execute the operation
197
		res, err := operation.execute(&pc, in.evm, contract, mem, stack)
198 199 200
		// verifyPool is a build flag. Pool verification makes sure the integrity
		// of the integer pool by comparing values to a default value.
		if verifyPool {
201
			verifyIntegerPool(in.intPool)
202
		}
203

204 205 206 207 208 209 210
		switch {
		case err != nil:
			return nil, err
		case operation.halts:
			return res, nil
		case !operation.jumps:
			pc++
obscuren's avatar
obscuren committed
211
		}
212 213 214 215 216
		// if the operation returned a value make sure that is also set
		// the last return data.
		if res != nil {
			mem.lastReturn = ret
		}
obscuren's avatar
obscuren committed
217
	}
218
	return nil, nil
219
}