github.com/aaa256/atlantis@v0.0.0-20210707112435-42ee889287a2/core/vm/interpreter.go (about)

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