github.com/phillinzzz/newBsc@v1.1.6/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 "hash" 21 "sync" 22 "sync/atomic" 23 24 "github.com/phillinzzz/newBsc/common" 25 "github.com/phillinzzz/newBsc/common/math" 26 "github.com/phillinzzz/newBsc/log" 27 ) 28 29 var EVMInterpreterPool = sync.Pool{ 30 New: func() interface{} { 31 return &EVMInterpreter{} 32 }, 33 } 34 35 // Config are the configuration options for the Interpreter 36 type Config struct { 37 Debug bool // Enables debugging 38 Tracer Tracer // Opcode logger 39 NoRecursion bool // Disables call, callcode, delegate call and create 40 EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages 41 42 JumpTable [256]*operation // EVM instruction table, automatically populated if unset 43 44 EWASMInterpreter string // External EWASM interpreter options 45 EVMInterpreter string // External EVM interpreter options 46 47 ExtraEips []int // Additional EIPS that are to be enabled 48 } 49 50 // Interpreter is used to run Ethereum based contracts and will utilise the 51 // passed environment to query external sources for state information. 52 // The Interpreter will run the byte code VM based on the passed 53 // configuration. 54 type Interpreter interface { 55 // Run loops and evaluates the contract's code with the given input data and returns 56 // the return byte-slice and an error if one occurred. 57 Run(contract *Contract, input []byte, static bool) ([]byte, error) 58 // CanRun tells if the contract, passed as an argument, can be 59 // run by the current interpreter. This is meant so that the 60 // caller can do something like: 61 // 62 // ```golang 63 // for _, interpreter := range interpreters { 64 // if interpreter.CanRun(contract.code) { 65 // interpreter.Run(contract.code, input) 66 // } 67 // } 68 // ``` 69 CanRun([]byte) bool 70 } 71 72 // ScopeContext contains the things that are per-call, such as stack and memory, 73 // but not transients like pc and gas 74 type ScopeContext struct { 75 Memory *Memory 76 Stack *Stack 77 Contract *Contract 78 } 79 80 // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports 81 // Read to get a variable amount of data from the hash state. Read is faster than Sum 82 // because it doesn't copy the internal state, but also modifies the internal state. 83 type keccakState interface { 84 hash.Hash 85 Read([]byte) (int, error) 86 } 87 88 // EVMInterpreter represents an EVM interpreter 89 type EVMInterpreter struct { 90 evm *EVM 91 cfg Config 92 93 hasher keccakState // Keccak256 hasher instance shared across opcodes 94 hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes 95 96 readOnly bool // Whether to throw on stateful modifications 97 returnData []byte // Last CALL's return data for subsequent reuse 98 } 99 100 // NewEVMInterpreter returns a new instance of the Interpreter. 101 func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter { 102 // We use the STOP instruction whether to see 103 // the jump table was initialised. If it was not 104 // we'll set the default jump table. 105 if cfg.JumpTable[STOP] == nil { 106 var jt JumpTable 107 switch { 108 case evm.chainRules.IsBerlin: 109 jt = berlinInstructionSet 110 case evm.chainRules.IsIstanbul: 111 jt = istanbulInstructionSet 112 case evm.chainRules.IsConstantinople: 113 jt = constantinopleInstructionSet 114 case evm.chainRules.IsByzantium: 115 jt = byzantiumInstructionSet 116 case evm.chainRules.IsEIP158: 117 jt = spuriousDragonInstructionSet 118 case evm.chainRules.IsEIP150: 119 jt = tangerineWhistleInstructionSet 120 case evm.chainRules.IsHomestead: 121 jt = homesteadInstructionSet 122 default: 123 jt = frontierInstructionSet 124 } 125 for i, eip := range cfg.ExtraEips { 126 if err := EnableEIP(eip, &jt); err != nil { 127 // Disable it, so caller can check if it's activated or not 128 cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...) 129 log.Error("EIP activation failed", "eip", eip, "error", err) 130 } 131 } 132 cfg.JumpTable = jt 133 } 134 evmInterpreter := EVMInterpreterPool.Get().(*EVMInterpreter) 135 evmInterpreter.evm = evm 136 evmInterpreter.cfg = cfg 137 evmInterpreter.readOnly = false 138 evmInterpreter.returnData = nil 139 return evmInterpreter 140 } 141 142 // Run loops and evaluates the contract's code with the given input data and returns 143 // the return byte-slice and an error if one occurred. 144 // 145 // It's important to note that any errors returned by the interpreter should be 146 // considered a revert-and-consume-all-gas operation except for 147 // ErrExecutionReverted which means revert-and-keep-gas-left. 148 func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) { 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 also makes 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 = &ScopeContext{ 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 // Don't move this deferrred function, it's placed before the capturestate-deferred method, 192 // so that it get's executed _after_: the capturestate needs the stacks before 193 // they are returned to the pools 194 defer func() { 195 returnStack(stack) 196 }() 197 contract.Input = input 198 199 if in.cfg.Debug { 200 defer func() { 201 if err != nil { 202 if !logged { 203 in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 204 } else { 205 in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, callContext, in.evm.depth, err) 206 } 207 } 208 }() 209 } 210 // The Interpreter main run loop (contextual). This loop runs until either an 211 // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during 212 // the execution of one of the operations or until the done flag is set by the 213 // parent context. 214 steps := 0 215 for { 216 steps++ 217 if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 { 218 break 219 } 220 if in.cfg.Debug { 221 // Capture pre-execution values for tracing. 222 logged, pcCopy, gasCopy = false, pc, contract.Gas 223 } 224 225 // Get the operation from the jump table and validate the stack to ensure there are 226 // enough stack items available to perform the operation. 227 op = contract.GetOp(pc) 228 operation := in.cfg.JumpTable[op] 229 if operation == nil { 230 return nil, &ErrInvalidOpCode{opcode: op} 231 } 232 // Validate stack 233 if sLen := stack.len(); sLen < operation.minStack { 234 return nil, &ErrStackUnderflow{stackLen: sLen, required: operation.minStack} 235 } else if sLen > operation.maxStack { 236 return nil, &ErrStackOverflow{stackLen: sLen, limit: operation.maxStack} 237 } 238 // If the operation is valid, enforce write restrictions 239 if in.readOnly && in.evm.chainRules.IsByzantium { 240 // If the interpreter is operating in readonly mode, make sure no 241 // state-modifying operation is performed. The 3rd stack item 242 // for a call operation is the value. Transferring value from one 243 // account to the others means the state is modified and should also 244 // return with an error. 245 if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) { 246 return nil, ErrWriteProtection 247 } 248 } 249 // Static portion of gas 250 cost = operation.constantGas // For tracing 251 if !contract.UseGas(operation.constantGas) { 252 return nil, ErrOutOfGas 253 } 254 255 var memorySize uint64 256 // calculate the new memory size and expand the memory to fit 257 // the operation 258 // Memory check needs to be done prior to evaluating the dynamic gas portion, 259 // to detect calculation overflows 260 if operation.memorySize != nil { 261 memSize, overflow := operation.memorySize(stack) 262 if overflow { 263 return nil, ErrGasUintOverflow 264 } 265 // memory is expanded in words of 32 bytes. Gas 266 // is also calculated in words. 267 if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow { 268 return nil, ErrGasUintOverflow 269 } 270 } 271 // Dynamic portion of gas 272 // consume the gas and return an error if not enough gas is available. 273 // cost is explicitly set so that the capture state defer method can get the proper cost 274 if operation.dynamicGas != nil { 275 var dynamicCost uint64 276 dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize) 277 cost += dynamicCost // total cost, for debug tracing 278 if err != nil || !contract.UseGas(dynamicCost) { 279 return nil, ErrOutOfGas 280 } 281 } 282 if memorySize > 0 { 283 mem.Resize(memorySize) 284 } 285 286 if in.cfg.Debug { 287 in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, callContext, in.returnData, in.evm.depth, err) 288 logged = true 289 } 290 291 // execute the operation 292 res, err = operation.execute(&pc, in, callContext) 293 // if the operation clears the return data (e.g. it has returning data) 294 // set the last return to the result of the operation. 295 if operation.returns { 296 in.returnData = res 297 } 298 299 switch { 300 case err != nil: 301 return nil, err 302 case operation.reverts: 303 return res, ErrExecutionReverted 304 case operation.halts: 305 return res, nil 306 case !operation.jumps: 307 pc++ 308 } 309 } 310 return nil, nil 311 } 312 313 // CanRun tells if the contract, passed as an argument, can be 314 // run by the current interpreter. 315 func (in *EVMInterpreter) CanRun(code []byte) bool { 316 return true 317 }