interpreter.go 9.0 KB

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