vm.go 11 KB

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