• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Verify that gdb can pretty-print the various PyObject* types
2#
3# The code for testing gdb was adapted from similar work in Unladen Swallow's
4# Lib/test/test_jit_gdb.py
5
6import os
7import platform
8import re
9import subprocess
10import sys
11import sysconfig
12import textwrap
13import unittest
14
15from test import support
16from test.support import run_unittest, findfile, python_is_optimized
17
18def get_gdb_version():
19    try:
20        cmd = ["gdb", "-nx", "--version"]
21        proc = subprocess.Popen(cmd,
22                                stdout=subprocess.PIPE,
23                                stderr=subprocess.PIPE,
24                                universal_newlines=True)
25        with proc:
26            version, stderr = proc.communicate()
27
28        if proc.returncode:
29            raise Exception(f"Command {' '.join(cmd)!r} failed "
30                            f"with exit code {proc.returncode}: "
31                            f"stdout={version!r} stderr={stderr!r}")
32    except OSError:
33        # This is what "no gdb" looks like.  There may, however, be other
34        # errors that manifest this way too.
35        raise unittest.SkipTest("Couldn't find gdb on the path")
36
37    # Regex to parse:
38    # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
39    # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
40    # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
41    # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
42    # 'HP gdb 6.7 for HP Itanium (32 or 64 bit) and target HP-UX 11iv2 and 11iv3.\n' -> 6.7
43    match = re.search(r"^(?:GNU|HP) gdb.*?\b(\d+)\.(\d+)", version)
44    if match is None:
45        raise Exception("unable to parse GDB version: %r" % version)
46    return (version, int(match.group(1)), int(match.group(2)))
47
48gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
49if gdb_major_version < 7:
50    raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
51                            "embedding. Saw %s.%s:\n%s"
52                            % (gdb_major_version, gdb_minor_version,
53                               gdb_version))
54
55if not sysconfig.is_python_build():
56    raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
57
58if 'Clang' in platform.python_compiler() and sys.platform == 'darwin':
59    raise unittest.SkipTest("test_gdb doesn't work correctly when python is"
60                            " built with LLVM clang")
61
62if ((sysconfig.get_config_var('PGO_PROF_USE_FLAG') or 'xxx') in
63    (sysconfig.get_config_var('PY_CORE_CFLAGS') or '')):
64    raise unittest.SkipTest("test_gdb is not reliable on PGO builds")
65
66# Location of custom hooks file in a repository checkout.
67checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
68                                  'python-gdb.py')
69
70PYTHONHASHSEED = '123'
71
72
73def cet_protection():
74    cflags = sysconfig.get_config_var('CFLAGS')
75    if not cflags:
76        return False
77    flags = cflags.split()
78    # True if "-mcet -fcf-protection" options are found, but false
79    # if "-fcf-protection=none" or "-fcf-protection=return" is found.
80    return (('-mcet' in flags)
81            and any((flag.startswith('-fcf-protection')
82                     and not flag.endswith(("=none", "=return")))
83                    for flag in flags))
84
85# Control-flow enforcement technology
86CET_PROTECTION = cet_protection()
87
88
89def run_gdb(*args, **env_vars):
90    """Runs gdb in --batch mode with the additional arguments given by *args.
91
92    Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
93    """
94    if env_vars:
95        env = os.environ.copy()
96        env.update(env_vars)
97    else:
98        env = None
99    # -nx: Do not execute commands from any .gdbinit initialization files
100    #      (issue #22188)
101    base_cmd = ('gdb', '--batch', '-nx')
102    if (gdb_major_version, gdb_minor_version) >= (7, 4):
103        base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
104    proc = subprocess.Popen(base_cmd + args,
105                            # Redirect stdin to prevent GDB from messing with
106                            # the terminal settings
107                            stdin=subprocess.PIPE,
108                            stdout=subprocess.PIPE,
109                            stderr=subprocess.PIPE,
110                            env=env)
111    with proc:
112        out, err = proc.communicate()
113    return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
114
115# Verify that "gdb" was built with the embedded python support enabled:
116gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
117if not gdbpy_version:
118    raise unittest.SkipTest("gdb not built with embedded python support")
119
120# Verify that "gdb" can load our custom hooks, as OS security settings may
121# disallow this without a customized .gdbinit.
122_, gdbpy_errors = run_gdb('--args', sys.executable)
123if "auto-loading has been declined" in gdbpy_errors:
124    msg = "gdb security settings prevent use of custom hooks: "
125    raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
126
127def gdb_has_frame_select():
128    # Does this build of gdb have gdb.Frame.select ?
129    stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
130    m = re.match(r'.*\[(.*)\].*', stdout)
131    if not m:
132        raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
133    gdb_frame_dir = m.group(1).split(', ')
134    return "'select'" in gdb_frame_dir
135
136HAS_PYUP_PYDOWN = gdb_has_frame_select()
137
138BREAKPOINT_FN='builtin_id'
139
140@unittest.skipIf(support.PGO, "not useful for PGO")
141class DebuggerTests(unittest.TestCase):
142
143    """Test that the debugger can debug Python."""
144
145    def get_stack_trace(self, source=None, script=None,
146                        breakpoint=BREAKPOINT_FN,
147                        cmds_after_breakpoint=None,
148                        import_site=False):
149        '''
150        Run 'python -c SOURCE' under gdb with a breakpoint.
151
152        Support injecting commands after the breakpoint is reached
153
154        Returns the stdout from gdb
155
156        cmds_after_breakpoint: if provided, a list of strings: gdb commands
157        '''
158        # We use "set breakpoint pending yes" to avoid blocking with a:
159        #   Function "foo" not defined.
160        #   Make breakpoint pending on future shared library load? (y or [n])
161        # error, which typically happens python is dynamically linked (the
162        # breakpoints of interest are to be found in the shared library)
163        # When this happens, we still get:
164        #   Function "textiowrapper_write" not defined.
165        # emitted to stderr each time, alas.
166
167        # Initially I had "--eval-command=continue" here, but removed it to
168        # avoid repeated print breakpoints when traversing hierarchical data
169        # structures
170
171        # Generate a list of commands in gdb's language:
172        commands = ['set breakpoint pending yes',
173                    'break %s' % breakpoint,
174
175                    # The tests assume that the first frame of printed
176                    #  backtrace will not contain program counter,
177                    #  that is however not guaranteed by gdb
178                    #  therefore we need to use 'set print address off' to
179                    #  make sure the counter is not there. For example:
180                    # #0 in PyObject_Print ...
181                    #  is assumed, but sometimes this can be e.g.
182                    # #0 0x00003fffb7dd1798 in PyObject_Print ...
183                    'set print address off',
184
185                    'run']
186
187        # GDB as of 7.4 onwards can distinguish between the
188        # value of a variable at entry vs current value:
189        #   http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
190        # which leads to the selftests failing with errors like this:
191        #   AssertionError: 'v@entry=()' != '()'
192        # Disable this:
193        if (gdb_major_version, gdb_minor_version) >= (7, 4):
194            commands += ['set print entry-values no']
195
196        if cmds_after_breakpoint:
197            if CET_PROTECTION:
198                # bpo-32962: When Python is compiled with -mcet
199                # -fcf-protection, function arguments are unusable before
200                # running the first instruction of the function entry point.
201                # The 'next' command makes the required first step.
202                commands += ['next']
203            commands += cmds_after_breakpoint
204        else:
205            commands += ['backtrace']
206
207        # print commands
208
209        # Use "commands" to generate the arguments with which to invoke "gdb":
210        args = ['--eval-command=%s' % cmd for cmd in commands]
211        args += ["--args",
212                 sys.executable]
213        args.extend(subprocess._args_from_interpreter_flags())
214
215        if not import_site:
216            # -S suppresses the default 'import site'
217            args += ["-S"]
218
219        if source:
220            args += ["-c", source]
221        elif script:
222            args += [script]
223
224        # Use "args" to invoke gdb, capturing stdout, stderr:
225        out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
226
227        for line in err.splitlines():
228            print(line, file=sys.stderr)
229
230        # bpo-34007: Sometimes some versions of the shared libraries that
231        # are part of the traceback are compiled in optimised mode and the
232        # Program Counter (PC) is not present, not allowing gdb to walk the
233        # frames back. When this happens, the Python bindings of gdb raise
234        # an exception, making the test impossible to succeed.
235        if "PC not saved" in err:
236            raise unittest.SkipTest("gdb cannot walk the frame object"
237                                    " because the Program Counter is"
238                                    " not present")
239
240        # bpo-40019: Skip the test if gdb failed to read debug information
241        # because the Python binary is optimized.
242        for pattern in (
243            '(frame information optimized out)',
244            'Unable to read information on python frame',
245        ):
246            if pattern in out:
247                raise unittest.SkipTest(f"{pattern!r} found in gdb output")
248
249        return out
250
251    def get_gdb_repr(self, source,
252                     cmds_after_breakpoint=None,
253                     import_site=False):
254        # Given an input python source representation of data,
255        # run "python -c'id(DATA)'" under gdb with a breakpoint on
256        # builtin_id and scrape out gdb's representation of the "op"
257        # parameter, and verify that the gdb displays the same string
258        #
259        # Verify that the gdb displays the expected string
260        #
261        # For a nested structure, the first time we hit the breakpoint will
262        # give us the top-level structure
263
264        # NOTE: avoid decoding too much of the traceback as some
265        # undecodable characters may lurk there in optimized mode
266        # (issue #19743).
267        cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
268        gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
269                                          cmds_after_breakpoint=cmds_after_breakpoint,
270                                          import_site=import_site)
271        # gdb can insert additional '\n' and space characters in various places
272        # in its output, depending on the width of the terminal it's connected
273        # to (using its "wrap_here" function)
274        m = re.search(
275            # Match '#0 builtin_id(self=..., v=...)'
276            r'#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)?\)'
277            # Match ' at Python/bltinmodule.c'.
278            # bpo-38239: builtin_id() is defined in Python/bltinmodule.c,
279            # but accept any "Directory\file.c" to support Link Time
280            # Optimization (LTO).
281            r'\s+at\s+\S*[A-Za-z]+/[A-Za-z0-9_-]+\.c',
282            gdb_output, re.DOTALL)
283        if not m:
284            self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
285        return m.group(1), gdb_output
286
287    def assertEndsWith(self, actual, exp_end):
288        '''Ensure that the given "actual" string ends with "exp_end"'''
289        self.assertTrue(actual.endswith(exp_end),
290                        msg='%r did not end with %r' % (actual, exp_end))
291
292    def assertMultilineMatches(self, actual, pattern):
293        m = re.match(pattern, actual, re.DOTALL)
294        if not m:
295            self.fail(msg='%r did not match %r' % (actual, pattern))
296
297    def get_sample_script(self):
298        return findfile('gdb_sample.py')
299
300class PrettyPrintTests(DebuggerTests):
301    def test_getting_backtrace(self):
302        gdb_output = self.get_stack_trace('id(42)')
303        self.assertTrue(BREAKPOINT_FN in gdb_output)
304
305    def assertGdbRepr(self, val, exp_repr=None):
306        # Ensure that gdb's rendering of the value in a debugged process
307        # matches repr(value) in this process:
308        gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
309        if not exp_repr:
310            exp_repr = repr(val)
311        self.assertEqual(gdb_repr, exp_repr,
312                         ('%r did not equal expected %r; full output was:\n%s'
313                          % (gdb_repr, exp_repr, gdb_output)))
314
315    def test_int(self):
316        'Verify the pretty-printing of various int values'
317        self.assertGdbRepr(42)
318        self.assertGdbRepr(0)
319        self.assertGdbRepr(-7)
320        self.assertGdbRepr(1000000000000)
321        self.assertGdbRepr(-1000000000000000)
322
323    def test_singletons(self):
324        'Verify the pretty-printing of True, False and None'
325        self.assertGdbRepr(True)
326        self.assertGdbRepr(False)
327        self.assertGdbRepr(None)
328
329    def test_dicts(self):
330        'Verify the pretty-printing of dictionaries'
331        self.assertGdbRepr({})
332        self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
333        # Python preserves insertion order since 3.6
334        self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
335
336    def test_lists(self):
337        'Verify the pretty-printing of lists'
338        self.assertGdbRepr([])
339        self.assertGdbRepr(list(range(5)))
340
341    def test_bytes(self):
342        'Verify the pretty-printing of bytes'
343        self.assertGdbRepr(b'')
344        self.assertGdbRepr(b'And now for something hopefully the same')
345        self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
346        self.assertGdbRepr(b'this is a tab:\t'
347                           b' this is a slash-N:\n'
348                           b' this is a slash-R:\r'
349                           )
350
351        self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
352
353        self.assertGdbRepr(bytes([b for b in range(255)]))
354
355    def test_strings(self):
356        'Verify the pretty-printing of unicode strings'
357        # We cannot simply call locale.getpreferredencoding() here,
358        # as GDB might have been linked against a different version
359        # of Python with a different encoding and coercion policy
360        # with respect to PEP 538 and PEP 540.
361        out, err = run_gdb(
362            '--eval-command',
363            'python import locale; print(locale.getpreferredencoding())')
364
365        encoding = out.rstrip()
366        if err or not encoding:
367            raise RuntimeError(
368                f'unable to determine the preferred encoding '
369                f'of embedded Python in GDB: {err}')
370
371        def check_repr(text):
372            try:
373                text.encode(encoding)
374                printable = True
375            except UnicodeEncodeError:
376                self.assertGdbRepr(text, ascii(text))
377            else:
378                self.assertGdbRepr(text)
379
380        self.assertGdbRepr('')
381        self.assertGdbRepr('And now for something hopefully the same')
382        self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
383
384        # Test printing a single character:
385        #    U+2620 SKULL AND CROSSBONES
386        check_repr('\u2620')
387
388        # Test printing a Japanese unicode string
389        # (I believe this reads "mojibake", using 3 characters from the CJK
390        # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
391        check_repr('\u6587\u5b57\u5316\u3051')
392
393        # Test a character outside the BMP:
394        #    U+1D121 MUSICAL SYMBOL C CLEF
395        # This is:
396        # UTF-8: 0xF0 0x9D 0x84 0xA1
397        # UTF-16: 0xD834 0xDD21
398        check_repr(chr(0x1D121))
399
400    def test_tuples(self):
401        'Verify the pretty-printing of tuples'
402        self.assertGdbRepr(tuple(), '()')
403        self.assertGdbRepr((1,), '(1,)')
404        self.assertGdbRepr(('foo', 'bar', 'baz'))
405
406    def test_sets(self):
407        'Verify the pretty-printing of sets'
408        if (gdb_major_version, gdb_minor_version) < (7, 3):
409            self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
410        self.assertGdbRepr(set(), "set()")
411        self.assertGdbRepr(set(['a']), "{'a'}")
412        # PYTHONHASHSEED is need to get the exact frozenset item order
413        if not sys.flags.ignore_environment:
414            self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
415            self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
416
417        # Ensure that we handle sets containing the "dummy" key value,
418        # which happens on deletion:
419        gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
420s.remove('a')
421id(s)''')
422        self.assertEqual(gdb_repr, "{'b'}")
423
424    def test_frozensets(self):
425        'Verify the pretty-printing of frozensets'
426        if (gdb_major_version, gdb_minor_version) < (7, 3):
427            self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
428        self.assertGdbRepr(frozenset(), "frozenset()")
429        self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
430        # PYTHONHASHSEED is need to get the exact frozenset item order
431        if not sys.flags.ignore_environment:
432            self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
433            self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
434
435    def test_exceptions(self):
436        # Test a RuntimeError
437        gdb_repr, gdb_output = self.get_gdb_repr('''
438try:
439    raise RuntimeError("I am an error")
440except RuntimeError as e:
441    id(e)
442''')
443        self.assertEqual(gdb_repr,
444                         "RuntimeError('I am an error',)")
445
446
447        # Test division by zero:
448        gdb_repr, gdb_output = self.get_gdb_repr('''
449try:
450    a = 1 / 0
451except ZeroDivisionError as e:
452    id(e)
453''')
454        self.assertEqual(gdb_repr,
455                         "ZeroDivisionError('division by zero',)")
456
457    def test_modern_class(self):
458        'Verify the pretty-printing of new-style class instances'
459        gdb_repr, gdb_output = self.get_gdb_repr('''
460class Foo:
461    pass
462foo = Foo()
463foo.an_int = 42
464id(foo)''')
465        m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
466        self.assertTrue(m,
467                        msg='Unexpected new-style class rendering %r' % gdb_repr)
468
469    def test_subclassing_list(self):
470        'Verify the pretty-printing of an instance of a list subclass'
471        gdb_repr, gdb_output = self.get_gdb_repr('''
472class Foo(list):
473    pass
474foo = Foo()
475foo += [1, 2, 3]
476foo.an_int = 42
477id(foo)''')
478        m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
479
480        self.assertTrue(m,
481                        msg='Unexpected new-style class rendering %r' % gdb_repr)
482
483    def test_subclassing_tuple(self):
484        'Verify the pretty-printing of an instance of a tuple subclass'
485        # This should exercise the negative tp_dictoffset code in the
486        # new-style class support
487        gdb_repr, gdb_output = self.get_gdb_repr('''
488class Foo(tuple):
489    pass
490foo = Foo((1, 2, 3))
491foo.an_int = 42
492id(foo)''')
493        m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
494
495        self.assertTrue(m,
496                        msg='Unexpected new-style class rendering %r' % gdb_repr)
497
498    def assertSane(self, source, corruption, exprepr=None):
499        '''Run Python under gdb, corrupting variables in the inferior process
500        immediately before taking a backtrace.
501
502        Verify that the variable's representation is the expected failsafe
503        representation'''
504        if corruption:
505            cmds_after_breakpoint=[corruption, 'backtrace']
506        else:
507            cmds_after_breakpoint=['backtrace']
508
509        gdb_repr, gdb_output = \
510            self.get_gdb_repr(source,
511                              cmds_after_breakpoint=cmds_after_breakpoint)
512        if exprepr:
513            if gdb_repr == exprepr:
514                # gdb managed to print the value in spite of the corruption;
515                # this is good (see http://bugs.python.org/issue8330)
516                return
517
518        # Match anything for the type name; 0xDEADBEEF could point to
519        # something arbitrary (see  http://bugs.python.org/issue8330)
520        pattern = '<.* at remote 0x-?[0-9a-f]+>'
521
522        m = re.match(pattern, gdb_repr)
523        if not m:
524            self.fail('Unexpected gdb representation: %r\n%s' % \
525                          (gdb_repr, gdb_output))
526
527    def test_NULL_ptr(self):
528        'Ensure that a NULL PyObject* is handled gracefully'
529        gdb_repr, gdb_output = (
530            self.get_gdb_repr('id(42)',
531                              cmds_after_breakpoint=['set variable v=0',
532                                                     'backtrace'])
533            )
534
535        self.assertEqual(gdb_repr, '0x0')
536
537    def test_NULL_ob_type(self):
538        'Ensure that a PyObject* with NULL ob_type is handled gracefully'
539        self.assertSane('id(42)',
540                        'set v->ob_type=0')
541
542    def test_corrupt_ob_type(self):
543        'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
544        self.assertSane('id(42)',
545                        'set v->ob_type=0xDEADBEEF',
546                        exprepr='42')
547
548    def test_corrupt_tp_flags(self):
549        'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
550        self.assertSane('id(42)',
551                        'set v->ob_type->tp_flags=0x0',
552                        exprepr='42')
553
554    def test_corrupt_tp_name(self):
555        'Ensure that a PyObject* with a type with corrupt tp_name is handled'
556        self.assertSane('id(42)',
557                        'set v->ob_type->tp_name=0xDEADBEEF',
558                        exprepr='42')
559
560    def test_builtins_help(self):
561        'Ensure that the new-style class _Helper in site.py can be handled'
562
563        if sys.flags.no_site:
564            self.skipTest("need site module, but -S option was used")
565
566        # (this was the issue causing tracebacks in
567        #  http://bugs.python.org/issue8032#msg100537 )
568        gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
569
570        m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
571        self.assertTrue(m,
572                        msg='Unexpected rendering %r' % gdb_repr)
573
574    def test_selfreferential_list(self):
575        '''Ensure that a reference loop involving a list doesn't lead proxyval
576        into an infinite loop:'''
577        gdb_repr, gdb_output = \
578            self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
579        self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
580
581        gdb_repr, gdb_output = \
582            self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
583        self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
584
585    def test_selfreferential_dict(self):
586        '''Ensure that a reference loop involving a dict doesn't lead proxyval
587        into an infinite loop:'''
588        gdb_repr, gdb_output = \
589            self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
590
591        self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
592
593    def test_selfreferential_old_style_instance(self):
594        gdb_repr, gdb_output = \
595            self.get_gdb_repr('''
596class Foo:
597    pass
598foo = Foo()
599foo.an_attr = foo
600id(foo)''')
601        self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
602                                 gdb_repr),
603                        'Unexpected gdb representation: %r\n%s' % \
604                            (gdb_repr, gdb_output))
605
606    def test_selfreferential_new_style_instance(self):
607        gdb_repr, gdb_output = \
608            self.get_gdb_repr('''
609class Foo(object):
610    pass
611foo = Foo()
612foo.an_attr = foo
613id(foo)''')
614        self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
615                                 gdb_repr),
616                        'Unexpected gdb representation: %r\n%s' % \
617                            (gdb_repr, gdb_output))
618
619        gdb_repr, gdb_output = \
620            self.get_gdb_repr('''
621class Foo(object):
622    pass
623a = Foo()
624b = Foo()
625a.an_attr = b
626b.an_attr = a
627id(a)''')
628        self.assertTrue(re.match(r'<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>\) at remote 0x-?[0-9a-f]+>',
629                                 gdb_repr),
630                        'Unexpected gdb representation: %r\n%s' % \
631                            (gdb_repr, gdb_output))
632
633    def test_truncation(self):
634        'Verify that very long output is truncated'
635        gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
636        self.assertEqual(gdb_repr,
637                         "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
638                         "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
639                         "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
640                         "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
641                         "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
642                         "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
643                         "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
644                         "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
645                         "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
646                         "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
647                         "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
648                         "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
649                         "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
650                         "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
651                         "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
652                         "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
653                         "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
654                         "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
655                         "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
656                         "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
657                         "224, 225, 226...(truncated)")
658        self.assertEqual(len(gdb_repr),
659                         1024 + len('...(truncated)'))
660
661    def test_builtin_method(self):
662        gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
663        self.assertTrue(re.match(r'<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
664                                 gdb_repr),
665                        'Unexpected gdb representation: %r\n%s' % \
666                            (gdb_repr, gdb_output))
667
668    def test_frames(self):
669        gdb_output = self.get_stack_trace('''
670def foo(a, b, c):
671    pass
672
673foo(3, 4, 5)
674id(foo.__code__)''',
675                                          breakpoint='builtin_id',
676                                          cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
677                                          )
678        self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
679                                 gdb_output,
680                                 re.DOTALL),
681                        'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
682
683@unittest.skipIf(python_is_optimized(),
684                 "Python was compiled with optimizations")
685class PyListTests(DebuggerTests):
686    def assertListing(self, expected, actual):
687        self.assertEndsWith(actual, expected)
688
689    def test_basic_command(self):
690        'Verify that the "py-list" command works'
691        bt = self.get_stack_trace(script=self.get_sample_script(),
692                                  cmds_after_breakpoint=['py-list'])
693
694        self.assertListing('   5    \n'
695                           '   6    def bar(a, b, c):\n'
696                           '   7        baz(a, b, c)\n'
697                           '   8    \n'
698                           '   9    def baz(*args):\n'
699                           ' >10        id(42)\n'
700                           '  11    \n'
701                           '  12    foo(1, 2, 3)\n',
702                           bt)
703
704    def test_one_abs_arg(self):
705        'Verify the "py-list" command with one absolute argument'
706        bt = self.get_stack_trace(script=self.get_sample_script(),
707                                  cmds_after_breakpoint=['py-list 9'])
708
709        self.assertListing('   9    def baz(*args):\n'
710                           ' >10        id(42)\n'
711                           '  11    \n'
712                           '  12    foo(1, 2, 3)\n',
713                           bt)
714
715    def test_two_abs_args(self):
716        'Verify the "py-list" command with two absolute arguments'
717        bt = self.get_stack_trace(script=self.get_sample_script(),
718                                  cmds_after_breakpoint=['py-list 1,3'])
719
720        self.assertListing('   1    # Sample script for use by test_gdb.py\n'
721                           '   2    \n'
722                           '   3    def foo(a, b, c):\n',
723                           bt)
724
725class StackNavigationTests(DebuggerTests):
726    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
727    @unittest.skipIf(python_is_optimized(),
728                     "Python was compiled with optimizations")
729    def test_pyup_command(self):
730        'Verify that the "py-up" command works'
731        bt = self.get_stack_trace(script=self.get_sample_script(),
732                                  cmds_after_breakpoint=['py-up', 'py-up'])
733        self.assertMultilineMatches(bt,
734                                    r'''^.*
735#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
736    baz\(a, b, c\)
737$''')
738
739    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
740    def test_down_at_bottom(self):
741        'Verify handling of "py-down" at the bottom of the stack'
742        bt = self.get_stack_trace(script=self.get_sample_script(),
743                                  cmds_after_breakpoint=['py-down'])
744        self.assertEndsWith(bt,
745                            'Unable to find a newer python frame\n')
746
747    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
748    def test_up_at_top(self):
749        'Verify handling of "py-up" at the top of the stack'
750        bt = self.get_stack_trace(script=self.get_sample_script(),
751                                  cmds_after_breakpoint=['py-up'] * 5)
752        self.assertEndsWith(bt,
753                            'Unable to find an older python frame\n')
754
755    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
756    @unittest.skipIf(python_is_optimized(),
757                     "Python was compiled with optimizations")
758    def test_up_then_down(self):
759        'Verify "py-up" followed by "py-down"'
760        bt = self.get_stack_trace(script=self.get_sample_script(),
761                                  cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
762        self.assertMultilineMatches(bt,
763                                    r'''^.*
764#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
765    baz\(a, b, c\)
766#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
767    id\(42\)
768$''')
769
770class PyBtTests(DebuggerTests):
771    @unittest.skipIf(python_is_optimized(),
772                     "Python was compiled with optimizations")
773    def test_bt(self):
774        'Verify that the "py-bt" command works'
775        bt = self.get_stack_trace(script=self.get_sample_script(),
776                                  cmds_after_breakpoint=['py-bt'])
777        self.assertMultilineMatches(bt,
778                                    r'''^.*
779Traceback \(most recent call first\):
780  <built-in method id of module object .*>
781  File ".*gdb_sample.py", line 10, in baz
782    id\(42\)
783  File ".*gdb_sample.py", line 7, in bar
784    baz\(a, b, c\)
785  File ".*gdb_sample.py", line 4, in foo
786    bar\(a, b, c\)
787  File ".*gdb_sample.py", line 12, in <module>
788    foo\(1, 2, 3\)
789''')
790
791    @unittest.skipIf(python_is_optimized(),
792                     "Python was compiled with optimizations")
793    def test_bt_full(self):
794        'Verify that the "py-bt-full" command works'
795        bt = self.get_stack_trace(script=self.get_sample_script(),
796                                  cmds_after_breakpoint=['py-bt-full'])
797        self.assertMultilineMatches(bt,
798                                    r'''^.*
799#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
800    baz\(a, b, c\)
801#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
802    bar\(a, b, c\)
803#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
804    foo\(1, 2, 3\)
805''')
806
807    def test_threads(self):
808        'Verify that "py-bt" indicates threads that are waiting for the GIL'
809        cmd = '''
810from threading import Thread
811
812class TestThread(Thread):
813    # These threads would run forever, but we'll interrupt things with the
814    # debugger
815    def run(self):
816        i = 0
817        while 1:
818             i += 1
819
820t = {}
821for i in range(4):
822   t[i] = TestThread()
823   t[i].start()
824
825# Trigger a breakpoint on the main thread
826id(42)
827
828'''
829        # Verify with "py-bt":
830        gdb_output = self.get_stack_trace(cmd,
831                                          cmds_after_breakpoint=['thread apply all py-bt'])
832        self.assertIn('Waiting for the GIL', gdb_output)
833
834        # Verify with "py-bt-full":
835        gdb_output = self.get_stack_trace(cmd,
836                                          cmds_after_breakpoint=['thread apply all py-bt-full'])
837        self.assertIn('Waiting for the GIL', gdb_output)
838
839    @unittest.skipIf(python_is_optimized(),
840                     "Python was compiled with optimizations")
841    # Some older versions of gdb will fail with
842    #  "Cannot find new threads: generic error"
843    # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
844    def test_gc(self):
845        'Verify that "py-bt" indicates if a thread is garbage-collecting'
846        cmd = ('from gc import collect\n'
847               'id(42)\n'
848               'def foo():\n'
849               '    collect()\n'
850               'def bar():\n'
851               '    foo()\n'
852               'bar()\n')
853        # Verify with "py-bt":
854        gdb_output = self.get_stack_trace(cmd,
855                                          cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
856                                          )
857        self.assertIn('Garbage-collecting', gdb_output)
858
859        # Verify with "py-bt-full":
860        gdb_output = self.get_stack_trace(cmd,
861                                          cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
862                                          )
863        self.assertIn('Garbage-collecting', gdb_output)
864
865    @unittest.skipIf(python_is_optimized(),
866                     "Python was compiled with optimizations")
867    # Some older versions of gdb will fail with
868    #  "Cannot find new threads: generic error"
869    # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
870    def test_pycfunction(self):
871        'Verify that "py-bt" displays invocations of PyCFunction instances'
872        # Various optimizations multiply the code paths by which these are
873        # called, so test a variety of calling conventions.
874        for py_name, py_args, c_name, expected_frame_number in (
875            ('gmtime', '', 'time_gmtime', 1),  # METH_VARARGS
876            ('len', '[]', 'builtin_len', 1),  # METH_O
877            ('locals', '', 'builtin_locals', 1),  # METH_NOARGS
878            ('iter', '[]', 'builtin_iter', 1),  # METH_FASTCALL
879            ('sorted', '[]', 'builtin_sorted', 1),  # METH_FASTCALL|METH_KEYWORDS
880        ):
881            with self.subTest(c_name):
882                cmd = ('from time import gmtime\n'  # (not always needed)
883                    'def foo():\n'
884                    f'    {py_name}({py_args})\n'
885                    'def bar():\n'
886                    '    foo()\n'
887                    'bar()\n')
888                # Verify with "py-bt":
889                gdb_output = self.get_stack_trace(
890                    cmd,
891                    breakpoint=c_name,
892                    cmds_after_breakpoint=['bt', 'py-bt'],
893                )
894                self.assertIn(f'<built-in method {py_name}', gdb_output)
895
896                # Verify with "py-bt-full":
897                gdb_output = self.get_stack_trace(
898                    cmd,
899                    breakpoint=c_name,
900                    cmds_after_breakpoint=['py-bt-full'],
901                )
902                self.assertIn(
903                    f'#{expected_frame_number} <built-in method {py_name}',
904                    gdb_output,
905                )
906
907    @unittest.skipIf(python_is_optimized(),
908                     "Python was compiled with optimizations")
909    def test_wrapper_call(self):
910        cmd = textwrap.dedent('''
911            class MyList(list):
912                def __init__(self):
913                    super().__init__()   # wrapper_call()
914
915            id("first break point")
916            l = MyList()
917        ''')
918        cmds_after_breakpoint = ['break wrapper_call', 'continue']
919        if CET_PROTECTION:
920            # bpo-32962: same case as in get_stack_trace():
921            # we need an additional 'next' command in order to read
922            # arguments of the innermost function of the call stack.
923            cmds_after_breakpoint.append('next')
924        cmds_after_breakpoint.append('py-bt')
925
926        # Verify with "py-bt":
927        gdb_output = self.get_stack_trace(cmd,
928                                          cmds_after_breakpoint=cmds_after_breakpoint)
929        self.assertRegex(gdb_output,
930                         r"<method-wrapper u?'__init__' of MyList object at ")
931
932
933class PyPrintTests(DebuggerTests):
934    @unittest.skipIf(python_is_optimized(),
935                     "Python was compiled with optimizations")
936    def test_basic_command(self):
937        'Verify that the "py-print" command works'
938        bt = self.get_stack_trace(script=self.get_sample_script(),
939                                  cmds_after_breakpoint=['py-up', 'py-print args'])
940        self.assertMultilineMatches(bt,
941                                    r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
942
943    @unittest.skipIf(python_is_optimized(),
944                     "Python was compiled with optimizations")
945    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
946    def test_print_after_up(self):
947        bt = self.get_stack_trace(script=self.get_sample_script(),
948                                  cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
949        self.assertMultilineMatches(bt,
950                                    r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
951
952    @unittest.skipIf(python_is_optimized(),
953                     "Python was compiled with optimizations")
954    def test_printing_global(self):
955        bt = self.get_stack_trace(script=self.get_sample_script(),
956                                  cmds_after_breakpoint=['py-up', 'py-print __name__'])
957        self.assertMultilineMatches(bt,
958                                    r".*\nglobal '__name__' = '__main__'\n.*")
959
960    @unittest.skipIf(python_is_optimized(),
961                     "Python was compiled with optimizations")
962    def test_printing_builtin(self):
963        bt = self.get_stack_trace(script=self.get_sample_script(),
964                                  cmds_after_breakpoint=['py-up', 'py-print len'])
965        self.assertMultilineMatches(bt,
966                                    r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
967
968class PyLocalsTests(DebuggerTests):
969    @unittest.skipIf(python_is_optimized(),
970                     "Python was compiled with optimizations")
971    def test_basic_command(self):
972        bt = self.get_stack_trace(script=self.get_sample_script(),
973                                  cmds_after_breakpoint=['py-up', 'py-locals'])
974        self.assertMultilineMatches(bt,
975                                    r".*\nargs = \(1, 2, 3\)\n.*")
976
977    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
978    @unittest.skipIf(python_is_optimized(),
979                     "Python was compiled with optimizations")
980    def test_locals_after_up(self):
981        bt = self.get_stack_trace(script=self.get_sample_script(),
982                                  cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
983        self.assertMultilineMatches(bt,
984                                    r".*\na = 1\nb = 2\nc = 3\n.*")
985
986def test_main():
987    if support.verbose:
988        print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
989        for line in gdb_version.splitlines():
990            print(" " * 4 + line)
991    run_unittest(PrettyPrintTests,
992                 PyListTests,
993                 StackNavigationTests,
994                 PyBtTests,
995                 PyPrintTests,
996                 PyLocalsTests
997                 )
998
999if __name__ == "__main__":
1000    test_main()
1001