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