interpreter.go 8.0 KB

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