interpreter.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. "hash"
  20. "sync/atomic"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/math"
  23. "github.com/ethereum/go-ethereum/log"
  24. )
  25. // Config are the configuration options for the Interpreter
  26. type Config struct {
  27. Debug bool // Enables debugging
  28. Tracer Tracer // Opcode logger
  29. NoRecursion bool // Disables call, callcode, delegate call and create
  30. EnablePreimageRecording bool // Enables recording of SHA3/keccak preimages
  31. JumpTable [256]operation // EVM instruction table, automatically populated if unset
  32. EWASMInterpreter string // External EWASM interpreter options
  33. EVMInterpreter string // External EVM interpreter options
  34. ExtraEips []int // Additional EIPS that are to be enabled
  35. }
  36. // Interpreter is used to run Ethereum based contracts and will utilise the
  37. // passed environment to query external sources for state information.
  38. // The Interpreter will run the byte code VM based on the passed
  39. // configuration.
  40. type Interpreter interface {
  41. // Run loops and evaluates the contract's code with the given input data and returns
  42. // the return byte-slice and an error if one occurred.
  43. Run(contract *Contract, input []byte, static bool) ([]byte, error)
  44. // CanRun tells if the contract, passed as an argument, can be
  45. // run by the current interpreter. This is meant so that the
  46. // caller can do something like:
  47. //
  48. // ```golang
  49. // for _, interpreter := range interpreters {
  50. // if interpreter.CanRun(contract.code) {
  51. // interpreter.Run(contract.code, input)
  52. // }
  53. // }
  54. // ```
  55. CanRun([]byte) bool
  56. }
  57. // callCtx contains the things that are per-call, such as stack and memory,
  58. // but not transients like pc and gas
  59. type callCtx struct {
  60. memory *Memory
  61. stack *Stack
  62. contract *Contract
  63. }
  64. // keccakState wraps sha3.state. In addition to the usual hash methods, it also supports
  65. // Read to get a variable amount of data from the hash state. Read is faster than Sum
  66. // because it doesn't copy the internal state, but also modifies the internal state.
  67. type keccakState interface {
  68. hash.Hash
  69. Read([]byte) (int, error)
  70. }
  71. // EVMInterpreter represents an EVM interpreter
  72. type EVMInterpreter struct {
  73. evm *EVM
  74. cfg Config
  75. intPool *intPool
  76. hasher keccakState // Keccak256 hasher instance shared across opcodes
  77. hasherBuf common.Hash // Keccak256 hasher result array shared aross opcodes
  78. readOnly bool // Whether to throw on stateful modifications
  79. returnData []byte // Last CALL's return data for subsequent reuse
  80. }
  81. // NewEVMInterpreter returns a new instance of the Interpreter.
  82. func NewEVMInterpreter(evm *EVM, cfg Config) *EVMInterpreter {
  83. // We use the STOP instruction whether to see
  84. // the jump table was initialised. If it was not
  85. // we'll set the default jump table.
  86. if !cfg.JumpTable[STOP].valid {
  87. var jt JumpTable
  88. switch {
  89. case evm.chainRules.IsIstanbul:
  90. jt = istanbulInstructionSet
  91. case evm.chainRules.IsConstantinople:
  92. jt = constantinopleInstructionSet
  93. case evm.chainRules.IsByzantium:
  94. jt = byzantiumInstructionSet
  95. case evm.chainRules.IsEIP158:
  96. jt = spuriousDragonInstructionSet
  97. case evm.chainRules.IsEIP150:
  98. jt = tangerineWhistleInstructionSet
  99. case evm.chainRules.IsHomestead:
  100. jt = homesteadInstructionSet
  101. default:
  102. jt = frontierInstructionSet
  103. }
  104. for i, eip := range cfg.ExtraEips {
  105. if err := EnableEIP(eip, &jt); err != nil {
  106. // Disable it, so caller can check if it's activated or not
  107. cfg.ExtraEips = append(cfg.ExtraEips[:i], cfg.ExtraEips[i+1:]...)
  108. log.Error("EIP activation failed", "eip", eip, "error", err)
  109. }
  110. }
  111. cfg.JumpTable = jt
  112. }
  113. return &EVMInterpreter{
  114. evm: evm,
  115. cfg: cfg,
  116. }
  117. }
  118. // Run loops and evaluates the contract's code with the given input data and returns
  119. // the return byte-slice and an error if one occurred.
  120. //
  121. // It's important to note that any errors returned by the interpreter should be
  122. // considered a revert-and-consume-all-gas operation except for
  123. // errExecutionReverted which means revert-and-keep-gas-left.
  124. func (in *EVMInterpreter) Run(contract *Contract, input []byte, readOnly bool) (ret []byte, err error) {
  125. if in.intPool == nil {
  126. in.intPool = poolOfIntPools.get()
  127. defer func() {
  128. poolOfIntPools.put(in.intPool)
  129. in.intPool = nil
  130. }()
  131. }
  132. // Increment the call depth which is restricted to 1024
  133. in.evm.depth++
  134. defer func() { in.evm.depth-- }()
  135. // Make sure the readOnly is only set if we aren't in readOnly yet.
  136. // This makes also sure that the readOnly flag isn't removed for child calls.
  137. if readOnly && !in.readOnly {
  138. in.readOnly = true
  139. defer func() { in.readOnly = false }()
  140. }
  141. // Reset the previous call's return data. It's unimportant to preserve the old buffer
  142. // as every returning call will return new data anyway.
  143. in.returnData = nil
  144. // TODO temporary fix for issue
  145. // Don't bother with the execution if there's no code.
  146. //if len(contract.Code) == 0 {
  147. // return nil, nil
  148. //}
  149. var (
  150. op OpCode // current opcode
  151. mem = NewMemory() // bound memory
  152. stack = newstack() // local stack
  153. callContext = &callCtx{
  154. memory: mem,
  155. stack: stack,
  156. contract: contract,
  157. }
  158. // For optimisation reason we're using uint64 as the program counter.
  159. // It's theoretically possible to go above 2^64. The YP defines the PC
  160. // to be uint256. Practically much less so feasible.
  161. pc = uint64(0) // program counter
  162. cost uint64
  163. // copies used by tracer
  164. pcCopy uint64 // needed for the deferred Tracer
  165. gasCopy uint64 // for Tracer to log gas remaining before execution
  166. logged bool // deferred Tracer should ignore already logged steps
  167. res []byte // result of the opcode execution function
  168. )
  169. contract.Input = input
  170. // Reclaim the stack as an int pool when the execution stops
  171. defer func() { in.intPool.put(stack.data...) }()
  172. if in.cfg.Debug {
  173. defer func() {
  174. if err != nil {
  175. if !logged {
  176. in.cfg.Tracer.CaptureState(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
  177. } else {
  178. in.cfg.Tracer.CaptureFault(in.evm, pcCopy, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
  179. }
  180. }
  181. }()
  182. }
  183. // The Interpreter main run loop (contextual). This loop runs until either an
  184. // explicit STOP, RETURN or SELFDESTRUCT is executed, an error occurred during
  185. // the execution of one of the operations or until the done flag is set by the
  186. // parent context.
  187. steps := 0
  188. for {
  189. steps++
  190. if steps%1000 == 0 && atomic.LoadInt32(&in.evm.abort) != 0 {
  191. break
  192. }
  193. if in.cfg.Debug {
  194. // Capture pre-execution values for tracing.
  195. logged, pcCopy, gasCopy = false, pc, contract.Gas
  196. }
  197. // Get the operation from the jump table and validate the stack to ensure there are
  198. // enough stack items available to perform the operation.
  199. op = contract.GetOp(pc)
  200. operation := in.cfg.JumpTable[op]
  201. if !operation.valid {
  202. return nil, fmt.Errorf("invalid opcode 0x%x", int(op))
  203. }
  204. // Validate stack
  205. if sLen := stack.len(); sLen < operation.minStack {
  206. return nil, fmt.Errorf("stack underflow (%d <=> %d)", sLen, operation.minStack)
  207. } else if sLen > operation.maxStack {
  208. return nil, fmt.Errorf("stack limit reached %d (%d)", sLen, operation.maxStack)
  209. }
  210. // If the operation is valid, enforce and write restrictions
  211. if in.readOnly && in.evm.chainRules.IsByzantium {
  212. // If the interpreter is operating in readonly mode, make sure no
  213. // state-modifying operation is performed. The 3rd stack item
  214. // for a call operation is the value. Transferring value from one
  215. // account to the others means the state is modified and should also
  216. // return with an error.
  217. if operation.writes || (op == CALL && stack.Back(2).Sign() != 0) {
  218. return nil, errWriteProtection
  219. }
  220. }
  221. // Static portion of gas
  222. cost = operation.constantGas // For tracing
  223. if !contract.UseGas(operation.constantGas) {
  224. return nil, ErrOutOfGas
  225. }
  226. var memorySize uint64
  227. // calculate the new memory size and expand the memory to fit
  228. // the operation
  229. // Memory check needs to be done prior to evaluating the dynamic gas portion,
  230. // to detect calculation overflows
  231. if operation.memorySize != nil {
  232. memSize, overflow := operation.memorySize(stack)
  233. if overflow {
  234. return nil, errGasUintOverflow
  235. }
  236. // memory is expanded in words of 32 bytes. Gas
  237. // is also calculated in words.
  238. if memorySize, overflow = math.SafeMul(toWordSize(memSize), 32); overflow {
  239. return nil, errGasUintOverflow
  240. }
  241. }
  242. // Dynamic portion of gas
  243. // consume the gas and return an error if not enough gas is available.
  244. // cost is explicitly set so that the capture state defer method can get the proper cost
  245. if operation.dynamicGas != nil {
  246. var dynamicCost uint64
  247. dynamicCost, err = operation.dynamicGas(in.evm, contract, stack, mem, memorySize)
  248. cost += dynamicCost // total cost, for debug tracing
  249. if err != nil || !contract.UseGas(dynamicCost) {
  250. return nil, ErrOutOfGas
  251. }
  252. }
  253. if memorySize > 0 {
  254. mem.Resize(memorySize)
  255. }
  256. if in.cfg.Debug {
  257. in.cfg.Tracer.CaptureState(in.evm, pc, op, gasCopy, cost, mem, stack, contract, in.evm.depth, err)
  258. logged = true
  259. }
  260. // execute the operation
  261. res, err = operation.execute(&pc, in, callContext)
  262. // verifyPool is a build flag. Pool verification makes sure the integrity
  263. // of the integer pool by comparing values to a default value.
  264. if verifyPool {
  265. verifyIntegerPool(in.intPool)
  266. }
  267. // if the operation clears the return data (e.g. it has returning data)
  268. // set the last return to the result of the operation.
  269. if operation.returns {
  270. in.returnData = res
  271. }
  272. switch {
  273. case err != nil:
  274. return nil, err
  275. case operation.reverts:
  276. return res, errExecutionReverted
  277. case operation.halts:
  278. return res, nil
  279. case !operation.jumps:
  280. pc++
  281. }
  282. }
  283. return nil, nil
  284. }
  285. // CanRun tells if the contract, passed as an argument, can be
  286. // run by the current interpreter.
  287. func (in *EVMInterpreter) CanRun(code []byte) bool {
  288. return true
  289. }