debugger.go 8.09 KB
Newer Older
Felix Lange's avatar
Felix Lange committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2013-2014, Jeffrey Wilcke. All rights reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301  USA

obscuren's avatar
obscuren committed
18
package main
obscuren's avatar
obscuren committed
19 20 21

import (
	"fmt"
obscuren's avatar
obscuren committed
22 23 24
	"math/big"
	"strconv"
	"strings"
obscuren's avatar
obscuren committed
25
	"unicode"
obscuren's avatar
obscuren committed
26

obscuren's avatar
obscuren committed
27
	"github.com/ethereum/go-ethereum/cmd/utils"
obscuren's avatar
obscuren committed
28
	"github.com/ethereum/go-ethereum/core"
29
	"github.com/ethereum/go-ethereum/ethutil"
obscuren's avatar
obscuren committed
30
	"github.com/ethereum/go-ethereum/state"
31
	"github.com/ethereum/go-ethereum/vm"
32
	"gopkg.in/qml.v1"
obscuren's avatar
obscuren committed
33 34 35 36 37 38
)

type DebuggerWindow struct {
	win    *qml.Window
	engine *qml.Engine
	lib    *UiLib
39

obscuren's avatar
obscuren committed
40
	vm *vm.DebugVm
obscuren's avatar
obscuren committed
41
	Db *Debugger
obscuren's avatar
obscuren committed
42

obscuren's avatar
obscuren committed
43
	state *state.StateDB
obscuren's avatar
obscuren committed
44 45 46 47 48 49 50 51 52 53 54 55 56
}

func NewDebuggerWindow(lib *UiLib) *DebuggerWindow {
	engine := qml.NewEngine()
	component, err := engine.LoadFile(lib.AssetPath("debugger/debugger.qml"))
	if err != nil {
		fmt.Println(err)

		return nil
	}

	win := component.CreateWindow(nil)

obscuren's avatar
obscuren committed
57
	w := &DebuggerWindow{engine: engine, win: win, lib: lib, vm: &vm.DebugVm{}}
obscuren's avatar
obscuren committed
58 59 60
	w.Db = NewDebugger(w)

	return w
obscuren's avatar
obscuren committed
61 62 63
}

func (self *DebuggerWindow) Show() {
obscuren's avatar
obscuren committed
64 65 66
	context := self.engine.Context()
	context.SetVar("dbg", self)

obscuren's avatar
obscuren committed
67 68 69 70 71 72
	go func() {
		self.win.Show()
		self.win.Wait()
	}()
}

73 74 75
func (self *DebuggerWindow) SetCode(code string) {
	self.win.Set("codeText", code)
}
76

77 78
func (self *DebuggerWindow) SetData(data string) {
	self.win.Set("dataText", data)
79
}
obscuren's avatar
obscuren committed
80

obscuren's avatar
obscuren committed
81 82 83
func (self *DebuggerWindow) SetAsm(data []byte) {
	self.win.Root().Call("clearAsm")

obscuren's avatar
obscuren committed
84
	dis := core.Disassemble(data)
85 86 87 88
	for _, str := range dis {
		self.win.Root().Call("setAsm", str)
	}
}
89

obscuren's avatar
obscuren committed
90 91 92
func (self *DebuggerWindow) Compile(code string) {
	var err error
	script := ethutil.StringToByteFunc(code, func(s string) (ret []byte) {
93
		ret, err = ethutil.Compile(s, true)
obscuren's avatar
obscuren committed
94 95 96 97 98 99 100 101
		return
	})

	if err == nil {
		self.SetAsm(script)
	}
}

102 103 104 105 106 107 108
// Used by QML
func (self *DebuggerWindow) AutoComp(code string) {
	if self.Db.done {
		self.Compile(code)
	}
}

obscuren's avatar
obscuren committed
109 110 111 112
func (self *DebuggerWindow) ClearLog() {
	self.win.Root().Call("clearLog")
}

113
func (self *DebuggerWindow) Debug(valueStr, gasStr, gasPriceStr, scriptStr, dataStr string) {
114
	self.Stop()
obscuren's avatar
obscuren committed
115

obscuren's avatar
obscuren committed
116 117 118 119 120 121
	defer func() {
		if r := recover(); r != nil {
			self.Logf("compile FAULT: %v", r)
		}
	}()

obscuren's avatar
obscuren committed
122
	data := utils.FormatTransactionData(dataStr)
123 124 125

	var err error
	script := ethutil.StringToByteFunc(scriptStr, func(s string) (ret []byte) {
126
		ret, err = ethutil.Compile(s, false)
127 128 129
		return
	})

obscuren's avatar
obscuren committed
130
	if err != nil {
obscuren's avatar
obscuren committed
131
		self.Logln(err)
obscuren's avatar
obscuren committed
132 133 134 135

		return
	}

136 137 138 139 140
	var (
		gas      = ethutil.Big(gasStr)
		gasPrice = ethutil.Big(gasPriceStr)
		value    = ethutil.Big(valueStr)
		// Contract addr as test address
obscuren's avatar
obscuren committed
141
		keyPair = self.lib.eth.KeyManager().KeyPair()
142
	)
obscuren's avatar
obscuren committed
143

obscuren's avatar
obscuren committed
144 145
	statedb := self.lib.eth.ChainManager().TransState()
	account := self.lib.eth.ChainManager().TransState().GetAccount(keyPair.Address())
obscuren's avatar
obscuren committed
146
	contract := statedb.NewStateObject([]byte{0})
147
	contract.SetCode(script)
obscuren's avatar
obscuren committed
148
	contract.SetBalance(value)
obscuren's avatar
obscuren committed
149

obscuren's avatar
obscuren committed
150 151
	self.SetAsm(script)

obscuren's avatar
obscuren committed
152
	block := self.lib.eth.ChainManager().CurrentBlock()
153

obscuren's avatar
obscuren committed
154
	env := utils.NewEnv(statedb, block, account.Address(), value)
obscuren's avatar
obscuren committed
155

obscuren's avatar
obscuren committed
156
	self.Logf("callsize %d", len(script))
obscuren's avatar
obscuren committed
157
	go func() {
158 159 160 161
		ret, err := env.Call(account, contract.Address(), data, gas, gasPrice, ethutil.Big0)
		//ret, g, err := callerClosure.Call(evm, data)
		tot := new(big.Int).Mul(env.Gas, gasPrice)
		self.Logf("gas usage %v total price = %v (%v)", env.Gas, tot, ethutil.CurrencyToString(tot))
obscuren's avatar
obscuren committed
162 163 164
		if err != nil {
			self.Logln("exited with errors:", err)
		} else {
obscuren's avatar
obscuren committed
165 166 167 168 169
			if len(ret) > 0 {
				self.Logf("exited: % x", ret)
			} else {
				self.Logf("exited: nil")
			}
obscuren's avatar
obscuren committed
170
		}
obscuren's avatar
obscuren committed
171

obscuren's avatar
obscuren committed
172
		statedb.Reset()
obscuren's avatar
obscuren committed
173

obscuren's avatar
obscuren committed
174 175 176 177 178
		if !self.Db.interrupt {
			self.Db.done = true
		} else {
			self.Db.interrupt = false
		}
obscuren's avatar
obscuren committed
179 180 181
	}()
}

obscuren's avatar
obscuren committed
182 183 184 185 186 187 188 189 190
func (self *DebuggerWindow) Logf(format string, v ...interface{}) {
	self.win.Root().Call("setLog", fmt.Sprintf(format, v...))
}

func (self *DebuggerWindow) Logln(v ...interface{}) {
	str := fmt.Sprintln(v...)
	self.Logf("%s", str[:len(str)-1])
}

obscuren's avatar
obscuren committed
191 192 193
func (self *DebuggerWindow) Next() {
	self.Db.Next()
}
obscuren's avatar
obscuren committed
194

195 196 197 198 199
func (self *DebuggerWindow) Continue() {
	self.vm.Stepping = false
	self.Next()
}

200 201 202 203 204 205
func (self *DebuggerWindow) Stop() {
	if !self.Db.done {
		self.Db.Q <- true
	}
}

206 207 208 209 210
func (self *DebuggerWindow) ExecCommand(command string) {
	if len(command) > 0 {
		cmd := strings.Split(command, " ")
		switch cmd[0] {
		case "help":
obscuren's avatar
obscuren committed
211
			self.Logln("Debugger commands:")
obscuren's avatar
obscuren committed
212 213
			self.Logln("break, bp                 Set breakpoint on instruction")
			self.Logln("clear [log, break, bp]    Clears previous set sub-command(s)")
214 215 216 217 218 219 220
		case "break", "bp":
			if len(cmd) > 1 {
				lineNo, err := strconv.Atoi(cmd[1])
				if err != nil {
					self.Logln(err)
					break
				}
obscuren's avatar
obscuren committed
221
				self.Db.breakPoints = append(self.Db.breakPoints, int64(lineNo))
222 223 224 225 226 227 228 229
				self.Logf("break point set on instruction %d", lineNo)
			} else {
				self.Logf("'%s' requires line number", cmd[0])
			}
		case "clear":
			if len(cmd) > 1 {
				switch cmd[1] {
				case "break", "bp":
obscuren's avatar
obscuren committed
230
					self.Db.breakPoints = nil
231 232

					self.Logln("Breakpoints cleared")
obscuren's avatar
obscuren committed
233 234
				case "log":
					self.ClearLog()
235 236 237 238 239 240 241 242 243 244 245 246 247
				default:
					self.Logf("clear '%s' is not valid", cmd[1])
				}
			} else {
				self.Logln("'clear' requires sub command")
			}

		default:
			self.Logf("Unknown command %s", cmd[0])
		}
	}
}

obscuren's avatar
obscuren committed
248
type Debugger struct {
obscuren's avatar
obscuren committed
249 250 251
	N               chan bool
	Q               chan bool
	done, interrupt bool
obscuren's avatar
obscuren committed
252 253 254 255 256 257 258 259 260
	breakPoints     []int64
	main            *DebuggerWindow
	win             *qml.Window
}

func NewDebugger(main *DebuggerWindow) *Debugger {
	db := &Debugger{make(chan bool), make(chan bool), true, false, nil, main, main.win}

	return db
obscuren's avatar
obscuren committed
261 262 263 264 265 266
}

type storeVal struct {
	Key, Value string
}

obscuren's avatar
obscuren committed
267
func (self *Debugger) BreakHook(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *state.StateObject) bool {
obscuren's avatar
obscuren committed
268 269 270 271 272
	self.main.Logln("break on instr:", pc)

	return self.halting(pc, op, mem, stack, stateObject)
}

obscuren's avatar
obscuren committed
273
func (self *Debugger) StepHook(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *state.StateObject) bool {
obscuren's avatar
obscuren committed
274 275 276
	return self.halting(pc, op, mem, stack, stateObject)
}

277 278 279 280
func (self *Debugger) SetCode(byteCode []byte) {
	self.main.SetAsm(byteCode)
}

obscuren's avatar
obscuren committed
281 282 283 284
func (self *Debugger) BreakPoints() []int64 {
	return self.breakPoints
}

obscuren's avatar
obscuren committed
285
func (d *Debugger) halting(pc int, op vm.OpCode, mem *vm.Memory, stack *vm.Stack, stateObject *state.StateObject) bool {
obscuren's avatar
obscuren committed
286 287 288 289 290 291
	d.win.Root().Call("setInstruction", pc)
	d.win.Root().Call("clearMem")
	d.win.Root().Call("clearStack")
	d.win.Root().Call("clearStorage")

	addr := 0
obscuren's avatar
obscuren committed
292
	for i := 0; i+16 <= mem.Len(); i += 16 {
obscuren's avatar
obscuren committed
293 294 295 296 297 298 299 300 301 302 303 304 305
		dat := mem.Data()[i : i+16]
		var str string

		for _, d := range dat {
			if unicode.IsGraphic(rune(d)) {
				str += string(d)
			} else {
				str += "?"
			}
		}

		d.win.Root().Call("setMem", memAddr{fmt.Sprintf("%03d", addr), fmt.Sprintf("%s  % x", str, dat)})
		addr += 16
obscuren's avatar
obscuren committed
306 307 308 309 310 311
	}

	for _, val := range stack.Data() {
		d.win.Root().Call("setStack", val.String())
	}

obscuren's avatar
obscuren committed
312
	stateObject.EachStorage(func(key string, node *ethutil.Value) {
obscuren's avatar
obscuren committed
313 314 315
		d.win.Root().Call("setStorage", storeVal{fmt.Sprintf("% x", key), fmt.Sprintf("% x", node.Str())})
	})

obscuren's avatar
obscuren committed
316 317 318 319 320
	stackFrameAt := new(big.Int).SetBytes(mem.Get(0, 32))
	psize := mem.Len() - int(new(big.Int).SetBytes(mem.Get(0, 32)).Uint64())
	d.win.Root().ObjectByName("stackFrame").Set("text", fmt.Sprintf(`<b>stack ptr</b>: %v`, stackFrameAt))
	d.win.Root().ObjectByName("stackSize").Set("text", fmt.Sprintf(`<b>stack size</b>: %d`, psize))
	d.win.Root().ObjectByName("memSize").Set("text", fmt.Sprintf(`<b>mem size</b>: %v`, mem.Len()))
obscuren's avatar
obscuren committed
321

322 323 324 325 326 327 328 329 330 331
out:
	for {
		select {
		case <-d.N:
			break out
		case <-d.Q:
			d.interrupt = true
			d.clearBuffers()

			return false
obscuren's avatar
obscuren committed
332 333
		}
	}
obscuren's avatar
obscuren committed
334 335

	return true
obscuren's avatar
obscuren committed
336 337
}

obscuren's avatar
obscuren committed
338 339 340 341 342 343 344 345 346 347 348 349 350
func (d *Debugger) clearBuffers() {
out:
	// drain
	for {
		select {
		case <-d.N:
		case <-d.Q:
		default:
			break out
		}
	}
}

obscuren's avatar
obscuren committed
351 352 353 354 355
func (d *Debugger) Next() {
	if !d.done {
		d.N <- true
	}
}