interpreter.go 11 KB

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