github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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  
    23  	"github.com/PlatONnetwork/PlatON-Go/common/math"
    24  	"github.com/PlatONnetwork/PlatON-Go/params"
    25  )
    26  
    27  // Interpreter is used to run Ethereum based contracts and will utilise the
    28  // passed environment to query external sources for state information.
    29  // The Interpreter will run the byte code VM based on the passed
    30  // configuration.
    31  type Interpreter interface {
    32  	// Run loops and evaluates the contract's code with the given input data and returns
    33  	// the return byte-slice and an error if one occurred.
    34  	Run(contract *Contract, input []byte, static bool) ([]byte, error)
    35  	// CanRun tells if the contract, passed as an argument, can be
    36  	// run by the current interpreter. This is meant so that the
    37  	// caller can do something like:
    38  	//
    39  	// ```golang
    40  	// for _, interpreter := range interpreters {
    41  	//   if interpreter.CanRun(contract.code) {
    42  	//     interpreter.Run(contract.code, input)
    43  	//   }
    44  	// }
    45  	// ```
    46  	CanRun([]byte) bool
    47  }
    48  
    49  // EVMInterpreter represents an EVM interpreter
    50  type EVMInterpreter struct {
    51  	evm      *EVM
    52  	cfg      Config
    53  	gasTable params.GasTable
    54  	intPool  *intPool
    55  
    56  	readOnly   bool   // Whether to throw on stateful modifications
    57  	returnData []byte // Last CALL's return data for subsequent reuse
    58  }
    59  
    60  // NewEVMInterpreter returns a new instance of the Interpreter.
    61  func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
    62  	// We use the STOP instruction whether to see
    63  	// the jump table was initialised. If it was not
    64  	// we'll set the default jump table.
    65  	if !cfg.JumpTable[STOP].valid {
    66  		switch {
    67  		case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
    68  			cfg.JumpTable = constantinopleInstructionSet
    69  		case evm.ChainConfig().IsByzantium(evm.BlockNumber):
    70  			cfg.JumpTable = byzantiumInstructionSet
    71  		case evm.ChainConfig().IsHomestead(evm.BlockNumber):
    72  			cfg.JumpTable = homesteadInstructionSet
    73  		default:
    74  			cfg.JumpTable = frontierInstructionSet
    75  		}
    76  	}
    77  
    78  	return &EVMInterpreter{
    79  		evm:      evm,
    80  		cfg:      cfg,
    81  		gasTable: evm.ChainConfig().GasTable(evm.BlockNumber),
    82  	}
    83  }
    84  
    85  func (in *EVMInterpreter) enforceRestrictions(op OpCode, operation operation, stack *Stack) error {
    86  	if in.evm.chainRules.IsByzantium {
    87  		if in.readOnly {
    88  			// If the interpreter is operating in readonly mode, make sure no
    89  			// state-modifying operation is performed. The 3rd stack item
    90  			// for a call operation is the value. Transferring value from one
    91  			// account to the others means the state is modified and should also
    92  			// return with an error.
    93  			if operation.writes || (op == CALL && stack.Back(2).BitLen() > 0) {
    94  				return errWriteProtection
    95  			}
    96  		}
    97  	}
    98  	return nil
    99  }
   100  
   101  // Run loops and evaluates the contract's code with the given input data and returns
   102  // the return byte-slice and an error if one occurred.
   103  //
   104  // It's important to note that any errors returned by the interpreter should be
   105  // considered a revert-and-consume-all-gas operation except for
   106  // errExecutionReverted which means revert-and-keep-gas-left.
   107  func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
   108  	if in.intPool == nil {
   109  		in.intPool = poolOfIntPools.get()
   110  		defer func() {
   111  			poolOfIntPools.put(in.intPool)
   112  			in.intPool = nil
   113  		}()
   114  	}
   115  
   116  	// Increment the call depth which is restricted to 1024
   117  	in.evm.depth++
   118  	defer func() { in.evm.depth-- }()
   119  
   120  	// Make sure the readOnly is only set if we aren't in readOnly yet.
   121  	// This makes also sure that the readOnly flag isn't removed for child calls.
   122  	if readOnly && !in.readOnly {
   123  		in.readOnly = true
   124  		defer func() { in.readOnly = false }()
   125  	}
   126  
   127  	// Reset the previous call's return data. It's unimportant to preserve the old buffer
   128  	// as every returning call will return new data anyway.
   129  	in.returnData = nil
   130  
   131  	// Don't bother with the execution if there's no code.
   132  	if len(contract.Code) == 0 {
   133  		return nil, nil
   134  	}
   135  
   136  	var (
   137  		op    OpCode        // current opcode
   138  		mem   = NewMemory() // bound memory
   139  		stack = newstack()  // local stack
   140  		// For optimisation reason we're using uint64 as the program counter.
   141  		// It's theoretically possible to go above 2^64. The YP defines the PC
   142  		// to be uint256. Practically much less so feasible.
   143  		pc   = uint64(0) // program counter
   144  		cost uint64
   145  		// copies used by tracer
   146  		pcCopy  uint64 // needed for the deferred Tracer
   147  		gasCopy uint64 // for Tracer to log gas remaining before execution
   148  		logged  bool   // deferred Tracer should ignore already logged steps
   149  	)
   150  	contract.Input = input
   151  
   152  	// Reclaim the stack as an int pool when the execution stops
   153  	defer func() { in.intPool.put(stack.data...) }()
   154  
   155  	if in.cfg.Debug {
   156  		defer func() {
   157  			if err != nil {
   158  				if !logged {
   159  					in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   160  				} else {
   161  					in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   162  				}
   163  			}
   164  		}()
   165  	}
   166  	// The Interpreter main run loop (contextual). This loop runs until either an
   167  	// explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
   168  	// the execution of one of the operations or until the done flag is set by the
   169  	// parent context.
   170  	for atomic.LoadInt32(&in.evm.abort) == 0 {
   171  		if in.cfg.Debug {
   172  			// Capture pre-execution values for tracing.
   173  			logged, pcCopy, gasCopy = false, pc, contract.Gas
   174  		}
   175  
   176  		// Get the operation from the jump table and validate the stack to ensure there are
   177  		// enough stack items available to perform the operation.
   178  		op = contract.GetOp(pc)
   179  		operation := in.cfg.JumpTable[op]
   180  		if !operation.valid {
   181  			return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
   182  		}
   183  		if err := operation.validateStack(stack); err != nil {
   184  			return nil, err
   185  		}
   186  		// If the operation is valid, enforce and write restrictions
   187  		if err := in.enforceRestrictions(op, operation, stack); err != nil {
   188  			return nil, err
   189  		}
   190  
   191  		var memorySize uint64
   192  		// calculate the new memory size and expand the memory to fit
   193  		// the operation
   194  		if operation.memorySize != nil {
   195  			memSize, overflow := bigUint64(operation.memorySize(stack))
   196  			if overflow {
   197  				return nil, errGasUintOverflow
   198  			}
   199  			// memory is expanded in words of 32 bytes. Gas
   200  			// is also calculated in words.
   201  			if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
   202  				return nil, errGasUintOverflow
   203  			}
   204  		}
   205  		// consume the gas and return an error if not enough gas is available.
   206  		// cost is explicitly set so that the capture state defer method can get the proper cost
   207  		cost, err = operation.gasCost(in.gasTable, in.evm, contract, stack, mem, memorySize)
   208  		if err != nil || !contract.UseGas(cost) {
   209  			return nil, ErrOutOfGas
   210  		}
   211  		if memorySize > 0 {
   212  			mem.Resize(memorySize)
   213  		}
   214  
   215  		if in.cfg.Debug {
   216  			in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
   217  			logged = true
   218  		}
   219  
   220  		// execute the operation
   221  		res, err := operation.execute(&pc, in, contract, mem, stack)
   222  		// verifyPool is a build flag. Pool verification makes sure the integrity
   223  		// of the integer pool by comparing values to a default value.
   224  		if verifyPool {
   225  			verifyIntegerPool(in.intPool)
   226  		}
   227  		// if the operation clears the return data (e.g. it has returning data)
   228  		// set the last return to the result of the operation.
   229  		if operation.returns {
   230  			in.returnData = res
   231  		}
   232  
   233  		switch {
   234  		case err != nil:
   235  			return nil, err
   236  		case operation.reverts:
   237  			return res, errExecutionReverted
   238  		case operation.halts:
   239  			return res, nil
   240  		case !operation.jumps:
   241  			pc++
   242  		}
   243  	}
   244  	return nil, nil
   245  }
   246  
   247  // CanRun tells if the contract, passed as an argument, can be
   248  // run by the current interpreter.
   249  func (in *EVMInterpreter) CanRun(code []byte) bool {
   250  	return true
   251  }