-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathdebuggercontroller.py
More file actions
3259 lines (2563 loc) · 125 KB
/
debuggercontroller.py
File metadata and controls
3259 lines (2563 loc) · 125 KB
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
# coding=utf-8
# Copyright 2020-2026 Vector 35 Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ctypes
import traceback
from dataclasses import dataclass
import binaryninja
# import debugger
from . import _debuggercore as dbgcore
from .debugger_enums import *
from typing import Callable, List, Optional, Union
# TTD (Time Travel Debugging) Memory Access Type parsing
def parse_ttd_access_type(access_spec):
"""
Parse TTD memory access type from string specification.
Args:
access_spec: String containing access type specification.
Can be combinations of 'r' (read), 'w' (write), 'e' (execute)
e.g., "r", "rw", "rwe", "we", etc.
Returns:
DebuggerTTDMemoryAccessType enum value
"""
if isinstance(access_spec, str):
access_value = 0
access_spec = access_spec.lower()
if 'r' in access_spec:
access_value |= DebuggerTTDMemoryAccessType.DebuggerTTDMemoryRead
if 'w' in access_spec:
access_value |= DebuggerTTDMemoryAccessType.DebuggerTTDMemoryWrite
if 'e' in access_spec:
access_value |= DebuggerTTDMemoryAccessType.DebuggerTTDMemoryExecute
if access_value == 0:
raise ValueError(f"Invalid access type specification: '{access_spec}'. Use combinations of 'r', 'w', 'e'")
return access_value
else:
# Assume it's already a DebuggerTTDMemoryAccessType enum value
return access_spec
class DebugProcess:
"""
DebugProcess represents a process in the target. It has the following fields:
* ``pid``: the ID of the process
* ``name``: the name of the process
* ``command_line``: the command line of the process
"""
def __init__(self, pid, name, command_line=""):
self.pid = pid
self.name = name
self.command_line = command_line
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.pid == other.pid and self.name == other.name
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.pid, self.pid))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<DebugProcess: pid={self.pid}, name='{self.name}'>"
class DebugThread:
"""
DebugThread represents a thread in the target. It has the following fields:
* ``tid``: the ID of the thread. On different systems, this may be either the system thread ID, or a sequential\
index starting from zero.
* ``rip``: the current address (instruction pointer) of the thread
In the future, we should provide both the internal thread ID and the system thread ID.
"""
def __init__(self, tid, rip):
self.tid = tid
self.rip = rip
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.tid == other.tid and self.rip == other.rip
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.tid, self.rip))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<DebugThread: {self.tid:#x} @ {self.rip:#x}>"
class DebugModule:
"""
DebugModule represents a module in the target. It has the following fields:
* ``name``: the path of the module
* ``short_name``: the name of the module
* ``address``: the base load address of the module
* ``size``: the size of the module
* ``loaded``: not used
"""
def __init__(self, name, short_name, address, size, loaded):
self.name = name
self.short_name = short_name
self.address = address
self.size = size
self.loaded = loaded
@staticmethod
def is_same_base_module(module1: Union[str, bytes], module2: Union[str, bytes]) -> bool:
return dbgcore.BNDebuggerIsSameBaseModule(module1, module2)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.name == other.name and self.short_name == other.short_name and self.address == other.address\
and self.size == other.size and self.loaded == other.loaded
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.name, self.short_name, self.address, self.size, self.loaded))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<DebugModule: {self.short_name}, {self.address:#x}-{self.address+self.size:#x}, size={self.size:#x}>"
class DebugRegister:
"""
DebugRegister represents a register in the target. It has the following fields:
* ``name``: the name of the register
* ``value``: the value of the register
* ``width``: the width of the register, in bits. E.g., ``rax`` register is 64-bits wide
* ``index``: the index of the register. This is reported by the DebugAdapter and should remain unchanged
* ``hint``: a string that shows the content of the memory pointed to by the register. It is empty if the register\
value do not point to a valid (mapped) memory region
"""
def __init__(self, name, value, width, index, hint):
self.name = name
self.value = value
self.width = width
self.index = index
self.hint = hint
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.name == other.name and self.value == other.value and self.width == other.width \
and self.index == other.index and self.hint == other.hint
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.name, self.value, self.width, self.index, self.hint))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
hint_str = f", {self.hint}" if self.hint != '' else ''
return f"<DebugRegister: {self.name}, {self.value:#x}{hint_str}>"
class DebugRegisters:
"""
DebugRegisters represents all registers of the target.
"""
def __init__(self, handle):
self.handle = handle
self.regs = {}
count = ctypes.c_ulonglong()
registers = dbgcore.BNDebuggerGetRegisters(handle, count)
for i in range(0, count.value):
bp = DebugRegister(registers[i].m_name, int.from_bytes(registers[i].m_value, byteorder='little'),
registers[i].m_width, registers[i].m_registerIndex, registers[i].m_hint)
self.regs[registers[i].m_name] = bp
dbgcore.BNDebuggerFreeRegisters(registers, count.value)
def __repr__(self) -> str:
if not self.regs:
return "<DebugRegisters: empty>"
# Show registers in a more readable format - one per line
reg_entries = []
# Sort registers by name for consistent output
for name in sorted(self.regs.keys()):
reg = self.regs[name]
hint_str = f" ({reg.hint})" if reg.hint else ""
reg_entries.append(f" {name}={reg.value:#x}{hint_str}")
# Show all registers, one per line
reg_list = "\n".join(reg_entries)
return f"<DebugRegisters:\n{reg_list}\n>"
def __getitem__(self, name):
if name not in self.regs:
return None
return self.regs[name]
def __setitem__(self, name, val):
buffer = val.to_bytes(64, byteorder='little', signed=False)
c_buffer = (ctypes.c_ubyte * 64)(*buffer)
dbgcore.BNDebuggerSetRegisterValue(self.handle, name, c_buffer)
def __len__(self):
return len(self.regs)
class DebugThreads:
"""
DebugThreads represents all threads of the target.
"""
def __init__(self, threads: List[DebugThread]):
self.threads = threads
def __repr__(self) -> str:
if not self.threads:
return "<DebugThreads: empty>"
# Show threads in a more readable format - one per line
thread_entries = []
for thread in self.threads:
thread_entries.append(f" {thread}")
# Show all threads, one per line
thread_list = "\n".join(thread_entries)
return f"<DebugThreads:\n{thread_list}\n>"
def __getitem__(self, index):
return self.threads[index]
def __len__(self):
return len(self.threads)
def __iter__(self):
return iter(self.threads)
class DebugModules:
"""
DebugModules represents all modules of the target.
"""
def __init__(self, modules: List[DebugModule]):
self.modules = modules
def __repr__(self) -> str:
if not self.modules:
return "<DebugModules: empty>"
# Show modules in a more readable format - one per line
module_entries = []
for module in self.modules:
module_entries.append(f" {module}")
# Show all modules, one per line
module_list = "\n".join(module_entries)
return f"<DebugModules:\n{module_list}\n>"
def __getitem__(self, index):
return self.modules[index]
def __len__(self):
return len(self.modules)
def __iter__(self):
return iter(self.modules)
class DebugBreakpoints:
"""
DebugBreakpoints represents all breakpoints of the target.
"""
def __init__(self, breakpoints: List['DebugBreakpoint']):
self.breakpoints = breakpoints
def __repr__(self) -> str:
if not self.breakpoints:
return "<DebugBreakpoints: empty>"
# Show breakpoints in a more readable format - one per line
bp_entries = []
for bp in self.breakpoints:
bp_entries.append(f" {bp}")
# Show all breakpoints, one per line
bp_list = "\n".join(bp_entries)
return f"<DebugBreakpoints:\n{bp_list}\n>"
def __getitem__(self, index):
return self.breakpoints[index]
def __len__(self):
return len(self.breakpoints)
def __iter__(self):
return iter(self.breakpoints)
@dataclass(frozen=True)
class DebugBreakpoint:
"""
DebugBreakpoint represents a breakpoint in the target. It has the following fields:
* ``module``: the name of the module for which the breakpoint is in
* ``offset``: the offset of the breakpoint to the start of the module
* ``address``: the absolute address of the breakpoint
* ``enabled``: whether the breakpoint is enabled (read-only)
* ``condition``: the condition expression for the breakpoint (empty if no condition)
* ``type``: the type of breakpoint (Software, HardwareExecute, HardwareRead, HardwareWrite, HardwareAccess)
* ``size``: the size in bytes for hardware breakpoints/watchpoints (1, 2, 4, or 8)
"""
module: str
offset: int
address: int
enabled: bool
condition: str = ""
type: DebugBreakpointType = DebugBreakpointType.BNSoftwareBreakpoint
size: int = 1
def __repr__(self):
status = "enabled" if self.enabled else "disabled"
cond_str = f", condition='{self.condition}'" if self.condition else ""
# Get type string (S, HE, HR, HW, HA)
if self.type == DebugBreakpointType.BNSoftwareBreakpoint:
type_str = "S"
elif self.type == DebugBreakpointType.BNHardwareExecuteBreakpoint:
type_str = "HE"
elif self.type == DebugBreakpointType.BNHardwareReadBreakpoint:
type_str = "HR"
elif self.type == DebugBreakpointType.BNHardwareWriteBreakpoint:
type_str = "HW"
elif self.type == DebugBreakpointType.BNHardwareAccessBreakpoint:
type_str = "HA"
else:
type_str = "?"
return f"<DebugBreakpoint: {self.module}:{self.offset:#x}, {self.address:#x}, type={type_str}, {status}{cond_str}>"
class ModuleNameAndOffset:
"""
ModuleNameAndOffset represents an address that is relative to the start of module. It is useful when ASLR is on.
* ``module``: the name of the module for which the address is in
* ``offset``: the offset of the address to the start of the module
"""
def __init__(self, module, offset):
self.module = module
self.offset = offset
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.module == other.module and self.offset == other.offset
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __lt__(self, other):
if self.module < other.module:
return True
elif self.module > other.module:
return False
return self.offset < other.offset
def __gt__(self, other):
if self.module > other.module:
return True
elif self.module < other.module:
return False
return self.offset > other.offset
def __hash__(self):
return hash((self.module, self.offset))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<ModuleNameAndOffset: {self.module}+{self.offset:#x}>"
class DebugFrame:
"""
DebugFrame represents a frame in the stack trace. It has the following fields:
* ``index``: the index of the frame
* ``pc``: the program counter of the frame
* ``sp``: the stack pointer of the frame
* ``fp``: the frame pointer of the frame
* ``func_name``: the function name which the pc is in
* ``func_start``: the start of the function
* ``module``: the module of the pc
"""
def __init__(self, index, pc, sp, fp, func_name, func_start, module):
self.index = index
self.pc = pc
self.sp = sp
self.fp = fp
self.func_name = func_name
self.func_start = func_start
self.module = module
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.index == other.index and self.pc == other.pc and self.sp == other.sp \
and self.fp == other.fp and self.func_name == other.func_name and self.func_start == other.func_start \
and self.module == other.module
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.index, self.pc, self.sp, self.fp, self.func_name, self.func_start, self.module))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
offset = self.pc - self.func_start
if self.func_name != '':
return f"<DebugFrame: {self.module}`{self.func_name} + {offset:#x}, sp: {self.sp:#x}, fp: {self.fp:#x}>"
else:
return f"<DebugFrame: {self.module} + {offset:#x}, sp: {self.sp:#x}, fp: {self.fp:#x}>"
class TargetStoppedEventData:
"""
TargetStoppedEventData is the data associated with a TargetStoppedEvent
* ``reason``: the reason of the stop
* ``last_active_thread``: not used
* ``exit_code``: not used
* ``data``: extra data. Not used.
"""
def __init__(self, reason: DebugStopReason, last_active_thread: int, exit_code: int, data):
self.reason = reason
self.last_active_thread = last_active_thread
self.exit_code = exit_code
self.data = data
def __repr__(self):
return f"<TargetStoppedEventData: reason={self.reason}, thread={self.last_active_thread}, exit_code={self.exit_code}>"
class ErrorEventData:
"""
ErrorEventData is the data associated with a ErrorEvent
* ``error``: the error message
* ``data``: extra data. Not used.
"""
def __init__(self, error: str, data):
self.error = error
self.data = data
def __repr__(self):
return f"<ErrorEventData: {self.error}>"
class TargetExitedEventData:
"""
TargetExitedEventData is the data associated with a TargetExitedEvent
* ``exit_code``: the exit code of the target
"""
def __init__(self, exit_code: int):
self.exit_code = exit_code
def __repr__(self):
return f"<TargetExitedEventData: exit_code={self.exit_code}>"
class StdOutMessageEventData:
"""
StdOutMessageEventData is the data associated with a StdOutMessageEvent
* ``message``: the message that the target writes to the stdout
"""
def __init__(self, message: str):
self.message = message
def __repr__(self):
# Truncate long messages for readability
msg = self.message[:50] + "..." if len(self.message) > 50 else self.message
return f"<StdOutMessageEventData: '{msg}'>"
class DebuggerEventData:
"""
DebuggerEventData is the collection of all possible data associated with the debugger events
* ``target_stopped_data``: the data associated with a TargetStoppedEvent
* ``error_data``: the data associated with an ErrorEvent
* ``absolute_address``: an integer address, which is used when an absolute breakpoint is added/removed
* ``relative_address``: a ModuleNameAndOffset, which is used when a relative breakpoint is added/removed
* ``exit_data``: the data associated with a TargetExitedEvent
* ``message_data``: message data, used by both StdOutMessageEvent and BackendMessageEvent
"""
def __init__(self, target_stopped_data: TargetStoppedEventData,
error_data: ErrorEventData,
absolute_address: int,
relative_address: ModuleNameAndOffset,
exit_data: TargetExitedEventData,
message_data: StdOutMessageEventData):
self.target_stopped_data = target_stopped_data
self.error_data = error_data
self.absolute_address = absolute_address
self.relative_address = relative_address
self.exit_data = exit_data
self.message_data = message_data
def __repr__(self):
# Show only the data that's not None for better readability
parts = []
if self.target_stopped_data is not None:
parts.append(f"stopped={self.target_stopped_data.reason}")
if self.error_data is not None:
parts.append(f"error='{self.error_data.error[:30]}..'" if len(self.error_data.error) > 30 else f"error='{self.error_data.error}'")
if self.absolute_address:
parts.append(f"abs_addr={self.absolute_address:#x}")
if self.relative_address:
parts.append(f"rel_addr={self.relative_address}")
if self.exit_data is not None:
parts.append(f"exit_code={self.exit_data.exit_code}")
if self.message_data is not None:
msg = self.message_data.message[:20] + "..." if len(self.message_data.message) > 20 else self.message_data.message
parts.append(f"msg='{msg}'")
return f"<DebuggerEventData: {', '.join(parts) if parts else 'empty'}>"
class DebuggerEvent:
"""
DebuggerEvent is the event object that a debugger event callback receives
* ``type``: a DebuggerEventType that specifies the event type
* ``data``: a DebuggerEventData that specifies the event data
"""
def __init__(self, type: DebuggerEventType, data: DebuggerEventData):
self.type = type
self.data = data
def __repr__(self):
return f"<DebuggerEvent: type={self.type}, data={self.data}>"
DebuggerEventCallback = Callable[['DebuggerEvent'], None]
class DebuggerEventWrapper:
# This has no functional purposes;
# we just need it to stop Python from prematurely freeing the object
_debugger_events = {}
@classmethod
def register(cls, controller: 'DebuggerController', callback: DebuggerEventCallback, name: Union[str, bytes]) -> int:
callback_obj = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.POINTER(dbgcore.BNDebuggerEvent))\
(lambda ctxt, event: cls._notify(event[0], callback))
handle = dbgcore.BNDebuggerRegisterEventCallback(controller.handle, callback_obj, name, None)
cls._debugger_events[handle] = callback_obj
return handle
@classmethod
def remove(cls, controller: 'DebuggerController', index: int) -> None:
try:
dbgcore.BNDebuggerRemoveEventCallback(controller.handle, index)
del cls._debugger_events[index]
except:
binaryninja.log_error(f'invalid debugger event callback index {index}')
@staticmethod
def _notify(event: dbgcore.BNDebuggerEvent, callback: DebuggerEventCallback) -> None:
try:
data = event.data
target_stopped_data = TargetStoppedEventData(data.targetStoppedData.reason,
data.targetStoppedData.lastActiveThread,
data.targetStoppedData.exitCode,
data.targetStoppedData.data)
error_data = ErrorEventData(data.errorData.error, data.errorData.data)
absolute_addr = data.absoluteAddress
relative_addr = ModuleNameAndOffset(data.relativeAddress.module, data.relativeAddress.offset)
exit_data = TargetExitedEventData(data.exitData.exitCode)
message_data = StdOutMessageEventData(data.messageData.message)
event_data = DebuggerEventData(target_stopped_data, error_data, absolute_addr, relative_addr, exit_data,
message_data)
event = DebuggerEvent(event.type, event_data)
callback(event)
except:
binaryninja.log_error(traceback.format_exc())
class TTDPosition:
"""
TTDPosition represents a position in a time travel debugging trace.
It has the following fields:
* ``sequence``: the sequence number (as hex string or int)
* ``step``: the step number within the sequence (as hex string or int)
"""
def __init__(self, sequence, step):
if isinstance(sequence, str):
self.sequence = int(sequence, 16)
else:
self.sequence = int(sequence)
if isinstance(step, str):
self.step = int(step, 16)
else:
self.step = int(step)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.sequence == other.sequence and self.step == other.step
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.sequence, self.step))
def __repr__(self):
return f"<TTDPosition: {self.sequence:x}:{self.step:x}>"
def __str__(self):
return f"{self.sequence:x}:{self.step:x}"
@classmethod
def from_string(cls, timestamp_str):
"""
Create a TTDPosition from a string in format "sequence:step"
Both sequence and step can be in hex or decimal format.
"""
if ':' not in timestamp_str:
raise ValueError("Timestamp must be in format 'sequence:step'")
parts = timestamp_str.strip().split(':')
if len(parts) != 2:
raise ValueError("Timestamp must be in format 'sequence:step'")
return cls(parts[0], parts[1])
class TTDBookmark:
"""
TTDBookmark represents a saved position in a TTD trace with an optional note and view address.
* ``position``: the TTD position (TTDPosition object)
* ``view_address``: the address the user was viewing when the bookmark was created
* ``note``: an optional note describing the bookmark
"""
def __init__(self, position: TTDPosition, note: str = "", view_address: int = 0):
self.position = position
self.note = note
self.view_address = view_address
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.position == other.position
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash(self.position)
def __repr__(self):
note_str = f" ({self.note})" if self.note else ""
return f"<TTDBookmark: {self.position}{note_str}>"
class TTDMemoryEvent:
"""
TTDMemoryEvent represents a memory access event in a TTD trace. It has the following fields:
* ``event_type``: type of the event (e.g., "Memory")
* ``thread_id``: OS thread ID that performed the memory access
* ``unique_thread_id``: unique thread ID across the trace
* ``time_start``: TTD position when the memory access started
* ``time_end``: TTD position when the memory access ended
* ``address``: memory address that was accessed
* ``size``: size of the memory access
* ``memory_address``: actual memory address (may differ from address field)
* ``instruction_address``: address of the instruction that performed the access
* ``value``: value that was read/written/executed
* ``access_type``: type of access (read/write/execute)
"""
def __init__(self, event_type: str, thread_id: int, unique_thread_id: int,
time_start: TTDPosition, time_end: TTDPosition, address: int,
size: int, memory_address: int, instruction_address: int,
value: int, access_type: int):
self.event_type = event_type
self.thread_id = thread_id
self.unique_thread_id = unique_thread_id
self.time_start = time_start
self.time_end = time_end
self.address = address
self.size = size
self.memory_address = memory_address
self.instruction_address = instruction_address
self.value = value
self.access_type = access_type
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.event_type == other.event_type and
self.thread_id == other.thread_id and
self.unique_thread_id == other.unique_thread_id and
self.time_start == other.time_start and
self.time_end == other.time_end and
self.address == other.address and
self.size == other.size and
self.memory_address == other.memory_address and
self.instruction_address == other.instruction_address and
self.value == other.value and
self.access_type == other.access_type)
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.event_type, self.thread_id, self.unique_thread_id,
self.time_start, self.time_end, self.address, self.size,
self.memory_address, self.instruction_address, self.value,
self.access_type))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<TTDMemoryEvent: {self.event_type} @ {self.address:#x}, thread {self.thread_id}>"
class TTDPositionRangeIndexedMemoryEvent:
"""
TTDPositionRangeIndexedMemoryEvent represents a memory access event in a TTD trace with position information.
This is used for memory queries filtered by both address range and time range.
* ``position``: TTD position when the memory access occurred
* ``thread_id``: OS thread ID that performed the memory access
* ``unique_thread_id``: unique thread ID across the trace
* ``address``: memory address that was accessed
* ``instruction_address``: address of the instruction that performed the access
* ``size``: size of the memory access in bytes
* ``access_type``: type of access (read/write/execute)
* ``value``: value that was read/written/executed (truncated to size)
* ``data``: the next 8 bytes of data at the memory address (as a bytes object)
"""
def __init__(self, position: TTDPosition, thread_id: int, unique_thread_id: int,
address: int, instruction_address: int, size: int,
access_type: int, value: int, data: bytes):
self.position = position
self.thread_id = thread_id
self.unique_thread_id = unique_thread_id
self.address = address
self.instruction_address = instruction_address
self.size = size
self.access_type = access_type
self.value = value
self.data = data
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.position == other.position and
self.thread_id == other.thread_id and
self.unique_thread_id == other.unique_thread_id and
self.address == other.address and
self.instruction_address == other.instruction_address and
self.size == other.size and
self.access_type == other.access_type and
self.value == other.value and
self.data == other.data)
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.position, self.thread_id, self.unique_thread_id,
self.address, self.instruction_address, self.size,
self.access_type, self.value, self.data))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<TTDPositionRangeIndexedMemoryEvent: @ {self.address:#x}, pos {self.position}, thread {self.thread_id}>"
class TTDCallEvent:
"""
TTDCallEvent represents a function call event in a TTD trace. It has the following fields:
* ``event_type``: type of the event (always "Call" for TTD.Calls objects)
* ``thread_id``: OS thread ID that made the call
* ``unique_thread_id``: unique thread ID across the trace
* ``function``: symbolic name of the function
* ``function_address``: function's address in memory
* ``return_address``: instruction to return to after the call
* ``return_value``: return value of the function (if not void)
* ``has_return_value``: whether the function has a return value
* ``parameters``: list of parameters passed to the function
* ``time_start``: TTD position when call started
* ``time_end``: TTD position when call ended
"""
def __init__(self, event_type: str, thread_id: int, unique_thread_id: int,
function: str, function_address: int, return_address: int,
return_value: int, has_return_value: bool, parameters: List[str],
time_start: TTDPosition, time_end: TTDPosition):
self.event_type = event_type
self.thread_id = thread_id
self.unique_thread_id = unique_thread_id
self.function = function
self.function_address = function_address
self.return_address = return_address
self.return_value = return_value
self.has_return_value = has_return_value
self.parameters = parameters
self.time_start = time_start
self.time_end = time_end
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (self.event_type == other.event_type and
self.thread_id == other.thread_id and
self.unique_thread_id == other.unique_thread_id and
self.function == other.function and
self.function_address == other.function_address and
self.return_address == other.return_address and
self.return_value == other.return_value and
self.has_return_value == other.has_return_value and
self.parameters == other.parameters and
self.time_start == other.time_start and
self.time_end == other.time_end)
def __ne__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return not (self == other)
def __hash__(self):
return hash((self.event_type, self.thread_id, self.unique_thread_id,
self.function, self.function_address, self.return_address,
self.return_value, self.has_return_value, tuple(self.parameters),
self.time_start, self.time_end))
def __setattr__(self, name, value):
try:
object.__setattr__(self, name, value)
except AttributeError:
raise AttributeError(f"attribute '{name}' is read only")
def __repr__(self):
return f"<TTDCallEvent: {self.function} @ {self.function_address:#x}, thread {self.thread_id}>"
class TTDEventType:
"""
TTD Event Type enumeration for different types of events in TTD traces.
These are bitfield flags that can be combined.
"""
NONE = 0
ThreadCreated = 1
ThreadTerminated = 2
ModuleLoaded = 4
ModuleUnloaded = 8
Exception = 16
ALL = ThreadCreated | ThreadTerminated | ModuleLoaded | ModuleUnloaded | Exception
class TTDModule:
"""
TTDModule represents information about modules that were loaded/unloaded during a TTD trace.
Attributes:
name (str): name and path of the module
address (int): address where the module was loaded
size (int): size of the module in bytes
checksum (int): checksum of the module
timestamp (int): timestamp of the module
"""
def __init__(self, name: str, address: int, size: int, checksum: int, timestamp: int):
self.name = name
self.address = address
self.size = size
self.checksum = checksum