blob: 0da1c02aa34aee01aeec04e507fc3bffaa6d7135 [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 Peterson51f461f2014-11-23 22:34:04 -060028if sys.platform.startswith("sunos"):
Benjamin Peterson0636a4b2014-11-23 22:02:47 -060029 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,
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200121
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200122 # The tests assume that the first frame of printed
123 # backtrace will not contain program counter,
124 # that is however not guaranteed by gdb
125 # therefore we need to use 'set print address off' to
126 # make sure the counter is not there. For example:
127 # #0 in PyObject_Print ...
128 # is assumed, but sometimes this can be e.g.
129 # #0 0x00003fffb7dd1798 in PyObject_Print ...
130 'set print address off',
131
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000132 'run']
Serhiy Storchakadd8430f2015-02-06 08:36:14 +0200133
134 # GDB as of 7.4 onwards can distinguish between the
135 # value of a variable at entry vs current value:
136 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
137 # which leads to the selftests failing with errors like this:
138 # AssertionError: 'v@entry=()' != '()'
139 # Disable this:
140 if (gdb_major_version, gdb_minor_version) >= (7, 4):
141 commands += ['set print entry-values no']
142
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000143 if cmds_after_breakpoint:
144 commands += cmds_after_breakpoint
145 else:
146 commands += ['backtrace']
147
148 # print commands
149
150 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200151 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000152 args += ['--eval-command=%s' % cmd for cmd in commands]
153 args += ["--args",
154 sys.executable]
155
156 if not import_site:
157 # -S suppresses the default 'import site'
158 args += ["-S"]
159
160 if source:
161 args += ["-c", source]
162 elif script:
163 args += [script]
164
165 # print args
166 # print ' '.join(args)
167
168 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400169 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000170
Antoine Pitroub996e042013-05-01 00:15:44 +0200171 errlines = err.splitlines()
172 unexpected_errlines = []
173
174 # Ignore some benign messages on stderr.
175 ignore_patterns = (
176 'Function "%s" not defined.' % breakpoint,
177 "warning: no loadable sections found in added symbol-file"
178 " system-supplied DSO",
179 "warning: Unable to find libthread_db matching"
180 " inferior's thread library, thread debugging will"
181 " not be available.",
182 "warning: Cannot initialize thread debugging"
183 " library: Debugger service failed",
184 'warning: Could not load shared library symbols for '
185 'linux-vdso.so',
186 'warning: Could not load shared library symbols for '
187 'linux-gate.so',
188 'Do you need "set solib-search-path" or '
189 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100190 'warning: Source file is more recent than executable.',
191 # Issue #19753: missing symbols on System Z
192 'Missing separate debuginfo for ',
193 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200194 )
195 for line in errlines:
196 if not line.startswith(ignore_patterns):
197 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000198
199 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200200 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000201 return out
202
203 def get_gdb_repr(self, source,
204 cmds_after_breakpoint=None,
205 import_site=False):
206 # Given an input python source representation of data,
207 # run "python -c'print DATA'" under gdb with a breakpoint on
208 # PyObject_Print and scrape out gdb's representation of the "op"
209 # parameter, and verify that the gdb displays the same string
210 #
211 # For a nested structure, the first time we hit the breakpoint will
212 # give us the top-level structure
213 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
214 cmds_after_breakpoint=cmds_after_breakpoint,
215 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000216 # gdb can insert additional '\n' and space characters in various places
217 # in its output, depending on the width of the terminal it's connected
218 # to (using its "wrap_here" function)
219 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000220 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000221 if not m:
222 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000223 return m.group(1), gdb_output
224
225 def assertEndsWith(self, actual, exp_end):
226 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000227 self.assertTrue(actual.endswith(exp_end),
228 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000229
230 def assertMultilineMatches(self, actual, pattern):
231 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000232 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000233
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000234 def get_sample_script(self):
235 return findfile('gdb_sample.py')
236
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000237class PrettyPrintTests(DebuggerTests):
238 def test_getting_backtrace(self):
239 gdb_output = self.get_stack_trace('print 42')
240 self.assertTrue('PyObject_Print' in gdb_output)
241
242 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
243 # Ensure that gdb's rendering of the value in a debugged process
244 # matches repr(value) in this process:
245 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
246 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100247 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000248
249 def test_int(self):
250 'Verify the pretty-printing of various "int" values'
251 self.assertGdbRepr(42)
252 self.assertGdbRepr(0)
253 self.assertGdbRepr(-7)
254 self.assertGdbRepr(sys.maxint)
255 self.assertGdbRepr(-sys.maxint)
256
257 def test_long(self):
258 'Verify the pretty-printing of various "long" values'
259 self.assertGdbRepr(0L)
260 self.assertGdbRepr(1000000000000L)
261 self.assertGdbRepr(-1L)
262 self.assertGdbRepr(-1000000000000000L)
263
264 def test_singletons(self):
265 'Verify the pretty-printing of True, False and None'
266 self.assertGdbRepr(True)
267 self.assertGdbRepr(False)
268 self.assertGdbRepr(None)
269
270 def test_dicts(self):
271 'Verify the pretty-printing of dictionaries'
272 self.assertGdbRepr({})
273 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500274 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000275
276 def test_lists(self):
277 'Verify the pretty-printing of lists'
278 self.assertGdbRepr([])
279 self.assertGdbRepr(range(5))
280
281 def test_strings(self):
282 'Verify the pretty-printing of strings'
283 self.assertGdbRepr('')
284 self.assertGdbRepr('And now for something hopefully the same')
285 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
286 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
287
288 def test_tuples(self):
289 'Verify the pretty-printing of tuples'
290 self.assertGdbRepr(tuple())
291 self.assertGdbRepr((1,))
292 self.assertGdbRepr(('foo', 'bar', 'baz'))
293
294 def test_unicode(self):
295 'Verify the pretty-printing of unicode values'
296 # Test the empty unicode string:
297 self.assertGdbRepr(u'')
298
299 self.assertGdbRepr(u'hello world')
300
301 # Test printing a single character:
302 # U+2620 SKULL AND CROSSBONES
303 self.assertGdbRepr(u'\u2620')
304
305 # Test printing a Japanese unicode string
306 # (I believe this reads "mojibake", using 3 characters from the CJK
307 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
308 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
309
310 # Test a character outside the BMP:
311 # U+1D121 MUSICAL SYMBOL C CLEF
312 # This is:
313 # UTF-8: 0xF0 0x9D 0x84 0xA1
314 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000315 # This will only work on wide-unicode builds:
316 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000317
318 def test_sets(self):
319 'Verify the pretty-printing of sets'
320 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500321 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
322 self.assertTrue(rep.startswith("set(["))
323 self.assertTrue(rep.endswith("])"))
324 self.assertEqual(eval(rep), {'a', 'b'})
325 rep = self.get_gdb_repr("print set([4, 5])")[0]
326 self.assertTrue(rep.startswith("set(["))
327 self.assertTrue(rep.endswith("])"))
328 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000329
330 # Ensure that we handled sets containing the "dummy" key value,
331 # which happens on deletion:
332 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
333s.pop()
334print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000335 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000336
337 def test_frozensets(self):
338 'Verify the pretty-printing of frozensets'
339 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500340 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
341 self.assertTrue(rep.startswith("frozenset(["))
342 self.assertTrue(rep.endswith("])"))
343 self.assertEqual(eval(rep), {'a', 'b'})
344 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
345 self.assertTrue(rep.startswith("frozenset(["))
346 self.assertTrue(rep.endswith("])"))
347 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000348
349 def test_exceptions(self):
350 # Test a RuntimeError
351 gdb_repr, gdb_output = self.get_gdb_repr('''
352try:
353 raise RuntimeError("I am an error")
354except RuntimeError, e:
355 print e
356''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000357 self.assertEqual(gdb_repr,
358 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000359
360
361 # Test division by zero:
362 gdb_repr, gdb_output = self.get_gdb_repr('''
363try:
364 a = 1 / 0
365except ZeroDivisionError, e:
366 print e
367''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000368 self.assertEqual(gdb_repr,
369 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000370
371 def test_classic_class(self):
372 'Verify the pretty-printing of classic class instances'
373 gdb_repr, gdb_output = self.get_gdb_repr('''
374class Foo:
375 pass
376foo = Foo()
377foo.an_int = 42
378print foo''')
379 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
380 self.assertTrue(m,
381 msg='Unexpected classic-class rendering %r' % gdb_repr)
382
383 def test_modern_class(self):
384 'Verify the pretty-printing of new-style class instances'
385 gdb_repr, gdb_output = self.get_gdb_repr('''
386class Foo(object):
387 pass
388foo = Foo()
389foo.an_int = 42
390print foo''')
391 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
392 self.assertTrue(m,
393 msg='Unexpected new-style class rendering %r' % gdb_repr)
394
395 def test_subclassing_list(self):
396 'Verify the pretty-printing of an instance of a list subclass'
397 gdb_repr, gdb_output = self.get_gdb_repr('''
398class Foo(list):
399 pass
400foo = Foo()
401foo += [1, 2, 3]
402foo.an_int = 42
403print foo''')
404 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
405 self.assertTrue(m,
406 msg='Unexpected new-style class rendering %r' % gdb_repr)
407
408 def test_subclassing_tuple(self):
409 'Verify the pretty-printing of an instance of a tuple subclass'
410 # This should exercise the negative tp_dictoffset code in the
411 # new-style class support
412 gdb_repr, gdb_output = self.get_gdb_repr('''
413class Foo(tuple):
414 pass
415foo = Foo((1, 2, 3))
416foo.an_int = 42
417print foo''')
418 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
419 self.assertTrue(m,
420 msg='Unexpected new-style class rendering %r' % gdb_repr)
421
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000422 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000423 '''Run Python under gdb, corrupting variables in the inferior process
424 immediately before taking a backtrace.
425
426 Verify that the variable's representation is the expected failsafe
427 representation'''
428 if corruption:
429 cmds_after_breakpoint=[corruption, 'backtrace']
430 else:
431 cmds_after_breakpoint=['backtrace']
432
433 gdb_repr, gdb_output = \
434 self.get_gdb_repr(source,
435 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000436
437 if expvalue:
438 if gdb_repr == repr(expvalue):
439 # gdb managed to print the value in spite of the corruption;
440 # this is good (see http://bugs.python.org/issue8330)
441 return
442
443 if exptype:
444 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
445 else:
446 # Match anything for the type name; 0xDEADBEEF could point to
447 # something arbitrary (see http://bugs.python.org/issue8330)
448 pattern = '<.* at remote 0x[0-9a-f]+>'
449
450 m = re.match(pattern, gdb_repr)
451 if not m:
452 self.fail('Unexpected gdb representation: %r\n%s' % \
453 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000454
455 def test_NULL_ptr(self):
456 'Ensure that a NULL PyObject* is handled gracefully'
457 gdb_repr, gdb_output = (
458 self.get_gdb_repr('print 42',
459 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000460 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000461 )
462
Ezio Melotti2623a372010-11-21 13:34:58 +0000463 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000464
465 def test_NULL_ob_type(self):
466 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
467 self.assertSane('print 42',
468 'set op->ob_type=0')
469
470 def test_corrupt_ob_type(self):
471 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
472 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000473 'set op->ob_type=0xDEADBEEF',
474 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000475
476 def test_corrupt_tp_flags(self):
477 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
478 self.assertSane('print 42',
479 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000480 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000481
482 def test_corrupt_tp_name(self):
483 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
484 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000485 'set op->ob_type->tp_name=0xDEADBEEF',
486 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000487
488 def test_NULL_instance_dict(self):
489 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
490 self.assertSane('''
491class Foo:
492 pass
493foo = Foo()
494foo.an_int = 42
495print foo''',
496 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000497 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000498
499 def test_builtins_help(self):
500 'Ensure that the new-style class _Helper in site.py can be handled'
501 # (this was the issue causing tracebacks in
502 # http://bugs.python.org/issue8032#msg100537 )
503
504 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
505 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
506 self.assertTrue(m,
507 msg='Unexpected rendering %r' % gdb_repr)
508
509 def test_selfreferential_list(self):
510 '''Ensure that a reference loop involving a list doesn't lead proxyval
511 into an infinite loop:'''
512 gdb_repr, gdb_output = \
513 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
514
Ezio Melotti2623a372010-11-21 13:34:58 +0000515 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000516
517 gdb_repr, gdb_output = \
518 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
519
Ezio Melotti2623a372010-11-21 13:34:58 +0000520 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000521
522 def test_selfreferential_dict(self):
523 '''Ensure that a reference loop involving a dict doesn't lead proxyval
524 into an infinite loop:'''
525 gdb_repr, gdb_output = \
526 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
527
Ezio Melotti2623a372010-11-21 13:34:58 +0000528 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000529
530 def test_selfreferential_old_style_instance(self):
531 gdb_repr, gdb_output = \
532 self.get_gdb_repr('''
533class Foo:
534 pass
535foo = Foo()
536foo.an_attr = foo
537print foo''')
538 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
539 gdb_repr),
540 'Unexpected gdb representation: %r\n%s' % \
541 (gdb_repr, gdb_output))
542
543 def test_selfreferential_new_style_instance(self):
544 gdb_repr, gdb_output = \
545 self.get_gdb_repr('''
546class Foo(object):
547 pass
548foo = Foo()
549foo.an_attr = foo
550print foo''')
551 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
552 gdb_repr),
553 'Unexpected gdb representation: %r\n%s' % \
554 (gdb_repr, gdb_output))
555
556 gdb_repr, gdb_output = \
557 self.get_gdb_repr('''
558class Foo(object):
559 pass
560a = Foo()
561b = Foo()
562a.an_attr = b
563b.an_attr = a
564print a''')
565 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
566 gdb_repr),
567 'Unexpected gdb representation: %r\n%s' % \
568 (gdb_repr, gdb_output))
569
570 def test_truncation(self):
571 'Verify that very long output is truncated'
572 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000573 self.assertEqual(gdb_repr,
574 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
575 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
576 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
577 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
578 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
579 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
580 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
581 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
582 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
583 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
584 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
585 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
586 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
587 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
588 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
589 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
590 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
591 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
592 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
593 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
594 "224, 225, 226...(truncated)")
595 self.assertEqual(len(gdb_repr),
596 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000597
598 def test_builtin_function(self):
599 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000600 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000601
602 def test_builtin_method(self):
603 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
604 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
605 gdb_repr),
606 'Unexpected gdb representation: %r\n%s' % \
607 (gdb_repr, gdb_output))
608
609 def test_frames(self):
610 gdb_output = self.get_stack_trace('''
611def foo(a, b, c):
612 pass
613
614foo(3, 4, 5)
615print foo.__code__''',
616 breakpoint='PyObject_Print',
617 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
618 )
R. David Murray0c080092010-04-05 16:28:49 +0000619 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
620 gdb_output,
621 re.DOTALL),
622 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000623
Victor Stinner99cff3f2011-12-19 13:59:58 +0100624@unittest.skipIf(python_is_optimized(),
625 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000626class PyListTests(DebuggerTests):
627 def assertListing(self, expected, actual):
628 self.assertEndsWith(actual, expected)
629
630 def test_basic_command(self):
631 'Verify that the "py-list" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000632 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000633 cmds_after_breakpoint=['py-list'])
634
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000635 self.assertListing(' 5 \n'
636 ' 6 def bar(a, b, c):\n'
637 ' 7 baz(a, b, c)\n'
638 ' 8 \n'
639 ' 9 def baz(*args):\n'
640 ' >10 print(42)\n'
641 ' 11 \n'
642 ' 12 foo(1, 2, 3)\n',
643 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000644
645 def test_one_abs_arg(self):
646 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000647 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000648 cmds_after_breakpoint=['py-list 9'])
649
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000650 self.assertListing(' 9 def baz(*args):\n'
651 ' >10 print(42)\n'
652 ' 11 \n'
653 ' 12 foo(1, 2, 3)\n',
654 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000655
656 def test_two_abs_args(self):
657 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000658 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000659 cmds_after_breakpoint=['py-list 1,3'])
660
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000661 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
662 ' 2 \n'
663 ' 3 def foo(a, b, c):\n',
664 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000665
666class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000667 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100668 @unittest.skipIf(python_is_optimized(),
669 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000670 def test_pyup_command(self):
671 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000672 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000673 cmds_after_breakpoint=['py-up'])
674 self.assertMultilineMatches(bt,
675 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000676#[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 +0000677 baz\(a, b, c\)
678$''')
679
Victor Stinnera92e81b2010-04-20 22:28:31 +0000680 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000681 def test_down_at_bottom(self):
682 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000683 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000684 cmds_after_breakpoint=['py-down'])
685 self.assertEndsWith(bt,
686 'Unable to find a newer python frame\n')
687
Victor Stinnera92e81b2010-04-20 22:28:31 +0000688 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000689 def test_up_at_top(self):
690 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000691 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000692 cmds_after_breakpoint=['py-up'] * 4)
693 self.assertEndsWith(bt,
694 'Unable to find an older python frame\n')
695
Victor Stinnera92e81b2010-04-20 22:28:31 +0000696 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100697 @unittest.skipIf(python_is_optimized(),
698 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000699 def test_up_then_down(self):
700 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000701 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000702 cmds_after_breakpoint=['py-up', 'py-down'])
703 self.assertMultilineMatches(bt,
704 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000705#[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 +0000706 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000707#[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 +0000708 print\(42\)
709$''')
710
711class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100712 @unittest.skipIf(python_is_optimized(),
713 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000714 def test_basic_command(self):
715 'Verify that the "py-bt" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000716 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000717 cmds_after_breakpoint=['py-bt'])
718 self.assertMultilineMatches(bt,
719 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000720#[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 +0000721 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000722#[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 +0000723 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000724#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100725 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000726''')
727
728class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100729 @unittest.skipIf(python_is_optimized(),
730 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000731 def test_basic_command(self):
732 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000733 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000734 cmds_after_breakpoint=['py-print args'])
735 self.assertMultilineMatches(bt,
736 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
737
Victor Stinnera92e81b2010-04-20 22:28:31 +0000738 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100739 @unittest.skipIf(python_is_optimized(),
740 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000741 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000742 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000743 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
744 self.assertMultilineMatches(bt,
745 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
746
Victor Stinner99cff3f2011-12-19 13:59:58 +0100747 @unittest.skipIf(python_is_optimized(),
748 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000749 def test_printing_global(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000750 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000751 cmds_after_breakpoint=['py-print __name__'])
752 self.assertMultilineMatches(bt,
753 r".*\nglobal '__name__' = '__main__'\n.*")
754
Victor Stinner99cff3f2011-12-19 13:59:58 +0100755 @unittest.skipIf(python_is_optimized(),
756 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000757 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000758 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000759 cmds_after_breakpoint=['py-print len'])
760 self.assertMultilineMatches(bt,
761 r".*\nbuiltin 'len' = <built-in function len>\n.*")
762
763class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100764 @unittest.skipIf(python_is_optimized(),
765 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000766 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000767 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000768 cmds_after_breakpoint=['py-locals'])
769 self.assertMultilineMatches(bt,
770 r".*\nargs = \(1, 2, 3\)\n.*")
771
Victor Stinnera92e81b2010-04-20 22:28:31 +0000772 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100773 @unittest.skipIf(python_is_optimized(),
774 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000775 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000776 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000777 cmds_after_breakpoint=['py-up', 'py-locals'])
778 self.assertMultilineMatches(bt,
779 r".*\na = 1\nb = 2\nc = 3\n.*")
780
781def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000782 run_unittest(PrettyPrintTests,
783 PyListTests,
784 StackNavigationTests,
785 PyBtTests,
786 PyPrintTests,
787 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000788 )
789
790if __name__ == "__main__":
791 test_main()