jit.go 16 KB

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