interpreter.go 11 KB

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