vm.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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/crypto"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  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. }
  59. // NewInterpreter returns a new instance of the Interpreter.
  60. func NewInterpreter(env *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. cfg.JumpTable = defaultJumpTable
  66. }
  67. return &Interpreter{
  68. env: env,
  69. cfg: cfg,
  70. gasTable: env.ChainConfig().GasTable(env.BlockNumber),
  71. }
  72. }
  73. // Run loops and evaluates the contract's code with the given input data
  74. func (evm *Interpreter) Run(contract *Contract, input []byte) (ret []byte, err error) {
  75. evm.env.depth++
  76. defer func() { evm.env.depth-- }()
  77. if contract.CodeAddr != nil {
  78. if p := PrecompiledContracts[*contract.CodeAddr]; p != nil {
  79. return RunPrecompiledContract(p, input, contract)
  80. }
  81. }
  82. // Don't bother with the execution if there's no code.
  83. if len(contract.Code) == 0 {
  84. return nil, nil
  85. }
  86. codehash := contract.CodeHash // codehash is used when doing jump dest caching
  87. if codehash == (common.Hash{}) {
  88. codehash = crypto.Keccak256Hash(contract.Code)
  89. }
  90. var (
  91. op OpCode // current opcode
  92. mem = NewMemory() // bound memory
  93. stack = newstack() // local stack
  94. // For optimisation reason we're using uint64 as the program counter.
  95. // It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Practically much less so feasible.
  96. pc = uint64(0) // program counter
  97. cost *big.Int
  98. )
  99. contract.Input = input
  100. // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
  101. defer func() {
  102. if err != nil && evm.cfg.Debug {
  103. evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.depth, err)
  104. }
  105. }()
  106. if glog.V(logger.Debug) {
  107. glog.Infof("evm running: %x\n", codehash[:4])
  108. tstart := time.Now()
  109. defer func() {
  110. glog.Infof("evm done: %x. time: %v\n", codehash[:4], time.Since(tstart))
  111. }()
  112. }
  113. // The Interpreter main run loop (contextual). This loop runs until either an
  114. // explicit STOP, RETURN or SUICIDE is executed, an error accured during
  115. // the execution of one of the operations or until the evm.done is set by
  116. // the parent context.Context.
  117. for atomic.LoadInt32(&evm.env.abort) == 0 {
  118. // Get the memory location of pc
  119. op = contract.GetOp(pc)
  120. // get the operation from the jump table matching the opcode
  121. operation := evm.cfg.JumpTable[op]
  122. // if the op is invalid abort the process and return an error
  123. if !operation.valid {
  124. return nil, fmt.Errorf("invalid opcode %x", op)
  125. }
  126. // validate the stack and make sure there enough stack items available
  127. // to perform the operation
  128. if err := operation.validateStack(stack); err != nil {
  129. return nil, err
  130. }
  131. var memorySize *big.Int
  132. // calculate the new memory size and expand the memory to fit
  133. // the operation
  134. if operation.memorySize != nil {
  135. memorySize = operation.memorySize(stack)
  136. // memory is expanded in words of 32 bytes. Gas
  137. // is also calculated in words.
  138. memorySize.Mul(toWordSize(memorySize), big.NewInt(32))
  139. }
  140. if !evm.cfg.DisableGasMetering {
  141. // consume the gas and return an error if not enough gas is available.
  142. // cost is explicitly set so that the capture state defer method cas get the proper cost
  143. cost = operation.gasCost(evm.gasTable, evm.env, contract, stack, mem, memorySize)
  144. if !contract.UseGas(cost) {
  145. return nil, ErrOutOfGas
  146. }
  147. }
  148. if memorySize != nil {
  149. mem.Resize(memorySize.Uint64())
  150. }
  151. if evm.cfg.Debug {
  152. evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.depth, err)
  153. }
  154. // execute the operation
  155. res, err := operation.execute(&pc, evm.env, contract, mem, stack)
  156. switch {
  157. case err != nil:
  158. return nil, err
  159. case operation.halts:
  160. return res, nil
  161. case !operation.jumps:
  162. pc++
  163. }
  164. }
  165. return nil, nil
  166. }