-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathdebugger_test.py
More file actions
540 lines (441 loc) · 19.9 KB
/
debugger_test.py
File metadata and controls
540 lines (441 loc) · 19.9 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
#!/usr/bin/env python3
#
# unit tests for debugger
import os
import sys
import time
import platform
import threading
import subprocess
import unittest
from binaryninja import load
try:
from debugger import DebuggerController, DebugStopReason, DebugBreakpointType
except:
from binaryninja.debugger import DebuggerController, DebugStopReason, DebugBreakpointType
# 'helloworld' -> '{BN_SOURCE_ROOT}\public\debugger\test\binaries\Windows-x64\helloworld.exe' (windows)
# 'helloworld' -> '{BN_SOURCE_ROOT}/public/debugger/test/binaries/Darwin/arm64/helloworld' (linux, macOS)
def name_to_fpath(testbin, arch=None, os_str=None):
if arch is None:
arch = platform.machine()
if os_str is None:
os_str = platform.system()
if os_str == 'Windows' and not testbin.endswith('.exe'):
testbin += '.exe'
signed = ''
if os_str == 'Darwin':
signed = '-signed'
base_path = os.path.dirname(os.path.realpath(__file__))
path = os.path.realpath(os.path.join(base_path, 'binaries', f'{os_str}-{arch}{signed}', testbin))
return path
def is_wow64(fpath):
if 'x86' not in fpath:
return False
a, b = platform.architecture()
return a == '64bit' and b.startswith('Windows')
def sleep_and_go(dbg):
time.sleep(0.1)
return dbg.go_and_wait()
def sleep_and_step_into(dbg):
time.sleep(0.1)
return dbg.step_into_and_wait()
class DebuggerAPI(unittest.TestCase):
# Always skip the base class so it will never be executed
@unittest.skip("do not run the base test class")
def setUp(self) -> None:
self.arch = ''
self.adapter_type = None # None means use default adapter
def create_debugger(self, bv):
"""Helper to create debugger with the correct adapter type"""
dbg = DebuggerController(bv)
if self.adapter_type:
dbg.adapter_type = self.adapter_type
return dbg
def test_repeated_use(self):
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
def run_once():
dbg = self.create_debugger(bv)
dbg.cmd_line = 'foobar'
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
# continue execution to the entry point, and check the stop reason
reason = sleep_and_step_into(dbg)
self.assertEqual(reason, DebugStopReason.SingleStep)
reason = sleep_and_step_into(dbg)
self.assertEqual(reason, DebugStopReason.SingleStep)
reason = sleep_and_step_into(dbg)
self.assertEqual(reason, DebugStopReason.SingleStep)
# go until executing done
reason = sleep_and_go(dbg)
self.assertEqual(reason, DebugStopReason.ProcessExited)
# Do the same thing for 10 times
n = 10
for i in range(n):
run_once()
def test_return_code(self):
# return code tests
fpath = name_to_fpath('exitcode', self.arch)
bv = load(fpath)
# some systems return byte, or low byte of 32-bit code and others return 32-bit code
testvals = [('-11', [245, 4294967285]),
('-1', [4294967295, 255]),
('-3', [4294967293, 253]),
('0', [0]),
('3', [3]),
('7', [7]),
('123', [123])]
for arg, expected in testvals:
dbg = self.create_debugger(bv)
dbg.cmd_line = arg
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
reason = sleep_and_go(dbg)
self.assertEqual(reason, DebugStopReason.ProcessExited)
exit_code = dbg.exit_code
self.assertIn(exit_code, expected)
def expect_segfault(self, reason):
if platform.system() == 'Linux':
self.assertEqual(reason, DebugStopReason.SignalSegv)
else:
self.assertEqual(reason, DebugStopReason.AccessViolation)
def test_exception_segfault(self):
fpath = name_to_fpath('do_exception', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
dbg.cmd_line = 'segfault'
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
# time.sleep(1)
reason = sleep_and_go(dbg)
self.expect_segfault(reason)
dbg.quit_and_wait()
# # This would not work until we fix the test binary
# def test_exception_illegalinstr(self):
# fpath = name_to_fpath('do_exception', self.arch)
# bv = load(fpath)
# dbg = DebuggerController(bv)
# dbg.cmd_line = 'illegalinstr'
# self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
# dbg.go()
# reason = dbg.go()
# if platform.system() in ['Windows', 'Linux']:
# expected = DebugStopReason.AccessViolation
# else:
# expected = DebugStopReason.IllegalInstruction
#
# self.assertEqual(reason, expected)
# dbg.quit_and_wait()
def expect_divide_by_zero(self, reason):
if platform.system() == 'Linux':
self.assertEqual(reason, DebugStopReason.SignalFpe)
else:
self.assertEqual(reason, DebugStopReason.Calculation)
def test_exception_divzero(self):
fpath = name_to_fpath('do_exception', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
if not self.arch == 'arm64':
dbg.cmd_line = 'divzero'
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
reason = sleep_and_go(dbg)
self.expect_divide_by_zero(reason)
dbg.quit_and_wait()
def test_step_into(self):
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
dbg.cmd_line = 'foobar'
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
reason = sleep_and_step_into(dbg)
self.assertEqual(reason, DebugStopReason.SingleStep)
reason = sleep_and_step_into(dbg)
self.assertEqual(reason, DebugStopReason.SingleStep)
reason = sleep_and_go(dbg)
self.assertEqual(reason, DebugStopReason.ProcessExited)
def test_breakpoint(self):
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
# TODO: right now we are not returning whether the operation succeeds, so we cannot use assertTrue/assertFalse
# breakpoint set/clear should fail at 0
self.assertIsNone(dbg.add_breakpoint(0))
self.assertIsNone(dbg.delete_breakpoint(0))
# breakpoint set/clear should succeed at entrypoint
entry = dbg.data.entry_point
self.assertIsNone(dbg.delete_breakpoint(entry))
self.assertIsNone(dbg.add_breakpoint(entry))
self.assertEqual(dbg.ip, entry)
dbg.quit_and_wait()
def test_breakpoint_condition(self):
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
entry = dbg.data.entry_point
dbg.add_breakpoint(entry)
arch_name = bv.arch.name
if arch_name == 'x86':
reg1, reg2 = '$eax', '$ebx'
elif arch_name == 'x86_64':
reg1, reg2 = '$rax', '$rbx'
else:
reg1, reg2 = '$x0', '$x1'
cond1 = f"{reg1} == 0x1234"
self.assertTrue(dbg.set_breakpoint_condition(entry, cond1))
self.assertEqual(dbg.get_breakpoint_condition(entry), cond1)
cond2 = f"{reg2} != 0"
self.assertTrue(dbg.set_breakpoint_condition(entry, cond2))
self.assertEqual(dbg.get_breakpoint_condition(entry), cond2)
self.assertTrue(dbg.set_breakpoint_condition(entry, ""))
self.assertEqual(dbg.get_breakpoint_condition(entry), "")
self.assertFalse(dbg.set_breakpoint_condition(0x12345678, f"{reg1} == 0"))
self.assertEqual(dbg.get_breakpoint_condition(0x12345678), "")
dbg.quit_and_wait()
def test_breakpoints_list_and_repr(self):
"""Test that dbg.breakpoints returns correctly and repr includes condition"""
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
entry = dbg.data.entry_point
second_addr = entry + 4
# Add breakpoint without condition
dbg.add_breakpoint(entry)
# Add breakpoint with condition
dbg.add_breakpoint(second_addr)
arch_name = bv.arch.name
if arch_name == 'x86':
reg = 'eax'
elif arch_name == 'x86_64':
reg = 'rax'
else:
reg = 'x0'
condition = f"{reg} == 0x1234"
self.assertTrue(dbg.set_breakpoint_condition(second_addr, condition))
# Access dbg.breakpoints - this should not raise an error
# (regression test for issue #953 where None condition caused AttributeError)
breakpoints = dbg.breakpoints
self.assertGreaterEqual(len(breakpoints), 2)
# Test repr contains condition when set
bp_repr = repr(breakpoints)
self.assertIn(condition, bp_repr)
# Test individual breakpoint repr
for bp in breakpoints:
bp_str = repr(bp)
if bp.address == second_addr:
self.assertIn("condition=", bp_str)
self.assertIn(condition, bp_str)
elif bp.address == entry:
# Breakpoint without condition should not have condition in repr
self.assertNotIn("condition=", bp_str)
dbg.quit_and_wait()
@unittest.skipIf(platform.system() == 'Linux', 'Hardware breakpoints not yet supported on Linux')
def test_hardware_breakpoint(self):
"""Test hardware breakpoint add and delete"""
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
entry = dbg.data.entry_point
# Test adding hardware execution breakpoint
self.assertTrue(dbg.add_hardware_breakpoint(entry, DebugBreakpointType.BNHardwareExecuteBreakpoint))
# Test adding hardware write watchpoint at a different address
# Note: Hardware data breakpoints must be aligned to their size on x86/x64
# A 4-byte watchpoint must be at a 4-byte aligned address
watch_addr = (entry + 0x100) & ~0x3 # Align to 4-byte boundary
self.assertTrue(dbg.add_hardware_breakpoint(watch_addr, DebugBreakpointType.BNHardwareWriteBreakpoint, size=4))
# Test deleting hardware breakpoints
self.assertTrue(dbg.delete_hardware_breakpoint(entry, DebugBreakpointType.BNHardwareExecuteBreakpoint))
self.assertTrue(dbg.delete_hardware_breakpoint(watch_addr, DebugBreakpointType.BNHardwareWriteBreakpoint, size=4))
dbg.quit_and_wait()
def test_register_read_write(self):
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
arch_name = bv.arch.name
if arch_name == 'x86':
(xax, xbx) = ('eax', 'ebx')
(testval_a, testval_b) = (0xDEADBEEF, 0xCAFEBABE)
elif arch_name == 'x86_64':
(xax, xbx) = ('rax', 'rbx')
(testval_a, testval_b) = (0xAAAAAAAADEADBEEF, 0xBBBBBBBBCAFEBABE)
else:
(xax, xbx) = ('x0', 'x1')
(testval_a, testval_b) = (0xAAAAAAAADEADBEEF, 0xBBBBBBBBCAFEBABE)
rax = dbg.get_reg_value(xax)
rbx = dbg.get_reg_value(xbx)
dbg.set_reg_value(xax, testval_a)
self.assertEqual(dbg.get_reg_value(xax), testval_a)
dbg.set_reg_value(xbx, testval_b)
self.assertEqual(dbg.get_reg_value(xbx), testval_b)
dbg.set_reg_value(xax, rax)
self.assertEqual(dbg.get_reg_value(xax), rax)
dbg.set_reg_value(xbx, rbx)
self.assertEqual(dbg.get_reg_value(xbx), rbx)
dbg.quit_and_wait()
def test_memory_read_write(self):
fpath = name_to_fpath('helloworld', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
# Due to https://github.com/Vector35/debugger/issues/124, we have to skip the bytes at the entry point
addr = dbg.ip + 10
data = dbg.read_memory(addr, 256)
self.assertFalse(dbg.write_memory(0, b'heheHAHAherherHARHAR'), False)
data2 = b'\xAA' * 256
dbg.write_memory(addr, data2)
self.assertEqual(len(dbg.read_memory(0, 256)), 0)
self.assertEqual(dbg.read_memory(addr, 256), data2)
dbg.write_memory(addr, data)
self.assertEqual(dbg.read_memory(addr, 256), data)
dbg.quit_and_wait()
# @unittest.skip
def test_thread(self):
fpath = name_to_fpath('helloworld_thread', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
dbg.go()
time.sleep(1)
dbg.pause_and_wait()
# print('switching to bad thread')
# self.assertFalse(dbg.thread_select(999))
threads = dbg.threads
self.assertGreater(len(threads), 1)
dbg.go()
time.sleep(1)
dbg.pause_and_wait()
threads = dbg.threads
self.assertGreater(len(threads), 1)
dbg.quit_and_wait()
@unittest.skipIf(platform.system() == 'Windows', 'Skip restart test on Windows for now')
def test_restart(self):
fpath = name_to_fpath('helloworld_thread', self.arch)
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
time.sleep(0.1)
dbg.go()
time.sleep(1)
dbg.pause_and_wait()
self.assertGreater(len(dbg.threads), 1)
time.sleep(0.1)
ret = dbg.restart_and_wait()
self.assertNotIn(ret, [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
time.sleep(0.1)
dbg.go()
time.sleep(1)
ret = dbg.restart_and_wait()
self.assertNotIn(ret, [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
dbg.quit_and_wait()
def test_assembly_code(self):
if self.arch == 'x86_64':
fpath = name_to_fpath('asmtest', 'x86_64')
bv = load(fpath)
dbg = self.create_debugger(bv)
self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError])
# Align the stack so the binary does not crash
dbg.set_reg_value('rsp', dbg.get_reg_value('rsp') & 0xfffffffffffffff0)
entry = dbg.data.entry_point
self.assertEqual(dbg.ip, entry)
# TODO: we can use BN to disassemble the binary and find out how long is the instruction
# step into nop
sleep_and_step_into(dbg)
self.assertEqual(dbg.ip, entry+1)
# step into call, return
sleep_and_step_into(dbg)
sleep_and_step_into(dbg)
# back
self.assertEqual(dbg.ip, entry+6)
sleep_and_step_into(dbg)
# step into call, return
sleep_and_step_into(dbg)
sleep_and_step_into(dbg)
# back
self.assertEqual(dbg.ip, entry+12)
reason = sleep_and_go(dbg)
self.assertEqual(reason, DebugStopReason.ProcessExited)
@unittest.skipIf(platform.system() == 'Linux', 'Cannot attach to pid unless running as root')
def test_attach(self):
pid = None
if platform.system() == 'Windows':
fpath = name_to_fpath('helloworld_loop', self.arch)
DETACHED_PROCESS = 0x00000008
CREATE_NEW_CONSOLE = 0x00000010
cmds = [fpath]
pid = subprocess.Popen(cmds, creationflags=CREATE_NEW_CONSOLE).pid
elif platform.system() in ['Darwin', 'Linux']:
fpath = name_to_fpath('helloworld_loop', self.arch)
cmds = [fpath]
pid = subprocess.Popen(cmds).pid
else:
print('attaching test not yet implemented on %s' % platform.system())
self.assertIsNotNone(pid)
bv = load(fpath)
dbg = self.create_debugger(bv)
dbg.pid_attach = pid
self.assertGreater(len(dbg.processes), 0)
self.assertTrue(dbg.attach_and_wait())
self.assertGreater(len(dbg.regs), 0)
dbg.quit_and_wait()
@unittest.skipIf(platform.machine() not in ['arm64', 'aarch64'], "Only run arm64 tests on arm Mac or Linux")
class DebuggerArm64Test(DebuggerAPI):
def setUp(self) -> None:
self.arch = 'arm64'
# Use LLDB on macOS/Linux, DbgEng on Windows
if platform.system() in ['Darwin', 'Linux']:
self.adapter_type = 'LLDB'
else:
self.adapter_type = 'DBGENG'
@unittest.skipIf(platform.system() == 'Linux' and platform.machine() in ['arm64', 'aarch64'], 'x86 tests not supported on arm64 macOS or Linux')
class Debuggerx64Test(DebuggerAPI):
def setUp(self) -> None:
self.arch = 'x86_64'
# Use LLDB on macOS/Linux, DbgEng on Windows
if platform.system() in ['Darwin', 'Linux']:
self.adapter_type = 'LLDB'
else:
self.adapter_type = 'DBGENG'
@unittest.skipIf(platform.machine() in ['arm64', 'aarch64'], 'x86 tests not supported on macOS or arm64 Linux')
class Debuggerx86Test(DebuggerAPI):
def setUp(self) -> None:
self.arch = 'x86'
# Use LLDB on macOS/Linux, DbgEng on Windows
if platform.system() in ['Darwin', 'Linux']:
self.adapter_type = 'LLDB'
else:
self.adapter_type = 'DBGENG'
# Windows Native Adapter Tests - only run on Windows
@unittest.skipUnless(platform.system() == 'Windows', 'Windows Native adapter only works on Windows')
@unittest.skipIf(platform.system() == 'Linux' and platform.machine() in ['arm64', 'aarch64'], 'x86 tests not supported on arm64 Linux')
class WindowsNativex64Test(DebuggerAPI):
def setUp(self) -> None:
self.arch = 'x86_64'
self.adapter_type = 'WINDOWS_NATIVE'
@unittest.skipUnless(platform.system() == 'Windows', 'Windows Native adapter only works on Windows')
@unittest.skipIf(platform.machine() in ['arm64', 'aarch64'], 'x86 tests not supported on arm64')
class WindowsNativex86Test(DebuggerAPI):
def setUp(self) -> None:
self.arch = 'x86'
self.adapter_type = 'WINDOWS_NATIVE'
def filter_test_suite(suite, keyword):
result = unittest.TestSuite()
for child in suite._tests:
if type(child) == unittest.suite.TestSuite:
result.addTest(filter_test_suite(child, keyword))
elif keyword.lower() in child._testMethodName.lower():
result.addTest(child)
return result
def main():
test_keyword = None
if len(sys.argv) > 1:
test_keyword = sys.argv[1]
runner = unittest.TextTestRunner(verbosity=2)
# Hack way to load the tests from the current file
test_suite = unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])
# if test keyword supplied, filter
if test_keyword:
test_suite = filter_test_suite(test_suite, test_keyword)
runner.run(test_suite)
if __name__ == "__main__":
main()