blob: 9cfe3e4ec4bcf0531bf72257e7b35f300a46b970 [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)
Benjamin Peterson0636a4b2014-11-23 22:02:47 -060028if sys.platform == "solaris":
29 raise unittest.SkipTest("test doesn't work very well on Solaris")
30
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000031
R David Murray3e66f0d2012-10-27 13:47:49 -040032# Location of custom hooks file in a repository checkout.
33checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
34 'python-gdb.py')
35
36def run_gdb(*args, **env_vars):
Victor Stinner8bd34152014-08-16 14:31:02 +020037 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040038
39 Returns its (stdout, stderr)
40 """
41 if env_vars:
42 env = os.environ.copy()
43 env.update(env_vars)
44 else:
45 env = None
Victor Stinner8bd34152014-08-16 14:31:02 +020046 # -nx: Do not execute commands from any .gdbinit initialization files
47 # (issue #22188)
48 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040049 if (gdb_major_version, gdb_minor_version) >= (7, 4):
50 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
51 out, err = subprocess.Popen(base_cmd + args,
52 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
53 ).communicate()
54 return out, err
55
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000056# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010057gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040058if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000059 raise unittest.SkipTest("gdb not built with embedded python support")
60
Nick Coghlan254a3772013-09-22 19:36:09 +100061# Verify that "gdb" can load our custom hooks, as OS security settings may
62# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040063cmd = ['--args', sys.executable]
64_, gdbpy_errors = run_gdb('--args', sys.executable)
65if "auto-loading has been declined" in gdbpy_errors:
66 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100067 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100068
Victor Stinner99cff3f2011-12-19 13:59:58 +010069def python_is_optimized():
70 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
71 final_opt = ""
72 for opt in cflags.split():
73 if opt.startswith('-O'):
74 final_opt = opt
75 return (final_opt and final_opt != '-O0')
76
Victor Stinnera92e81b2010-04-20 22:28:31 +000077def gdb_has_frame_select():
78 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -040079 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +000080 m = re.match(r'.*\[(.*)\].*', stdout)
81 if not m:
82 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
83 gdb_frame_dir = m.group(1).split(', ')
84 return "'select'" in gdb_frame_dir
85
86HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000087
88class DebuggerTests(unittest.TestCase):
89
90 """Test that the debugger can debug Python."""
91
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000092 def get_stack_trace(self, source=None, script=None,
93 breakpoint='PyObject_Print',
94 cmds_after_breakpoint=None,
95 import_site=False):
96 '''
97 Run 'python -c SOURCE' under gdb with a breakpoint.
98
99 Support injecting commands after the breakpoint is reached
100
101 Returns the stdout from gdb
102
103 cmds_after_breakpoint: if provided, a list of strings: gdb commands
104 '''
105 # We use "set breakpoint pending yes" to avoid blocking with a:
106 # Function "foo" not defined.
107 # Make breakpoint pending on future shared library load? (y or [n])
108 # error, which typically happens python is dynamically linked (the
109 # breakpoints of interest are to be found in the shared library)
110 # When this happens, we still get:
111 # Function "PyObject_Print" not defined.
112 # emitted to stderr each time, alas.
113
114 # Initially I had "--eval-command=continue" here, but removed it to
115 # avoid repeated print breakpoints when traversing hierarchical data
116 # structures
117
118 # Generate a list of commands in gdb's language:
119 commands = ['set breakpoint pending yes',
120 'break %s' % breakpoint,
121 'run']
122 if cmds_after_breakpoint:
123 commands += cmds_after_breakpoint
124 else:
125 commands += ['backtrace']
126
127 # print commands
128
129 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200130 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000131 args += ['--eval-command=%s' % cmd for cmd in commands]
132 args += ["--args",
133 sys.executable]
134
135 if not import_site:
136 # -S suppresses the default 'import site'
137 args += ["-S"]
138
139 if source:
140 args += ["-c", source]
141 elif script:
142 args += [script]
143
144 # print args
145 # print ' '.join(args)
146
147 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400148 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000149
Antoine Pitroub996e042013-05-01 00:15:44 +0200150 errlines = err.splitlines()
151 unexpected_errlines = []
152
153 # Ignore some benign messages on stderr.
154 ignore_patterns = (
155 'Function "%s" not defined.' % breakpoint,
156 "warning: no loadable sections found in added symbol-file"
157 " system-supplied DSO",
158 "warning: Unable to find libthread_db matching"
159 " inferior's thread library, thread debugging will"
160 " not be available.",
161 "warning: Cannot initialize thread debugging"
162 " library: Debugger service failed",
163 'warning: Could not load shared library symbols for '
164 'linux-vdso.so',
165 'warning: Could not load shared library symbols for '
166 'linux-gate.so',
167 'Do you need "set solib-search-path" or '
168 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100169 'warning: Source file is more recent than executable.',
170 # Issue #19753: missing symbols on System Z
171 'Missing separate debuginfo for ',
172 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200173 )
174 for line in errlines:
175 if not line.startswith(ignore_patterns):
176 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000177
178 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200179 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000180 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'print DATA'" under gdb with a breakpoint on
187 # PyObject_Print and scrape out gdb's representation of the "op"
188 # parameter, and verify that the gdb displays the same string
189 #
190 # For a nested structure, the first time we hit the breakpoint will
191 # give us the top-level structure
192 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
193 cmds_after_breakpoint=cmds_after_breakpoint,
194 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000195 # gdb can insert additional '\n' and space characters in various places
196 # in its output, depending on the width of the terminal it's connected
197 # to (using its "wrap_here" function)
198 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000199 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000200 if not m:
201 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000202 return m.group(1), gdb_output
203
204 def assertEndsWith(self, actual, exp_end):
205 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000206 self.assertTrue(actual.endswith(exp_end),
207 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000208
209 def assertMultilineMatches(self, actual, pattern):
210 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000211 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000212
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000213 def get_sample_script(self):
214 return findfile('gdb_sample.py')
215
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000216class PrettyPrintTests(DebuggerTests):
217 def test_getting_backtrace(self):
218 gdb_output = self.get_stack_trace('print 42')
219 self.assertTrue('PyObject_Print' in gdb_output)
220
221 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
222 # Ensure that gdb's rendering of the value in a debugged process
223 # matches repr(value) in this process:
224 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
225 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100226 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000227
228 def test_int(self):
229 'Verify the pretty-printing of various "int" values'
230 self.assertGdbRepr(42)
231 self.assertGdbRepr(0)
232 self.assertGdbRepr(-7)
233 self.assertGdbRepr(sys.maxint)
234 self.assertGdbRepr(-sys.maxint)
235
236 def test_long(self):
237 'Verify the pretty-printing of various "long" values'
238 self.assertGdbRepr(0L)
239 self.assertGdbRepr(1000000000000L)
240 self.assertGdbRepr(-1L)
241 self.assertGdbRepr(-1000000000000000L)
242
243 def test_singletons(self):
244 'Verify the pretty-printing of True, False and None'
245 self.assertGdbRepr(True)
246 self.assertGdbRepr(False)
247 self.assertGdbRepr(None)
248
249 def test_dicts(self):
250 'Verify the pretty-printing of dictionaries'
251 self.assertGdbRepr({})
252 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500253 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000254
255 def test_lists(self):
256 'Verify the pretty-printing of lists'
257 self.assertGdbRepr([])
258 self.assertGdbRepr(range(5))
259
260 def test_strings(self):
261 'Verify the pretty-printing of strings'
262 self.assertGdbRepr('')
263 self.assertGdbRepr('And now for something hopefully the same')
264 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
265 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
266
267 def test_tuples(self):
268 'Verify the pretty-printing of tuples'
269 self.assertGdbRepr(tuple())
270 self.assertGdbRepr((1,))
271 self.assertGdbRepr(('foo', 'bar', 'baz'))
272
273 def test_unicode(self):
274 'Verify the pretty-printing of unicode values'
275 # Test the empty unicode string:
276 self.assertGdbRepr(u'')
277
278 self.assertGdbRepr(u'hello world')
279
280 # Test printing a single character:
281 # U+2620 SKULL AND CROSSBONES
282 self.assertGdbRepr(u'\u2620')
283
284 # Test printing a Japanese unicode string
285 # (I believe this reads "mojibake", using 3 characters from the CJK
286 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
287 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
288
289 # Test a character outside the BMP:
290 # U+1D121 MUSICAL SYMBOL C CLEF
291 # This is:
292 # UTF-8: 0xF0 0x9D 0x84 0xA1
293 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000294 # This will only work on wide-unicode builds:
295 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000296
297 def test_sets(self):
298 'Verify the pretty-printing of sets'
299 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500300 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
301 self.assertTrue(rep.startswith("set(["))
302 self.assertTrue(rep.endswith("])"))
303 self.assertEqual(eval(rep), {'a', 'b'})
304 rep = self.get_gdb_repr("print set([4, 5])")[0]
305 self.assertTrue(rep.startswith("set(["))
306 self.assertTrue(rep.endswith("])"))
307 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000308
309 # Ensure that we handled sets containing the "dummy" key value,
310 # which happens on deletion:
311 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
312s.pop()
313print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000314 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000315
316 def test_frozensets(self):
317 'Verify the pretty-printing of frozensets'
318 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500319 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
320 self.assertTrue(rep.startswith("frozenset(["))
321 self.assertTrue(rep.endswith("])"))
322 self.assertEqual(eval(rep), {'a', 'b'})
323 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
324 self.assertTrue(rep.startswith("frozenset(["))
325 self.assertTrue(rep.endswith("])"))
326 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000327
328 def test_exceptions(self):
329 # Test a RuntimeError
330 gdb_repr, gdb_output = self.get_gdb_repr('''
331try:
332 raise RuntimeError("I am an error")
333except RuntimeError, e:
334 print e
335''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000336 self.assertEqual(gdb_repr,
337 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000338
339
340 # Test division by zero:
341 gdb_repr, gdb_output = self.get_gdb_repr('''
342try:
343 a = 1 / 0
344except ZeroDivisionError, e:
345 print e
346''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000347 self.assertEqual(gdb_repr,
348 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000349
350 def test_classic_class(self):
351 'Verify the pretty-printing of classic class instances'
352 gdb_repr, gdb_output = self.get_gdb_repr('''
353class Foo:
354 pass
355foo = Foo()
356foo.an_int = 42
357print foo''')
358 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
359 self.assertTrue(m,
360 msg='Unexpected classic-class rendering %r' % gdb_repr)
361
362 def test_modern_class(self):
363 'Verify the pretty-printing of new-style class instances'
364 gdb_repr, gdb_output = self.get_gdb_repr('''
365class Foo(object):
366 pass
367foo = Foo()
368foo.an_int = 42
369print foo''')
370 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
371 self.assertTrue(m,
372 msg='Unexpected new-style class rendering %r' % gdb_repr)
373
374 def test_subclassing_list(self):
375 'Verify the pretty-printing of an instance of a list subclass'
376 gdb_repr, gdb_output = self.get_gdb_repr('''
377class Foo(list):
378 pass
379foo = Foo()
380foo += [1, 2, 3]
381foo.an_int = 42
382print foo''')
383 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
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('''
392class Foo(tuple):
393 pass
394foo = Foo((1, 2, 3))
395foo.an_int = 42
396print foo''')
397 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
398 self.assertTrue(m,
399 msg='Unexpected new-style class rendering %r' % gdb_repr)
400
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000401 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000402 '''Run Python under gdb, corrupting variables in the inferior process
403 immediately before taking a backtrace.
404
405 Verify that the variable's representation is the expected failsafe
406 representation'''
407 if corruption:
408 cmds_after_breakpoint=[corruption, 'backtrace']
409 else:
410 cmds_after_breakpoint=['backtrace']
411
412 gdb_repr, gdb_output = \
413 self.get_gdb_repr(source,
414 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000415
416 if expvalue:
417 if gdb_repr == repr(expvalue):
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 if exptype:
423 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
424 else:
425 # Match anything for the type name; 0xDEADBEEF could point to
426 # something arbitrary (see http://bugs.python.org/issue8330)
427 pattern = '<.* at remote 0x[0-9a-f]+>'
428
429 m = re.match(pattern, gdb_repr)
430 if not m:
431 self.fail('Unexpected gdb representation: %r\n%s' % \
432 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000433
434 def test_NULL_ptr(self):
435 'Ensure that a NULL PyObject* is handled gracefully'
436 gdb_repr, gdb_output = (
437 self.get_gdb_repr('print 42',
438 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000439 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000440 )
441
Ezio Melotti2623a372010-11-21 13:34:58 +0000442 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000443
444 def test_NULL_ob_type(self):
445 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
446 self.assertSane('print 42',
447 'set op->ob_type=0')
448
449 def test_corrupt_ob_type(self):
450 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
451 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000452 'set op->ob_type=0xDEADBEEF',
453 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000454
455 def test_corrupt_tp_flags(self):
456 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
457 self.assertSane('print 42',
458 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000459 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000460
461 def test_corrupt_tp_name(self):
462 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
463 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000464 'set op->ob_type->tp_name=0xDEADBEEF',
465 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000466
467 def test_NULL_instance_dict(self):
468 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
469 self.assertSane('''
470class Foo:
471 pass
472foo = Foo()
473foo.an_int = 42
474print foo''',
475 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000476 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000477
478 def test_builtins_help(self):
479 'Ensure that the new-style class _Helper in site.py can be handled'
480 # (this was the issue causing tracebacks in
481 # http://bugs.python.org/issue8032#msg100537 )
482
483 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
484 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
485 self.assertTrue(m,
486 msg='Unexpected rendering %r' % gdb_repr)
487
488 def test_selfreferential_list(self):
489 '''Ensure that a reference loop involving a list doesn't lead proxyval
490 into an infinite loop:'''
491 gdb_repr, gdb_output = \
492 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
493
Ezio Melotti2623a372010-11-21 13:34:58 +0000494 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000495
496 gdb_repr, gdb_output = \
497 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
498
Ezio Melotti2623a372010-11-21 13:34:58 +0000499 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000500
501 def test_selfreferential_dict(self):
502 '''Ensure that a reference loop involving a dict doesn't lead proxyval
503 into an infinite loop:'''
504 gdb_repr, gdb_output = \
505 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
506
Ezio Melotti2623a372010-11-21 13:34:58 +0000507 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000508
509 def test_selfreferential_old_style_instance(self):
510 gdb_repr, gdb_output = \
511 self.get_gdb_repr('''
512class Foo:
513 pass
514foo = Foo()
515foo.an_attr = foo
516print foo''')
517 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
518 gdb_repr),
519 'Unexpected gdb representation: %r\n%s' % \
520 (gdb_repr, gdb_output))
521
522 def test_selfreferential_new_style_instance(self):
523 gdb_repr, gdb_output = \
524 self.get_gdb_repr('''
525class Foo(object):
526 pass
527foo = Foo()
528foo.an_attr = foo
529print foo''')
530 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
531 gdb_repr),
532 'Unexpected gdb representation: %r\n%s' % \
533 (gdb_repr, gdb_output))
534
535 gdb_repr, gdb_output = \
536 self.get_gdb_repr('''
537class Foo(object):
538 pass
539a = Foo()
540b = Foo()
541a.an_attr = b
542b.an_attr = a
543print a''')
544 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
545 gdb_repr),
546 'Unexpected gdb representation: %r\n%s' % \
547 (gdb_repr, gdb_output))
548
549 def test_truncation(self):
550 'Verify that very long output is truncated'
551 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000552 self.assertEqual(gdb_repr,
553 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
554 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
555 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
556 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
557 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
558 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
559 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
560 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
561 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
562 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
563 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
564 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
565 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
566 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
567 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
568 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
569 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
570 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
571 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
572 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
573 "224, 225, 226...(truncated)")
574 self.assertEqual(len(gdb_repr),
575 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000576
577 def test_builtin_function(self):
578 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000579 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000580
581 def test_builtin_method(self):
582 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
583 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
584 gdb_repr),
585 'Unexpected gdb representation: %r\n%s' % \
586 (gdb_repr, gdb_output))
587
588 def test_frames(self):
589 gdb_output = self.get_stack_trace('''
590def foo(a, b, c):
591 pass
592
593foo(3, 4, 5)
594print foo.__code__''',
595 breakpoint='PyObject_Print',
596 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
597 )
R. David Murray0c080092010-04-05 16:28:49 +0000598 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
599 gdb_output,
600 re.DOTALL),
601 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000602
Victor Stinner99cff3f2011-12-19 13:59:58 +0100603@unittest.skipIf(python_is_optimized(),
604 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000605class PyListTests(DebuggerTests):
606 def assertListing(self, expected, actual):
607 self.assertEndsWith(actual, expected)
608
609 def test_basic_command(self):
610 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000611 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000612 cmds_after_breakpoint=['py-list'])
613
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000614 self.assertListing(' 5 \n'
615 ' 6 def bar(a, b, c):\n'
616 ' 7 baz(a, b, c)\n'
617 ' 8 \n'
618 ' 9 def baz(*args):\n'
619 ' >10 print(42)\n'
620 ' 11 \n'
621 ' 12 foo(1, 2, 3)\n',
622 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000623
624 def test_one_abs_arg(self):
625 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000626 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000627 cmds_after_breakpoint=['py-list 9'])
628
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000629 self.assertListing(' 9 def baz(*args):\n'
630 ' >10 print(42)\n'
631 ' 11 \n'
632 ' 12 foo(1, 2, 3)\n',
633 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000634
635 def test_two_abs_args(self):
636 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000637 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000638 cmds_after_breakpoint=['py-list 1,3'])
639
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000640 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
641 ' 2 \n'
642 ' 3 def foo(a, b, c):\n',
643 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000644
645class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000646 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100647 @unittest.skipIf(python_is_optimized(),
648 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000649 def test_pyup_command(self):
650 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000651 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000652 cmds_after_breakpoint=['py-up'])
653 self.assertMultilineMatches(bt,
654 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000655#[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 +0000656 baz\(a, b, c\)
657$''')
658
Victor Stinnera92e81b2010-04-20 22:28:31 +0000659 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000660 def test_down_at_bottom(self):
661 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000662 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000663 cmds_after_breakpoint=['py-down'])
664 self.assertEndsWith(bt,
665 'Unable to find a newer python frame\n')
666
Victor Stinnera92e81b2010-04-20 22:28:31 +0000667 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000668 def test_up_at_top(self):
669 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000670 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000671 cmds_after_breakpoint=['py-up'] * 4)
672 self.assertEndsWith(bt,
673 'Unable to find an older python frame\n')
674
Victor Stinnera92e81b2010-04-20 22:28:31 +0000675 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100676 @unittest.skipIf(python_is_optimized(),
677 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000678 def test_up_then_down(self):
679 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000680 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000681 cmds_after_breakpoint=['py-up', 'py-down'])
682 self.assertMultilineMatches(bt,
683 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000684#[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 +0000685 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000686#[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 +0000687 print\(42\)
688$''')
689
690class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100691 @unittest.skipIf(python_is_optimized(),
692 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000693 def test_basic_command(self):
694 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000695 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000696 cmds_after_breakpoint=['py-bt'])
697 self.assertMultilineMatches(bt,
698 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000699#[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 +0000700 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000701#[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 +0000702 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000703#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100704 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000705''')
706
707class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100708 @unittest.skipIf(python_is_optimized(),
709 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000710 def test_basic_command(self):
711 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000712 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000713 cmds_after_breakpoint=['py-print args'])
714 self.assertMultilineMatches(bt,
715 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
716
Victor Stinnera92e81b2010-04-20 22:28:31 +0000717 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100718 @unittest.skipIf(python_is_optimized(),
719 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000720 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000721 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000722 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
723 self.assertMultilineMatches(bt,
724 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
725
Victor Stinner99cff3f2011-12-19 13:59:58 +0100726 @unittest.skipIf(python_is_optimized(),
727 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000728 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000729 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000730 cmds_after_breakpoint=['py-print __name__'])
731 self.assertMultilineMatches(bt,
732 r".*\nglobal '__name__' = '__main__'\n.*")
733
Victor Stinner99cff3f2011-12-19 13:59:58 +0100734 @unittest.skipIf(python_is_optimized(),
735 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000736 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000737 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000738 cmds_after_breakpoint=['py-print len'])
739 self.assertMultilineMatches(bt,
740 r".*\nbuiltin 'len' = <built-in function len>\n.*")
741
742class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100743 @unittest.skipIf(python_is_optimized(),
744 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000745 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000746 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000747 cmds_after_breakpoint=['py-locals'])
748 self.assertMultilineMatches(bt,
749 r".*\nargs = \(1, 2, 3\)\n.*")
750
Victor Stinnera92e81b2010-04-20 22:28:31 +0000751 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100752 @unittest.skipIf(python_is_optimized(),
753 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000754 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000755 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000756 cmds_after_breakpoint=['py-up', 'py-locals'])
757 self.assertMultilineMatches(bt,
758 r".*\na = 1\nb = 2\nc = 3\n.*")
759
760def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000761 run_unittest(PrettyPrintTests,
762 PyListTests,
763 StackNavigationTests,
764 PyBtTests,
765 PyPrintTests,
766 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000767 )
768
769if __name__ == "__main__":
770 test_main()