github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/core/vm/interpreter.go (about)

     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  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     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  // GNU Lesser General Public License for more details.
    13  //
    14  // 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  
    17  package vm
    18  
    19  import (
    20  	"fmt"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/common/math"
    26  	"github.com/ethereum/go-ethereum/crypto"
    27  	"github.com/ethereum/go-ethereum/log"
    28  	"github.com/ethereum/go-ethereum/params"
    29  )
    30  
    31  // Config are the configuration options for the Interpreter
    32  type Config struct {
    33  	// Debug enabled debugging Interpreter options
    34  	Debug bool
    35  	// EnableJit enabled the JIT VM
    36  	EnableJit bool
    37  	// ForceJit forces the JIT VM
    38  	ForceJit bool
    39  	// Tracer is the op code logger
    40  	Tracer Tracer
    41  	// NoRecursion disabled Interpreter call, callcode,
    42  	// delegate call and create.
    43  	NoRecursion bool
    44  	// Disable gas metering
    45  	DisableGasMetering bool
    46  	// Enable recording of SHA3/keccak preimages
    47  	EnablePreimageRecording bool
    48  	// JumpTable contains the EVM instruction table. This
    49  	// may me left uninitialised and will be set the default
    50  	// table.
    51  	JumpTable [256]operation
    52  }
    53  
    54  // Interpreter is used to run Ethereum based contracts and will utilise the
    55  // passed environment 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  	env      *EVM
    60  	cfg      Config
    61  	gasTable params.GasTable
    62  	intPool  *intPool
    63  }
    64  
    65  // NewInterpreter returns a new instance of the Interpreter.
    66  func NewInterpreter(env *EVM, cfg Config) *Interpreter {
    67  	// We use the STOP instruction whether to see
    68  	// the jump table was initialised. If it was not
    69  	// we'll set the default jump table.
    70  	if !cfg.JumpTable[STOP].valid {
    71  		cfg.JumpTable = defaultJumpTable
    72  	}
    73  
    74  	return &Interpreter{
    75  		env:      env,
    76  		cfg:      cfg,
    77  		gasTable: env.ChainConfig().GasTable(env.BlockNumber),
    78  		intPool:  newIntPool(),
    79  	}
    80  }
    81  
    82  // Run loops and evaluates the contract's code with the given input data
    83  func (evm *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err error) {
    84  	evm.env.depth++
    85  	defer func() { evm.env.depth-- }()
    86  
    87  	if contract.CodeAddr != nil {
    88  		if p := PrecompiledContracts[*contract.CodeAddr]; p != nil {
    89  			return RunPrecompiledContract(p, input, contract)
    90  		}
    91  	}
    92  
    93  	// Don't bother with the execution if there's no code.
    94  	if len(contract.Code) == 0 {
    95  		return nil, nil
    96  	}
    97  
    98  	codehash := contract.CodeHash // codehash is used when doing jump dest caching
    99  	if codehash == (common.Hash{}) {
   100  		codehash = crypto.Keccak256Hash(contract.Code)
   101  	}
   102  
   103  	var (
   104  		op    OpCode        // current opcode
   105  		mem   = NewMemory() // bound memory
   106  		stack = newstack()  // local stack
   107  		// For optimisation reason we're using uint64 as the program counter.
   108  		// It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Practically much less so feasible.
   109  		pc   = uint64(0) // program counter
   110  		cost uint64
   111  	)
   112  	contract.Input = input
   113  
   114  	// User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
   115  	defer func() {
   116  		if err != nil && evm.cfg.Debug {
   117  			// XXX For debugging
   118  			//fmt.Printf("%04d: %8v    cost = %-8d stack = %-8d ERR = %v\n", pc, op, cost, stack.len(), err)
   119  			evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.depth, err)
   120  		}
   121  	}()
   122  
   123  	log.Debug("EVM running contract", "hash", codehash[:])
   124  	tstart := time.Now()
   125  	defer log.Debug("EVM finished running contract", "hash", codehash[:], "elapsed", time.Since(tstart))
   126  
   127  	// The Interpreter main run loop (contextual). This loop runs until either an
   128  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   129  	// the execution of one of the operations or until the evm.done is set by
   130  	// the parent context.Context.
   131  	for atomic.LoadInt32(&evm.env.abort) == 0 {
   132  		// Get the memory location of pc
   133  		op = contract.GetOp(pc)
   134  
   135  		// get the operation from the jump table matching the opcode
   136  		operation := evm.cfg.JumpTable[op]
   137  
   138  		// if the op is invalid abort the process and return an error
   139  		if !operation.valid {
   140  			return nil, fmt.Errorf("invalid opcode %x", op)
   141  		}
   142  
   143  		// validate the stack and make sure there enough stack items available
   144  		// to perform the operation
   145  		if err := operation.validateStack(stack); err != nil {
   146  			return nil, err
   147  		}
   148  
   149  		var memorySize uint64
   150  		// calculate the new memory size and expand the memory to fit
   151  		// the operation
   152  		if operation.memorySize != nil {
   153  			memSize, overflow := bigUint64(operation.memorySize(stack))
   154  			if overflow {
   155  				return nil, errGasUintOverflow
   156  			}
   157  			// memory is expanded in words of 32 bytes. Gas
   158  			// is also calculated in words.
   159  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   160  				return nil, errGasUintOverflow
   161  			}
   162  		}
   163  
   164  		if !evm.cfg.DisableGasMetering {
   165  			// consume the gas and return an error if not enough gas is available.
   166  			// cost is explicitly set so that the capture state defer method cas get the proper cost
   167  			cost, err = operation.gasCost(evm.gasTable, evm.env, contract, stack, mem, memorySize)
   168  			if err != nil || !contract.UseGas(cost) {
   169  				return nil, ErrOutOfGas
   170  			}
   171  		}
   172  		if memorySize > 0 {
   173  			mem.Resize(memorySize)
   174  		}
   175  
   176  		if evm.cfg.Debug {
   177  			evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.depth, err)
   178  		}
   179  		// XXX For debugging
   180  		//fmt.Printf("%04d: %8v    cost = %-8d stack = %-8d\n", pc, op, cost, stack.len())
   181  
   182  		// execute the operation
   183  		res, err := operation.execute(&pc, evm.env, contract, mem, stack)
   184  		// verifyPool is a build flag. Pool verification makes sure the integrity
   185  		// of the integer pool by comparing values to a default value.
   186  		if verifyPool {
   187  			verifyIntegerPool(evm.intPool)
   188  		}
   189  		switch {
   190  		case err != nil:
   191  			return nil, err
   192  		case operation.halts:
   193  			return res, nil
   194  		case !operation.jumps:
   195  			pc++
   196  		}
   197  	}
   198  	return nil, nil
   199  }