interpreter.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. "math/big"
  20. "sync/atomic"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/math"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/params"
  27. )
  28. // Config are the configuration options for the Interpreter
  29. type Config struct {
  30. // Debug enabled debugging Interpreter options
  31. Debug bool
  32. // EnableJit enabled the JIT VM
  33. EnableJit bool
  34. // ForceJit forces the JIT VM
  35. ForceJit bool
  36. // Tracer is the op code logger
  37. Tracer Tracer
  38. // NoRecursion disabled Interpreter call, callcode,
  39. // delegate call and create.
  40. NoRecursion bool
  41. // Disable gas metering
  42. DisableGasMetering bool
  43. // Enable recording of SHA3/keccak preimages
  44. EnablePreimageRecording bool
  45. // JumpTable contains the EVM instruction table. This
  46. // may me left uninitialised and will be set the default
  47. // table.
  48. JumpTable [256]operation
  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 or JIT VM based on the passed
  53. // configuration.
  54. type Interpreter struct {
  55. env *EVM
  56. cfg Config
  57. gasTable params.GasTable
  58. intPool *intPool
  59. }
  60. // NewInterpreter returns a new instance of the Interpreter.
  61. func NewInterpreter(env *EVM, cfg Config) *Interpreter {
  62. // We use the STOP instruction whether to see
  63. // the jump table was initialised. If it was not
  64. // we'll set the default jump table.
  65. if !cfg.JumpTable[STOP].valid {
  66. cfg.JumpTable = defaultJumpTable
  67. }
  68. return &Interpreter{
  69. env: env,
  70. cfg: cfg,
  71. gasTable: env.ChainConfig().GasTable(env.BlockNumber),
  72. intPool: newIntPool(),
  73. }
  74. }
  75. // Run loops and evaluates the contract's code with the given input data
  76. func (evm *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err error) {
  77. evm.env.depth++
  78. defer func() { evm.env.depth-- }()
  79. if contract.CodeAddr != nil {
  80. if p := PrecompiledContracts[*contract.CodeAddr]; p != nil {
  81. return RunPrecompiledContract(p, input, contract)
  82. }
  83. }
  84. // Don't bother with the execution if there's no code.
  85. if len(contract.Code) == 0 {
  86. return nil, nil
  87. }
  88. codehash := contract.CodeHash // codehash is used when doing jump dest caching
  89. if codehash == (common.Hash{}) {
  90. codehash = crypto.Keccak256Hash(contract.Code)
  91. }
  92. var (
  93. op OpCode // current opcode
  94. mem = NewMemory() // bound memory
  95. stack = newstack() // local stack
  96. // For optimisation reason we're using uint64 as the program counter.
  97. // It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Practically much less so feasible.
  98. pc = uint64(0) // program counter
  99. cost uint64
  100. )
  101. contract.Input = input
  102. // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
  103. defer func() {
  104. if err != nil && evm.cfg.Debug {
  105. // XXX For debugging
  106. //fmt.Printf("%04d: %8v cost = %-8d stack = %-8d ERR = %v\n", pc, op, cost, stack.len(), err)
  107. // TODO update the tracer
  108. g, c := new(big.Int).SetUint64(contract.Gas), new(big.Int).SetUint64(cost)
  109. evm.cfg.Tracer.CaptureState(evm.env, pc, op, g, c, mem, stack, contract, evm.env.depth, err)
  110. }
  111. }()
  112. log.Debug("", "msg", log.Lazy{Fn: func() string {
  113. return fmt.Sprintf("evm running: %x\n", codehash[:4])
  114. }})
  115. tstart := time.Now()
  116. defer log.Debug("", "msg", log.Lazy{Fn: func() string {
  117. return fmt.Sprintf("evm done: %x. time: %v\n", codehash[:4], time.Since(tstart))
  118. }})
  119. // The Interpreter main run loop (contextual). This loop runs until either an
  120. // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
  121. // the execution of one of the operations or until the evm.done is set by
  122. // the parent context.Context.
  123. for atomic.LoadInt32(&evm.env.abort) == 0 {
  124. // Get the memory location of pc
  125. op = contract.GetOp(pc)
  126. // get the operation from the jump table matching the opcode
  127. operation := evm.cfg.JumpTable[op]
  128. // if the op is invalid abort the process and return an error
  129. if !operation.valid {
  130. return nil, fmt.Errorf("invalid opcode %x", op)
  131. }
  132. // validate the stack and make sure there enough stack items available
  133. // to perform the operation
  134. if err := operation.validateStack(stack); err != nil {
  135. return nil, err
  136. }
  137. var memorySize uint64
  138. // calculate the new memory size and expand the memory to fit
  139. // the operation
  140. if operation.memorySize != nil {
  141. memSize, overflow := bigUint64(operation.memorySize(stack))
  142. if overflow {
  143. return nil, errGasUintOverflow
  144. }
  145. // memory is expanded in words of 32 bytes. Gas
  146. // is also calculated in words.
  147. if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
  148. return nil, errGasUintOverflow
  149. }
  150. }
  151. if !evm.cfg.DisableGasMetering {
  152. // consume the gas and return an error if not enough gas is available.
  153. // cost is explicitly set so that the capture state defer method cas get the proper cost
  154. cost, err = operation.gasCost(evm.gasTable, evm.env, contract, stack, mem, memorySize)
  155. if err != nil || !contract.UseGas(cost) {
  156. return nil, ErrOutOfGas
  157. }
  158. }
  159. if memorySize > 0 {
  160. mem.Resize(memorySize)
  161. }
  162. if evm.cfg.Debug {
  163. g, c := new(big.Int).SetUint64(contract.Gas), new(big.Int).SetUint64(cost)
  164. evm.cfg.Tracer.CaptureState(evm.env, pc, op, g, c, mem, stack, contract, evm.env.depth, err)
  165. }
  166. // XXX For debugging
  167. //fmt.Printf("%04d: %8v cost = %-8d stack = %-8d\n", pc, op, cost, stack.len())
  168. // execute the operation
  169. res, err := operation.execute(&pc, evm.env, contract, mem, stack)
  170. // verifyPool is a build flag. Pool verification makes sure the integrity
  171. // of the integer pool by comparing values to a default value.
  172. if verifyPool {
  173. verifyIntegerPool(evm.intPool)
  174. }
  175. switch {
  176. case err != nil:
  177. return nil, err
  178. case operation.halts:
  179. return res, nil
  180. case !operation.jumps:
  181. pc++
  182. }
  183. }
  184. return nil, nil
  185. }