jit.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. "sync/atomic"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/logger"
  25. "github.com/ethereum/go-ethereum/logger/glog"
  26. "github.com/ethereum/go-ethereum/params"
  27. "github.com/hashicorp/golang-lru"
  28. )
  29. type progStatus int32
  30. const (
  31. progUnknown progStatus = iota
  32. progCompile
  33. progReady
  34. progError
  35. defaultJitMaxCache int = 64
  36. )
  37. var (
  38. EnableJit bool // Enables the JIT VM
  39. ForceJit bool // Force the JIT, skip byte VM
  40. MaxProgSize int // Max cache size for JIT Programs
  41. )
  42. var programs *lru.Cache
  43. func init() {
  44. programs, _ = lru.New(defaultJitMaxCache)
  45. }
  46. // SetJITCacheSize recreates the program cache with the max given size. Setting
  47. // a new cache is **not** thread safe. Use with caution.
  48. func SetJITCacheSize(size int) {
  49. programs, _ = lru.New(size)
  50. }
  51. // GetProgram returns the program by id or nil when non-existent
  52. func GetProgram(id common.Hash) *Program {
  53. if p, ok := programs.Get(id); ok {
  54. return p.(*Program)
  55. }
  56. return nil
  57. }
  58. // GenProgramStatus returns the status of the given program id
  59. func GetProgramStatus(id common.Hash) progStatus {
  60. program := GetProgram(id)
  61. if program != nil {
  62. return progStatus(atomic.LoadInt32(&program.status))
  63. }
  64. return progUnknown
  65. }
  66. // Program is a compiled program for the JIT VM and holds all required for
  67. // running a compiled JIT program.
  68. type Program struct {
  69. Id common.Hash // Id of the program
  70. status int32 // status should be accessed atomically
  71. contract *Contract
  72. instructions []programInstruction // instruction set
  73. mapping map[uint64]uint64 // real PC mapping to array indices
  74. destinations map[uint64]struct{} // cached jump destinations
  75. code []byte
  76. }
  77. // NewProgram returns a new JIT program
  78. func NewProgram(code []byte) *Program {
  79. program := &Program{
  80. Id: crypto.Keccak256Hash(code),
  81. mapping: make(map[uint64]uint64),
  82. destinations: make(map[uint64]struct{}),
  83. code: code,
  84. }
  85. programs.Add(program.Id, program)
  86. return program
  87. }
  88. func (p *Program) addInstr(op OpCode, pc uint64, fn instrFn, data *big.Int) {
  89. // PUSH and DUP are a bit special. They all cost the same but we do want to have checking on stack push limit
  90. // PUSH is also allowed to calculate the same price for all PUSHes
  91. // DUP requirements are handled elsewhere (except for the stack limit check)
  92. baseOp := op
  93. if op >= PUSH1 && op <= PUSH32 {
  94. baseOp = PUSH1
  95. }
  96. if op >= DUP1 && op <= DUP16 {
  97. baseOp = DUP1
  98. }
  99. base := _baseCheck[baseOp]
  100. returns := op == RETURN || op == SUICIDE || op == STOP
  101. instr := instruction{op, pc, fn, data, base.gas, base.stackPop, base.stackPush, returns}
  102. p.instructions = append(p.instructions, instr)
  103. p.mapping[pc] = uint64(len(p.instructions) - 1)
  104. }
  105. // CompileProgram compiles the given program and return an error when it fails
  106. func CompileProgram(program *Program) (err error) {
  107. if progStatus(atomic.LoadInt32(&program.status)) == progCompile {
  108. return nil
  109. }
  110. atomic.StoreInt32(&program.status, int32(progCompile))
  111. defer func() {
  112. if err != nil {
  113. atomic.StoreInt32(&program.status, int32(progError))
  114. } else {
  115. atomic.StoreInt32(&program.status, int32(progReady))
  116. }
  117. }()
  118. if glog.V(logger.Debug) {
  119. glog.Infof("compiling %x\n", program.Id[:4])
  120. tstart := time.Now()
  121. defer func() {
  122. glog.Infof("compiled %x instrc: %d time: %v\n", program.Id[:4], len(program.instructions), time.Since(tstart))
  123. }()
  124. }
  125. // loop thru the opcodes and "compile" in to instructions
  126. for pc := uint64(0); pc < uint64(len(program.code)); pc++ {
  127. switch op := OpCode(program.code[pc]); op {
  128. case ADD:
  129. program.addInstr(op, pc, opAdd, nil)
  130. case SUB:
  131. program.addInstr(op, pc, opSub, nil)
  132. case MUL:
  133. program.addInstr(op, pc, opMul, nil)
  134. case DIV:
  135. program.addInstr(op, pc, opDiv, nil)
  136. case SDIV:
  137. program.addInstr(op, pc, opSdiv, nil)
  138. case MOD:
  139. program.addInstr(op, pc, opMod, nil)
  140. case SMOD:
  141. program.addInstr(op, pc, opSmod, nil)
  142. case EXP:
  143. program.addInstr(op, pc, opExp, nil)
  144. case SIGNEXTEND:
  145. program.addInstr(op, pc, opSignExtend, nil)
  146. case NOT:
  147. program.addInstr(op, pc, opNot, nil)
  148. case LT:
  149. program.addInstr(op, pc, opLt, nil)
  150. case GT:
  151. program.addInstr(op, pc, opGt, nil)
  152. case SLT:
  153. program.addInstr(op, pc, opSlt, nil)
  154. case SGT:
  155. program.addInstr(op, pc, opSgt, nil)
  156. case EQ:
  157. program.addInstr(op, pc, opEq, nil)
  158. case ISZERO:
  159. program.addInstr(op, pc, opIszero, nil)
  160. case AND:
  161. program.addInstr(op, pc, opAnd, nil)
  162. case OR:
  163. program.addInstr(op, pc, opOr, nil)
  164. case XOR:
  165. program.addInstr(op, pc, opXor, nil)
  166. case BYTE:
  167. program.addInstr(op, pc, opByte, nil)
  168. case ADDMOD:
  169. program.addInstr(op, pc, opAddmod, nil)
  170. case MULMOD:
  171. program.addInstr(op, pc, opMulmod, nil)
  172. case SHA3:
  173. program.addInstr(op, pc, opSha3, nil)
  174. case ADDRESS:
  175. program.addInstr(op, pc, opAddress, nil)
  176. case BALANCE:
  177. program.addInstr(op, pc, opBalance, nil)
  178. case ORIGIN:
  179. program.addInstr(op, pc, opOrigin, nil)
  180. case CALLER:
  181. program.addInstr(op, pc, opCaller, nil)
  182. case CALLVALUE:
  183. program.addInstr(op, pc, opCallValue, nil)
  184. case CALLDATALOAD:
  185. program.addInstr(op, pc, opCalldataLoad, nil)
  186. case CALLDATASIZE:
  187. program.addInstr(op, pc, opCalldataSize, nil)
  188. case CALLDATACOPY:
  189. program.addInstr(op, pc, opCalldataCopy, nil)
  190. case CODESIZE:
  191. program.addInstr(op, pc, opCodeSize, nil)
  192. case EXTCODESIZE:
  193. program.addInstr(op, pc, opExtCodeSize, nil)
  194. case CODECOPY:
  195. program.addInstr(op, pc, opCodeCopy, nil)
  196. case EXTCODECOPY:
  197. program.addInstr(op, pc, opExtCodeCopy, nil)
  198. case GASPRICE:
  199. program.addInstr(op, pc, opGasprice, nil)
  200. case BLOCKHASH:
  201. program.addInstr(op, pc, opBlockhash, nil)
  202. case COINBASE:
  203. program.addInstr(op, pc, opCoinbase, nil)
  204. case TIMESTAMP:
  205. program.addInstr(op, pc, opTimestamp, nil)
  206. case NUMBER:
  207. program.addInstr(op, pc, opNumber, nil)
  208. case DIFFICULTY:
  209. program.addInstr(op, pc, opDifficulty, nil)
  210. case GASLIMIT:
  211. program.addInstr(op, pc, opGasLimit, nil)
  212. case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
  213. size := uint64(op - PUSH1 + 1)
  214. bytes := getData([]byte(program.code), new(big.Int).SetUint64(pc+1), new(big.Int).SetUint64(size))
  215. program.addInstr(op, pc, opPush, common.Bytes2Big(bytes))
  216. pc += size
  217. case POP:
  218. program.addInstr(op, pc, opPop, nil)
  219. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  220. program.addInstr(op, pc, opDup, big.NewInt(int64(op-DUP1+1)))
  221. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  222. program.addInstr(op, pc, opSwap, big.NewInt(int64(op-SWAP1+2)))
  223. case LOG0, LOG1, LOG2, LOG3, LOG4:
  224. program.addInstr(op, pc, opLog, big.NewInt(int64(op-LOG0)))
  225. case MLOAD:
  226. program.addInstr(op, pc, opMload, nil)
  227. case MSTORE:
  228. program.addInstr(op, pc, opMstore, nil)
  229. case MSTORE8:
  230. program.addInstr(op, pc, opMstore8, nil)
  231. case SLOAD:
  232. program.addInstr(op, pc, opSload, nil)
  233. case SSTORE:
  234. program.addInstr(op, pc, opSstore, nil)
  235. case JUMP:
  236. program.addInstr(op, pc, opJump, nil)
  237. case JUMPI:
  238. program.addInstr(op, pc, opJumpi, nil)
  239. case JUMPDEST:
  240. program.addInstr(op, pc, opJumpdest, nil)
  241. program.destinations[pc] = struct{}{}
  242. case PC:
  243. program.addInstr(op, pc, opPc, big.NewInt(int64(pc)))
  244. case MSIZE:
  245. program.addInstr(op, pc, opMsize, nil)
  246. case GAS:
  247. program.addInstr(op, pc, opGas, nil)
  248. case CREATE:
  249. program.addInstr(op, pc, opCreate, nil)
  250. case DELEGATECALL:
  251. // Instruction added regardless of homestead phase.
  252. // Homestead (and execution of the opcode) is checked during
  253. // runtime.
  254. program.addInstr(op, pc, opDelegateCall, nil)
  255. case CALL:
  256. program.addInstr(op, pc, opCall, nil)
  257. case CALLCODE:
  258. program.addInstr(op, pc, opCallCode, nil)
  259. case RETURN:
  260. program.addInstr(op, pc, opReturn, nil)
  261. case SUICIDE:
  262. program.addInstr(op, pc, opSuicide, nil)
  263. case STOP: // Stop the contract
  264. program.addInstr(op, pc, opStop, nil)
  265. default:
  266. program.addInstr(op, pc, nil, nil)
  267. }
  268. }
  269. optimiseProgram(program)
  270. return nil
  271. }
  272. // RunProgram runs the program given the environment and contract and returns an
  273. // error if the execution failed (non-consensus)
  274. func RunProgram(program *Program, env Environment, contract *Contract, input []byte) ([]byte, error) {
  275. return runProgram(program, 0, NewMemory(), newstack(), env, contract, input)
  276. }
  277. func runProgram(program *Program, pcstart uint64, mem *Memory, stack *stack, env Environment, contract *Contract, input []byte) ([]byte, error) {
  278. contract.Input = input
  279. var (
  280. pc uint64 = program.mapping[pcstart]
  281. instrCount = 0
  282. )
  283. if glog.V(logger.Debug) {
  284. glog.Infof("running JIT program %x\n", program.Id[:4])
  285. tstart := time.Now()
  286. defer func() {
  287. glog.Infof("JIT program %x done. time: %v instrc: %v\n", program.Id[:4], time.Since(tstart), instrCount)
  288. }()
  289. }
  290. homestead := params.IsHomestead(env.BlockNumber())
  291. for pc < uint64(len(program.instructions)) {
  292. instrCount++
  293. instr := program.instructions[pc]
  294. if instr.Op() == DELEGATECALL && !homestead {
  295. return nil, fmt.Errorf("Invalid opcode 0x%x", instr.Op())
  296. }
  297. ret, err := instr.do(program, &pc, env, contract, mem, stack)
  298. if err != nil {
  299. return nil, err
  300. }
  301. if instr.halts() {
  302. return ret, nil
  303. }
  304. }
  305. contract.Input = nil
  306. return nil, nil
  307. }
  308. // validDest checks if the given destination is a valid one given the
  309. // destination table of the program
  310. func validDest(dests map[uint64]struct{}, dest *big.Int) bool {
  311. // PC cannot go beyond len(code) and certainly can't be bigger than 64bits.
  312. // Don't bother checking for JUMPDEST in that case.
  313. if dest.Cmp(bigMaxUint64) > 0 {
  314. return false
  315. }
  316. _, ok := dests[dest.Uint64()]
  317. return ok
  318. }
  319. // jitCalculateGasAndSize calculates the required given the opcode and stack items calculates the new memorysize for
  320. // the operation. This does not reduce gas or resizes the memory.
  321. func jitCalculateGasAndSize(env Environment, contract *Contract, instr instruction, statedb Database, mem *Memory, stack *stack) (*big.Int, *big.Int, error) {
  322. var (
  323. gas = new(big.Int)
  324. newMemSize *big.Int = new(big.Int)
  325. )
  326. err := jitBaseCheck(instr, stack, gas)
  327. if err != nil {
  328. return nil, nil, err
  329. }
  330. // stack Check, memory resize & gas phase
  331. switch op := instr.op; op {
  332. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  333. n := int(op - SWAP1 + 2)
  334. err := stack.require(n)
  335. if err != nil {
  336. return nil, nil, err
  337. }
  338. gas.Set(GasFastestStep)
  339. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  340. n := int(op - DUP1 + 1)
  341. err := stack.require(n)
  342. if err != nil {
  343. return nil, nil, err
  344. }
  345. gas.Set(GasFastestStep)
  346. case LOG0, LOG1, LOG2, LOG3, LOG4:
  347. n := int(op - LOG0)
  348. err := stack.require(n + 2)
  349. if err != nil {
  350. return nil, nil, err
  351. }
  352. mSize, mStart := stack.data[stack.len()-2], stack.data[stack.len()-1]
  353. add := new(big.Int)
  354. gas.Add(gas, params.LogGas)
  355. gas.Add(gas, add.Mul(big.NewInt(int64(n)), params.LogTopicGas))
  356. gas.Add(gas, add.Mul(mSize, params.LogDataGas))
  357. newMemSize = calcMemSize(mStart, mSize)
  358. case EXP:
  359. gas.Add(gas, new(big.Int).Mul(big.NewInt(int64(len(stack.data[stack.len()-2].Bytes()))), params.ExpByteGas))
  360. case SSTORE:
  361. err := stack.require(2)
  362. if err != nil {
  363. return nil, nil, err
  364. }
  365. var g *big.Int
  366. y, x := stack.data[stack.len()-2], stack.data[stack.len()-1]
  367. val := statedb.GetState(contract.Address(), common.BigToHash(x))
  368. // This checks for 3 scenario's and calculates gas accordingly
  369. // 1. From a zero-value address to a non-zero value (NEW VALUE)
  370. // 2. From a non-zero value address to a zero-value address (DELETE)
  371. // 3. From a non-zero to a non-zero (CHANGE)
  372. if common.EmptyHash(val) && !common.EmptyHash(common.BigToHash(y)) {
  373. g = params.SstoreSetGas
  374. } else if !common.EmptyHash(val) && common.EmptyHash(common.BigToHash(y)) {
  375. statedb.AddRefund(params.SstoreRefundGas)
  376. g = params.SstoreClearGas
  377. } else {
  378. g = params.SstoreClearGas
  379. }
  380. gas.Set(g)
  381. case SUICIDE:
  382. if !statedb.IsDeleted(contract.Address()) {
  383. statedb.AddRefund(params.SuicideRefundGas)
  384. }
  385. case MLOAD:
  386. newMemSize = calcMemSize(stack.peek(), u256(32))
  387. case MSTORE8:
  388. newMemSize = calcMemSize(stack.peek(), u256(1))
  389. case MSTORE:
  390. newMemSize = calcMemSize(stack.peek(), u256(32))
  391. case RETURN:
  392. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  393. case SHA3:
  394. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-2])
  395. words := toWordSize(stack.data[stack.len()-2])
  396. gas.Add(gas, words.Mul(words, params.Sha3WordGas))
  397. case CALLDATACOPY:
  398. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  399. words := toWordSize(stack.data[stack.len()-3])
  400. gas.Add(gas, words.Mul(words, params.CopyGas))
  401. case CODECOPY:
  402. newMemSize = calcMemSize(stack.peek(), stack.data[stack.len()-3])
  403. words := toWordSize(stack.data[stack.len()-3])
  404. gas.Add(gas, words.Mul(words, params.CopyGas))
  405. case EXTCODECOPY:
  406. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-4])
  407. words := toWordSize(stack.data[stack.len()-4])
  408. gas.Add(gas, words.Mul(words, params.CopyGas))
  409. case CREATE:
  410. newMemSize = calcMemSize(stack.data[stack.len()-2], stack.data[stack.len()-3])
  411. case CALL, CALLCODE:
  412. gas.Add(gas, stack.data[stack.len()-1])
  413. if op == CALL {
  414. if !env.Db().Exist(common.BigToAddress(stack.data[stack.len()-2])) {
  415. gas.Add(gas, params.CallNewAccountGas)
  416. }
  417. }
  418. if len(stack.data[stack.len()-3].Bytes()) > 0 {
  419. gas.Add(gas, params.CallValueTransferGas)
  420. }
  421. x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7])
  422. y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5])
  423. newMemSize = common.BigMax(x, y)
  424. case DELEGATECALL:
  425. gas.Add(gas, stack.data[stack.len()-1])
  426. x := calcMemSize(stack.data[stack.len()-5], stack.data[stack.len()-6])
  427. y := calcMemSize(stack.data[stack.len()-3], stack.data[stack.len()-4])
  428. newMemSize = common.BigMax(x, y)
  429. }
  430. quadMemGas(mem, newMemSize, gas)
  431. return newMemSize, gas, nil
  432. }
  433. // jitBaseCheck is the same as baseCheck except it doesn't do the look up in the
  434. // gas table. This is done during compilation instead.
  435. func jitBaseCheck(instr instruction, stack *stack, gas *big.Int) error {
  436. err := stack.require(instr.spop)
  437. if err != nil {
  438. return err
  439. }
  440. if instr.spush > 0 && stack.len()-instr.spop+instr.spush > int(params.StackLimit.Int64()) {
  441. return fmt.Errorf("stack limit reached %d (%d)", stack.len(), params.StackLimit.Int64())
  442. }
  443. // nil on gas means no base calculation
  444. if instr.gas == nil {
  445. return nil
  446. }
  447. gas.Add(gas, instr.gas)
  448. return nil
  449. }