vm.go 11 KB

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