interpreter.go 7.0 KB

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