vm_debug.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. package vm
  2. import (
  3. "fmt"
  4. "math"
  5. "math/big"
  6. "github.com/ethereum/go-ethereum/crypto"
  7. "github.com/ethereum/go-ethereum/ethutil"
  8. "github.com/ethereum/go-ethereum/state"
  9. )
  10. type DebugVm struct {
  11. env Environment
  12. logTy byte
  13. logStr string
  14. err error
  15. // Debugging
  16. Dbg Debugger
  17. BreakPoints []int64
  18. Stepping bool
  19. Fn string
  20. Recoverable bool
  21. }
  22. func NewDebugVm(env Environment) *DebugVm {
  23. lt := LogTyPretty
  24. if ethutil.Config.Diff {
  25. lt = LogTyDiff
  26. }
  27. return &DebugVm{env: env, logTy: lt, Recoverable: true}
  28. }
  29. func (self *DebugVm) Run(me, caller ContextRef, code []byte, value, gas, price *big.Int, callData []byte) (ret []byte, err error) {
  30. self.env.SetDepth(self.env.Depth() + 1)
  31. msg := self.env.State().Manifest().AddMessage(&state.Message{
  32. To: me.Address(), From: caller.Address(),
  33. Input: callData,
  34. Origin: self.env.Origin(),
  35. Block: self.env.BlockHash(), Timestamp: self.env.Time(), Coinbase: self.env.Coinbase(), Number: self.env.BlockNumber(),
  36. Value: value,
  37. })
  38. context := NewContext(msg, caller, me, code, gas, price)
  39. if self.Recoverable {
  40. // Recover from any require exception
  41. defer func() {
  42. if r := recover(); r != nil {
  43. self.Printf(" %v", r).Endl()
  44. context.UseGas(context.Gas)
  45. ret = context.Return(nil)
  46. err = fmt.Errorf("%v", r)
  47. }
  48. }()
  49. }
  50. if p := Precompiled[string(me.Address())]; p != nil {
  51. return self.RunPrecompiled(p, callData, context)
  52. }
  53. var (
  54. op OpCode
  55. destinations = analyseJumpDests(context.Code)
  56. mem = NewMemory()
  57. stack = NewStack()
  58. pc uint64 = 0
  59. step = 0
  60. prevStep = 0
  61. statedb = self.env.State()
  62. jump = func(from uint64, to *big.Int) {
  63. p := to.Uint64()
  64. self.Printf(" ~> %v", to)
  65. /* NOTE: new model. Will change soon
  66. nop := OpCode(context.GetOp(p))
  67. if nop != JUMPDEST {
  68. panic(fmt.Sprintf("invalid jump destination (%v) %v", nop, p))
  69. }
  70. pc = to.Uint64()
  71. */
  72. // Return to start
  73. if p == 0 {
  74. pc = 0
  75. } else {
  76. nop := OpCode(context.GetOp(p))
  77. if !(nop == JUMPDEST || destinations[from] != nil) {
  78. panic(fmt.Sprintf("invalid jump destination (%v) %v", nop, p))
  79. } else if nop == JUMP || nop == JUMPI {
  80. panic(fmt.Sprintf("not allowed to JUMP(I) in to JUMP"))
  81. }
  82. pc = to.Uint64()
  83. }
  84. self.Endl()
  85. }
  86. )
  87. vmlogger.Debugf("(%d) (%x) %x (code=%d) gas: %v (d) %x\n", self.env.Depth(), caller.Address()[:4], context.Address(), len(code), context.Gas, callData)
  88. // Don't bother with the execution if there's no code.
  89. if len(code) == 0 {
  90. return context.Return(nil), nil
  91. }
  92. for {
  93. prevStep = step
  94. // The base for all big integer arithmetic
  95. base := new(big.Int)
  96. step++
  97. // Get the memory location of pc
  98. op = context.GetOp(pc)
  99. self.Printf("(pc) %-3d -o- %-14s (m) %-4d (s) %-4d ", pc, op.String(), mem.Len(), stack.Len())
  100. newMemSize, gas := self.calculateGasAndSize(context, caller, op, statedb, mem, stack)
  101. self.Printf("(g) %-3v (%v)", gas, context.Gas)
  102. if !context.UseGas(gas) {
  103. self.Endl()
  104. tmp := new(big.Int).Set(context.Gas)
  105. context.UseGas(context.Gas)
  106. return context.Return(nil), OOG(gas, tmp)
  107. }
  108. mem.Resize(newMemSize.Uint64())
  109. switch op {
  110. // 0x20 range
  111. case ADD:
  112. x, y := stack.Popn()
  113. self.Printf(" %v + %v", y, x)
  114. base.Add(y, x)
  115. U256(base)
  116. self.Printf(" = %v", base)
  117. // Pop result back on the stack
  118. stack.Push(base)
  119. case SUB:
  120. x, y := stack.Popn()
  121. self.Printf(" %v - %v", y, x)
  122. base.Sub(y, x)
  123. U256(base)
  124. self.Printf(" = %v", base)
  125. // Pop result back on the stack
  126. stack.Push(base)
  127. case MUL:
  128. x, y := stack.Popn()
  129. self.Printf(" %v * %v", y, x)
  130. base.Mul(y, x)
  131. U256(base)
  132. self.Printf(" = %v", base)
  133. // Pop result back on the stack
  134. stack.Push(base)
  135. case DIV:
  136. x, y := stack.Pop(), stack.Pop()
  137. self.Printf(" %v / %v", x, y)
  138. if y.Cmp(ethutil.Big0) != 0 {
  139. base.Div(x, y)
  140. }
  141. U256(base)
  142. self.Printf(" = %v", base)
  143. // Pop result back on the stack
  144. stack.Push(base)
  145. case SDIV:
  146. x, y := S256(stack.Pop()), S256(stack.Pop())
  147. self.Printf(" %v / %v", x, y)
  148. if y.Cmp(ethutil.Big0) == 0 {
  149. base.Set(ethutil.Big0)
  150. } else {
  151. n := new(big.Int)
  152. if new(big.Int).Mul(x, y).Cmp(ethutil.Big0) < 0 {
  153. n.SetInt64(-1)
  154. } else {
  155. n.SetInt64(1)
  156. }
  157. base.Div(x.Abs(x), y.Abs(y)).Mul(base, n)
  158. U256(base)
  159. }
  160. self.Printf(" = %v", base)
  161. stack.Push(base)
  162. case MOD:
  163. x, y := stack.Pop(), stack.Pop()
  164. self.Printf(" %v %% %v", x, y)
  165. if y.Cmp(ethutil.Big0) == 0 {
  166. base.Set(ethutil.Big0)
  167. } else {
  168. base.Mod(x, y)
  169. }
  170. U256(base)
  171. self.Printf(" = %v", base)
  172. stack.Push(base)
  173. case SMOD:
  174. x, y := S256(stack.Pop()), S256(stack.Pop())
  175. self.Printf(" %v %% %v", x, y)
  176. if y.Cmp(ethutil.Big0) == 0 {
  177. base.Set(ethutil.Big0)
  178. } else {
  179. n := new(big.Int)
  180. if x.Cmp(ethutil.Big0) < 0 {
  181. n.SetInt64(-1)
  182. } else {
  183. n.SetInt64(1)
  184. }
  185. base.Mod(x.Abs(x), y.Abs(y)).Mul(base, n)
  186. U256(base)
  187. }
  188. self.Printf(" = %v", base)
  189. stack.Push(base)
  190. case EXP:
  191. x, y := stack.Popn()
  192. self.Printf(" %v ** %v", y, x)
  193. base.Exp(y, x, Pow256)
  194. U256(base)
  195. self.Printf(" = %v", base)
  196. stack.Push(base)
  197. case SIGNEXTEND:
  198. back := stack.Pop().Uint64()
  199. if back < 31 {
  200. bit := uint(back*8 + 7)
  201. num := stack.Pop()
  202. mask := new(big.Int).Lsh(ethutil.Big1, bit)
  203. mask.Sub(mask, ethutil.Big1)
  204. if ethutil.BitTest(num, int(bit)) {
  205. num.Or(num, mask.Not(mask))
  206. } else {
  207. num.And(num, mask)
  208. }
  209. num = U256(num)
  210. self.Printf(" = %v", num)
  211. stack.Push(num)
  212. }
  213. case NOT:
  214. base.Sub(Pow256, stack.Pop()).Sub(base, ethutil.Big1)
  215. // Not needed
  216. //base = U256(base)
  217. stack.Push(base)
  218. case LT:
  219. x, y := stack.Popn()
  220. self.Printf(" %v < %v", y, x)
  221. // x < y
  222. if y.Cmp(x) < 0 {
  223. stack.Push(ethutil.BigTrue)
  224. } else {
  225. stack.Push(ethutil.BigFalse)
  226. }
  227. case GT:
  228. x, y := stack.Popn()
  229. self.Printf(" %v > %v", y, x)
  230. // x > y
  231. if y.Cmp(x) > 0 {
  232. stack.Push(ethutil.BigTrue)
  233. } else {
  234. stack.Push(ethutil.BigFalse)
  235. }
  236. case SLT:
  237. y, x := S256(stack.Pop()), S256(stack.Pop())
  238. self.Printf(" %v < %v", y, x)
  239. // x < y
  240. if y.Cmp(S256(x)) < 0 {
  241. stack.Push(ethutil.BigTrue)
  242. } else {
  243. stack.Push(ethutil.BigFalse)
  244. }
  245. case SGT:
  246. y, x := S256(stack.Pop()), S256(stack.Pop())
  247. self.Printf(" %v > %v", y, x)
  248. // x > y
  249. if y.Cmp(x) > 0 {
  250. stack.Push(ethutil.BigTrue)
  251. } else {
  252. stack.Push(ethutil.BigFalse)
  253. }
  254. case EQ:
  255. x, y := stack.Popn()
  256. self.Printf(" %v == %v", y, x)
  257. // x == y
  258. if x.Cmp(y) == 0 {
  259. stack.Push(ethutil.BigTrue)
  260. } else {
  261. stack.Push(ethutil.BigFalse)
  262. }
  263. case ISZERO:
  264. x := stack.Pop()
  265. if x.Cmp(ethutil.BigFalse) > 0 {
  266. stack.Push(ethutil.BigFalse)
  267. } else {
  268. stack.Push(ethutil.BigTrue)
  269. }
  270. // 0x10 range
  271. case AND:
  272. x, y := stack.Popn()
  273. self.Printf(" %v & %v", y, x)
  274. stack.Push(base.And(y, x))
  275. case OR:
  276. x, y := stack.Popn()
  277. self.Printf(" %v | %v", y, x)
  278. stack.Push(base.Or(y, x))
  279. case XOR:
  280. x, y := stack.Popn()
  281. self.Printf(" %v ^ %v", y, x)
  282. stack.Push(base.Xor(y, x))
  283. case BYTE:
  284. val, th := stack.Popn()
  285. if th.Cmp(big.NewInt(32)) < 0 {
  286. byt := big.NewInt(int64(ethutil.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))
  287. base.Set(byt)
  288. } else {
  289. base.Set(ethutil.BigFalse)
  290. }
  291. self.Printf(" => 0x%x", base.Bytes())
  292. stack.Push(base)
  293. case ADDMOD:
  294. x := stack.Pop()
  295. y := stack.Pop()
  296. z := stack.Pop()
  297. base.Add(x, y)
  298. base.Mod(base, z)
  299. U256(base)
  300. self.Printf(" = %v", base)
  301. stack.Push(base)
  302. case MULMOD:
  303. x := stack.Pop()
  304. y := stack.Pop()
  305. z := stack.Pop()
  306. base.Mul(x, y)
  307. base.Mod(base, z)
  308. U256(base)
  309. self.Printf(" = %v", base)
  310. stack.Push(base)
  311. // 0x20 range
  312. case SHA3:
  313. size, offset := stack.Popn()
  314. data := crypto.Sha3(mem.Get(offset.Int64(), size.Int64()))
  315. stack.Push(ethutil.BigD(data))
  316. self.Printf(" => %x", data)
  317. // 0x30 range
  318. case ADDRESS:
  319. stack.Push(ethutil.BigD(context.Address()))
  320. self.Printf(" => %x", context.Address())
  321. case BALANCE:
  322. addr := stack.Pop().Bytes()
  323. balance := statedb.GetBalance(addr)
  324. stack.Push(balance)
  325. self.Printf(" => %v (%x)", balance, addr)
  326. case ORIGIN:
  327. origin := self.env.Origin()
  328. stack.Push(ethutil.BigD(origin))
  329. self.Printf(" => %x", origin)
  330. case CALLER:
  331. caller := context.caller.Address()
  332. stack.Push(ethutil.BigD(caller))
  333. self.Printf(" => %x", caller)
  334. case CALLVALUE:
  335. stack.Push(value)
  336. self.Printf(" => %v", value)
  337. case CALLDATALOAD:
  338. var (
  339. offset = stack.Pop()
  340. data = make([]byte, 32)
  341. lenData = big.NewInt(int64(len(callData)))
  342. )
  343. if lenData.Cmp(offset) >= 0 {
  344. length := new(big.Int).Add(offset, ethutil.Big32)
  345. length = ethutil.BigMin(length, lenData)
  346. copy(data, callData[offset.Int64():length.Int64()])
  347. }
  348. self.Printf(" => 0x%x", data)
  349. stack.Push(ethutil.BigD(data))
  350. case CALLDATASIZE:
  351. l := int64(len(callData))
  352. stack.Push(big.NewInt(l))
  353. self.Printf(" => %d", l)
  354. case CALLDATACOPY:
  355. var (
  356. size = uint64(len(callData))
  357. mOff = stack.Pop().Uint64()
  358. cOff = stack.Pop().Uint64()
  359. l = stack.Pop().Uint64()
  360. )
  361. if cOff > size {
  362. cOff = 0
  363. l = 0
  364. } else if cOff+l > size {
  365. l = 0
  366. }
  367. code := callData[cOff : cOff+l]
  368. mem.Set(mOff, l, code)
  369. self.Printf(" => [%v, %v, %v] %x", mOff, cOff, l, callData[cOff:cOff+l])
  370. case CODESIZE, EXTCODESIZE:
  371. var code []byte
  372. if op == EXTCODESIZE {
  373. addr := stack.Pop().Bytes()
  374. code = statedb.GetCode(addr)
  375. } else {
  376. code = context.Code
  377. }
  378. l := big.NewInt(int64(len(code)))
  379. stack.Push(l)
  380. self.Printf(" => %d", l)
  381. case CODECOPY, EXTCODECOPY:
  382. var code []byte
  383. if op == EXTCODECOPY {
  384. code = statedb.GetCode(stack.Pop().Bytes())
  385. } else {
  386. code = context.Code
  387. }
  388. var (
  389. size = uint64(len(code))
  390. mOff = stack.Pop().Uint64()
  391. cOff = stack.Pop().Uint64()
  392. l = stack.Pop().Uint64()
  393. )
  394. if cOff > size {
  395. cOff = 0
  396. l = 0
  397. } else if cOff+l > size {
  398. l = uint64(math.Min(float64(cOff+l), float64(size)))
  399. }
  400. codeCopy := code[cOff : cOff+l]
  401. mem.Set(mOff, l, codeCopy)
  402. self.Printf(" => [%v, %v, %v] %x", mOff, cOff, l, codeCopy)
  403. case GASPRICE:
  404. stack.Push(context.Price)
  405. self.Printf(" => %v", context.Price)
  406. // 0x40 range
  407. case PREVHASH:
  408. prevHash := self.env.PrevHash()
  409. stack.Push(ethutil.BigD(prevHash))
  410. self.Printf(" => 0x%x", prevHash)
  411. case COINBASE:
  412. coinbase := self.env.Coinbase()
  413. stack.Push(ethutil.BigD(coinbase))
  414. self.Printf(" => 0x%x", coinbase)
  415. case TIMESTAMP:
  416. time := self.env.Time()
  417. stack.Push(big.NewInt(time))
  418. self.Printf(" => 0x%x", time)
  419. case NUMBER:
  420. number := self.env.BlockNumber()
  421. stack.Push(number)
  422. self.Printf(" => 0x%x", number.Bytes())
  423. case DIFFICULTY:
  424. difficulty := self.env.Difficulty()
  425. stack.Push(difficulty)
  426. self.Printf(" => 0x%x", difficulty.Bytes())
  427. case GASLIMIT:
  428. stack.Push(self.env.GasLimit())
  429. // 0x50 range
  430. 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:
  431. a := uint64(op - PUSH1 + 1)
  432. byts := context.GetRangeValue(pc+1, a)
  433. // Push value to stack
  434. stack.Push(ethutil.BigD(byts))
  435. pc += a
  436. step += int(op) - int(PUSH1) + 1
  437. self.Printf(" => 0x%x", byts)
  438. case POP:
  439. stack.Pop()
  440. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  441. n := int(op - DUP1 + 1)
  442. stack.Dupn(n)
  443. self.Printf(" => [%d] 0x%x", n, stack.Peek().Bytes())
  444. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  445. n := int(op - SWAP1 + 2)
  446. x, y := stack.Swapn(n)
  447. self.Printf(" => [%d] %x [0] %x", n, x.Bytes(), y.Bytes())
  448. case LOG0, LOG1, LOG2, LOG3, LOG4:
  449. n := int(op - LOG0)
  450. topics := make([][]byte, n)
  451. mSize, mStart := stack.Popn()
  452. for i := 0; i < n; i++ {
  453. topics[i] = ethutil.LeftPadBytes(stack.Pop().Bytes(), 32)
  454. }
  455. data := mem.Geti(mStart.Int64(), mSize.Int64())
  456. log := &Log{context.Address(), topics, data}
  457. self.env.AddLog(log)
  458. self.Printf(" => %v", log)
  459. case MLOAD:
  460. offset := stack.Pop()
  461. val := ethutil.BigD(mem.Get(offset.Int64(), 32))
  462. stack.Push(val)
  463. self.Printf(" => 0x%x", val.Bytes())
  464. case MSTORE: // Store the value at stack top-1 in to memory at location stack top
  465. // Pop value of the stack
  466. val, mStart := stack.Popn()
  467. mem.Set(mStart.Uint64(), 32, ethutil.BigToBytes(val, 256))
  468. self.Printf(" => 0x%x", val)
  469. case MSTORE8:
  470. off := stack.Pop()
  471. val := stack.Pop()
  472. mem.store[off.Int64()] = byte(val.Int64() & 0xff)
  473. self.Printf(" => [%v] 0x%x", off, val)
  474. case SLOAD:
  475. loc := stack.Pop()
  476. val := ethutil.BigD(statedb.GetState(context.Address(), loc.Bytes()))
  477. stack.Push(val)
  478. self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes())
  479. case SSTORE:
  480. val, loc := stack.Popn()
  481. statedb.SetState(context.Address(), loc.Bytes(), val)
  482. context.message.AddStorageChange(loc.Bytes())
  483. self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes())
  484. case JUMP:
  485. jump(pc, stack.Pop())
  486. continue
  487. case JUMPI:
  488. cond, pos := stack.Popn()
  489. if cond.Cmp(ethutil.BigTrue) >= 0 {
  490. jump(pc, pos)
  491. continue
  492. }
  493. case JUMPDEST:
  494. case PC:
  495. stack.Push(big.NewInt(int64(pc)))
  496. case MSIZE:
  497. stack.Push(big.NewInt(int64(mem.Len())))
  498. case GAS:
  499. stack.Push(context.Gas)
  500. // 0x60 range
  501. case CREATE:
  502. var (
  503. err error
  504. value = stack.Pop()
  505. size, offset = stack.Popn()
  506. input = mem.Get(offset.Int64(), size.Int64())
  507. gas = new(big.Int).Set(context.Gas)
  508. // Snapshot the current stack so we are able to
  509. // revert back to it later.
  510. //snapshot = self.env.State().Copy()
  511. )
  512. // Generate a new address
  513. n := statedb.GetNonce(context.Address())
  514. addr := crypto.CreateAddress(context.Address(), n)
  515. statedb.SetNonce(context.Address(), n+1)
  516. self.Printf(" (*) %x", addr).Endl()
  517. context.UseGas(context.Gas)
  518. ret, err, ref := self.env.Create(context, addr, input, gas, price, value)
  519. if err != nil {
  520. stack.Push(ethutil.BigFalse)
  521. self.Printf("CREATE err %v", err)
  522. } else {
  523. // gas < len(ret) * CreateDataGas == NO_CODE
  524. dataGas := big.NewInt(int64(len(ret)))
  525. dataGas.Mul(dataGas, GasCreateByte)
  526. if context.UseGas(dataGas) {
  527. ref.SetCode(ret)
  528. msg.Output = ret
  529. }
  530. stack.Push(ethutil.BigD(addr))
  531. }
  532. self.Endl()
  533. // Debug hook
  534. if self.Dbg != nil {
  535. self.Dbg.SetCode(context.Code)
  536. }
  537. case CALL, CALLCODE:
  538. self.Endl()
  539. gas := stack.Pop()
  540. // Pop gas and value of the stack.
  541. value, addr := stack.Popn()
  542. // Pop input size and offset
  543. inSize, inOffset := stack.Popn()
  544. // Pop return size and offset
  545. retSize, retOffset := stack.Popn()
  546. // Get the arguments from the memory
  547. args := mem.Get(inOffset.Int64(), inSize.Int64())
  548. var (
  549. ret []byte
  550. err error
  551. )
  552. if op == CALLCODE {
  553. ret, err = self.env.CallCode(context, addr.Bytes(), args, gas, price, value)
  554. } else {
  555. ret, err = self.env.Call(context, addr.Bytes(), args, gas, price, value)
  556. }
  557. if err != nil {
  558. stack.Push(ethutil.BigFalse)
  559. vmlogger.Debugln(err)
  560. } else {
  561. stack.Push(ethutil.BigTrue)
  562. msg.Output = ret
  563. mem.Set(retOffset.Uint64(), retSize.Uint64(), ret)
  564. }
  565. self.Printf("resume %x (%v)", context.Address(), context.Gas)
  566. // Debug hook
  567. if self.Dbg != nil {
  568. self.Dbg.SetCode(context.Code)
  569. }
  570. case RETURN:
  571. size, offset := stack.Popn()
  572. ret := mem.Get(offset.Int64(), size.Int64())
  573. self.Printf(" => [%v, %v] (%d) 0x%x", offset, size, len(ret), ret).Endl()
  574. return context.Return(ret), nil
  575. case SUICIDE:
  576. receiver := statedb.GetOrNewStateObject(stack.Pop().Bytes())
  577. balance := statedb.GetBalance(context.Address())
  578. self.Printf(" => (%x) %v", receiver.Address()[:4], balance)
  579. receiver.AddAmount(balance)
  580. statedb.Delete(context.Address())
  581. fallthrough
  582. case STOP: // Stop the context
  583. self.Endl()
  584. return context.Return(nil), nil
  585. default:
  586. vmlogger.Debugf("(pc) %-3v Invalid opcode %x\n", pc, op)
  587. context.ReturnGas(big.NewInt(1), nil)
  588. return context.Return(nil), fmt.Errorf("Invalid opcode %x", op)
  589. }
  590. pc++
  591. self.Endl()
  592. if self.Dbg != nil {
  593. for _, instrNo := range self.Dbg.BreakPoints() {
  594. if pc == uint64(instrNo) {
  595. self.Stepping = true
  596. if !self.Dbg.BreakHook(prevStep, op, mem, stack, statedb.GetStateObject(context.Address())) {
  597. return nil, nil
  598. }
  599. } else if self.Stepping {
  600. if !self.Dbg.StepHook(prevStep, op, mem, stack, statedb.GetStateObject(context.Address())) {
  601. return nil, nil
  602. }
  603. }
  604. }
  605. }
  606. }
  607. }
  608. func (self *DebugVm) calculateGasAndSize(context *Context, caller ContextRef, op OpCode, statedb *state.StateDB, mem *Memory, stack *Stack) (*big.Int, *big.Int) {
  609. gas := new(big.Int)
  610. addStepGasUsage := func(amount *big.Int) {
  611. if amount.Cmp(ethutil.Big0) >= 0 {
  612. gas.Add(gas, amount)
  613. }
  614. }
  615. addStepGasUsage(GasStep)
  616. var newMemSize *big.Int = ethutil.Big0
  617. var additionalGas *big.Int = new(big.Int)
  618. // Stack Check, memory resize & gas phase
  619. switch op {
  620. // Stack checks only
  621. case ISZERO, CALLDATALOAD, POP, JUMP, NOT: // 1
  622. stack.require(1)
  623. case JUMPI, ADD, SUB, DIV, SDIV, MOD, SMOD, LT, GT, SLT, SGT, EQ, AND, OR, XOR, BYTE, SIGNEXTEND: // 2
  624. stack.require(2)
  625. case ADDMOD, MULMOD: // 3
  626. stack.require(3)
  627. case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16:
  628. n := int(op - SWAP1 + 2)
  629. stack.require(n)
  630. case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16:
  631. n := int(op - DUP1 + 1)
  632. stack.require(n)
  633. case LOG0, LOG1, LOG2, LOG3, LOG4:
  634. n := int(op - LOG0)
  635. stack.require(n + 2)
  636. gas.Set(GasLog)
  637. addStepGasUsage(new(big.Int).Mul(big.NewInt(int64(n)), GasLog))
  638. mSize, mStart := stack.Peekn()
  639. addStepGasUsage(mSize)
  640. newMemSize = calcMemSize(mStart, mSize)
  641. case EXP:
  642. stack.require(2)
  643. gas.Set(big.NewInt(int64(len(stack.data[stack.Len()-2].Bytes()) + 1)))
  644. // Gas only
  645. case STOP:
  646. gas.Set(ethutil.Big0)
  647. case SUICIDE:
  648. stack.require(1)
  649. gas.Set(ethutil.Big0)
  650. case SLOAD:
  651. stack.require(1)
  652. gas.Set(GasSLoad)
  653. // Memory resize & Gas
  654. case SSTORE:
  655. stack.require(2)
  656. var mult *big.Int
  657. y, x := stack.Peekn()
  658. val := statedb.GetState(context.Address(), x.Bytes())
  659. if len(val) == 0 && len(y.Bytes()) > 0 {
  660. // 0 => non 0
  661. mult = ethutil.Big3
  662. } else if len(val) > 0 && len(y.Bytes()) == 0 {
  663. statedb.Refund(caller.Address(), GasSStoreRefund)
  664. mult = ethutil.Big0
  665. } else {
  666. // non 0 => non 0 (or 0 => 0)
  667. mult = ethutil.Big1
  668. }
  669. gas.Set(new(big.Int).Mul(mult, GasSStore))
  670. case BALANCE:
  671. stack.require(1)
  672. gas.Set(GasBalance)
  673. case MSTORE:
  674. stack.require(2)
  675. newMemSize = calcMemSize(stack.Peek(), u256(32))
  676. case MLOAD:
  677. stack.require(1)
  678. newMemSize = calcMemSize(stack.Peek(), u256(32))
  679. case MSTORE8:
  680. stack.require(2)
  681. newMemSize = calcMemSize(stack.Peek(), u256(1))
  682. case RETURN:
  683. stack.require(2)
  684. newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-2])
  685. case SHA3:
  686. stack.require(2)
  687. gas.Set(GasSha)
  688. newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-2])
  689. additionalGas.Set(stack.data[stack.Len()-2])
  690. case CALLDATACOPY:
  691. stack.require(2)
  692. newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-3])
  693. additionalGas.Set(stack.data[stack.Len()-3])
  694. case CODECOPY:
  695. stack.require(3)
  696. newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-3])
  697. additionalGas.Set(stack.data[stack.Len()-3])
  698. case EXTCODECOPY:
  699. stack.require(4)
  700. newMemSize = calcMemSize(stack.data[stack.Len()-2], stack.data[stack.Len()-4])
  701. additionalGas.Set(stack.data[stack.Len()-4])
  702. case CALL, CALLCODE:
  703. stack.require(7)
  704. gas.Set(GasCall)
  705. addStepGasUsage(stack.data[stack.Len()-1])
  706. x := calcMemSize(stack.data[stack.Len()-6], stack.data[stack.Len()-7])
  707. y := calcMemSize(stack.data[stack.Len()-4], stack.data[stack.Len()-5])
  708. newMemSize = ethutil.BigMax(x, y)
  709. case CREATE:
  710. stack.require(3)
  711. gas.Set(GasCreate)
  712. newMemSize = calcMemSize(stack.data[stack.Len()-2], stack.data[stack.Len()-3])
  713. }
  714. switch op {
  715. case CALLDATACOPY, CODECOPY, EXTCODECOPY:
  716. additionalGas.Add(additionalGas, u256(31))
  717. additionalGas.Div(additionalGas, u256(32))
  718. addStepGasUsage(additionalGas)
  719. case SHA3:
  720. additionalGas.Add(additionalGas, u256(31))
  721. additionalGas.Div(additionalGas, u256(32))
  722. additionalGas.Mul(additionalGas, GasSha3Byte)
  723. addStepGasUsage(additionalGas)
  724. }
  725. if newMemSize.Cmp(ethutil.Big0) > 0 {
  726. newMemSize.Add(newMemSize, u256(31))
  727. newMemSize.Div(newMemSize, u256(32))
  728. newMemSize.Mul(newMemSize, u256(32))
  729. if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 {
  730. memGasUsage := new(big.Int).Sub(newMemSize, u256(int64(mem.Len())))
  731. memGasUsage.Mul(GasMemory, memGasUsage)
  732. memGasUsage.Div(memGasUsage, u256(32))
  733. addStepGasUsage(memGasUsage)
  734. }
  735. }
  736. return newMemSize, gas
  737. }
  738. func (self *DebugVm) RunPrecompiled(p *PrecompiledAccount, callData []byte, context *Context) (ret []byte, err error) {
  739. gas := p.Gas(len(callData))
  740. if context.UseGas(gas) {
  741. ret = p.Call(callData)
  742. self.Printf("NATIVE_FUNC => %x", ret)
  743. self.Endl()
  744. return context.Return(ret), nil
  745. } else {
  746. self.Endl()
  747. tmp := new(big.Int).Set(context.Gas)
  748. context.UseGas(context.Gas)
  749. return context.Return(nil), OOG(gas, tmp)
  750. }
  751. }
  752. func (self *DebugVm) Printf(format string, v ...interface{}) VirtualMachine {
  753. if self.logTy == LogTyPretty {
  754. self.logStr += fmt.Sprintf(format, v...)
  755. }
  756. return self
  757. }
  758. func (self *DebugVm) Endl() VirtualMachine {
  759. if self.logTy == LogTyPretty {
  760. vmlogger.Debugln(self.logStr)
  761. self.logStr = ""
  762. }
  763. return self
  764. }
  765. func (self *DebugVm) Env() Environment {
  766. return self.env
  767. }