github.com/tenderly/bsc@v1.0.7/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 "hash" 22 "sync/atomic" 23 24 "github.com/tenderly/bsc/common" 25 "github.com/tenderly/bsc/common/math" 26 "github.com/tenderly/bsc/log" 27 ) 28 29 // Config are the configuration options for the Interpreter 30 type Config struct { 31 Debug bool // Enables debugging 32 Tracer Tracer // Opcode logger 33 NoRecursion bool // Disables call, callcode, delegate call and create 34 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 35 36 JumpTable [256]operation // EVM instruction table, automatically populated if unset 37 38 EWASMInterpreter string // External EWASM interpreter options 39 EVMInterpreter string // External EVM interpreter options 40 41 ExtraEips []int // Additional EIPS that are to be enabled 42 } 43 44 // Interpreter is used to run Ethereum 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 interface { 49 // Run loops and evaluates the contract's code with the given input data and returns 50 // the return byte-slice and an error if one occurred. 51 Run(contract *Contract, input []byte, static bool) ([]byte, error) 52 // CanRun tells if the contract, passed as an argument, can be 53 // run by the current interpreter. This is meant so that the 54 // caller can do something like: 55 // 56 // ```golang 57 // for _, interpreter := range interpreters { 58 // if interpreter.CanRun(contract.code) { 59 // interpreter.Run(contract.code, input) 60 // } 61 // } 62 // ``` 63 CanRun([]byte) bool 64 } 65 66 // callCtx contains the things that are per-call, such as stack and memory, 67 // but not transients like pc and gas 68 type callCtx struct { 69 memory *Memory 70 stack *Stack 71 contract *Contract 72 } 73 74 // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports 75 // Read to get a variable amount of data from the hash state. Read is faster than Sum 76 // because it doesn't copy the internal state, but also modifies the internal state. 77 type keccakState interface { 78 hash.Hash 79 Read([]byte) (int, error) 80 } 81 82 // EVMInterpreter represents an EVM interpreter 83 type EVMInterpreter struct { 84 evm *EVM 85 cfg Config 86 87 intPool *intPool 88 89 hasher keccakState // Keccak256 hasher instance shared across opcodes 90 hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes 91 92 readOnly bool // Whether to throw on stateful modifications 93 returnData []byte // Last CALL's return data for subsequent reuse 94 } 95 96 // NewEVMInterpreter returns a new instance of the Interpreter. 97 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 98 // We use the STOP instruction whether to see 99 // the jump table was initialised. If it was not 100 // we'll set the default jump table. 101 if !cfg.JumpTable[STOP].valid { 102 var jt JumpTable 103 switch { 104 case evm.chainRules.IsIstanbul: 105 jt = istanbulInstructionSet 106 case evm.chainRules.IsConstantinople: 107 jt = constantinopleInstructionSet 108 case evm.chainRules.IsByzantium: 109 jt = byzantiumInstructionSet 110 case evm.chainRules.IsEIP158: 111 jt = spuriousDragonInstructionSet 112 case evm.chainRules.IsEIP150: 113 jt = tangerineWhistleInstructionSet 114 case evm.chainRules.IsHomestead: 115 jt = homesteadInstructionSet 116 default: 117 jt = frontierInstructionSet 118 } 119 for i, eip := range cfg.ExtraEips { 120 if err := EnableEIP(eip, &jt); err != nil { 121 // Disable it, so caller can check if it's activated or not 122 cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...) 123 log.Error("EIP activation failed", "eip", eip, "error", err) 124 } 125 } 126 cfg.JumpTable = jt 127 } 128 129 return &EVMInterpreter{ 130 evm: evm, 131 cfg: cfg, 132 } 133 } 134 135 // Run loops and evaluates the contract's code with the given input data and returns 136 // the return byte-slice and an error if one occurred. 137 // 138 // It's important to note that any errors returned by the interpreter should be 139 // considered a revert-and-consume-all-gas operation except for 140 // errExecutionReverted which means revert-and-keep-gas-left. 141 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 142 if in.intPool == nil { 143 in.intPool = poolOfIntPools.get() 144 defer func() { 145 poolOfIntPools.put(in.intPool) 146 in.intPool = nil 147 }() 148 } 149 150 // Increment the call depth which is restricted to 1024 151 in.evm.depth++ 152 defer func() { in.evm.depth-- }() 153 154 // Make sure the readOnly is only set if we aren't in readOnly yet. 155 // This makes also sure that the readOnly flag isn't removed for child calls. 156 if readOnly && !in.readOnly { 157 in.readOnly = true 158 defer func() { in.readOnly = false }() 159 } 160 161 // Reset the previous call's return data. It's unimportant to preserve the old buffer 162 // as every returning call will return new data anyway. 163 in.returnData = nil 164 165 // TODO temporary fix for issue 166 // Don't bother with the execution if there's no code. 167 //if len(contract.Code) == 0 { 168 // return nil, nil 169 //} 170 171 var ( 172 op OpCode // current opcode 173 mem = NewMemory() // bound memory 174 stack = newstack() // local stack 175 callContext = &callCtx{ 176 memory: mem, 177 stack: stack, 178 contract: contract, 179 } 180 // For optimisation reason we're using uint64 as the program counter. 181 // It's theoretically possible to go above 2^64. The YP defines the PC 182 // to be uint256. Practically much less so feasible. 183 pc = uint64(0) // program counter 184 cost uint64 185 // copies used by tracer 186 pcCopy uint64 // needed for the deferred Tracer 187 gasCopy uint64 // for Tracer to log gas remaining before execution 188 logged bool // deferred Tracer should ignore already logged steps 189 res []byte // result of the opcode execution function 190 ) 191 contract.Input = input 192 193 // Reclaim the stack as an int pool when the execution stops 194 defer func() { in.intPool.put(stack.data...) }() 195 196 if in.cfg.Debug { 197 defer func() { 198 if err != nil { 199 if !logged { 200 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 201 } else { 202 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 203 } 204 } 205 }() 206 } 207 // The Interpreter main run loop (contextual). This loop runs until either an 208 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 209 // the execution of one of the operations or until the done flag is set by the 210 // parent context. 211 steps := 0 212 for { 213 steps++ 214 if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 { 215 break 216 } 217 if in.cfg.Debug { 218 // Capture pre-execution values for tracing. 219 logged, pcCopy, gasCopy = false, pc, contract.Gas 220 } 221 222 // Get the operation from the jump table and validate the stack to ensure there are 223 // enough stack items available to perform the operation. 224 op = contract.GetOp(pc) 225 operation := in.cfg.JumpTable[op] 226 if !operation.valid { 227 return nil, fmt.Errorf("invalid opcode 0x%x", int(op)) 228 } 229 // Validate stack 230 if sLen := stack.len(); sLen < operation.minStack { 231 return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack) 232 } else if sLen > operation.maxStack { 233 return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack) 234 } 235 // If the operation is valid, enforce and write restrictions 236 if in.readOnly && in.evm.chainRules.IsByzantium { 237 // If the interpreter is operating in readonly mode, make sure no 238 // state-modifying operation is performed. The 3rd stack item 239 // for a call operation is the value. Transferring value from one 240 // account to the others means the state is modified and should also 241 // return with an error. 242 if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) { 243 return nil, errWriteProtection 244 } 245 } 246 // Static portion of gas 247 cost = operation.constantGas // For tracing 248 if !contract.UseGas(operation.constantGas) { 249 return nil, ErrOutOfGas 250 } 251 252 var memorySize uint64 253 // calculate the new memory size and expand the memory to fit 254 // the operation 255 // Memory check needs to be done prior to evaluating the dynamic gas portion, 256 // to detect calculation overflows 257 if operation.memorySize != nil { 258 memSize, overflow := operation.memorySize(stack) 259 if overflow { 260 return nil, errGasUintOverflow 261 } 262 // memory is expanded in words of 32 bytes. Gas 263 // is also calculated in words. 264 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 265 return nil, errGasUintOverflow 266 } 267 } 268 // Dynamic portion of gas 269 // consume the gas and return an error if not enough gas is available. 270 // cost is explicitly set so that the capture state defer method can get the proper cost 271 if operation.dynamicGas != nil { 272 var dynamicCost uint64 273 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 274 cost += dynamicCost // total cost, for debug tracing 275 if err != nil || !contract.UseGas(dynamicCost) { 276 return nil, ErrOutOfGas 277 } 278 } 279 if memorySize > 0 { 280 mem.Resize(memorySize) 281 } 282 283 if in.cfg.Debug { 284 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err) 285 logged = true 286 } 287 288 // execute the operation 289 res, err = operation.execute(&pc, in, callContext) 290 // verifyPool is a build flag. Pool verification makes sure the integrity 291 // of the integer pool by comparing values to a default value. 292 if verifyPool { 293 verifyIntegerPool(in.intPool) 294 } 295 // if the operation clears the return data (e.g. it has returning data) 296 // set the last return to the result of the operation. 297 if operation.returns { 298 in.returnData = res 299 } 300 301 switch { 302 case err != nil: 303 return nil, err 304 case operation.reverts: 305 return res, errExecutionReverted 306 case operation.halts: 307 return res, nil 308 case !operation.jumps: 309 pc++ 310 } 311 } 312 return nil, nil 313 } 314 315 // CanRun tells if the contract, passed as an argument, can be 316 // run by the current interpreter. 317 func (in *EVMInterpreter) CanRun(code []byte) bool { 318 return true 319 }