-
Notifications
You must be signed in to change notification settings - Fork 0
/
debug.py
executable file
·296 lines (229 loc) · 8.47 KB
/
debug.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#! /usr/bin/env python
import urwid
import urwid.signals
import socket
import sys
import getopt
import math
import itertools
class Window(urwid.BoxAdapter):
def __init__(self, body, title = "Unknown title", height = 34):
#super(Window, self).__init__(
self.frame = urwid.Frame(
body,
header=urwid.AttrMap(
urwid.Text(('title', title)),
'title'
),
footer=urwid.AttrMap(
urwid.Text(('footer', '')),
'footer'
)
)
super(Window, self).__init__(self.frame, height)
def selectable(self):
return False
class Command:
def __init__(self, command = b"show"):
self.command = command
self.response = b""
def executeCommand(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
global config
sock.connect(("localhost", config['port']))
self.send(sock, self.command + "\n")
self.response = self.receive(sock)
sock.close()
self.edit_text = ""
return self.response
def send(self, sock, msg):
if not msg:
return
totalsent = 0
while totalsent < len(msg):
sent = sock.send(bytes(msg, "UTF-8")[totalsent:])
if sent == 0:
raise RuntimeError("Socket connection broken")
totalsent = totalsent + sent
def receive(self, sock):
chunk = sock.recv(4096)
if chunk == b'':
raise RuntimeError("Socket connection broken")
return chunk
class CommandView(Window):
def __init__(self, command, height = 34):
self.command = command
self.txt = urwid.Text("No output")
self.walker = urwid.SimpleFocusListWalker([self.txt])
self.box = urwid.ListBox(self.walker)
self.lastResponse = []
super(CommandView, self).__init__(
self.box,
"%s" % command,
height)
global cli
urwid.connect_signal(cli, 'executed', self.onExecuted)
def onExecuted(self):
cmd = Command(self.command)
response = cmd.executeCommand()
self.updateResponse(response)
def updateResponse(self, raw):
response = raw.expandtabs(2)
lines = response.split(b'\n')
if self.lastResponse:
contents = []
for (last, current) in itertools.zip_longest(self.lastResponse, lines, fillvalue=''):
if last == current:
contents.append(urwid.Text(current))
else:
contents.append(urwid.Text(('change', current)))
else:
contents = [urwid.Text(line) for line in lines]
self.box.body[:] = contents
self.lastResponse = lines
#with open("focus.log", "a") as f: f.write("%s" % self.box.focus_position)
def selectable(self):
return False
class MultipleCommandView(urwid.Pile):
def __init__(self, commands):
clen = len(commands);
lengths = [math.floor(34 / clen) for c in commands];
lengths[-1] += 34 - sum(lengths)
views = [CommandView(cmd, height) for (cmd, height) in zip(commands, lengths)]
super(MultipleCommandView, self).__init__(views)
def selectable(self):
return False
class SourceBrowser(Window):
def __init__(self):
lines = []
self.retreiveFilename()
with open(self.filename, "r") as f:
i = 1
for line in f:
lines.append(urwid.Text(u"%4d %s" % (i, line.expandtabs(2).rstrip())))
i += 1
walker = urwid.SimpleFocusListWalker(lines)
self.box = urwid.ListBox(walker)
global cli
urwid.connect_signal(cli, 'executed', self.onExecuted)
super(SourceBrowser, self).__init__(self.box, "file: %s" % self.filename)
self.onExecuted()
def retreiveFilename(self):
cmd = Command("show file")
resp = cmd.executeCommand()
self.filename = resp.rstrip();
def onExecuted(self):
cmd = Command("show instruction");
resp = cmd.executeCommand()
parts = resp.split(b' ')
if len(parts) > 0:
linenr = int(parts[0].strip(b'[]'))
oldLine = self.box.focus
oldLine.set_text(oldLine.get_text()[0])
self.box.focus_position = linenr - 1
line = self.box.focus
self.box.focus.set_text(('currentLine', line.get_text()[0]))
class CliOutput(CommandView):
def __init__(self):
super(CliOutput, self).__init__("")
self.frame.header.original_widget.set_text('Output: %s' % self.command)
#self.header.original_widget.set_text('Command output')
def onExecuted(self):
global cli
self.updateResponse(cli.command.response)
self.frame.header.original_widget.set_text('Output: %s' % cli.command.command)
class Info(urwid.Columns):
def __init__(self):
super(Info, self).__init__([], 1)
class CliEdit(urwid.Edit):
__metaclass__ = urwid.signals.MetaSignals
signals = ["executed"]
def __init__(self):
self.history = []
self.historyIdx = -1
super(CliEdit, self).__init__(('ps1', '>>> '))
def keypress(self, size, key):
if key == 'enter':
if self.edit_text == "" and self.history:
self.command = Command(self.history[-1])
else:
self.command = Command(self.edit_text)
self.history.append(self.edit_text)
self.command.executeCommand()
self.historyIdx = -1
self.edit_text = ""
urwid.emit_signal(self, "executed")
elif key == 'up':
if len(self.history) != 0:
self.edit_text = self.history[self.historyIdx]
self.edit_pos = len(self.edit_text)
if self.historyIdx - 1 >= -1 * len(self.history):
self.historyIdx -= 1
elif key == "down":
if self.historyIdx == -1:
self.edit_text = "";
else:
self.historyIdx += 1
self.edit_text = self.history[self.historyIdx]
self.edit_pos = len(self.edit_text)
else:
return super(CliEdit, self).keypress(size, key)
class Root(urwid.Frame):
def __init__(self):
global cli
self.info = Info()
self.browser = SourceBrowser();
self.info.contents = [
(CommandView("show registers"), self.info.options('weight', 1)),
(MultipleCommandView(["show flags", "show xyz", "show breakpoints"]), self.info.options('weight', 1)),
(self.browser, self.info.options('weight', 4)),
(CommandView("show stack"), self.info.options('weight', 2)),
]
self.cliOutput = CliOutput()
self.infoBottom = Info()
self.infoBottom.contents = [
(CommandView("show state"), self.info.options('weight', 1)),
(CommandView("show data 0x50 0x5f"), self.info.options('weight', 1)),
(self.cliOutput, self.info.options('weight', 4)),
(CommandView("show since"), self.info.options('weight', 2)),
]
self.pile = urwid.Pile([self.info, self.infoBottom])
self.filler = urwid.Filler(self.pile, "top")
self.footer = urwid.Pile([urwid.Divider('-'), cli]);
super(Root, self).__init__(self.filler, footer = self.footer, focus_part='footer')
def keypress(self, size, key):
global cli
trans = {'page up': 'up', 'page down': 'down' }
if key in trans:
return self.cliOutput.box.keypress((size[0], 1), trans[key])
elif key in ['up', 'down']:
return cli.keypress(size, key)
return super(Root, self).keypress(size, key)
cli = CliEdit()
config = {
'port': 3742,
}
def main():
args = sys.argv[1:]
try:
(optlist, args) = getopt.getopt(args, 'p:', ['port='])
except getopt.GetoptError as e:
print(e)
sys.exit(2)
global config
for o,a in optlist:
if o in ['-p', '--port']:
if a:
config['port'] = int(a)
root = Root()
cli = CliEdit()
palette = [
('title', 'black', 'light gray'),
('footer', '', 'dark gray'),
('currentLine', 'black', 'light gray'),
('change', 'light green', ''),
]
loop = urwid.MainLoop(root, palette)
loop.run()
if __name__ == "__main__":
main();