blob: 2208eb31d4f484e2b3ef2eeb7ad9ce1626e4483a [file] [log] [blame]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +00001# 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
Antoine Pitrou22db7352010-07-08 18:54:04 +000011import sysconfig
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000012
Martin v. Löwis24f09fd2010-04-17 22:40:40 +000013from test.test_support import run_unittest, findfile
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000014
15try:
Victor Stinner8bd34152014-08-16 14:31:02 +020016 gdb_version, _ = subprocess.Popen(["gdb", "-nx", "--version"],
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000017 stdout=subprocess.PIPE).communicate()
18except OSError:
19 # This is what "no gdb" looks like. There may, however, be other
20 # errors that manifest this way too.
21 raise unittest.SkipTest("Couldn't find gdb on the path")
R David Murray3e66f0d2012-10-27 13:47:49 -040022gdb_version_number = re.search("^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
23gdb_major_version = int(gdb_version_number.group(1))
24gdb_minor_version = int(gdb_version_number.group(2))
25if gdb_major_version < 7:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000026 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
27 " Saw:\n" + gdb_version)
28
R David Murray3e66f0d2012-10-27 13:47:49 -040029# Location of custom hooks file in a repository checkout.
30checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
31 'python-gdb.py')
32
33def run_gdb(*args, **env_vars):
Victor Stinner8bd34152014-08-16 14:31:02 +020034 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040035
36 Returns its (stdout, stderr)
37 """
38 if env_vars:
39 env = os.environ.copy()
40 env.update(env_vars)
41 else:
42 env = None
Victor Stinner8bd34152014-08-16 14:31:02 +020043 # -nx: Do not execute commands from any .gdbinit initialization files
44 # (issue #22188)
45 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040046 if (gdb_major_version, gdb_minor_version) >= (7, 4):
47 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
48 out, err = subprocess.Popen(base_cmd + args,
49 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
50 ).communicate()
51 return out, err
52
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000053# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010054gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040055if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000056 raise unittest.SkipTest("gdb not built with embedded python support")
57
Nick Coghlan254a3772013-09-22 19:36:09 +100058# Verify that "gdb" can load our custom hooks, as OS security settings may
59# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040060cmd = ['--args', sys.executable]
61_, gdbpy_errors = run_gdb('--args', sys.executable)
62if "auto-loading has been declined" in gdbpy_errors:
63 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100064 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100065
Victor Stinner99cff3f2011-12-19 13:59:58 +010066def python_is_optimized():
67 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
68 final_opt = ""
69 for opt in cflags.split():
70 if opt.startswith('-O'):
71 final_opt = opt
72 return (final_opt and final_opt != '-O0')
73
Victor Stinnera92e81b2010-04-20 22:28:31 +000074def gdb_has_frame_select():
75 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -040076 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +000077 m = re.match(r'.*\[(.*)\].*', stdout)
78 if not m:
79 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
80 gdb_frame_dir = m.group(1).split(', ')
81 return "'select'" in gdb_frame_dir
82
83HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000084
85class DebuggerTests(unittest.TestCase):
86
87 """Test that the debugger can debug Python."""
88
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000089 def get_stack_trace(self, source=None, script=None,
90 breakpoint='PyObject_Print',
91 cmds_after_breakpoint=None,
92 import_site=False):
93 '''
94 Run 'python -c SOURCE' under gdb with a breakpoint.
95
96 Support injecting commands after the breakpoint is reached
97
98 Returns the stdout from gdb
99
100 cmds_after_breakpoint: if provided, a list of strings: gdb commands
101 '''
102 # We use "set breakpoint pending yes" to avoid blocking with a:
103 # Function "foo" not defined.
104 # Make breakpoint pending on future shared library load? (y or [n])
105 # error, which typically happens python is dynamically linked (the
106 # breakpoints of interest are to be found in the shared library)
107 # When this happens, we still get:
108 # Function "PyObject_Print" not defined.
109 # emitted to stderr each time, alas.
110
111 # Initially I had "--eval-command=continue" here, but removed it to
112 # avoid repeated print breakpoints when traversing hierarchical data
113 # structures
114
115 # Generate a list of commands in gdb's language:
116 commands = ['set breakpoint pending yes',
117 'break %s' % breakpoint,
118 'run']
119 if cmds_after_breakpoint:
120 commands += cmds_after_breakpoint
121 else:
122 commands += ['backtrace']
123
124 # print commands
125
126 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200127 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000128 args += ['--eval-command=%s' % cmd for cmd in commands]
129 args += ["--args",
130 sys.executable]
131
132 if not import_site:
133 # -S suppresses the default 'import site'
134 args += ["-S"]
135
136 if source:
137 args += ["-c", source]
138 elif script:
139 args += [script]
140
141 # print args
142 # print ' '.join(args)
143
144 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400145 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000146
Antoine Pitroub996e042013-05-01 00:15:44 +0200147 errlines = err.splitlines()
148 unexpected_errlines = []
149
150 # Ignore some benign messages on stderr.
151 ignore_patterns = (
152 'Function "%s" not defined.' % breakpoint,
153 "warning: no loadable sections found in added symbol-file"
154 " system-supplied DSO",
155 "warning: Unable to find libthread_db matching"
156 " inferior's thread library, thread debugging will"
157 " not be available.",
158 "warning: Cannot initialize thread debugging"
159 " library: Debugger service failed",
160 'warning: Could not load shared library symbols for '
161 'linux-vdso.so',
162 'warning: Could not load shared library symbols for '
163 'linux-gate.so',
164 'Do you need "set solib-search-path" or '
165 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100166 'warning: Source file is more recent than executable.',
167 # Issue #19753: missing symbols on System Z
168 'Missing separate debuginfo for ',
169 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200170 )
171 for line in errlines:
172 if not line.startswith(ignore_patterns):
173 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000174
175 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200176 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000177 return out
178
179 def get_gdb_repr(self, source,
180 cmds_after_breakpoint=None,
181 import_site=False):
182 # Given an input python source representation of data,
183 # run "python -c'print DATA'" under gdb with a breakpoint on
184 # PyObject_Print and scrape out gdb's representation of the "op"
185 # parameter, and verify that the gdb displays the same string
186 #
187 # For a nested structure, the first time we hit the breakpoint will
188 # give us the top-level structure
189 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
190 cmds_after_breakpoint=cmds_after_breakpoint,
191 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000192 # gdb can insert additional '\n' and space characters in various places
193 # in its output, depending on the width of the terminal it's connected
194 # to (using its "wrap_here" function)
195 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000196 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000197 if not m:
198 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000199 return m.group(1), gdb_output
200
201 def assertEndsWith(self, actual, exp_end):
202 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000203 self.assertTrue(actual.endswith(exp_end),
204 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000205
206 def assertMultilineMatches(self, actual, pattern):
207 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000208 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000209
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000210 def get_sample_script(self):
211 return findfile('gdb_sample.py')
212
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000213class PrettyPrintTests(DebuggerTests):
214 def test_getting_backtrace(self):
215 gdb_output = self.get_stack_trace('print 42')
216 self.assertTrue('PyObject_Print' in gdb_output)
217
218 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
219 # Ensure that gdb's rendering of the value in a debugged process
220 # matches repr(value) in this process:
221 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
222 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100223 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000224
225 def test_int(self):
226 'Verify the pretty-printing of various "int" values'
227 self.assertGdbRepr(42)
228 self.assertGdbRepr(0)
229 self.assertGdbRepr(-7)
230 self.assertGdbRepr(sys.maxint)
231 self.assertGdbRepr(-sys.maxint)
232
233 def test_long(self):
234 'Verify the pretty-printing of various "long" values'
235 self.assertGdbRepr(0L)
236 self.assertGdbRepr(1000000000000L)
237 self.assertGdbRepr(-1L)
238 self.assertGdbRepr(-1000000000000000L)
239
240 def test_singletons(self):
241 'Verify the pretty-printing of True, False and None'
242 self.assertGdbRepr(True)
243 self.assertGdbRepr(False)
244 self.assertGdbRepr(None)
245
246 def test_dicts(self):
247 'Verify the pretty-printing of dictionaries'
248 self.assertGdbRepr({})
249 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500250 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000251
252 def test_lists(self):
253 'Verify the pretty-printing of lists'
254 self.assertGdbRepr([])
255 self.assertGdbRepr(range(5))
256
257 def test_strings(self):
258 'Verify the pretty-printing of strings'
259 self.assertGdbRepr('')
260 self.assertGdbRepr('And now for something hopefully the same')
261 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
262 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
263
264 def test_tuples(self):
265 'Verify the pretty-printing of tuples'
266 self.assertGdbRepr(tuple())
267 self.assertGdbRepr((1,))
268 self.assertGdbRepr(('foo', 'bar', 'baz'))
269
270 def test_unicode(self):
271 'Verify the pretty-printing of unicode values'
272 # Test the empty unicode string:
273 self.assertGdbRepr(u'')
274
275 self.assertGdbRepr(u'hello world')
276
277 # Test printing a single character:
278 # U+2620 SKULL AND CROSSBONES
279 self.assertGdbRepr(u'\u2620')
280
281 # Test printing a Japanese unicode string
282 # (I believe this reads "mojibake", using 3 characters from the CJK
283 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
284 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
285
286 # Test a character outside the BMP:
287 # U+1D121 MUSICAL SYMBOL C CLEF
288 # This is:
289 # UTF-8: 0xF0 0x9D 0x84 0xA1
290 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000291 # This will only work on wide-unicode builds:
292 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000293
294 def test_sets(self):
295 'Verify the pretty-printing of sets'
296 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500297 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
298 self.assertTrue(rep.startswith("set(["))
299 self.assertTrue(rep.endswith("])"))
300 self.assertEqual(eval(rep), {'a', 'b'})
301 rep = self.get_gdb_repr("print set([4, 5])")[0]
302 self.assertTrue(rep.startswith("set(["))
303 self.assertTrue(rep.endswith("])"))
304 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000305
306 # Ensure that we handled sets containing the "dummy" key value,
307 # which happens on deletion:
308 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
309s.pop()
310print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000311 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000312
313 def test_frozensets(self):
314 'Verify the pretty-printing of frozensets'
315 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500316 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
317 self.assertTrue(rep.startswith("frozenset(["))
318 self.assertTrue(rep.endswith("])"))
319 self.assertEqual(eval(rep), {'a', 'b'})
320 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
321 self.assertTrue(rep.startswith("frozenset(["))
322 self.assertTrue(rep.endswith("])"))
323 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000324
325 def test_exceptions(self):
326 # Test a RuntimeError
327 gdb_repr, gdb_output = self.get_gdb_repr('''
328try:
329 raise RuntimeError("I am an error")
330except RuntimeError, e:
331 print e
332''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000333 self.assertEqual(gdb_repr,
334 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000335
336
337 # Test division by zero:
338 gdb_repr, gdb_output = self.get_gdb_repr('''
339try:
340 a = 1 / 0
341except ZeroDivisionError, e:
342 print e
343''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000344 self.assertEqual(gdb_repr,
345 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000346
347 def test_classic_class(self):
348 'Verify the pretty-printing of classic class instances'
349 gdb_repr, gdb_output = self.get_gdb_repr('''
350class Foo:
351 pass
352foo = Foo()
353foo.an_int = 42
354print foo''')
355 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
356 self.assertTrue(m,
357 msg='Unexpected classic-class rendering %r' % gdb_repr)
358
359 def test_modern_class(self):
360 'Verify the pretty-printing of new-style class instances'
361 gdb_repr, gdb_output = self.get_gdb_repr('''
362class Foo(object):
363 pass
364foo = Foo()
365foo.an_int = 42
366print foo''')
367 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
368 self.assertTrue(m,
369 msg='Unexpected new-style class rendering %r' % gdb_repr)
370
371 def test_subclassing_list(self):
372 'Verify the pretty-printing of an instance of a list subclass'
373 gdb_repr, gdb_output = self.get_gdb_repr('''
374class Foo(list):
375 pass
376foo = Foo()
377foo += [1, 2, 3]
378foo.an_int = 42
379print foo''')
380 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
381 self.assertTrue(m,
382 msg='Unexpected new-style class rendering %r' % gdb_repr)
383
384 def test_subclassing_tuple(self):
385 'Verify the pretty-printing of an instance of a tuple subclass'
386 # This should exercise the negative tp_dictoffset code in the
387 # new-style class support
388 gdb_repr, gdb_output = self.get_gdb_repr('''
389class Foo(tuple):
390 pass
391foo = Foo((1, 2, 3))
392foo.an_int = 42
393print foo''')
394 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
395 self.assertTrue(m,
396 msg='Unexpected new-style class rendering %r' % gdb_repr)
397
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000398 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000399 '''Run Python under gdb, corrupting variables in the inferior process
400 immediately before taking a backtrace.
401
402 Verify that the variable's representation is the expected failsafe
403 representation'''
404 if corruption:
405 cmds_after_breakpoint=[corruption, 'backtrace']
406 else:
407 cmds_after_breakpoint=['backtrace']
408
409 gdb_repr, gdb_output = \
410 self.get_gdb_repr(source,
411 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000412
413 if expvalue:
414 if gdb_repr == repr(expvalue):
415 # gdb managed to print the value in spite of the corruption;
416 # this is good (see http://bugs.python.org/issue8330)
417 return
418
419 if exptype:
420 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
421 else:
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))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000430
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('print 42',
435 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000436 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000437 )
438
Ezio Melotti2623a372010-11-21 13:34:58 +0000439 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000440
441 def test_NULL_ob_type(self):
442 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
443 self.assertSane('print 42',
444 'set op->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('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000449 'set op->ob_type=0xDEADBEEF',
450 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000451
452 def test_corrupt_tp_flags(self):
453 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
454 self.assertSane('print 42',
455 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000456 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000457
458 def test_corrupt_tp_name(self):
459 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
460 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000461 'set op->ob_type->tp_name=0xDEADBEEF',
462 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000463
464 def test_NULL_instance_dict(self):
465 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
466 self.assertSane('''
467class Foo:
468 pass
469foo = Foo()
470foo.an_int = 42
471print foo''',
472 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000473 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000474
475 def test_builtins_help(self):
476 'Ensure that the new-style class _Helper in site.py can be handled'
477 # (this was the issue causing tracebacks in
478 # http://bugs.python.org/issue8032#msg100537 )
479
480 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
481 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
482 self.assertTrue(m,
483 msg='Unexpected rendering %r' % gdb_repr)
484
485 def test_selfreferential_list(self):
486 '''Ensure that a reference loop involving a list doesn't lead proxyval
487 into an infinite loop:'''
488 gdb_repr, gdb_output = \
489 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
490
Ezio Melotti2623a372010-11-21 13:34:58 +0000491 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000492
493 gdb_repr, gdb_output = \
494 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
495
Ezio Melotti2623a372010-11-21 13:34:58 +0000496 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000497
498 def test_selfreferential_dict(self):
499 '''Ensure that a reference loop involving a dict doesn't lead proxyval
500 into an infinite loop:'''
501 gdb_repr, gdb_output = \
502 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
503
Ezio Melotti2623a372010-11-21 13:34:58 +0000504 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000505
506 def test_selfreferential_old_style_instance(self):
507 gdb_repr, gdb_output = \
508 self.get_gdb_repr('''
509class Foo:
510 pass
511foo = Foo()
512foo.an_attr = foo
513print 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 def test_selfreferential_new_style_instance(self):
520 gdb_repr, gdb_output = \
521 self.get_gdb_repr('''
522class Foo(object):
523 pass
524foo = Foo()
525foo.an_attr = foo
526print foo''')
527 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
528 gdb_repr),
529 'Unexpected gdb representation: %r\n%s' % \
530 (gdb_repr, gdb_output))
531
532 gdb_repr, gdb_output = \
533 self.get_gdb_repr('''
534class Foo(object):
535 pass
536a = Foo()
537b = Foo()
538a.an_attr = b
539b.an_attr = a
540print a''')
541 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
542 gdb_repr),
543 'Unexpected gdb representation: %r\n%s' % \
544 (gdb_repr, gdb_output))
545
546 def test_truncation(self):
547 'Verify that very long output is truncated'
548 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000549 self.assertEqual(gdb_repr,
550 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
551 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
552 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
553 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
554 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
555 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
556 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
557 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
558 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
559 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
560 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
561 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
562 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
563 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
564 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
565 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
566 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
567 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
568 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
569 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
570 "224, 225, 226...(truncated)")
571 self.assertEqual(len(gdb_repr),
572 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000573
574 def test_builtin_function(self):
575 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000576 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000577
578 def test_builtin_method(self):
579 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
580 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
581 gdb_repr),
582 'Unexpected gdb representation: %r\n%s' % \
583 (gdb_repr, gdb_output))
584
585 def test_frames(self):
586 gdb_output = self.get_stack_trace('''
587def foo(a, b, c):
588 pass
589
590foo(3, 4, 5)
591print foo.__code__''',
592 breakpoint='PyObject_Print',
593 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
594 )
R. David Murray0c080092010-04-05 16:28:49 +0000595 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
596 gdb_output,
597 re.DOTALL),
598 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000599
Victor Stinner99cff3f2011-12-19 13:59:58 +0100600@unittest.skipIf(python_is_optimized(),
601 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000602class PyListTests(DebuggerTests):
603 def assertListing(self, expected, actual):
604 self.assertEndsWith(actual, expected)
605
606 def test_basic_command(self):
607 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000608 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000609 cmds_after_breakpoint=['py-list'])
610
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000611 self.assertListing(' 5 \n'
612 ' 6 def bar(a, b, c):\n'
613 ' 7 baz(a, b, c)\n'
614 ' 8 \n'
615 ' 9 def baz(*args):\n'
616 ' >10 print(42)\n'
617 ' 11 \n'
618 ' 12 foo(1, 2, 3)\n',
619 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000620
621 def test_one_abs_arg(self):
622 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000623 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000624 cmds_after_breakpoint=['py-list 9'])
625
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000626 self.assertListing(' 9 def baz(*args):\n'
627 ' >10 print(42)\n'
628 ' 11 \n'
629 ' 12 foo(1, 2, 3)\n',
630 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000631
632 def test_two_abs_args(self):
633 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000634 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000635 cmds_after_breakpoint=['py-list 1,3'])
636
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000637 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
638 ' 2 \n'
639 ' 3 def foo(a, b, c):\n',
640 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000641
642class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000643 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100644 @unittest.skipIf(python_is_optimized(),
645 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000646 def test_pyup_command(self):
647 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000648 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000649 cmds_after_breakpoint=['py-up'])
650 self.assertMultilineMatches(bt,
651 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000652#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000653 baz\(a, b, c\)
654$''')
655
Victor Stinnera92e81b2010-04-20 22:28:31 +0000656 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000657 def test_down_at_bottom(self):
658 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000659 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000660 cmds_after_breakpoint=['py-down'])
661 self.assertEndsWith(bt,
662 'Unable to find a newer python frame\n')
663
Victor Stinnera92e81b2010-04-20 22:28:31 +0000664 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000665 def test_up_at_top(self):
666 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000667 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000668 cmds_after_breakpoint=['py-up'] * 4)
669 self.assertEndsWith(bt,
670 'Unable to find an older python frame\n')
671
Victor Stinnera92e81b2010-04-20 22:28:31 +0000672 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100673 @unittest.skipIf(python_is_optimized(),
674 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000675 def test_up_then_down(self):
676 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000677 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000678 cmds_after_breakpoint=['py-up', 'py-down'])
679 self.assertMultilineMatches(bt,
680 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000681#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000682 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000683#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000684 print\(42\)
685$''')
686
687class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100688 @unittest.skipIf(python_is_optimized(),
689 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000690 def test_basic_command(self):
691 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000692 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000693 cmds_after_breakpoint=['py-bt'])
694 self.assertMultilineMatches(bt,
695 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000696#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000697 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000698#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000699 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000700#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100701 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000702''')
703
704class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100705 @unittest.skipIf(python_is_optimized(),
706 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000707 def test_basic_command(self):
708 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000709 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000710 cmds_after_breakpoint=['py-print args'])
711 self.assertMultilineMatches(bt,
712 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
713
Victor Stinnera92e81b2010-04-20 22:28:31 +0000714 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100715 @unittest.skipIf(python_is_optimized(),
716 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000717 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000718 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000719 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
720 self.assertMultilineMatches(bt,
721 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
722
Victor Stinner99cff3f2011-12-19 13:59:58 +0100723 @unittest.skipIf(python_is_optimized(),
724 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000725 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000726 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000727 cmds_after_breakpoint=['py-print __name__'])
728 self.assertMultilineMatches(bt,
729 r".*\nglobal '__name__' = '__main__'\n.*")
730
Victor Stinner99cff3f2011-12-19 13:59:58 +0100731 @unittest.skipIf(python_is_optimized(),
732 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000733 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000734 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000735 cmds_after_breakpoint=['py-print len'])
736 self.assertMultilineMatches(bt,
737 r".*\nbuiltin 'len' = <built-in function len>\n.*")
738
739class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100740 @unittest.skipIf(python_is_optimized(),
741 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000742 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000743 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000744 cmds_after_breakpoint=['py-locals'])
745 self.assertMultilineMatches(bt,
746 r".*\nargs = \(1, 2, 3\)\n.*")
747
Victor Stinnera92e81b2010-04-20 22:28:31 +0000748 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100749 @unittest.skipIf(python_is_optimized(),
750 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000751 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000752 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000753 cmds_after_breakpoint=['py-up', 'py-locals'])
754 self.assertMultilineMatches(bt,
755 r".*\na = 1\nb = 2\nc = 3\n.*")
756
757def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000758 run_unittest(PrettyPrintTests,
759 PyListTests,
760 StackNavigationTests,
761 PyBtTests,
762 PyPrintTests,
763 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000764 )
765
766if __name__ == "__main__":
767 test_main()