blob: 965601058a0643114a4ac56c005e484a635def8a [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
Victor Stinner582265f2015-03-27 15:44:13 +010075 return final_opt not in ('', '-O0', '-Og')
Victor Stinner99cff3f2011-12-19 13:59:58 +010076
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',
Serhiy Storchakab6b48e62015-02-14 22:44:35 +0200188 'warning: Could not load shared library symbols for '
189 'linux-vdso64.so',
Antoine Pitroub996e042013-05-01 00:15:44 +0200190 'Do you need "set solib-search-path" or '
191 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100192 'warning: Source file is more recent than executable.',
193 # Issue #19753: missing symbols on System Z
194 'Missing separate debuginfo for ',
195 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200196 )
197 for line in errlines:
198 if not line.startswith(ignore_patterns):
199 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000200
201 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200202 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000203 return out
204
205 def get_gdb_repr(self, source,
206 cmds_after_breakpoint=None,
207 import_site=False):
208 # Given an input python source representation of data,
209 # run "python -c'print DATA'" under gdb with a breakpoint on
210 # PyObject_Print and scrape out gdb's representation of the "op"
211 # parameter, and verify that the gdb displays the same string
212 #
213 # For a nested structure, the first time we hit the breakpoint will
214 # give us the top-level structure
215 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
216 cmds_after_breakpoint=cmds_after_breakpoint,
217 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000218 # gdb can insert additional '\n' and space characters in various places
219 # in its output, depending on the width of the terminal it's connected
220 # to (using its "wrap_here" function)
221 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000222 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000223 if not m:
224 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000225 return m.group(1), gdb_output
226
227 def assertEndsWith(self, actual, exp_end):
228 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000229 self.assertTrue(actual.endswith(exp_end),
230 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000231
232 def assertMultilineMatches(self, actual, pattern):
233 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000234 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000235
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000236 def get_sample_script(self):
237 return findfile('gdb_sample.py')
238
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000239class PrettyPrintTests(DebuggerTests):
240 def test_getting_backtrace(self):
241 gdb_output = self.get_stack_trace('print 42')
242 self.assertTrue('PyObject_Print' in gdb_output)
243
244 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
245 # Ensure that gdb's rendering of the value in a debugged process
246 # matches repr(value) in this process:
247 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
248 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100249 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000250
251 def test_int(self):
252 'Verify the pretty-printing of various "int" values'
253 self.assertGdbRepr(42)
254 self.assertGdbRepr(0)
255 self.assertGdbRepr(-7)
256 self.assertGdbRepr(sys.maxint)
257 self.assertGdbRepr(-sys.maxint)
258
259 def test_long(self):
260 'Verify the pretty-printing of various "long" values'
261 self.assertGdbRepr(0L)
262 self.assertGdbRepr(1000000000000L)
263 self.assertGdbRepr(-1L)
264 self.assertGdbRepr(-1000000000000000L)
265
266 def test_singletons(self):
267 'Verify the pretty-printing of True, False and None'
268 self.assertGdbRepr(True)
269 self.assertGdbRepr(False)
270 self.assertGdbRepr(None)
271
272 def test_dicts(self):
273 'Verify the pretty-printing of dictionaries'
274 self.assertGdbRepr({})
275 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500276 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000277
278 def test_lists(self):
279 'Verify the pretty-printing of lists'
280 self.assertGdbRepr([])
281 self.assertGdbRepr(range(5))
282
283 def test_strings(self):
284 'Verify the pretty-printing of strings'
285 self.assertGdbRepr('')
286 self.assertGdbRepr('And now for something hopefully the same')
287 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
288 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
289
290 def test_tuples(self):
291 'Verify the pretty-printing of tuples'
292 self.assertGdbRepr(tuple())
293 self.assertGdbRepr((1,))
294 self.assertGdbRepr(('foo', 'bar', 'baz'))
295
296 def test_unicode(self):
297 'Verify the pretty-printing of unicode values'
298 # Test the empty unicode string:
299 self.assertGdbRepr(u'')
300
301 self.assertGdbRepr(u'hello world')
302
303 # Test printing a single character:
304 # U+2620 SKULL AND CROSSBONES
305 self.assertGdbRepr(u'\u2620')
306
307 # Test printing a Japanese unicode string
308 # (I believe this reads "mojibake", using 3 characters from the CJK
309 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
310 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
311
312 # Test a character outside the BMP:
313 # U+1D121 MUSICAL SYMBOL C CLEF
314 # This is:
315 # UTF-8: 0xF0 0x9D 0x84 0xA1
316 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000317 # This will only work on wide-unicode builds:
318 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000319
320 def test_sets(self):
321 'Verify the pretty-printing of sets'
322 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500323 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
324 self.assertTrue(rep.startswith("set(["))
325 self.assertTrue(rep.endswith("])"))
326 self.assertEqual(eval(rep), {'a', 'b'})
327 rep = self.get_gdb_repr("print set([4, 5])")[0]
328 self.assertTrue(rep.startswith("set(["))
329 self.assertTrue(rep.endswith("])"))
330 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000331
332 # Ensure that we handled sets containing the "dummy" key value,
333 # which happens on deletion:
334 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
335s.pop()
336print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000337 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000338
339 def test_frozensets(self):
340 'Verify the pretty-printing of frozensets'
341 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500342 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
343 self.assertTrue(rep.startswith("frozenset(["))
344 self.assertTrue(rep.endswith("])"))
345 self.assertEqual(eval(rep), {'a', 'b'})
346 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
347 self.assertTrue(rep.startswith("frozenset(["))
348 self.assertTrue(rep.endswith("])"))
349 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000350
351 def test_exceptions(self):
352 # Test a RuntimeError
353 gdb_repr, gdb_output = self.get_gdb_repr('''
354try:
355 raise RuntimeError("I am an error")
356except RuntimeError, e:
357 print e
358''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000359 self.assertEqual(gdb_repr,
360 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000361
362
363 # Test division by zero:
364 gdb_repr, gdb_output = self.get_gdb_repr('''
365try:
366 a = 1 / 0
367except ZeroDivisionError, e:
368 print e
369''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000370 self.assertEqual(gdb_repr,
371 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000372
373 def test_classic_class(self):
374 'Verify the pretty-printing of classic class instances'
375 gdb_repr, gdb_output = self.get_gdb_repr('''
376class Foo:
377 pass
378foo = Foo()
379foo.an_int = 42
380print foo''')
381 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
382 self.assertTrue(m,
383 msg='Unexpected classic-class rendering %r' % gdb_repr)
384
385 def test_modern_class(self):
386 'Verify the pretty-printing of new-style class instances'
387 gdb_repr, gdb_output = self.get_gdb_repr('''
388class Foo(object):
389 pass
390foo = Foo()
391foo.an_int = 42
392print foo''')
393 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
394 self.assertTrue(m,
395 msg='Unexpected new-style class rendering %r' % gdb_repr)
396
397 def test_subclassing_list(self):
398 'Verify the pretty-printing of an instance of a list subclass'
399 gdb_repr, gdb_output = self.get_gdb_repr('''
400class Foo(list):
401 pass
402foo = Foo()
403foo += [1, 2, 3]
404foo.an_int = 42
405print foo''')
406 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
407 self.assertTrue(m,
408 msg='Unexpected new-style class rendering %r' % gdb_repr)
409
410 def test_subclassing_tuple(self):
411 'Verify the pretty-printing of an instance of a tuple subclass'
412 # This should exercise the negative tp_dictoffset code in the
413 # new-style class support
414 gdb_repr, gdb_output = self.get_gdb_repr('''
415class Foo(tuple):
416 pass
417foo = Foo((1, 2, 3))
418foo.an_int = 42
419print foo''')
420 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
421 self.assertTrue(m,
422 msg='Unexpected new-style class rendering %r' % gdb_repr)
423
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000424 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000425 '''Run Python under gdb, corrupting variables in the inferior process
426 immediately before taking a backtrace.
427
428 Verify that the variable's representation is the expected failsafe
429 representation'''
430 if corruption:
431 cmds_after_breakpoint=[corruption, 'backtrace']
432 else:
433 cmds_after_breakpoint=['backtrace']
434
435 gdb_repr, gdb_output = \
436 self.get_gdb_repr(source,
437 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000438
439 if expvalue:
440 if gdb_repr == repr(expvalue):
441 # gdb managed to print the value in spite of the corruption;
442 # this is good (see http://bugs.python.org/issue8330)
443 return
444
445 if exptype:
446 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
447 else:
448 # Match anything for the type name; 0xDEADBEEF could point to
449 # something arbitrary (see http://bugs.python.org/issue8330)
450 pattern = '<.* at remote 0x[0-9a-f]+>'
451
452 m = re.match(pattern, gdb_repr)
453 if not m:
454 self.fail('Unexpected gdb representation: %r\n%s' % \
455 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000456
457 def test_NULL_ptr(self):
458 'Ensure that a NULL PyObject* is handled gracefully'
459 gdb_repr, gdb_output = (
460 self.get_gdb_repr('print 42',
461 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000462 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000463 )
464
Ezio Melotti2623a372010-11-21 13:34:58 +0000465 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000466
467 def test_NULL_ob_type(self):
468 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
469 self.assertSane('print 42',
470 'set op->ob_type=0')
471
472 def test_corrupt_ob_type(self):
473 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
474 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000475 'set op->ob_type=0xDEADBEEF',
476 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000477
478 def test_corrupt_tp_flags(self):
479 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
480 self.assertSane('print 42',
481 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000482 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000483
484 def test_corrupt_tp_name(self):
485 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
486 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000487 'set op->ob_type->tp_name=0xDEADBEEF',
488 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000489
490 def test_NULL_instance_dict(self):
491 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
492 self.assertSane('''
493class Foo:
494 pass
495foo = Foo()
496foo.an_int = 42
497print foo''',
498 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000499 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000500
501 def test_builtins_help(self):
502 'Ensure that the new-style class _Helper in site.py can be handled'
503 # (this was the issue causing tracebacks in
504 # http://bugs.python.org/issue8032#msg100537 )
505
506 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
507 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
508 self.assertTrue(m,
509 msg='Unexpected rendering %r' % gdb_repr)
510
511 def test_selfreferential_list(self):
512 '''Ensure that a reference loop involving a list doesn't lead proxyval
513 into an infinite loop:'''
514 gdb_repr, gdb_output = \
515 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
516
Ezio Melotti2623a372010-11-21 13:34:58 +0000517 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000518
519 gdb_repr, gdb_output = \
520 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
521
Ezio Melotti2623a372010-11-21 13:34:58 +0000522 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000523
524 def test_selfreferential_dict(self):
525 '''Ensure that a reference loop involving a dict doesn't lead proxyval
526 into an infinite loop:'''
527 gdb_repr, gdb_output = \
528 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
529
Ezio Melotti2623a372010-11-21 13:34:58 +0000530 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000531
532 def test_selfreferential_old_style_instance(self):
533 gdb_repr, gdb_output = \
534 self.get_gdb_repr('''
535class Foo:
536 pass
537foo = Foo()
538foo.an_attr = foo
539print foo''')
540 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
541 gdb_repr),
542 'Unexpected gdb representation: %r\n%s' % \
543 (gdb_repr, gdb_output))
544
545 def test_selfreferential_new_style_instance(self):
546 gdb_repr, gdb_output = \
547 self.get_gdb_repr('''
548class Foo(object):
549 pass
550foo = Foo()
551foo.an_attr = foo
552print foo''')
553 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
554 gdb_repr),
555 'Unexpected gdb representation: %r\n%s' % \
556 (gdb_repr, gdb_output))
557
558 gdb_repr, gdb_output = \
559 self.get_gdb_repr('''
560class Foo(object):
561 pass
562a = Foo()
563b = Foo()
564a.an_attr = b
565b.an_attr = a
566print a''')
567 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
568 gdb_repr),
569 'Unexpected gdb representation: %r\n%s' % \
570 (gdb_repr, gdb_output))
571
572 def test_truncation(self):
573 'Verify that very long output is truncated'
574 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000575 self.assertEqual(gdb_repr,
576 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
577 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
578 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
579 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
580 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
581 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
582 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
583 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
584 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
585 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
586 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
587 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
588 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
589 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
590 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
591 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
592 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
593 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
594 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
595 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
596 "224, 225, 226...(truncated)")
597 self.assertEqual(len(gdb_repr),
598 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000599
600 def test_builtin_function(self):
601 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000602 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000603
604 def test_builtin_method(self):
605 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
606 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
607 gdb_repr),
608 'Unexpected gdb representation: %r\n%s' % \
609 (gdb_repr, gdb_output))
610
611 def test_frames(self):
612 gdb_output = self.get_stack_trace('''
613def foo(a, b, c):
614 pass
615
616foo(3, 4, 5)
617print foo.__code__''',
618 breakpoint='PyObject_Print',
619 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
620 )
R. David Murray0c080092010-04-05 16:28:49 +0000621 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
622 gdb_output,
623 re.DOTALL),
624 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000625
Victor Stinner99cff3f2011-12-19 13:59:58 +0100626@unittest.skipIf(python_is_optimized(),
627 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000628class PyListTests(DebuggerTests):
629 def assertListing(self, expected, actual):
630 self.assertEndsWith(actual, expected)
631
632 def test_basic_command(self):
633 'Verify that the "py-list" command works'
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'])
636
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000637 self.assertListing(' 5 \n'
638 ' 6 def bar(a, b, c):\n'
639 ' 7 baz(a, b, c)\n'
640 ' 8 \n'
641 ' 9 def baz(*args):\n'
642 ' >10 print(42)\n'
643 ' 11 \n'
644 ' 12 foo(1, 2, 3)\n',
645 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000646
647 def test_one_abs_arg(self):
648 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000649 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000650 cmds_after_breakpoint=['py-list 9'])
651
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000652 self.assertListing(' 9 def baz(*args):\n'
653 ' >10 print(42)\n'
654 ' 11 \n'
655 ' 12 foo(1, 2, 3)\n',
656 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000657
658 def test_two_abs_args(self):
659 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000660 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000661 cmds_after_breakpoint=['py-list 1,3'])
662
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000663 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
664 ' 2 \n'
665 ' 3 def foo(a, b, c):\n',
666 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000667
668class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000669 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100670 @unittest.skipIf(python_is_optimized(),
671 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000672 def test_pyup_command(self):
673 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000674 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000675 cmds_after_breakpoint=['py-up'])
676 self.assertMultilineMatches(bt,
677 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000678#[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 +0000679 baz\(a, b, c\)
680$''')
681
Victor Stinnera92e81b2010-04-20 22:28:31 +0000682 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000683 def test_down_at_bottom(self):
684 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000685 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000686 cmds_after_breakpoint=['py-down'])
687 self.assertEndsWith(bt,
688 'Unable to find a newer python frame\n')
689
Victor Stinnera92e81b2010-04-20 22:28:31 +0000690 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000691 def test_up_at_top(self):
692 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000693 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000694 cmds_after_breakpoint=['py-up'] * 4)
695 self.assertEndsWith(bt,
696 'Unable to find an older python frame\n')
697
Victor Stinnera92e81b2010-04-20 22:28:31 +0000698 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100699 @unittest.skipIf(python_is_optimized(),
700 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000701 def test_up_then_down(self):
702 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000703 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000704 cmds_after_breakpoint=['py-up', 'py-down'])
705 self.assertMultilineMatches(bt,
706 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000707#[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 +0000708 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000709#[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 +0000710 print\(42\)
711$''')
712
713class PyBtTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100714 @unittest.skipIf(python_is_optimized(),
715 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000716 def test_basic_command(self):
717 'Verify that the "py-bt" command works'
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-bt'])
720 self.assertMultilineMatches(bt,
721 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000722#[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 +0000723 baz\(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 4, in foo \(a=1, b=2, c=3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000725 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000726#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100727 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000728''')
729
730class PyPrintTests(DebuggerTests):
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_basic_command(self):
734 'Verify that the "py-print" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000735 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000736 cmds_after_breakpoint=['py-print args'])
737 self.assertMultilineMatches(bt,
738 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
739
Victor Stinnera92e81b2010-04-20 22:28:31 +0000740 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100741 @unittest.skipIf(python_is_optimized(),
742 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000743 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000744 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000745 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
746 self.assertMultilineMatches(bt,
747 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
748
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_printing_global(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-print __name__'])
754 self.assertMultilineMatches(bt,
755 r".*\nglobal '__name__' = '__main__'\n.*")
756
Victor Stinner99cff3f2011-12-19 13:59:58 +0100757 @unittest.skipIf(python_is_optimized(),
758 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000759 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000760 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000761 cmds_after_breakpoint=['py-print len'])
762 self.assertMultilineMatches(bt,
763 r".*\nbuiltin 'len' = <built-in function len>\n.*")
764
765class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100766 @unittest.skipIf(python_is_optimized(),
767 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000768 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000769 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000770 cmds_after_breakpoint=['py-locals'])
771 self.assertMultilineMatches(bt,
772 r".*\nargs = \(1, 2, 3\)\n.*")
773
Victor Stinnera92e81b2010-04-20 22:28:31 +0000774 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100775 @unittest.skipIf(python_is_optimized(),
776 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000777 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000778 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000779 cmds_after_breakpoint=['py-up', 'py-locals'])
780 self.assertMultilineMatches(bt,
781 r".*\na = 1\nb = 2\nc = 3\n.*")
782
783def test_main():
Martin v. Löwis5a965432010-04-12 05:22:25 +0000784 run_unittest(PrettyPrintTests,
785 PyListTests,
786 StackNavigationTests,
787 PyBtTests,
788 PyPrintTests,
789 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000790 )
791
792if __name__ == "__main__":
793 test_main()