1
# Verify that gdb can pretty-print the various PyObject* types
3
# The code for testing gdb was adapted from similar work in Unladen Swallow's
4
# Lib/test/test_jit_gdb.py
15
# Is this Python configured to support threads?
21
from test import support
22
from test.support import run_unittest, findfile, python_is_optimized
25
gdb_version, _ = subprocess.Popen(["gdb", "--version"],
26
stdout=subprocess.PIPE).communicate()
28
# This is what "no gdb" looks like. There may, however, be other
29
# errors that manifest this way too.
30
raise unittest.SkipTest("Couldn't find gdb on the path")
31
gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
32
gdb_major_version = int(gdb_version_number.group(1))
33
gdb_minor_version = int(gdb_version_number.group(2))
34
if gdb_major_version < 7:
35
raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
36
" Saw:\n" + gdb_version.decode('ascii', 'replace'))
38
if not sysconfig.is_python_build():
39
raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
41
# Location of custom hooks file in a repository checkout.
42
checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
45
PYTHONHASHSEED = '123'
47
def run_gdb(*args, **env_vars):
48
"""Runs gdb in --batch mode with the additional arguments given by *args.
50
Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
53
env = os.environ.copy()
57
base_cmd = ('gdb', '--batch')
58
if (gdb_major_version, gdb_minor_version) >= (7, 4):
59
base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
60
out, err = subprocess.Popen(base_cmd + args,
61
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
63
return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
65
# Verify that "gdb" was built with the embedded python support enabled:
66
gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
68
raise unittest.SkipTest("gdb not built with embedded python support")
70
# Verify that "gdb" can load our custom hooks, as OS security settings may
71
# disallow this without a customised .gdbinit.
72
cmd = ['--args', sys.executable]
73
_, gdbpy_errors = run_gdb('--args', sys.executable)
74
if "auto-loading has been declined" in gdbpy_errors:
75
msg = "gdb security settings prevent use of custom hooks: "
76
raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
78
def gdb_has_frame_select():
79
# Does this build of gdb have gdb.Frame.select ?
80
stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
81
m = re.match(r'.*\[(.*)\].*', stdout)
83
raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
84
gdb_frame_dir = m.group(1).split(', ')
85
return "'select'" in gdb_frame_dir
87
HAS_PYUP_PYDOWN = gdb_has_frame_select()
89
BREAKPOINT_FN='builtin_id'
91
class DebuggerTests(unittest.TestCase):
93
"""Test that the debugger can debug Python."""
95
def get_stack_trace(self, source=None, script=None,
96
breakpoint=BREAKPOINT_FN,
97
cmds_after_breakpoint=None,
100
Run 'python -c SOURCE' under gdb with a breakpoint.
102
Support injecting commands after the breakpoint is reached
104
Returns the stdout from gdb
106
cmds_after_breakpoint: if provided, a list of strings: gdb commands
108
# We use "set breakpoint pending yes" to avoid blocking with a:
109
# Function "foo" not defined.
110
# Make breakpoint pending on future shared library load? (y or [n])
111
# error, which typically happens python is dynamically linked (the
112
# breakpoints of interest are to be found in the shared library)
113
# When this happens, we still get:
114
# Function "textiowrapper_write" not defined.
115
# emitted to stderr each time, alas.
117
# Initially I had "--eval-command=continue" here, but removed it to
118
# avoid repeated print breakpoints when traversing hierarchical data
121
# Generate a list of commands in gdb's language:
122
commands = ['set breakpoint pending yes',
123
'break %s' % breakpoint,
125
if cmds_after_breakpoint:
126
commands += cmds_after_breakpoint
128
commands += ['backtrace']
132
# Use "commands" to generate the arguments with which to invoke "gdb":
133
args = ["gdb", "--batch"]
134
args += ['--eval-command=%s' % cmd for cmd in commands]
139
# -S suppresses the default 'import site'
143
args += ["-c", source]
148
# print (' '.join(args))
150
# Use "args" to invoke gdb, capturing stdout, stderr:
151
out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
153
errlines = err.splitlines()
154
unexpected_errlines = []
156
# Ignore some benign messages on stderr.
158
'Function "%s" not defined.' % breakpoint,
159
"warning: no loadable sections found in added symbol-file"
160
" system-supplied DSO",
161
"warning: Unable to find libthread_db matching"
162
" inferior's thread library, thread debugging will"
163
" not be available.",
164
"warning: Cannot initialize thread debugging"
165
" library: Debugger service failed",
166
'warning: Could not load shared library symbols for '
168
'warning: Could not load shared library symbols for '
170
'Do you need "set solib-search-path" or '
172
'warning: Source file is more recent than executable.',
174
for line in errlines:
175
if not line.startswith(ignore_patterns):
176
unexpected_errlines.append(line)
178
# Ensure no unexpected error messages:
179
self.assertEqual(unexpected_errlines, [])
182
def get_gdb_repr(self, source,
183
cmds_after_breakpoint=None,
185
# Given an input python source representation of data,
186
# run "python -c'id(DATA)'" under gdb with a breakpoint on
187
# builtin_id and scrape out gdb's representation of the "op"
188
# parameter, and verify that the gdb displays the same string
190
# Verify that the gdb displays the expected string
192
# For a nested structure, the first time we hit the breakpoint will
193
# give us the top-level structure
195
# NOTE: avoid decoding too much of the traceback as some
196
# undecodable characters may lurk there in optimized mode
198
cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
199
gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
200
cmds_after_breakpoint=cmds_after_breakpoint,
201
import_site=import_site)
202
# gdb can insert additional '\n' and space characters in various places
203
# in its output, depending on the width of the terminal it's connected
204
# to (using its "wrap_here" function)
205
m = re.match('.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
206
gdb_output, re.DOTALL)
208
self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
209
return m.group(1), gdb_output
211
def assertEndsWith(self, actual, exp_end):
212
'''Ensure that the given "actual" string ends with "exp_end"'''
213
self.assertTrue(actual.endswith(exp_end),
214
msg='%r did not end with %r' % (actual, exp_end))
216
def assertMultilineMatches(self, actual, pattern):
217
m = re.match(pattern, actual, re.DOTALL)
219
self.fail(msg='%r did not match %r' % (actual, pattern))
221
def get_sample_script(self):
222
return findfile('gdb_sample.py')
224
class PrettyPrintTests(DebuggerTests):
225
def test_getting_backtrace(self):
226
gdb_output = self.get_stack_trace('id(42)')
227
self.assertTrue(BREAKPOINT_FN in gdb_output)
229
def assertGdbRepr(self, val, exp_repr=None):
230
# Ensure that gdb's rendering of the value in a debugged process
231
# matches repr(value) in this process:
232
gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
235
self.assertEqual(gdb_repr, exp_repr,
236
('%r did not equal expected %r; full output was:\n%s'
237
% (gdb_repr, exp_repr, gdb_output)))
240
'Verify the pretty-printing of various int values'
241
self.assertGdbRepr(42)
242
self.assertGdbRepr(0)
243
self.assertGdbRepr(-7)
244
self.assertGdbRepr(1000000000000)
245
self.assertGdbRepr(-1000000000000000)
247
def test_singletons(self):
248
'Verify the pretty-printing of True, False and None'
249
self.assertGdbRepr(True)
250
self.assertGdbRepr(False)
251
self.assertGdbRepr(None)
253
def test_dicts(self):
254
'Verify the pretty-printing of dictionaries'
255
self.assertGdbRepr({})
256
self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
257
self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
259
def test_lists(self):
260
'Verify the pretty-printing of lists'
261
self.assertGdbRepr([])
262
self.assertGdbRepr(list(range(5)))
264
def test_bytes(self):
265
'Verify the pretty-printing of bytes'
266
self.assertGdbRepr(b'')
267
self.assertGdbRepr(b'And now for something hopefully the same')
268
self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
269
self.assertGdbRepr(b'this is a tab:\t'
270
b' this is a slash-N:\n'
271
b' this is a slash-R:\r'
274
self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
276
self.assertGdbRepr(bytes([b for b in range(255)]))
278
def test_strings(self):
279
'Verify the pretty-printing of unicode strings'
280
encoding = locale.getpreferredencoding()
281
def check_repr(text):
283
text.encode(encoding)
285
except UnicodeEncodeError:
286
self.assertGdbRepr(text, ascii(text))
288
self.assertGdbRepr(text)
290
self.assertGdbRepr('')
291
self.assertGdbRepr('And now for something hopefully the same')
292
self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
294
# Test printing a single character:
295
# U+2620 SKULL AND CROSSBONES
298
# Test printing a Japanese unicode string
299
# (I believe this reads "mojibake", using 3 characters from the CJK
300
# Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
301
check_repr('\u6587\u5b57\u5316\u3051')
303
# Test a character outside the BMP:
304
# U+1D121 MUSICAL SYMBOL C CLEF
306
# UTF-8: 0xF0 0x9D 0x84 0xA1
307
# UTF-16: 0xD834 0xDD21
308
check_repr(chr(0x1D121))
310
def test_tuples(self):
311
'Verify the pretty-printing of tuples'
312
self.assertGdbRepr(tuple(), '()')
313
self.assertGdbRepr((1,), '(1,)')
314
self.assertGdbRepr(('foo', 'bar', 'baz'))
317
'Verify the pretty-printing of sets'
318
if (gdb_major_version, gdb_minor_version) < (7, 3):
319
self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
320
self.assertGdbRepr(set(), 'set()')
321
self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
322
self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
324
# Ensure that we handle sets containing the "dummy" key value,
325
# which happens on deletion:
326
gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
329
self.assertEqual(gdb_repr, "{'b'}")
331
def test_frozensets(self):
332
'Verify the pretty-printing of frozensets'
333
if (gdb_major_version, gdb_minor_version) < (7, 3):
334
self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
335
self.assertGdbRepr(frozenset(), 'frozenset()')
336
self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
337
self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
339
def test_exceptions(self):
340
# Test a RuntimeError
341
gdb_repr, gdb_output = self.get_gdb_repr('''
343
raise RuntimeError("I am an error")
344
except RuntimeError as e:
347
self.assertEqual(gdb_repr,
348
"RuntimeError('I am an error',)")
351
# Test division by zero:
352
gdb_repr, gdb_output = self.get_gdb_repr('''
355
except ZeroDivisionError as e:
358
self.assertEqual(gdb_repr,
359
"ZeroDivisionError('division by zero',)")
361
def test_modern_class(self):
362
'Verify the pretty-printing of new-style class instances'
363
gdb_repr, gdb_output = self.get_gdb_repr('''
369
m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
371
msg='Unexpected new-style class rendering %r' % gdb_repr)
373
def test_subclassing_list(self):
374
'Verify the pretty-printing of an instance of a list subclass'
375
gdb_repr, gdb_output = self.get_gdb_repr('''
382
m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
385
msg='Unexpected new-style class rendering %r' % gdb_repr)
387
def test_subclassing_tuple(self):
388
'Verify the pretty-printing of an instance of a tuple subclass'
389
# This should exercise the negative tp_dictoffset code in the
390
# new-style class support
391
gdb_repr, gdb_output = self.get_gdb_repr('''
397
m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
400
msg='Unexpected new-style class rendering %r' % gdb_repr)
402
def assertSane(self, source, corruption, exprepr=None):
403
'''Run Python under gdb, corrupting variables in the inferior process
404
immediately before taking a backtrace.
406
Verify that the variable's representation is the expected failsafe
409
cmds_after_breakpoint=[corruption, 'backtrace']
411
cmds_after_breakpoint=['backtrace']
413
gdb_repr, gdb_output = \
414
self.get_gdb_repr(source,
415
cmds_after_breakpoint=cmds_after_breakpoint)
417
if gdb_repr == exprepr:
418
# gdb managed to print the value in spite of the corruption;
419
# this is good (see http://bugs.python.org/issue8330)
422
# Match anything for the type name; 0xDEADBEEF could point to
423
# something arbitrary (see http://bugs.python.org/issue8330)
424
pattern = '<.* at remote 0x-?[0-9a-f]+>'
426
m = re.match(pattern, gdb_repr)
428
self.fail('Unexpected gdb representation: %r\n%s' % \
429
(gdb_repr, gdb_output))
431
def test_NULL_ptr(self):
432
'Ensure that a NULL PyObject* is handled gracefully'
433
gdb_repr, gdb_output = (
434
self.get_gdb_repr('id(42)',
435
cmds_after_breakpoint=['set variable v=0',
439
self.assertEqual(gdb_repr, '0x0')
441
def test_NULL_ob_type(self):
442
'Ensure that a PyObject* with NULL ob_type is handled gracefully'
443
self.assertSane('id(42)',
446
def test_corrupt_ob_type(self):
447
'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
448
self.assertSane('id(42)',
449
'set v->ob_type=0xDEADBEEF',
452
def test_corrupt_tp_flags(self):
453
'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
454
self.assertSane('id(42)',
455
'set v->ob_type->tp_flags=0x0',
458
def test_corrupt_tp_name(self):
459
'Ensure that a PyObject* with a type with corrupt tp_name is handled'
460
self.assertSane('id(42)',
461
'set v->ob_type->tp_name=0xDEADBEEF',
464
def test_builtins_help(self):
465
'Ensure that the new-style class _Helper in site.py can be handled'
466
# (this was the issue causing tracebacks in
467
# http://bugs.python.org/issue8032#msg100537 )
468
gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
470
m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
472
msg='Unexpected rendering %r' % gdb_repr)
474
def test_selfreferential_list(self):
475
'''Ensure that a reference loop involving a list doesn't lead proxyval
476
into an infinite loop:'''
477
gdb_repr, gdb_output = \
478
self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
479
self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
481
gdb_repr, gdb_output = \
482
self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
483
self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
485
def test_selfreferential_dict(self):
486
'''Ensure that a reference loop involving a dict doesn't lead proxyval
487
into an infinite loop:'''
488
gdb_repr, gdb_output = \
489
self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
491
self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
493
def test_selfreferential_old_style_instance(self):
494
gdb_repr, gdb_output = \
495
self.get_gdb_repr('''
501
self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
503
'Unexpected gdb representation: %r\n%s' % \
504
(gdb_repr, gdb_output))
506
def test_selfreferential_new_style_instance(self):
507
gdb_repr, gdb_output = \
508
self.get_gdb_repr('''
514
self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
516
'Unexpected gdb representation: %r\n%s' % \
517
(gdb_repr, gdb_output))
519
gdb_repr, gdb_output = \
520
self.get_gdb_repr('''
528
self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>\) at remote 0x-?[0-9a-f]+>',
530
'Unexpected gdb representation: %r\n%s' % \
531
(gdb_repr, gdb_output))
533
def test_truncation(self):
534
'Verify that very long output is truncated'
535
gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
536
self.assertEqual(gdb_repr,
537
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
538
"14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
539
"27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
540
"40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
541
"53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
542
"66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
543
"79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
544
"92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
545
"104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
546
"114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
547
"124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
548
"134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
549
"144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
550
"154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
551
"164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
552
"174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
553
"184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
554
"194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
555
"204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
556
"214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
557
"224, 225, 226...(truncated)")
558
self.assertEqual(len(gdb_repr),
559
1024 + len('...(truncated)'))
561
def test_builtin_method(self):
562
gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
563
self.assertTrue(re.match('<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
565
'Unexpected gdb representation: %r\n%s' % \
566
(gdb_repr, gdb_output))
568
def test_frames(self):
569
gdb_output = self.get_stack_trace('''
575
breakpoint='builtin_id',
576
cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
578
self.assertTrue(re.match('.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
581
'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
583
@unittest.skipIf(python_is_optimized(),
584
"Python was compiled with optimizations")
585
class PyListTests(DebuggerTests):
586
def assertListing(self, expected, actual):
587
self.assertEndsWith(actual, expected)
589
def test_basic_command(self):
590
'Verify that the "py-list" command works'
591
bt = self.get_stack_trace(script=self.get_sample_script(),
592
cmds_after_breakpoint=['py-list'])
594
self.assertListing(' 5 \n'
595
' 6 def bar(a, b, c):\n'
598
' 9 def baz(*args):\n'
601
' 12 foo(1, 2, 3)\n',
604
def test_one_abs_arg(self):
605
'Verify the "py-list" command with one absolute argument'
606
bt = self.get_stack_trace(script=self.get_sample_script(),
607
cmds_after_breakpoint=['py-list 9'])
609
self.assertListing(' 9 def baz(*args):\n'
612
' 12 foo(1, 2, 3)\n',
615
def test_two_abs_args(self):
616
'Verify the "py-list" command with two absolute arguments'
617
bt = self.get_stack_trace(script=self.get_sample_script(),
618
cmds_after_breakpoint=['py-list 1,3'])
620
self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
622
' 3 def foo(a, b, c):\n',
625
class StackNavigationTests(DebuggerTests):
626
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
627
@unittest.skipIf(python_is_optimized(),
628
"Python was compiled with optimizations")
629
def test_pyup_command(self):
630
'Verify that the "py-up" command works'
631
bt = self.get_stack_trace(script=self.get_sample_script(),
632
cmds_after_breakpoint=['py-up'])
633
self.assertMultilineMatches(bt,
635
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
639
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
640
def test_down_at_bottom(self):
641
'Verify handling of "py-down" at the bottom of the stack'
642
bt = self.get_stack_trace(script=self.get_sample_script(),
643
cmds_after_breakpoint=['py-down'])
644
self.assertEndsWith(bt,
645
'Unable to find a newer python frame\n')
647
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
648
def test_up_at_top(self):
649
'Verify handling of "py-up" at the top of the stack'
650
bt = self.get_stack_trace(script=self.get_sample_script(),
651
cmds_after_breakpoint=['py-up'] * 4)
652
self.assertEndsWith(bt,
653
'Unable to find an older python frame\n')
655
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
656
@unittest.skipIf(python_is_optimized(),
657
"Python was compiled with optimizations")
658
def test_up_then_down(self):
659
'Verify "py-up" followed by "py-down"'
660
bt = self.get_stack_trace(script=self.get_sample_script(),
661
cmds_after_breakpoint=['py-up', 'py-down'])
662
self.assertMultilineMatches(bt,
664
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
666
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
670
class PyBtTests(DebuggerTests):
671
@unittest.skipIf(python_is_optimized(),
672
"Python was compiled with optimizations")
674
'Verify that the "py-bt" command works'
675
bt = self.get_stack_trace(script=self.get_sample_script(),
676
cmds_after_breakpoint=['py-bt'])
677
self.assertMultilineMatches(bt,
679
Traceback \(most recent call first\):
680
File ".*gdb_sample.py", line 10, in baz
682
File ".*gdb_sample.py", line 7, in bar
684
File ".*gdb_sample.py", line 4, in foo
686
File ".*gdb_sample.py", line 12, in <module>
690
@unittest.skipIf(python_is_optimized(),
691
"Python was compiled with optimizations")
692
def test_bt_full(self):
693
'Verify that the "py-bt-full" command works'
694
bt = self.get_stack_trace(script=self.get_sample_script(),
695
cmds_after_breakpoint=['py-bt-full'])
696
self.assertMultilineMatches(bt,
698
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
700
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
702
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
706
@unittest.skipUnless(_thread,
707
"Python was compiled without thread support")
708
def test_threads(self):
709
'Verify that "py-bt" indicates threads that are waiting for the GIL'
711
from threading import Thread
713
class TestThread(Thread):
714
# These threads would run forever, but we'll interrupt things with the
726
# Trigger a breakpoint on the main thread
730
# Verify with "py-bt":
731
gdb_output = self.get_stack_trace(cmd,
732
cmds_after_breakpoint=['thread apply all py-bt'])
733
self.assertIn('Waiting for the GIL', gdb_output)
735
# Verify with "py-bt-full":
736
gdb_output = self.get_stack_trace(cmd,
737
cmds_after_breakpoint=['thread apply all py-bt-full'])
738
self.assertIn('Waiting for the GIL', gdb_output)
740
@unittest.skipIf(python_is_optimized(),
741
"Python was compiled with optimizations")
742
# Some older versions of gdb will fail with
743
# "Cannot find new threads: generic error"
744
# unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
745
@unittest.skipUnless(_thread,
746
"Python was compiled without thread support")
748
'Verify that "py-bt" indicates if a thread is garbage-collecting'
749
cmd = ('from gc import collect\n'
756
# Verify with "py-bt":
757
gdb_output = self.get_stack_trace(cmd,
758
cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
760
self.assertIn('Garbage-collecting', gdb_output)
762
# Verify with "py-bt-full":
763
gdb_output = self.get_stack_trace(cmd,
764
cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
766
self.assertIn('Garbage-collecting', gdb_output)
768
@unittest.skipIf(python_is_optimized(),
769
"Python was compiled with optimizations")
770
# Some older versions of gdb will fail with
771
# "Cannot find new threads: generic error"
772
# unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
773
@unittest.skipUnless(_thread,
774
"Python was compiled without thread support")
775
def test_pycfunction(self):
776
'Verify that "py-bt" displays invocations of PyCFunction instances'
777
cmd = ('from time import sleep\n'
783
# Verify with "py-bt":
784
gdb_output = self.get_stack_trace(cmd,
785
breakpoint='time_sleep',
786
cmds_after_breakpoint=['bt', 'py-bt'],
788
self.assertIn('<built-in method sleep', gdb_output)
790
# Verify with "py-bt-full":
791
gdb_output = self.get_stack_trace(cmd,
792
breakpoint='time_sleep',
793
cmds_after_breakpoint=['py-bt-full'],
795
self.assertIn('#0 <built-in method sleep', gdb_output)
798
class PyPrintTests(DebuggerTests):
799
@unittest.skipIf(python_is_optimized(),
800
"Python was compiled with optimizations")
801
def test_basic_command(self):
802
'Verify that the "py-print" command works'
803
bt = self.get_stack_trace(script=self.get_sample_script(),
804
cmds_after_breakpoint=['py-print args'])
805
self.assertMultilineMatches(bt,
806
r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
808
@unittest.skipIf(python_is_optimized(),
809
"Python was compiled with optimizations")
810
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
811
def test_print_after_up(self):
812
bt = self.get_stack_trace(script=self.get_sample_script(),
813
cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
814
self.assertMultilineMatches(bt,
815
r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
817
@unittest.skipIf(python_is_optimized(),
818
"Python was compiled with optimizations")
819
def test_printing_global(self):
820
bt = self.get_stack_trace(script=self.get_sample_script(),
821
cmds_after_breakpoint=['py-print __name__'])
822
self.assertMultilineMatches(bt,
823
r".*\nglobal '__name__' = '__main__'\n.*")
825
@unittest.skipIf(python_is_optimized(),
826
"Python was compiled with optimizations")
827
def test_printing_builtin(self):
828
bt = self.get_stack_trace(script=self.get_sample_script(),
829
cmds_after_breakpoint=['py-print len'])
830
self.assertMultilineMatches(bt,
831
r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
833
class PyLocalsTests(DebuggerTests):
834
@unittest.skipIf(python_is_optimized(),
835
"Python was compiled with optimizations")
836
def test_basic_command(self):
837
bt = self.get_stack_trace(script=self.get_sample_script(),
838
cmds_after_breakpoint=['py-locals'])
839
self.assertMultilineMatches(bt,
840
r".*\nargs = \(1, 2, 3\)\n.*")
842
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
843
@unittest.skipIf(python_is_optimized(),
844
"Python was compiled with optimizations")
845
def test_locals_after_up(self):
846
bt = self.get_stack_trace(script=self.get_sample_script(),
847
cmds_after_breakpoint=['py-up', 'py-locals'])
848
self.assertMultilineMatches(bt,
849
r".*\na = 1\nb = 2\nc = 3\n.*")
853
print("GDB version:")
854
for line in os.fsdecode(gdb_version).splitlines():
855
print(" " * 4 + line)
856
run_unittest(PrettyPrintTests,
858
StackNavigationTests,
864
if __name__ == "__main__":