interpreter.go 7.6 KB

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