vm.go 12 KB

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