vm.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/logger"
  24. "github.com/ethereum/go-ethereum/logger/glog"
  25. "github.com/ethereum/go-ethereum/params"
  26. )
  27. // Config are the configuration options for the EVM
  28. type Config struct {
  29. Debug bool
  30. EnableJit bool
  31. ForceJit bool
  32. Tracer Tracer
  33. }
  34. // EVM is used to run Ethereum based contracts and will utilise the
  35. // passed environment to query external sources for state information.
  36. // The EVM will run the byte code VM or JIT VM based on the passed
  37. // configuration.
  38. type EVM struct {
  39. env Environment
  40. jumpTable vmJumpTable
  41. cfg Config
  42. }
  43. // New returns a new instance of the EVM.
  44. func New(env Environment, cfg Config) *EVM {
  45. return &EVM{
  46. env: env,
  47. jumpTable: newJumpTable(env.RuleSet(), env.BlockNumber()),
  48. cfg: cfg,
  49. }
  50. }
  51. // Run loops and evaluates the contract's code with the given input data
  52. func (evm *EVM) Run(contract *Contract, input []byte) (ret []byte, err error) {
  53. evm.env.SetDepth(evm.env.Depth() + 1)
  54. defer evm.env.SetDepth(evm.env.Depth() - 1)
  55. if contract.CodeAddr != nil {
  56. if p := Precompiled[contract.CodeAddr.Str()]; p != nil {
  57. return evm.RunPrecompiled(p, input, contract)
  58. }
  59. }
  60. // Don't bother with the execution if there's no code.
  61. if len(contract.Code) == 0 {
  62. return nil, nil
  63. }
  64. codehash := contract.CodeHash // codehash is used when doing jump dest caching
  65. if codehash == (common.Hash{}) {
  66. codehash = crypto.Keccak256Hash(contract.Code)
  67. }
  68. var program *Program
  69. if evm.cfg.EnableJit {
  70. // If the JIT is enabled check the status of the JIT program,
  71. // if it doesn't exist compile a new program in a separate
  72. // goroutine or wait for compilation to finish if the JIT is
  73. // forced.
  74. switch GetProgramStatus(codehash) {
  75. case progReady:
  76. return RunProgram(GetProgram(codehash), evm.env, contract, input)
  77. case progUnknown:
  78. if evm.cfg.ForceJit {
  79. // Create and compile program
  80. program = NewProgram(contract.Code)
  81. perr := CompileProgram(program)
  82. if perr == nil {
  83. return RunProgram(program, evm.env, contract, input)
  84. }
  85. glog.V(logger.Info).Infoln("error compiling program", err)
  86. } else {
  87. // create and compile the program. Compilation
  88. // is done in a separate goroutine
  89. program = NewProgram(contract.Code)
  90. go func() {
  91. err := CompileProgram(program)
  92. if err != nil {
  93. glog.V(logger.Info).Infoln("error compiling program", err)
  94. return
  95. }
  96. }()
  97. }
  98. }
  99. }
  100. var (
  101. caller = contract.caller
  102. code = contract.Code
  103. instrCount = 0
  104. op OpCode // current opcode
  105. mem = NewMemory() // bound memory
  106. stack = newstack() // local stack
  107. statedb = evm.env.Db() // current state
  108. // For optimisation reason we're using uint64 as the program counter.
  109. // It's theoretically possible to go above 2^64. The YP defines the PC to be uint256. Practically much less so feasible.
  110. pc = uint64(0) // program counter
  111. // jump evaluates and checks whether the given jump destination is a valid one
  112. // if valid move the `pc` otherwise return an error.
  113. jump = func(from uint64, to *big.Int) error {
  114. if !contract.jumpdests.has(codehash, code, to) {
  115. nop := contract.GetOp(to.Uint64())
  116. return fmt.Errorf("invalid jump destination (%v) %v", nop, to)
  117. }
  118. pc = to.Uint64()
  119. return nil
  120. }
  121. newMemSize *big.Int
  122. cost *big.Int
  123. )
  124. contract.Input = input
  125. // User defer pattern to check for an error and, based on the error being nil or not, use all gas and return.
  126. defer func() {
  127. if err != nil && evm.cfg.Debug {
  128. evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.Depth(), err)
  129. }
  130. }()
  131. if glog.V(logger.Debug) {
  132. glog.Infof("running byte VM %x\n", codehash[:4])
  133. tstart := time.Now()
  134. defer func() {
  135. glog.Infof("byte VM %x done. time: %v instrc: %v\n", codehash[:4], time.Since(tstart), instrCount)
  136. }()
  137. }
  138. for ; ; instrCount++ {
  139. /*
  140. if EnableJit && it%100 == 0 {
  141. if program != nil && progStatus(atomic.LoadInt32(&program.status)) == progReady {
  142. // move execution
  143. fmt.Println("moved", it)
  144. glog.V(logger.Info).Infoln("Moved execution to JIT")
  145. return runProgram(program, pc, mem, stack, evm.env, contract, input)
  146. }
  147. }
  148. */
  149. // Get the memory location of pc
  150. op = contract.GetOp(pc)
  151. // calculate the new memory size and gas price for the current executing opcode
  152. newMemSize, cost, err = calculateGasAndSize(evm.env, contract, caller, op, statedb, mem, stack)
  153. if err != nil {
  154. return nil, err
  155. }
  156. // Use the calculated gas. When insufficient gas is present, use all gas and return an
  157. // Out Of Gas error
  158. if !contract.UseGas(cost) {
  159. return nil, OutOfGasError
  160. }
  161. // Resize the memory calculated previously
  162. mem.Resize(newMemSize.Uint64())
  163. // Add a log message
  164. if evm.cfg.Debug {
  165. evm.cfg.Tracer.CaptureState(evm.env, pc, op, contract.Gas, cost, mem, stack, contract, evm.env.Depth(), nil)
  166. }
  167. if opPtr := evm.jumpTable[op]; opPtr.valid {
  168. if opPtr.fn != nil {
  169. opPtr.fn(instruction{}, &pc, evm.env, contract, mem, stack)
  170. } else {
  171. switch op {
  172. case PC:
  173. opPc(instruction{data: new(big.Int).SetUint64(pc)}, &pc, evm.env, contract, mem, stack)
  174. case JUMP:
  175. if err := jump(pc, stack.pop()); err != nil {
  176. return nil, err
  177. }
  178. continue
  179. case JUMPI:
  180. pos, cond := stack.pop(), stack.pop()
  181. if cond.Cmp(common.BigTrue) >= 0 {
  182. if err := jump(pc, pos); err != nil {
  183. return nil, err
  184. }
  185. continue
  186. }
  187. case RETURN:
  188. offset, size := stack.pop(), stack.pop()
  189. ret := mem.GetPtr(offset.Int64(), size.Int64())
  190. return ret, nil
  191. case SUICIDE:
  192. opSuicide(instruction{}, nil, evm.env, contract, mem, stack)
  193. fallthrough
  194. case STOP: // Stop the contract
  195. return nil, nil
  196. }
  197. }
  198. } else {
  199. return nil, fmt.Errorf("Invalid opcode %x", op)
  200. }
  201. pc++
  202. }
  203. }
  204. // calculateGasAndSize calculates the required given the opcode and stack items calculates the new memorysize for
  205. // the operation. This does not reduce gas or resizes the memory.
  206. func calculateGasAndSize(env Environment, contract *Contract, caller ContractRef, op OpCode, statedb Database, mem *Memory, stack *Stack) (*big.Int, *big.Int, error) {
  207. var (
  208. gas = new(big.Int)
  209. newMemSize *big.Int = new(big.Int)
  210. )
  211. err := baseCheck(op, stack, gas)
  212. if err != nil {
  213. return nil, nil, err
  214. }
  215. // stack Check, memory resize & gas phase
  216. switch op {
  217. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  218. n := int(op - SWAP1 + 2)
  219. err := stack.require(n)
  220. if err != nil {
  221. return nil, nil, err
  222. }
  223. gas.Set(GasFastestStep)
  224. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  225. n := int(op - DUP1 + 1)
  226. err := stack.require(n)
  227. if err != nil {
  228. return nil, nil, err
  229. }
  230. gas.Set(GasFastestStep)
  231. case LOG0, LOG1, LOG2, LOG3, LOG4:
  232. n := int(op - LOG0)
  233. err := stack.require(n + 2)
  234. if err != nil {
  235. return nil, nil, err
  236. }
  237. mSize, mStart := stack.data[stack.len()-2], stack.data[stack.len()-1]
  238. gas.Add(gas, params.LogGas)
  239. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(n)), params.LogTopicGas))
  240. gas.Add(gas, new(big.Int).Mul(mSize, params.LogDataGas))
  241. newMemSize = calcMemSize(mStart, mSize)
  242. case EXP:
  243. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(len(stack.data[stack.len()-2].Bytes()))), params.ExpByteGas))
  244. case SSTORE:
  245. err := stack.require(2)
  246. if err != nil {
  247. return nil, nil, err
  248. }
  249. var g *big.Int
  250. y, x := stack.data[stack.len()-2], stack.data[stack.len()-1]
  251. val := statedb.GetState(contract.Address(), common.BigToHash(x))
  252. // This checks for 3 scenario's and calculates gas accordingly
  253. // 1. From a zero-value address to a non-zero value (NEW VALUE)
  254. // 2. From a non-zero value address to a zero-value address (DELETE)
  255. // 3. From a non-zero to a non-zero (CHANGE)
  256. if common.EmptyHash(val) && !common.EmptyHash(common.BigToHash(y)) {
  257. // 0 => non 0
  258. g = params.SstoreSetGas
  259. } else if !common.EmptyHash(val) && common.EmptyHash(common.BigToHash(y)) {
  260. statedb.AddRefund(params.SstoreRefundGas)
  261. g = params.SstoreClearGas
  262. } else {
  263. // non 0 => non 0 (or 0 => 0)
  264. g = params.SstoreResetGas
  265. }
  266. gas.Set(g)
  267. case SUICIDE:
  268. if !statedb.IsDeleted(contract.Address()) {
  269. statedb.AddRefund(params.SuicideRefundGas)
  270. }
  271. case MLOAD:
  272. newMemSize = calcMemSize(stack.peek(), u256(32))
  273. case MSTORE8:
  274. newMemSize = calcMemSize(stack.peek(), u256(1))
  275. case MSTORE:
  276. newMemSize = calcMemSize(stack.peek(), u256(32))
  277. case RETURN:
  278. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  279. case SHA3:
  280. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  281. words := toWordSize(stack.data[stack.len()-2])
  282. gas.Add(gas, words.Mul(words, params.Sha3WordGas))
  283. case CALLDATACOPY:
  284. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  285. words := toWordSize(stack.data[stack.len()-3])
  286. gas.Add(gas, words.Mul(words, params.CopyGas))
  287. case CODECOPY:
  288. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  289. words := toWordSize(stack.data[stack.len()-3])
  290. gas.Add(gas, words.Mul(words, params.CopyGas))
  291. case EXTCODECOPY:
  292. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
  293. words := toWordSize(stack.data[stack.len()-4])
  294. gas.Add(gas, words.Mul(words, params.CopyGas))
  295. case CREATE:
  296. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
  297. case CALL, CALLCODE:
  298. gas.Add(gas, stack.data[stack.len()-1])
  299. if op == CALL {
  300. if !env.Db().Exist(common.BigToAddress(stack.data[stack.len()-2])) {
  301. gas.Add(gas, params.CallNewAccountGas)
  302. }
  303. }
  304. if len(stack.data[stack.len()-3].Bytes()) > 0 {
  305. gas.Add(gas, params.CallValueTransferGas)
  306. }
  307. x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
  308. y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
  309. newMemSize = common.BigMax(x, y)
  310. case DELEGATECALL:
  311. gas.Add(gas, stack.data[stack.len()-1])
  312. x := calcMemSize(stack.data[stack.len()-5], stack.data[stack.len()-6])
  313. y := calcMemSize(stack.data[stack.len()-3], stack.data[stack.len()-4])
  314. newMemSize = common.BigMax(x, y)
  315. }
  316. quadMemGas(mem, newMemSize, gas)
  317. return newMemSize, gas, nil
  318. }
  319. // RunPrecompile runs and evaluate the output of a precompiled contract defined in contracts.go
  320. func (evm *EVM) RunPrecompiled(p *PrecompiledAccount, input []byte, contract *Contract) (ret []byte, err error) {
  321. gas := p.Gas(len(input))
  322. if contract.UseGas(gas) {
  323. ret = p.Call(input)
  324. return ret, nil
  325. } else {
  326. return nil, OutOfGasError
  327. }
  328. }