forked from joxeankoret/mynav
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mynav.py
executable file
·1576 lines (1318 loc) · 53.7 KB
/
mynav.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
MyNav, a tool 'similar' to BinNavi
Copyright (C) 2010 Joxean Koret
Itsaslapurraren izenean, beti gogoan izango zaitugu.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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
"""
import os
import sys
import time
import random
try:
import sqlite3
hasSqlite = True
except ImportError:
hasSqlite = False
print "Warning! Your python version lacks SQLite support!"
from idc import (GetBptQty, GetBptEA, GetRegValue, FindText, NextAddr, GetDisasm, GetMnem,
GetFunctionName, MakeFunction, ItemSize, GetBptAttr, AskFile, StopDebugger)
from idaapi import (askyn_c, asklong, get_func, info, get_dbg_byte, get_idp_name,
DBG_Hooks, run_requests, request_run_to, showAuto, find_not_func,
get_func, msg)
try:
from idaapi import GraphViewer
import mybrowser
hasGraphViewer = True
except ImportError:
hasGraphViewer = False
import myexport
APPLICATION_NAME = "MyNav"
VERSION = 0x01020200
COLORS = [0xfff000, 0x95AFCD, 0x4FFF4F, 0xc0ffff, 0xffffc0, 0xc0cfff, 0xc0ffcf, 0x95AFFD]
reload(sys)
sys.setdefaultencoding('utf8')
def mynav_print(amsg):
msg("[%s] %s\n" % (APPLICATION_NAME, amsg))
class FunctionsGraph(GraphViewer):
def __init__(self, title, session):
GraphViewer.__init__(self, title)
self.result = session
self.nodes = {}
def OnRefresh(self):
try:
self.Clear()
dones = []
for hit in self.result:
if not hit in dones:
ea = int(hit[0])
name = GetFunctionName(ea)
self.nodes[ea] = self.AddNode((ea, name))
for n1 in self.nodes:
l1 = map(GetFunctionName, list(CodeRefsTo(n1, 1)))
l2 = map(GetFunctionName, list(DataRefsTo(n1)))
for n2 in self.nodes:
if n1 != n2:
name = GetFunctionName(n2)
if name in l1 or name in l2:
self.AddEdge(self.nodes[n2], self.nodes[n1])
return True
except:
print "***Error", sys.exc_info()[1]
def OnGetText(self, node_id):
ea, label = self[node_id]
return label
def OnDblClick(self, node_id):
ea, label = self[node_id]
Jump(ea)
return True
class CMyNav:
def __init__(self):
# Initialize basic properties
self.db = None
self.filename = None
self.debugMode = False
self.sessions = {}
self.records = {}
self.timeout = 0
self.step_mode = False
self.step_functions = []
random.seed(time.time())
self.current_color = random.choice(COLORS)
self.current_name = None
self.default_name = "Session1"
self.current_session = []
self.current_session_cpu = []
self.save_cpu = False
self.endpoints = []
self.temporary_breakpoints = []
self.dbg_path = ""
self.dbg_arguments = ""
self.dbg_directory = ""
self.on_exception = None
if hasSqlite:
self._loadDatabase()
def __del__(self):
if self.db is not None:
self.db.close()
def _createSchema(self):
""" Try to create the schema or silently exit if some error ocurred. """
try:
sql = """CREATE TABLE NODES (
NODE_ID INTEGER PRIMARY KEY,
FUNC_ADDR VARCHAR(50),
STATUS INTEGER)"""
cur = self.db.cursor()
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE GRAPHS (
GRAPH_ID INTEGER PRIMARY KEY,
NAME VARCHAR(50),
SHOW_STRINGS INTEGER,
SHOW_APIS INTEGER,
RECURSION_LEVEL INTEGER,
FATHER VARCHAR(50))"""
cur = self.db.cursor()
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE GRAPH_NODES (
GRAPH_NODES_ID INTEGER PRIMARY KEY,
GRAPH_ID INTEGER,
NODE_ID INTEGER)"""
cur = self.db.cursor()
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE POINTS (
POINT_ID INTEGER PRIMARY KEY,
FUNC_ADDR VARCHAR(50),
TYPE VARCHAR(50))"""
cur = self.db.cursor()
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE SETTINGS (
SETTING_ID INTEGER PRIMARY KEY,
NAME VARCHAR(50),
VALUE VARCHAR(50))"""
cur = self.db.cursor()
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE RECORDS (
RECORD_ID INTEGER PRIMARY KEY,
NAME VARCHAR(50),
DESCRIPTION VARCHAR(255),
TIMESTAMP DATETIME,
TYPE VARCHAR(50))"""
cur = self.db.cursor()
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE RECORD_DATA (
RECORD_DATA_ID INTEGER PRIMARY KEY,
RECORD_ID INTEGER,
LINE_ID INTEGER,
FUNC_ADDR VARCHAR(50),
TIMESTAMP DATETIME)"""
cur.execute(sql)
except:
pass
try:
sql = """CREATE TABLE CPU_STATE (
CPU_STATE_ID INTEGER PRIMARY KEY,
RECORD_DATA_ID INTEGER,
LINE_ID INTEGER,
REG_NAME VARCHAR(50),
REG_VALUE VARCHAR(255),
MEMORY VARCHAR(255),
TEXT VARCHAR(255))"""
cur.execute(sql)
except:
pass
try:
sql = """CREATE VIEW SESSIONS_STRINGS
AS
SELECT rec.name session,
data.func_addr address,
cpu.text text,
cpu.reg_name register,
cpu.reg_value value,
rec.record_id id
FROM CPU_STATE cpu,
RECORDS rec,
RECORD_DATA data
WHERE CPU.TEXT IS NOT NULL
AND LENGTH(CPU.TEXT) > 6
AND DATA.record_id = REC.record_id
AND CPU.record_data_id = DATA.record_data_id """
cur.execute(sql)
except:
pass
cur.close()
self.db.commit()
def _loadDatabase(self):
""" Connect to the SQLite database and create the schema if needed """
try:
self.filename = "%s.sqlite" % GetInputFilePath()
self.db = sqlite3.connect(self.filename, check_same_thread=False, isolation_level=None)
except:
self.filename = idc.AskFile(1, "*.sqlite", "Select an existing or new SQLite database")
if self.filename is not None:
self.db = sqlite3.connect(self.filename, check_same_thread=False, isolation_level=None)
self.db.text_factory = str
self._createSchema()
def _debug(self, msg):
""" Print a message if debugMode is enabled """
if self.debugMode:
mynav_print(msg)
def saveSession(self, name, session, cpu):
""" Save a session """
if self.step_mode:
mtype = 1
else:
mtype = 0
cur = self.db.cursor()
sql = "insert into records (name, description, timestamp, type) values (?, ?, ?, ?)"
cur.execute(sql, (name, "", time.time(), mtype))
i = 0
id = cur.lastrowid
total = len(session)
for event in session:
pct = i * 100 / total
temp = "Saved " + str(pct) + "%"
sql = """insert into record_data (record_id, line_id, func_addr, timestamp)
values (?, ?, ?, ?)"""
cur.execute(sql, (id, i, event[0], event[1]))
m_id = cur.lastrowid
if self.save_cpu:
j = 0
for name, val, mem, txt in cpu[i]:
sql = """insert into cpu_state (record_data_id, line_id, reg_name, reg_value,
memory, text)
values (?, ?, ?, ?, ?, ?) """
cur.execute(sql, (m_id, j, name, "0x%08x" % val, mem, txt))
j += 1
i += 1
self.db.commit()
return id
def readSetting(self, setting):
""" Read some configuration setting """
cur = self.db.cursor()
sql = "select value from settings where name = ?"
cur.execute(sql, (setting,))
val = None
for row in cur.fetchall():
val = row[0]
cur.close()
return val
def saveSetting(self, setting, value):
""" Save a configuration setting """
old_value = self.readSetting(setting)
if not old_value:
sql = """ insert into settings (value, name) values (?, ?)"""
else:
sql = """ update settings set value = ? where name = ?"""
cur = self.db.cursor()
cur.execute(sql, (value, setting))
self.db.commit()
return True
def addPoint(self, ea, strtype):
""" Add the function ea as point. strtype can be either 'E' for entry point or 'T' for target point """
new_ea = GetFunctionAttr(ea, FUNCATTR_START)
if not new_ea:
new_ea = ea
cur = self.db.cursor()
sql = """ insert into points (func_addr, type) values (?, ?) """
cur.execute(sql, (new_ea, strtype))
self.db.commit()
cur.close()
return True
def removePoint(self, ea, strtype):
""" Remove the function ea as point. strtype can be either 'E' for entry point or 'T' for target point """
new_ea = GetFunctionAttr(ea, FUNCATTR_START)
if not new_ea:
new_ea = ea
cur = self.db.cursor()
sql = """ delete from points where func_addr = ? and type = ? """
cur.execute(sql, (new_ea, strtype))
self.db.commit()
cur.close()
return True
def removeDataEntryPoint(self, ea):
""" Remove data entry point ea """
self.removePoint(ea, "E")
def removeTargetPoint(self, ea):
""" Remove target point ea """
self.removePoint(ea, "T")
def addDataEntryPoint(self, ea):
""" Add a data entry point """
self.addPoint(ea, "E")
def addTargetPoint(self, ea):
""" Add a target point """
self.addPoint(ea, "T")
def addCurrentAsDataEntryPoint(self):
""" Add current function as entry point """
self.addDataEntryPoint(ScreenEA())
def addCurrentAsTargetPoint(self):
""" Add current function as target point """
self.addTargetPoint(ScreenEA())
def removeCurrentDataEntryPoint(self):
""" Remove current entry point """
self.removeDataEntryPoint(ScreenEA())
def removeCurrentTargetPoint(self):
""" Remove current target point """
self.removeTargetPoint(ScreenEA())
def getAllPointsList(self):
""" Return a list with all entry and target points """
cur = self.db.cursor()
sql = """ select func_addr from points """
cur.execute(sql, (strtype, ))
l = []
for row in cur.fetchall():
l.append(row[0])
cur.close()
return l
def getPointsList(self, strtype):
""" Return a list with all either entry or target points. strtype can be either 'E' or 'T' """
cur = self.db.cursor()
sql = """ select func_addr from points where type = ? """
cur.execute(sql, (strtype, ))
l = []
for row in cur.fetchall():
l.append(int(row[0]))
cur.close()
return l
def getDataEntryPointsList(self):
l = self.getPointsList('E')
return l
def getTargetPointsList(self):
l = self.getPointsList('T')
return l
def getPoint(self, strtype, p):
""" Read from database an specific point """
cur = self.db.cursor()
sql = """ select 1 from points where type = ? and func_addr = ?"""
cur.execute(sql, (strtype, p))
l = []
for row in cur.fetchall():
l.append(int(row[0]))
cur.close()
return l
def addRemoveTargetPoint(self):
ea = GetFunctionAttr(ScreenEA(), FUNCATTR_START)
if self.getPoint("T", ea):
self.removeCurrentTargetPoint()
mynav_print("Target point 0x%08x removed" % ea)
else:
self.addCurrentAsTargetPoint()
mynav_print("Target point 0x%08x added" % ea)
def addRemoveEntryPoint(self):
ea = GetFunctionAttr(ScreenEA(), FUNCATTR_START)
if self.getPoint("E", ea):
self.removeCurrentDataEntryPoint()
mynav_print("Data entry point 0x%08x removed" % ea)
else:
self.addCurrentAsDataEntryPoint()
mynav_print("Data entry point 0x%08x added" % ea)
def saveCurrentSession(self, name):
return self.saveSession(name, self.current_session, self.current_session_cpu)
def showTargetPoints(self):
tps = self.getTargetPointsList()
if len(tps) == 0:
info("No target entry point selected!")
return False
g = mybrowser.PathsBrowser("Target points graph", tps, [], [])
g.Show()
return True
def showDataEntryPoints(self):
eps = self.getDataEntryPointsList()
if len(eps) == 0:
info("No entry point selected!")
return False
g = mybrowser.PathsBrowser("Entry points graph", eps, [], [])
g.Show()
return True
def showPointsGraph(self):
""" Show a graph with all entry and target points and the relationships between them """
eps = self.getDataEntryPointsList()
if len(eps) == 0:
info("No entry point selected!")
return False
tps = self.getTargetPointsList()
if len(tps) == 0:
info("No target point selected!")
return False
l = eps
l.extend(tps)
g = mybrowser.PathsBrowser("Entry and target points graph", l, [], [])
g.Show()
return True
def getCodePathsBetweenPoints(self):
eps = self.getDataEntryPointsList()
if len(eps) == 0:
mynav_print("No entry point selected!")
return None
tps = self.getTargetPointsList()
if len(tps) == 0:
mynav_print("No target point selected!")
return None
mynav_print("Searching code paths between all the points, it will take a while...")
l = []
for p1 in eps:
for p2 in tps:
tmp = mybrowser.SearchCodePath(p1, p2)
l.extend(tmp)
if len(l) == 0:
info("No data to show :(")
return None
return l, eps, tps
def showCodePathsBetweenPoints(self):
ret = self.getCodePathsBetweenPoints()
if ret:
l, eps, tps = ret
if l:
g = mybrowser.PathsBrowser("Code paths graph", l, eps, tps)
g.Show()
def selectCodePathsBetweenPoints(self):
l = self.getCodePathsBetweenPoints()
if l:
for p in l:
for x in p:
self.addBreakpoint(x)
def deselectCodePathsBetweenPoints(self):
l = self.getCodePathsBetweenPoints()
if l:
for p in l:
for x in p:
DelBpt(p)
def selectDataEntryPoints(self):
eps = self.getDataEntryPointsList()
for p in eps:
self.addBreakpoint(p)
def deselectDataEntryPoints(self):
eps = self.getDataEntryPointsList()
for p in eps:
DelBpt(p)
def tracePoints(self):
self.preserveBreakpoints()
self.selectCodePathsBetweenPoints()
self.newSession()
self.restoreBreakpoints()
def selectTargetPoints(self):
tps = self.getTargetPointsList()
for p in tps:
self.addBreakpoint(p)
def deselectTargetPoints(self):
tps = self.getTargetPointsList()
for p in tps:
DelBpt(p)
def getSessionsList(self, mtype=0, all=False):
if not all:
sql = "select * from records where type=?"
else:
sql = "select * from records"
cur = self.db.cursor()
if not all:
cur.execute(sql, (mtype, ))
else:
cur.execute(sql)
l = []
for row in cur.fetchall():
s = "%s: %s %s %s" % (row[0], row[1], row[2], time.asctime(time.gmtime(row[3])))
l.append(s)
cur.close()
return l
def showSessions(self, mtype=0, all=False, only_first=True):
""" Show the session's list """
l = self.getSessionsList(mtype)
chooser = Choose([], "Active Sessions", 3)
chooser.width = 50
chooser.list = l
c = chooser.choose()
if c > 0:
if only_first:
c = l[c-1].split(":")[0]
else:
c = [c]
else:
c = None
return c
def showSessionsGraph(self):
id = self.showSessions()
if id is not None:
self.showGraph(id)
def showSessionsFunctions(self):
id = self.showSessions()
if id is not None:
if self.loadSession(id):
results = []
for hit in self.current_session:
ea = int(hit[0])
tmp_item = {}
tmp_item["func_name"] = GetFunctionName(ea)
tmp_item["xref"] = ea
if tmp_item not in results:
results.append( tmp_item )
if results:
ch2 = mybrowser.UnsafeFunctionsChoose2("%s (Functions List)" % self.current_name, self)
for item in results:
ch2.add_item(mybrowser.UnsafeFunctionsChoose2.Item(item))
r = ch2.show()
def loadSession(self, id):
cur = self.db.cursor()
sql = "select name from records where record_id = ?"
cur.execute(sql, (int(id), ))
self.current_name = cur.fetchone()[0]
self.default_name = "Trace: " + str(self.current_name)
sql = "select func_addr, timestamp from record_data where record_id = ?"
cur.execute(sql, (int(id), ))
self.current_session = []
for row in cur.fetchall():
self.current_session.append([row[0], row[1]])
return len(self.current_session) > 0
def showGraph(self, id=None, name=None):
""" Show a graph for one specific recorded session """
if not hasGraphViewer:
print "No GraphViewer support :("
return
if id is not None:
if not self.loadSession(id):
mynav_print("No records found for session %s" % id)
return
g = FunctionsGraph("%s - Session %s - %s" % (APPLICATION_NAME, self.current_name, time.ctime()), self.current_session)
g.Show()
def addBreakpoint(self, f):
val = self.readSetting("save_cpu")
if val is None:
val = 0
if int(val) == 1:
save_cpu = True
else:
save_cpu = False
DelBpt(int(f))
AddBpt(int(f))
if not save_cpu:
SetBptAttr(f, BPTATTR_FLAGS, BPT_TRACE)
EnableBpt(int(f),1)
def setBreakpoints(self, trace=True):
""" Set a breakpoint in every function """
mynav_print("Setting breakpoints. Please, wait...")
val = self.readSetting("save_cpu")
if val is None:
val = True
else:
if int(val) == 0:
val = True
else:
val = False
for f in list(Functions()):
self.addBreakpoint(f)
mynav_print("Done")
def clearBreakpoints(self):
""" Clear all breakpoints """
mynav_print("Removing breakpoints. Please, wait...")
i = 0
while 1:
ea = GetBptEA(i)
if ea == BADADDR:
break
DelBpt(ea)
mynav_print("Done")
def getRegisters(self):
l = []
try:
for x in idaapi.dbg_get_registers():
name = x[0]
try:
addr = idc.GetRegValue(name)
except:
break
bytes = None
"""try:
if get_dbg_byte(addr) != 0xFF:
for i in range(16):
bytes += "%02x " % get_byte(addr+i)
bytes = bytes.strip(" ")
except:
bytes = None"""
try:
strdata = GetString(int(addr), -1, ASCSTR_C)
except:
try:
strdata = "Unicode: " + GetString(int(addr), -1, ASCSTR_UNICODE)
except:
strdata = None
l.append([name, addr, bytes, strdata])
except:
print "getRegisters()", sys.exc_info()[1]
return l
def recordBreakpoint(self):
try:
pc = self.getPC()
t2 = time.time()
self.current_session.append([pc, t2])
if self.save_cpu:
self.current_session_cpu.append(self.getRegisters())
self._debug("Hit %s:%08x" % (GetFunctionName(pc), pc))
if self.step_mode:
SetColor(pc, 1, self.current_color)
"""if not all:
DelBpt(pc)"""
DelBpt(pc)
"""
if self.endRecording(pc):
mynav_print("Session's endpoint reached")
"""
except:
print "recordBreakpoint:", sys.exc_info()[1]
def stop(self):
StopDebugger()
def startRecording(self, all=False):
""" Start recording breakpoint hits """
"""if not dbg_can_query():
info("Select a debugger first!")
return False"""
StartDebugger(self.dbg_path, self.dbg_arguments, self.dbg_directory)
t = time.time()
if self.timeout != 0:
mtimeout = min(self.timeout, 10)
else:
mtimeout = 10
last = -1
while 1:
#WFNE_CONT|WFNE_SUSP
code = GetDebuggerEvent(WFNE_ANY|WFNE_CONT|WFNE_SUSP, mtimeout)
if code == BREAKPOINT or code == STEP and last != BREAKPOINT:
pc = GetEventEa()
t2 = time.time()
self.current_session.append([pc, t2])
if self.save_cpu:
self.current_session_cpu.append(self.getRegisters())
self._debug("Hit %s:%08x" % (GetFunctionName(pc), pc))
if self.step_mode:
SetColor(pc, 1, self.current_color)
if not all:
DelBpt(pc)
if self.endRecording(pc):
mynav_print("Session's endpoint reached")
break
elif code == INFORMATION:
#print "INFORMATION"
pass
elif GetProcessState() != DSTATE_RUN:
if GetEventExceptionCode() != 0 and self.on_exception is not None:
self.on_exception(GetEventEa(), GetEventExceptionCode())
break
elif code in [EXCEPTION, 0x40]:
#print "**EXCEPTION", hex(GetEventEa()), hex(GetEventExceptionCode())
if self.on_exception is not None:
self.on_exception(GetEventEa(), GetEventExceptionCode())
elif code not in [DBG_TIMEOUT, PROCESS_START, PROCESS_EXIT, THREAD_START,
THREAD_EXIT, LIBRARY_LOAD, LIBRARY_UNLOAD, PROCESS_ATTACH,
PROCESS_DETACH, STEP]:
print "DEBUGGER: Code 0x%08x" % code
last = code
if time.time() - t > self.timeout and self.timeout != 0:
mynav_print("Timeout, exiting...")
break
def endRecording(self, ea):
""" End recording breakpoint hits """
return ea in self.endpoints
def intersectHits(self, rec1, rec2):
""" Return the intersection of 2 recorded sessions """
pass
def showIntersectionGraph(self, inter):
""" Show a graph with the given intersection """
pass
def showUniqueInGraph(self, rec1, rec2):
""" Show a graph with the nodes uniques in rec1 and not in rec2 """
pass
def getPC(self):
try:
pc = GetEventEa()
return pc
except:
print "getPc", sys.exc_info()[1]
def start(self, do_show=True, session_name=None):
if session_name is None:
name = AskStr(self.default_name, "Enter new session name")
else:
name = session_name
if name:
if GetBptEA(0) == BADADDR:
res = AskYN(1, "There is no breakpoint set. Do you want to set breakpoints in all functions?")
if res == 1:
self.setBreakpoints()
elif res == -1:
return
val = self.readSetting("timeout")
if val is not None:
self.timeout = int(val)
val = self.readSetting("save_cpu")
if val is None:
self.save_cpu = False
elif int(val) == 1:
self.save_cpu = True
else:
self.save_cpu = False
self.current_name = name
self.current_session = []
self.current_session_cpu = []
try:
mynav_print("Starting debugger ...")
self.startRecording()
except:
print sys.exc_info()[1]
mynav_print("Cancelled by user")
mynav_print("Saving current session ...")
id = None
if len(self.current_session) > 0:
id = self.saveCurrentSession(name)
if not self.step_mode and do_show:
if len(self.current_session) > 100:
if askyn_c(1, "There are %d node(s), it will take a long while to show the graph. Do you want to show it?" % len(self.current_session)) == 1:
self.showGraph()
else:
self.showGraph()
self.current_session = []
self.current_session_cpu = []
else:
mynav_print("No data to save")
mynav_print("OK, all done")
return id
def newSession(self):
self.step_mode = False
self.start()
def clearSessions(self):
if AskYN(0, "Are you sure to delete *ALL* saved sessions?") == 1:
cur = self.db.cursor()
cur.execute("delete from records")
cur.execute("delete from record_data")
cur.execute("delete from cpu_state")
self.db.commit()
cur.close()
mynav_print("Done")
def deleteSession(self):
l = self.showSessions(all=True, only_first=False)
if l is not None:
for id in l:
cur = self.db.cursor()
cur.execute("delete from records where record_id = ?", (str(id),))
cur.execute("delete from record_data where record_id = ?", (str(id),))
cur.execute("delete from cpu_state where record_data_id = ?", (str(id),))
self.db.commit()
cur.close()
mynav_print("Deleted session %s" % str(id))
def loadBreakpointsFromSession(self):
l = self.showSessions(only_first=False)
if l is not None:
for c in l:
self.loadSession(c)
self.clearBreakpoints()
for addr in self.current_session:
self.addBreakpoint(int(addr[0]))
mynav_print("Done loading " + str(c))
def loadBreakpointsFromSessionInverse(self):
l = self.showSessions(only_first=False)
if l is not None:
for c in l:
self.loadSession(c)
#self.setBreakpoints()
for addr in self.current_session:
DelBpt(int(addr[0]))
mynav_print("Done unloading " + str(c))
def preserveBreakpoints(self):
self.temporary_breakpoints = []
i = 0
while 1:
ea = GetBptEA(i)
if ea == BADADDR:
break
self.temporary_breakpoints.append(ea)
i += 1
def restoreBreakpoints(self):
for bpt in self.temporary_breakpoints:
self.addBreakpoint(bpt)
self.temporary_breakpoints = []
def traceInSession(self):
c = self.showSessions(mtype=0)
if c is not None:
if not self.loadSession(c):
return
self.preserveBreakpoints()
self.step_mode = True
self.current_color = random.choice(COLORS)
self.step_functions = []
for addr in self.current_session:
for ea in FuncItems(int(addr[0])):
self.addBreakpoint(ea)
self.start()
self.clearBreakpoints()
self.restoreBreakpoints()
def clearTraceSession(self):
l = self.showSessions(mtype=1, only_first=False)
if l is not None:
for c in l:
self.loadSession(c)
for addr in self.current_session:
SetColor(int(addr[0]), 1, 0xFFFFFFFF)
def showTraceSession(self):
c = self.showSessions(mtype=1)
if c is not None:
self.loadSession(c)
self.current_color = random.choice(COLORS)
for addr in self.current_session: