~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Lib/test/test_gdb.py

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
ImportĀ upstreamĀ versionĀ 3.4~b1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
6
import os
 
7
import re
 
8
import pprint
 
9
import subprocess
 
10
import sys
 
11
import sysconfig
 
12
import unittest
 
13
import locale
 
14
 
 
15
# Is this Python configured to support threads?
 
16
try:
 
17
    import _thread
 
18
except ImportError:
 
19
    _thread = None
 
20
 
 
21
from test import support
 
22
from test.support import run_unittest, findfile, python_is_optimized
 
23
 
 
24
try:
 
25
    gdb_version, _ = subprocess.Popen(["gdb", "--version"],
 
26
                                      stdout=subprocess.PIPE).communicate()
 
27
except OSError:
 
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'))
 
37
 
 
38
if not sysconfig.is_python_build():
 
39
    raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
 
40
 
 
41
# Location of custom hooks file in a repository checkout.
 
42
checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
 
43
                                  'python-gdb.py')
 
44
 
 
45
PYTHONHASHSEED = '123'
 
46
 
 
47
def run_gdb(*args, **env_vars):
 
48
    """Runs gdb in --batch mode with the additional arguments given by *args.
 
49
 
 
50
    Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
 
51
    """
 
52
    if env_vars:
 
53
        env = os.environ.copy()
 
54
        env.update(env_vars)
 
55
    else:
 
56
        env = None
 
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,
 
62
        ).communicate()
 
63
    return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
 
64
 
 
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)")
 
67
if not gdbpy_version:
 
68
    raise unittest.SkipTest("gdb not built with embedded python support")
 
69
 
 
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())
 
77
 
 
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)
 
82
    if not m:
 
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
 
86
 
 
87
HAS_PYUP_PYDOWN = gdb_has_frame_select()
 
88
 
 
89
BREAKPOINT_FN='builtin_id'
 
90
 
 
91
class DebuggerTests(unittest.TestCase):
 
92
 
 
93
    """Test that the debugger can debug Python."""
 
94
 
 
95
    def get_stack_trace(self, source=None, script=None,
 
96
                        breakpoint=BREAKPOINT_FN,
 
97
                        cmds_after_breakpoint=None,
 
98
                        import_site=False):
 
99
        '''
 
100
        Run 'python -c SOURCE' under gdb with a breakpoint.
 
101
 
 
102
        Support injecting commands after the breakpoint is reached
 
103
 
 
104
        Returns the stdout from gdb
 
105
 
 
106
        cmds_after_breakpoint: if provided, a list of strings: gdb commands
 
107
        '''
 
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.
 
116
 
 
117
        # Initially I had "--eval-command=continue" here, but removed it to
 
118
        # avoid repeated print breakpoints when traversing hierarchical data
 
119
        # structures
 
120
 
 
121
        # Generate a list of commands in gdb's language:
 
122
        commands = ['set breakpoint pending yes',
 
123
                    'break %s' % breakpoint,
 
124
                    'run']
 
125
        if cmds_after_breakpoint:
 
126
            commands += cmds_after_breakpoint
 
127
        else:
 
128
            commands += ['backtrace']
 
129
 
 
130
        # print commands
 
131
 
 
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]
 
135
        args += ["--args",
 
136
                 sys.executable]
 
137
 
 
138
        if not import_site:
 
139
            # -S suppresses the default 'import site'
 
140
            args += ["-S"]
 
141
 
 
142
        if source:
 
143
            args += ["-c", source]
 
144
        elif script:
 
145
            args += [script]
 
146
 
 
147
        # print args
 
148
        # print (' '.join(args))
 
149
 
 
150
        # Use "args" to invoke gdb, capturing stdout, stderr:
 
151
        out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
 
152
 
 
153
        errlines = err.splitlines()
 
154
        unexpected_errlines = []
 
155
 
 
156
        # Ignore some benign messages on stderr.
 
157
        ignore_patterns = (
 
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 '
 
167
            'linux-vdso.so',
 
168
            'warning: Could not load shared library symbols for '
 
169
            'linux-gate.so',
 
170
            'Do you need "set solib-search-path" or '
 
171
            '"set sysroot"?',
 
172
            'warning: Source file is more recent than executable.',
 
173
            )
 
174
        for line in errlines:
 
175
            if not line.startswith(ignore_patterns):
 
176
                unexpected_errlines.append(line)
 
177
 
 
178
        # Ensure no unexpected error messages:
 
179
        self.assertEqual(unexpected_errlines, [])
 
180
        return out
 
181
 
 
182
    def get_gdb_repr(self, source,
 
183
                     cmds_after_breakpoint=None,
 
184
                     import_site=False):
 
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
 
189
        #
 
190
        # Verify that the gdb displays the expected string
 
191
        #
 
192
        # For a nested structure, the first time we hit the breakpoint will
 
193
        # give us the top-level structure
 
194
 
 
195
        # NOTE: avoid decoding too much of the traceback as some
 
196
        # undecodable characters may lurk there in optimized mode
 
197
        # (issue #19743).
 
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)
 
207
        if not m:
 
208
            self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
 
209
        return m.group(1), gdb_output
 
210
 
 
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))
 
215
 
 
216
    def assertMultilineMatches(self, actual, pattern):
 
217
        m = re.match(pattern, actual, re.DOTALL)
 
218
        if not m:
 
219
            self.fail(msg='%r did not match %r' % (actual, pattern))
 
220
 
 
221
    def get_sample_script(self):
 
222
        return findfile('gdb_sample.py')
 
223
 
 
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)
 
228
 
 
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) + ')')
 
233
        if not exp_repr:
 
234
            exp_repr = repr(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)))
 
238
 
 
239
    def test_int(self):
 
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)
 
246
 
 
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)
 
252
 
 
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'}")
 
258
 
 
259
    def test_lists(self):
 
260
        'Verify the pretty-printing of lists'
 
261
        self.assertGdbRepr([])
 
262
        self.assertGdbRepr(list(range(5)))
 
263
 
 
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'
 
272
                           )
 
273
 
 
274
        self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
 
275
 
 
276
        self.assertGdbRepr(bytes([b for b in range(255)]))
 
277
 
 
278
    def test_strings(self):
 
279
        'Verify the pretty-printing of unicode strings'
 
280
        encoding = locale.getpreferredencoding()
 
281
        def check_repr(text):
 
282
            try:
 
283
                text.encode(encoding)
 
284
                printable = True
 
285
            except UnicodeEncodeError:
 
286
                self.assertGdbRepr(text, ascii(text))
 
287
            else:
 
288
                self.assertGdbRepr(text)
 
289
 
 
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')
 
293
 
 
294
        # Test printing a single character:
 
295
        #    U+2620 SKULL AND CROSSBONES
 
296
        check_repr('\u2620')
 
297
 
 
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')
 
302
 
 
303
        # Test a character outside the BMP:
 
304
        #    U+1D121 MUSICAL SYMBOL C CLEF
 
305
        # This is:
 
306
        # UTF-8: 0xF0 0x9D 0x84 0xA1
 
307
        # UTF-16: 0xD834 0xDD21
 
308
        check_repr(chr(0x1D121))
 
309
 
 
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'))
 
315
 
 
316
    def test_sets(self):
 
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}")
 
323
 
 
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'])
 
327
s.remove('a')
 
328
id(s)''')
 
329
        self.assertEqual(gdb_repr, "{'b'}")
 
330
 
 
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})")
 
338
 
 
339
    def test_exceptions(self):
 
340
        # Test a RuntimeError
 
341
        gdb_repr, gdb_output = self.get_gdb_repr('''
 
342
try:
 
343
    raise RuntimeError("I am an error")
 
344
except RuntimeError as e:
 
345
    id(e)
 
346
''')
 
347
        self.assertEqual(gdb_repr,
 
348
                         "RuntimeError('I am an error',)")
 
349
 
 
350
 
 
351
        # Test division by zero:
 
352
        gdb_repr, gdb_output = self.get_gdb_repr('''
 
353
try:
 
354
    a = 1 / 0
 
355
except ZeroDivisionError as e:
 
356
    id(e)
 
357
''')
 
358
        self.assertEqual(gdb_repr,
 
359
                         "ZeroDivisionError('division by zero',)")
 
360
 
 
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('''
 
364
class Foo:
 
365
    pass
 
366
foo = Foo()
 
367
foo.an_int = 42
 
368
id(foo)''')
 
369
        m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
 
370
        self.assertTrue(m,
 
371
                        msg='Unexpected new-style class rendering %r' % gdb_repr)
 
372
 
 
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('''
 
376
class Foo(list):
 
377
    pass
 
378
foo = Foo()
 
379
foo += [1, 2, 3]
 
380
foo.an_int = 42
 
381
id(foo)''')
 
382
        m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
 
383
 
 
384
        self.assertTrue(m,
 
385
                        msg='Unexpected new-style class rendering %r' % gdb_repr)
 
386
 
 
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('''
 
392
class Foo(tuple):
 
393
    pass
 
394
foo = Foo((1, 2, 3))
 
395
foo.an_int = 42
 
396
id(foo)''')
 
397
        m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
 
398
 
 
399
        self.assertTrue(m,
 
400
                        msg='Unexpected new-style class rendering %r' % gdb_repr)
 
401
 
 
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.
 
405
 
 
406
        Verify that the variable's representation is the expected failsafe
 
407
        representation'''
 
408
        if corruption:
 
409
            cmds_after_breakpoint=[corruption, 'backtrace']
 
410
        else:
 
411
            cmds_after_breakpoint=['backtrace']
 
412
 
 
413
        gdb_repr, gdb_output = \
 
414
            self.get_gdb_repr(source,
 
415
                              cmds_after_breakpoint=cmds_after_breakpoint)
 
416
        if exprepr:
 
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)
 
420
                return
 
421
 
 
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]+>'
 
425
 
 
426
        m = re.match(pattern, gdb_repr)
 
427
        if not m:
 
428
            self.fail('Unexpected gdb representation: %r\n%s' % \
 
429
                          (gdb_repr, gdb_output))
 
430
 
 
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',
 
436
                                                     'backtrace'])
 
437
            )
 
438
 
 
439
        self.assertEqual(gdb_repr, '0x0')
 
440
 
 
441
    def test_NULL_ob_type(self):
 
442
        'Ensure that a PyObject* with NULL ob_type is handled gracefully'
 
443
        self.assertSane('id(42)',
 
444
                        'set v->ob_type=0')
 
445
 
 
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',
 
450
                        exprepr='42')
 
451
 
 
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',
 
456
                        exprepr='42')
 
457
 
 
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',
 
462
                        exprepr='42')
 
463
 
 
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)
 
469
 
 
470
        m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
 
471
        self.assertTrue(m,
 
472
                        msg='Unexpected rendering %r' % gdb_repr)
 
473
 
 
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, [...]]')
 
480
 
 
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, [[...]]]')
 
484
 
 
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)")
 
490
 
 
491
        self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
 
492
 
 
493
    def test_selfreferential_old_style_instance(self):
 
494
        gdb_repr, gdb_output = \
 
495
            self.get_gdb_repr('''
 
496
class Foo:
 
497
    pass
 
498
foo = Foo()
 
499
foo.an_attr = foo
 
500
id(foo)''')
 
501
        self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
 
502
                                 gdb_repr),
 
503
                        'Unexpected gdb representation: %r\n%s' % \
 
504
                            (gdb_repr, gdb_output))
 
505
 
 
506
    def test_selfreferential_new_style_instance(self):
 
507
        gdb_repr, gdb_output = \
 
508
            self.get_gdb_repr('''
 
509
class Foo(object):
 
510
    pass
 
511
foo = Foo()
 
512
foo.an_attr = foo
 
513
id(foo)''')
 
514
        self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
 
515
                                 gdb_repr),
 
516
                        'Unexpected gdb representation: %r\n%s' % \
 
517
                            (gdb_repr, gdb_output))
 
518
 
 
519
        gdb_repr, gdb_output = \
 
520
            self.get_gdb_repr('''
 
521
class Foo(object):
 
522
    pass
 
523
a = Foo()
 
524
b = Foo()
 
525
a.an_attr = b
 
526
b.an_attr = a
 
527
id(a)''')
 
528
        self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>\) at remote 0x-?[0-9a-f]+>',
 
529
                                 gdb_repr),
 
530
                        'Unexpected gdb representation: %r\n%s' % \
 
531
                            (gdb_repr, gdb_output))
 
532
 
 
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)'))
 
560
 
 
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]+>',
 
564
                                 gdb_repr),
 
565
                        'Unexpected gdb representation: %r\n%s' % \
 
566
                            (gdb_repr, gdb_output))
 
567
 
 
568
    def test_frames(self):
 
569
        gdb_output = self.get_stack_trace('''
 
570
def foo(a, b, c):
 
571
    pass
 
572
 
 
573
foo(3, 4, 5)
 
574
id(foo.__code__)''',
 
575
                                          breakpoint='builtin_id',
 
576
                                          cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
 
577
                                          )
 
578
        self.assertTrue(re.match('.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
 
579
                                 gdb_output,
 
580
                                 re.DOTALL),
 
581
                        'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
 
582
 
 
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)
 
588
 
 
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'])
 
593
 
 
594
        self.assertListing('   5    \n'
 
595
                           '   6    def bar(a, b, c):\n'
 
596
                           '   7        baz(a, b, c)\n'
 
597
                           '   8    \n'
 
598
                           '   9    def baz(*args):\n'
 
599
                           ' >10        id(42)\n'
 
600
                           '  11    \n'
 
601
                           '  12    foo(1, 2, 3)\n',
 
602
                           bt)
 
603
 
 
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'])
 
608
 
 
609
        self.assertListing('   9    def baz(*args):\n'
 
610
                           ' >10        id(42)\n'
 
611
                           '  11    \n'
 
612
                           '  12    foo(1, 2, 3)\n',
 
613
                           bt)
 
614
 
 
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'])
 
619
 
 
620
        self.assertListing('   1    # Sample script for use by test_gdb.py\n'
 
621
                           '   2    \n'
 
622
                           '   3    def foo(a, b, c):\n',
 
623
                           bt)
 
624
 
 
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,
 
634
                                    r'''^.*
 
635
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
 
636
    baz\(a, b, c\)
 
637
$''')
 
638
 
 
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')
 
646
 
 
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')
 
654
 
 
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,
 
663
                                    r'''^.*
 
664
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
 
665
    baz\(a, b, c\)
 
666
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
 
667
    id\(42\)
 
668
$''')
 
669
 
 
670
class PyBtTests(DebuggerTests):
 
671
    @unittest.skipIf(python_is_optimized(),
 
672
                     "Python was compiled with optimizations")
 
673
    def test_bt(self):
 
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,
 
678
                                    r'''^.*
 
679
Traceback \(most recent call first\):
 
680
  File ".*gdb_sample.py", line 10, in baz
 
681
    id\(42\)
 
682
  File ".*gdb_sample.py", line 7, in bar
 
683
    baz\(a, b, c\)
 
684
  File ".*gdb_sample.py", line 4, in foo
 
685
    bar\(a, b, c\)
 
686
  File ".*gdb_sample.py", line 12, in <module>
 
687
    foo\(1, 2, 3\)
 
688
''')
 
689
 
 
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,
 
697
                                    r'''^.*
 
698
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
 
699
    baz\(a, b, c\)
 
700
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
 
701
    bar\(a, b, c\)
 
702
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
 
703
    foo\(1, 2, 3\)
 
704
''')
 
705
 
 
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'
 
710
        cmd = '''
 
711
from threading import Thread
 
712
 
 
713
class TestThread(Thread):
 
714
    # These threads would run forever, but we'll interrupt things with the
 
715
    # debugger
 
716
    def run(self):
 
717
        i = 0
 
718
        while 1:
 
719
             i += 1
 
720
 
 
721
t = {}
 
722
for i in range(4):
 
723
   t[i] = TestThread()
 
724
   t[i].start()
 
725
 
 
726
# Trigger a breakpoint on the main thread
 
727
id(42)
 
728
 
 
729
'''
 
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)
 
734
 
 
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)
 
739
 
 
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")
 
747
    def test_gc(self):
 
748
        'Verify that "py-bt" indicates if a thread is garbage-collecting'
 
749
        cmd = ('from gc import collect\n'
 
750
               'id(42)\n'
 
751
               'def foo():\n'
 
752
               '    collect()\n'
 
753
               'def bar():\n'
 
754
               '    foo()\n'
 
755
               'bar()\n')
 
756
        # Verify with "py-bt":
 
757
        gdb_output = self.get_stack_trace(cmd,
 
758
                                          cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
 
759
                                          )
 
760
        self.assertIn('Garbage-collecting', gdb_output)
 
761
 
 
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'],
 
765
                                          )
 
766
        self.assertIn('Garbage-collecting', gdb_output)
 
767
 
 
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'
 
778
               'def foo():\n'
 
779
               '    sleep(1)\n'
 
780
               'def bar():\n'
 
781
               '    foo()\n'
 
782
               'bar()\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'],
 
787
                                          )
 
788
        self.assertIn('<built-in method sleep', gdb_output)
 
789
 
 
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'],
 
794
                                          )
 
795
        self.assertIn('#0 <built-in method sleep', gdb_output)
 
796
 
 
797
 
 
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.*")
 
807
 
 
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.*")
 
816
 
 
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.*")
 
824
 
 
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.*")
 
832
 
 
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.*")
 
841
 
 
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.*")
 
850
 
 
851
def test_main():
 
852
    if support.verbose:
 
853
        print("GDB version:")
 
854
        for line in os.fsdecode(gdb_version).splitlines():
 
855
            print(" " * 4 + line)
 
856
    run_unittest(PrettyPrintTests,
 
857
                 PyListTests,
 
858
                 StackNavigationTests,
 
859
                 PyBtTests,
 
860
                 PyPrintTests,
 
861
                 PyLocalsTests
 
862
                 )
 
863
 
 
864
if __name__ == "__main__":
 
865
    test_main()