interpreter.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. "fmt"
  19. "hash"
  20. "sync/atomic"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/math"
  23. "github.com/ethereum/go-ethereum/params"
  24. )
  25. // Config are the configuration options for the Interpreter
  26. type Config struct {
  27. // Debug enabled debugging Interpreter options
  28. Debug bool
  29. // Tracer is the op code logger
  30. Tracer Tracer
  31. // NoRecursion disabled Interpreter call, callcode,
  32. // delegate call and create.
  33. NoRecursion bool
  34. // Enable recording of SHA3/keccak preimages
  35. EnablePreimageRecording bool
  36. // JumpTable contains the EVM instruction table. This
  37. // may be left uninitialised and will be set to the default
  38. // table.
  39. JumpTable [256]operation
  40. // Type of the EWASM interpreter
  41. EWASMInterpreter string
  42. // Type of the EVM interpreter
  43. EVMInterpreter string
  44. }
  45. // Interpreter is used to run Ethereum based contracts and will utilise the
  46. // passed environment to query external sources for state information.
  47. // The Interpreter will run the byte code VM based on the passed
  48. // configuration.
  49. type Interpreter interface {
  50. // Run loops and evaluates the contract's code with the given input data and returns
  51. // the return byte-slice and an error if one occurred.
  52. Run(contract *Contract, input []byte, static bool) ([]byte, error)
  53. // CanRun tells if the contract, passed as an argument, can be
  54. // run by the current interpreter. This is meant so that the
  55. // caller can do something like:
  56. //
  57. // ```golang
  58. // for _, interpreter := range interpreters {
  59. // if interpreter.CanRun(contract.code) {
  60. // interpreter.Run(contract.code, input)
  61. // }
  62. // }
  63. // ```
  64. CanRun([]byte) bool
  65. }
  66. // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  67. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  68. // because it doesn't copy the internal state, but also modifies the internal state.
  69. type keccakState interface {
  70. hash.Hash
  71. Read([]byte) (int, error)
  72. }
  73. // EVMInterpreter represents an EVM interpreter
  74. type EVMInterpreter struct {
  75. evm *EVM
  76. cfg Config
  77. gasTable params.GasTable
  78. intPool *intPool
  79. hasher keccakState // Keccak256 hasher instance shared across opcodes
  80. hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
  81. readOnly bool // Whether to throw on stateful modifications
  82. returnData []byte // Last CALL's return data for subsequent reuse
  83. }
  84. // NewEVMInterpreter returns a new instance of the Interpreter.
  85. func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
  86. // We use the STOP instruction whether to see
  87. // the jump table was initialised. If it was not
  88. // we'll set the default jump table.
  89. if !cfg.JumpTable[STOP].valid {
  90. switch {
  91. case evm.ChainConfig().IsConstantinople(evm.BlockNumber):
  92. cfg.JumpTable = constantinopleInstructionSet
  93. case evm.ChainConfig().IsByzantium(evm.BlockNumber):
  94. cfg.JumpTable = byzantiumInstructionSet
  95. case evm.ChainConfig().IsHomestead(evm.BlockNumber):
  96. cfg.JumpTable = homesteadInstructionSet
  97. default:
  98. cfg.JumpTable = frontierInstructionSet
  99. }
  100. }
  101. return &EVMInterpreter{
  102. evm: evm,
  103. cfg: cfg,
  104. gasTable: evm.ChainConfig().GasTable(evm.BlockNumber),
  105. }
  106. }
  107. // Run loops and evaluates the contract's code with the given input data and returns
  108. // the return byte-slice and an error if one occurred.
  109. //
  110. // It's important to note that any errors returned by the interpreter should be
  111. // considered a revert-and-consume-all-gas operation except for
  112. // errExecutionReverted which means revert-and-keep-gas-left.
  113. func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
  114. if in.intPool == nil {
  115. in.intPool = poolOfIntPools.get()
  116. defer func() {
  117. poolOfIntPools.put(in.intPool)
  118. in.intPool = nil
  119. }()
  120. }
  121. // Increment the call depth which is restricted to 1024
  122. in.evm.depth++
  123. defer func() { in.evm.depth-- }()
  124. // Make sure the readOnly is only set if we aren't in readOnly yet.
  125. // This makes also sure that the readOnly flag isn't removed for child calls.
  126. if readOnly && !in.readOnly {
  127. in.readOnly = true
  128. defer func() { in.readOnly = false }()
  129. }
  130. // Reset the previous call's return data. It's unimportant to preserve the old buffer
  131. // as every returning call will return new data anyway.
  132. in.returnData = nil
  133. // Don't bother with the execution if there's no code.
  134. if len(contract.Code) == 0 {
  135. return nil, nil
  136. }
  137. var (
  138. op OpCode // current opcode
  139. mem = NewMemory() // bound memory
  140. stack = newstack() // local stack
  141. // For optimisation reason we're using uint64 as the program counter.
  142. // It's theoretically possible to go above 2^64. The YP defines the PC
  143. // to be uint256. Practically much less so feasible.
  144. pc = uint64(0) // program counter
  145. cost uint64
  146. // copies used by tracer
  147. pcCopy uint64 // needed for the deferred Tracer
  148. gasCopy uint64 // for Tracer to log gas remaining before execution
  149. logged bool // deferred Tracer should ignore already logged steps
  150. res []byte // result of the opcode execution function
  151. )
  152. contract.Input = input
  153. // Reclaim the stack as an int pool when the execution stops
  154. defer func() { in.intPool.put(stack.data...) }()
  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. // Get the operation from the jump table and validate the stack to ensure there are
  176. // enough stack items available to perform the operation.
  177. op = contract.GetOp(pc)
  178. operation := in.cfg.JumpTable[op]
  179. if !operation.valid {
  180. return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
  181. }
  182. // Validate stack
  183. if sLen := stack.len(); sLen < operation.minStack {
  184. return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack)
  185. } else if sLen > operation.maxStack {
  186. return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack)
  187. }
  188. // If the operation is valid, enforce and write restrictions
  189. if in.readOnly && in.evm.chainRules.IsByzantium {
  190. // If the interpreter is operating in readonly mode, make sure no
  191. // state-modifying operation is performed. The 3rd stack item
  192. // for a call operation is the value. Transferring value from one
  193. // account to the others means the state is modified and should also
  194. // return with an error.
  195. if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
  196. return nil, errWriteProtection
  197. }
  198. }
  199. // Static portion of gas
  200. if !contract.UseGas(operation.constantGas) {
  201. return nil, ErrOutOfGas
  202. }
  203. var memorySize uint64
  204. // calculate the new memory size and expand the memory to fit
  205. // the operation
  206. // Memory check needs to be done prior to evaluating the dynamic gas portion,
  207. // to detect calculation overflows
  208. if operation.memorySize != nil {
  209. memSize, overflow := operation.memorySize(stack)
  210. if overflow {
  211. return nil, errGasUintOverflow
  212. }
  213. // memory is expanded in words of 32 bytes. Gas
  214. // is also calculated in words.
  215. if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
  216. return nil, errGasUintOverflow
  217. }
  218. }
  219. // Dynamic portion of gas
  220. // consume the gas and return an error if not enough gas is available.
  221. // cost is explicitly set so that the capture state defer method can get the proper cost
  222. if operation.dynamicGas != nil {
  223. cost, err = operation.dynamicGas(in.gasTable, in.evm, contract, stack, mem, memorySize)
  224. if err != nil || !contract.UseGas(cost) {
  225. return nil, ErrOutOfGas
  226. }
  227. }
  228. if memorySize > 0 {
  229. mem.Resize(memorySize)
  230. }
  231. if in.cfg.Debug {
  232. in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
  233. logged = true
  234. }
  235. // execute the operation
  236. res, err = operation.execute(&pc, in, contract, mem, stack)
  237. // verifyPool is a build flag. Pool verification makes sure the integrity
  238. // of the integer pool by comparing values to a default value.
  239. if verifyPool {
  240. verifyIntegerPool(in.intPool)
  241. }
  242. // if the operation clears the return data (e.g. it has returning data)
  243. // set the last return to the result of the operation.
  244. if operation.returns {
  245. in.returnData = res
  246. }
  247. switch {
  248. case err != nil:
  249. return nil, err
  250. case operation.reverts:
  251. return res, errExecutionReverted
  252. case operation.halts:
  253. return res, nil
  254. case !operation.jumps:
  255. pc++
  256. }
  257. }
  258. return nil, nil
  259. }
  260. // CanRun tells if the contract, passed as an argument, can be
  261. // run by the current interpreter.
  262. func (in *EVMInterpreter) CanRun(code []byte) bool {
  263. return true
  264. }