blob: 0b8c0c83112ae4e3b23c02e78868b7965fd28242 [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
Victor Stinner3c5ce402015-09-03 09:51:59 +020013from test import test_support
Martin v. Löwis24f09fd2010-04-17 22:40:40 +000014from test.test_support import run_unittest, findfile
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000015
Victor Stinner3c5ce402015-09-03 09:51:59 +020016def get_gdb_version():
17 try:
18 proc = subprocess.Popen(["gdb", "-nx", "--version"],
19 stdout=subprocess.PIPE,
20 universal_newlines=True)
21 version = proc.communicate()[0]
22 except OSError:
23 # This is what "no gdb" looks like. There may, however, be other
24 # errors that manifest this way too.
25 raise unittest.SkipTest("Couldn't find gdb on the path")
26
27 # Regex to parse:
28 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
29 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
30 # 'GNU gdb 6.1.1 [FreeBSD]\n'
31 match = re.search("^GNU gdb.*? (\d+)\.(\d)", version)
32 if match is None:
33 raise Exception("unable to parse GDB version: %r" % version)
34 return (version, int(match.group(1)), int(match.group(2)))
35
36gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murray3e66f0d2012-10-27 13:47:49 -040037if gdb_major_version < 7:
Victor Stinner3c5ce402015-09-03 09:51:59 +020038 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
39 "embedding. Saw %s.%s:\n%s"
40 % (gdb_major_version, gdb_minor_version,
41 gdb_version))
42
Benjamin Peterson51f461f2014-11-23 22:34:04 -060043if sys.platform.startswith("sunos"):
Benjamin Peterson0636a4b2014-11-23 22:02:47 -060044 raise unittest.SkipTest("test doesn't work very well on Solaris")
45
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000046
R David Murray3e66f0d2012-10-27 13:47:49 -040047# Location of custom hooks file in a repository checkout.
48checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
49 'python-gdb.py')
50
51def run_gdb(*args, **env_vars):
Victor Stinner8bd34152014-08-16 14:31:02 +020052 """Runs gdb in batch mode with the additional arguments given by *args.
R David Murray3e66f0d2012-10-27 13:47:49 -040053
54 Returns its (stdout, stderr)
55 """
56 if env_vars:
57 env = os.environ.copy()
58 env.update(env_vars)
59 else:
60 env = None
Victor Stinner8bd34152014-08-16 14:31:02 +020061 # -nx: Do not execute commands from any .gdbinit initialization files
62 # (issue #22188)
63 base_cmd = ('gdb', '--batch', '-nx')
R David Murray3e66f0d2012-10-27 13:47:49 -040064 if (gdb_major_version, gdb_minor_version) >= (7, 4):
65 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
66 out, err = subprocess.Popen(base_cmd + args,
67 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
68 ).communicate()
69 return out, err
70
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000071# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitrou358da5b2013-11-23 17:40:36 +010072gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murray3e66f0d2012-10-27 13:47:49 -040073if not gdbpy_version:
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +000074 raise unittest.SkipTest("gdb not built with embedded python support")
75
Nick Coghlan254a3772013-09-22 19:36:09 +100076# Verify that "gdb" can load our custom hooks, as OS security settings may
77# disallow this without a customised .gdbinit.
R David Murray3e66f0d2012-10-27 13:47:49 -040078cmd = ['--args', sys.executable]
79_, gdbpy_errors = run_gdb('--args', sys.executable)
80if "auto-loading has been declined" in gdbpy_errors:
81 msg = "gdb security settings prevent use of custom hooks: "
Nick Coghlan254a3772013-09-22 19:36:09 +100082 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlana0933122012-06-17 19:03:39 +100083
Victor Stinner99cff3f2011-12-19 13:59:58 +010084def python_is_optimized():
85 cflags = sysconfig.get_config_vars()['PY_CFLAGS']
86 final_opt = ""
87 for opt in cflags.split():
88 if opt.startswith('-O'):
89 final_opt = opt
Victor Stinner582265f2015-03-27 15:44:13 +010090 return final_opt not in ('', '-O0', '-Og')
Victor Stinner99cff3f2011-12-19 13:59:58 +010091
Victor Stinnera92e81b2010-04-20 22:28:31 +000092def gdb_has_frame_select():
93 # Does this build of gdb have gdb.Frame.select ?
R David Murray3e66f0d2012-10-27 13:47:49 -040094 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
Victor Stinnera92e81b2010-04-20 22:28:31 +000095 m = re.match(r'.*\[(.*)\].*', stdout)
96 if not m:
97 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
98 gdb_frame_dir = m.group(1).split(', ')
99 return "'select'" in gdb_frame_dir
100
101HAS_PYUP_PYDOWN = gdb_has_frame_select()
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000102
103class DebuggerTests(unittest.TestCase):
104
105 """Test that the debugger can debug Python."""
106
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000107 def get_stack_trace(self, source=None, script=None,
108 breakpoint='PyObject_Print',
109 cmds_after_breakpoint=None,
110 import_site=False):
111 '''
112 Run 'python -c SOURCE' under gdb with a breakpoint.
113
114 Support injecting commands after the breakpoint is reached
115
116 Returns the stdout from gdb
117
118 cmds_after_breakpoint: if provided, a list of strings: gdb commands
119 '''
120 # We use "set breakpoint pending yes" to avoid blocking with a:
121 # Function "foo" not defined.
122 # Make breakpoint pending on future shared library load? (y or [n])
123 # error, which typically happens python is dynamically linked (the
124 # breakpoints of interest are to be found in the shared library)
125 # When this happens, we still get:
126 # Function "PyObject_Print" not defined.
127 # emitted to stderr each time, alas.
128
129 # Initially I had "--eval-command=continue" here, but removed it to
130 # avoid repeated print breakpoints when traversing hierarchical data
131 # structures
132
133 # Generate a list of commands in gdb's language:
134 commands = ['set breakpoint pending yes',
135 'break %s' % breakpoint,
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200136
Serhiy Storchaka73bcde22015-01-31 11:48:36 +0200137 # The tests assume that the first frame of printed
138 # backtrace will not contain program counter,
139 # that is however not guaranteed by gdb
140 # therefore we need to use 'set print address off' to
141 # make sure the counter is not there. For example:
142 # #0 in PyObject_Print ...
143 # is assumed, but sometimes this can be e.g.
144 # #0 0x00003fffb7dd1798 in PyObject_Print ...
145 'set print address off',
146
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000147 'run']
Serhiy Storchakadd8430f2015-02-06 08:36:14 +0200148
149 # GDB as of 7.4 onwards can distinguish between the
150 # value of a variable at entry vs current value:
151 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
152 # which leads to the selftests failing with errors like this:
153 # AssertionError: 'v@entry=()' != '()'
154 # Disable this:
155 if (gdb_major_version, gdb_minor_version) >= (7, 4):
156 commands += ['set print entry-values no']
157
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000158 if cmds_after_breakpoint:
159 commands += cmds_after_breakpoint
160 else:
161 commands += ['backtrace']
162
163 # print commands
164
165 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner8bd34152014-08-16 14:31:02 +0200166 args = ["gdb", "--batch", "-nx"]
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000167 args += ['--eval-command=%s' % cmd for cmd in commands]
168 args += ["--args",
169 sys.executable]
170
171 if not import_site:
172 # -S suppresses the default 'import site'
173 args += ["-S"]
174
175 if source:
176 args += ["-c", source]
177 elif script:
178 args += [script]
179
180 # print args
181 # print ' '.join(args)
182
183 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murray3e66f0d2012-10-27 13:47:49 -0400184 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000185
Antoine Pitroub996e042013-05-01 00:15:44 +0200186 errlines = err.splitlines()
187 unexpected_errlines = []
188
189 # Ignore some benign messages on stderr.
190 ignore_patterns = (
191 'Function "%s" not defined.' % breakpoint,
192 "warning: no loadable sections found in added symbol-file"
193 " system-supplied DSO",
194 "warning: Unable to find libthread_db matching"
195 " inferior's thread library, thread debugging will"
196 " not be available.",
197 "warning: Cannot initialize thread debugging"
198 " library: Debugger service failed",
199 'warning: Could not load shared library symbols for '
200 'linux-vdso.so',
201 'warning: Could not load shared library symbols for '
202 'linux-gate.so',
Serhiy Storchakab6b48e62015-02-14 22:44:35 +0200203 'warning: Could not load shared library symbols for '
204 'linux-vdso64.so',
Antoine Pitroub996e042013-05-01 00:15:44 +0200205 'Do you need "set solib-search-path" or '
206 '"set sysroot"?',
Victor Stinner57b00ed2014-11-05 15:07:18 +0100207 'warning: Source file is more recent than executable.',
208 # Issue #19753: missing symbols on System Z
209 'Missing separate debuginfo for ',
210 'Try: zypper install -C ',
Antoine Pitroub996e042013-05-01 00:15:44 +0200211 )
212 for line in errlines:
213 if not line.startswith(ignore_patterns):
214 unexpected_errlines.append(line)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000215
216 # Ensure no unexpected error messages:
Antoine Pitroub996e042013-05-01 00:15:44 +0200217 self.assertEqual(unexpected_errlines, [])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000218 return out
219
220 def get_gdb_repr(self, source,
221 cmds_after_breakpoint=None,
222 import_site=False):
223 # Given an input python source representation of data,
224 # run "python -c'print DATA'" under gdb with a breakpoint on
225 # PyObject_Print and scrape out gdb's representation of the "op"
226 # parameter, and verify that the gdb displays the same string
227 #
228 # For a nested structure, the first time we hit the breakpoint will
229 # give us the top-level structure
230 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print',
231 cmds_after_breakpoint=cmds_after_breakpoint,
232 import_site=import_site)
R. David Murray0c080092010-04-05 16:28:49 +0000233 # gdb can insert additional '\n' and space characters in various places
234 # in its output, depending on the width of the terminal it's connected
235 # to (using its "wrap_here" function)
236 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*',
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000237 gdb_output, re.DOTALL)
R. David Murray0c080092010-04-05 16:28:49 +0000238 if not m:
239 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000240 return m.group(1), gdb_output
241
242 def assertEndsWith(self, actual, exp_end):
243 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melotti2623a372010-11-21 13:34:58 +0000244 self.assertTrue(actual.endswith(exp_end),
245 msg='%r did not end with %r' % (actual, exp_end))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000246
247 def assertMultilineMatches(self, actual, pattern):
248 m = re.match(pattern, actual, re.DOTALL)
Ezio Melotti2623a372010-11-21 13:34:58 +0000249 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000250
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000251 def get_sample_script(self):
252 return findfile('gdb_sample.py')
253
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000254class PrettyPrintTests(DebuggerTests):
255 def test_getting_backtrace(self):
256 gdb_output = self.get_stack_trace('print 42')
257 self.assertTrue('PyObject_Print' in gdb_output)
258
259 def assertGdbRepr(self, val, cmds_after_breakpoint=None):
260 # Ensure that gdb's rendering of the value in a debugged process
261 # matches repr(value) in this process:
262 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val),
263 cmds_after_breakpoint)
Antoine Pitrou358da5b2013-11-23 17:40:36 +0100264 self.assertEqual(gdb_repr, repr(val))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000265
266 def test_int(self):
267 'Verify the pretty-printing of various "int" values'
268 self.assertGdbRepr(42)
269 self.assertGdbRepr(0)
270 self.assertGdbRepr(-7)
271 self.assertGdbRepr(sys.maxint)
272 self.assertGdbRepr(-sys.maxint)
273
274 def test_long(self):
275 'Verify the pretty-printing of various "long" values'
276 self.assertGdbRepr(0L)
277 self.assertGdbRepr(1000000000000L)
278 self.assertGdbRepr(-1L)
279 self.assertGdbRepr(-1000000000000000L)
280
281 def test_singletons(self):
282 'Verify the pretty-printing of True, False and None'
283 self.assertGdbRepr(True)
284 self.assertGdbRepr(False)
285 self.assertGdbRepr(None)
286
287 def test_dicts(self):
288 'Verify the pretty-printing of dictionaries'
289 self.assertGdbRepr({})
290 self.assertGdbRepr({'foo': 'bar'})
Benjamin Peterson11fa11b2012-02-20 21:55:32 -0500291 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000292
293 def test_lists(self):
294 'Verify the pretty-printing of lists'
295 self.assertGdbRepr([])
296 self.assertGdbRepr(range(5))
297
298 def test_strings(self):
299 'Verify the pretty-printing of strings'
300 self.assertGdbRepr('')
301 self.assertGdbRepr('And now for something hopefully the same')
302 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
303 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80')
304
305 def test_tuples(self):
306 'Verify the pretty-printing of tuples'
307 self.assertGdbRepr(tuple())
308 self.assertGdbRepr((1,))
309 self.assertGdbRepr(('foo', 'bar', 'baz'))
310
311 def test_unicode(self):
312 'Verify the pretty-printing of unicode values'
313 # Test the empty unicode string:
314 self.assertGdbRepr(u'')
315
316 self.assertGdbRepr(u'hello world')
317
318 # Test printing a single character:
319 # U+2620 SKULL AND CROSSBONES
320 self.assertGdbRepr(u'\u2620')
321
322 # Test printing a Japanese unicode string
323 # (I believe this reads "mojibake", using 3 characters from the CJK
324 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
325 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051')
326
327 # Test a character outside the BMP:
328 # U+1D121 MUSICAL SYMBOL C CLEF
329 # This is:
330 # UTF-8: 0xF0 0x9D 0x84 0xA1
331 # UTF-16: 0xD834 0xDD21
Victor Stinnerb1556c52010-05-20 11:29:45 +0000332 # This will only work on wide-unicode builds:
333 self.assertGdbRepr(u"\U0001D121")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000334
335 def test_sets(self):
336 'Verify the pretty-printing of sets'
337 self.assertGdbRepr(set())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500338 rep = self.get_gdb_repr("print set(['a', 'b'])")[0]
339 self.assertTrue(rep.startswith("set(["))
340 self.assertTrue(rep.endswith("])"))
341 self.assertEqual(eval(rep), {'a', 'b'})
342 rep = self.get_gdb_repr("print set([4, 5])")[0]
343 self.assertTrue(rep.startswith("set(["))
344 self.assertTrue(rep.endswith("])"))
345 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000346
347 # Ensure that we handled sets containing the "dummy" key value,
348 # which happens on deletion:
349 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
350s.pop()
351print s''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000352 self.assertEqual(gdb_repr, "set(['b'])")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000353
354 def test_frozensets(self):
355 'Verify the pretty-printing of frozensets'
356 self.assertGdbRepr(frozenset())
Benjamin Petersone39ccef2012-02-21 09:07:40 -0500357 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0]
358 self.assertTrue(rep.startswith("frozenset(["))
359 self.assertTrue(rep.endswith("])"))
360 self.assertEqual(eval(rep), {'a', 'b'})
361 rep = self.get_gdb_repr("print frozenset([4, 5])")[0]
362 self.assertTrue(rep.startswith("frozenset(["))
363 self.assertTrue(rep.endswith("])"))
364 self.assertEqual(eval(rep), {4, 5})
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000365
366 def test_exceptions(self):
367 # Test a RuntimeError
368 gdb_repr, gdb_output = self.get_gdb_repr('''
369try:
370 raise RuntimeError("I am an error")
371except RuntimeError, e:
372 print e
373''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000374 self.assertEqual(gdb_repr,
375 "exceptions.RuntimeError('I am an error',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000376
377
378 # Test division by zero:
379 gdb_repr, gdb_output = self.get_gdb_repr('''
380try:
381 a = 1 / 0
382except ZeroDivisionError, e:
383 print e
384''')
Ezio Melotti2623a372010-11-21 13:34:58 +0000385 self.assertEqual(gdb_repr,
386 "exceptions.ZeroDivisionError('integer division or modulo by zero',)")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000387
388 def test_classic_class(self):
389 'Verify the pretty-printing of classic class instances'
390 gdb_repr, gdb_output = self.get_gdb_repr('''
391class Foo:
392 pass
393foo = Foo()
394foo.an_int = 42
395print foo''')
396 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
397 self.assertTrue(m,
398 msg='Unexpected classic-class rendering %r' % gdb_repr)
399
400 def test_modern_class(self):
401 'Verify the pretty-printing of new-style class instances'
402 gdb_repr, gdb_output = self.get_gdb_repr('''
403class Foo(object):
404 pass
405foo = Foo()
406foo.an_int = 42
407print foo''')
408 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
409 self.assertTrue(m,
410 msg='Unexpected new-style class rendering %r' % gdb_repr)
411
412 def test_subclassing_list(self):
413 'Verify the pretty-printing of an instance of a list subclass'
414 gdb_repr, gdb_output = self.get_gdb_repr('''
415class Foo(list):
416 pass
417foo = Foo()
418foo += [1, 2, 3]
419foo.an_int = 42
420print foo''')
421 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
422 self.assertTrue(m,
423 msg='Unexpected new-style class rendering %r' % gdb_repr)
424
425 def test_subclassing_tuple(self):
426 'Verify the pretty-printing of an instance of a tuple subclass'
427 # This should exercise the negative tp_dictoffset code in the
428 # new-style class support
429 gdb_repr, gdb_output = self.get_gdb_repr('''
430class Foo(tuple):
431 pass
432foo = Foo((1, 2, 3))
433foo.an_int = 42
434print foo''')
435 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
436 self.assertTrue(m,
437 msg='Unexpected new-style class rendering %r' % gdb_repr)
438
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000439 def assertSane(self, source, corruption, expvalue=None, exptype=None):
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000440 '''Run Python under gdb, corrupting variables in the inferior process
441 immediately before taking a backtrace.
442
443 Verify that the variable's representation is the expected failsafe
444 representation'''
445 if corruption:
446 cmds_after_breakpoint=[corruption, 'backtrace']
447 else:
448 cmds_after_breakpoint=['backtrace']
449
450 gdb_repr, gdb_output = \
451 self.get_gdb_repr(source,
452 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000453
454 if expvalue:
455 if gdb_repr == repr(expvalue):
456 # gdb managed to print the value in spite of the corruption;
457 # this is good (see http://bugs.python.org/issue8330)
458 return
459
460 if exptype:
461 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>'
462 else:
463 # Match anything for the type name; 0xDEADBEEF could point to
464 # something arbitrary (see http://bugs.python.org/issue8330)
465 pattern = '<.* at remote 0x[0-9a-f]+>'
466
467 m = re.match(pattern, gdb_repr)
468 if not m:
469 self.fail('Unexpected gdb representation: %r\n%s' % \
470 (gdb_repr, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000471
472 def test_NULL_ptr(self):
473 'Ensure that a NULL PyObject* is handled gracefully'
474 gdb_repr, gdb_output = (
475 self.get_gdb_repr('print 42',
476 cmds_after_breakpoint=['set variable op=0',
R. David Murray0c080092010-04-05 16:28:49 +0000477 'backtrace'])
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000478 )
479
Ezio Melotti2623a372010-11-21 13:34:58 +0000480 self.assertEqual(gdb_repr, '0x0')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000481
482 def test_NULL_ob_type(self):
483 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
484 self.assertSane('print 42',
485 'set op->ob_type=0')
486
487 def test_corrupt_ob_type(self):
488 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
489 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000490 'set op->ob_type=0xDEADBEEF',
491 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000492
493 def test_corrupt_tp_flags(self):
494 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
495 self.assertSane('print 42',
496 'set op->ob_type->tp_flags=0x0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000497 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000498
499 def test_corrupt_tp_name(self):
500 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
501 self.assertSane('print 42',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000502 'set op->ob_type->tp_name=0xDEADBEEF',
503 expvalue=42)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000504
505 def test_NULL_instance_dict(self):
506 'Ensure that a PyInstanceObject with with a NULL in_dict is handled'
507 self.assertSane('''
508class Foo:
509 pass
510foo = Foo()
511foo.an_int = 42
512print foo''',
513 'set ((PyInstanceObject*)op)->in_dict = 0',
Martin v. Löwis7f7765c2010-04-12 05:18:16 +0000514 exptype='Foo')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000515
516 def test_builtins_help(self):
517 'Ensure that the new-style class _Helper in site.py can be handled'
518 # (this was the issue causing tracebacks in
519 # http://bugs.python.org/issue8032#msg100537 )
520
521 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True)
522 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
523 self.assertTrue(m,
524 msg='Unexpected rendering %r' % gdb_repr)
525
526 def test_selfreferential_list(self):
527 '''Ensure that a reference loop involving a list doesn't lead proxyval
528 into an infinite loop:'''
529 gdb_repr, gdb_output = \
530 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a")
531
Ezio Melotti2623a372010-11-21 13:34:58 +0000532 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000533
534 gdb_repr, gdb_output = \
535 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a")
536
Ezio Melotti2623a372010-11-21 13:34:58 +0000537 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000538
539 def test_selfreferential_dict(self):
540 '''Ensure that a reference loop involving a dict doesn't lead proxyval
541 into an infinite loop:'''
542 gdb_repr, gdb_output = \
543 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a")
544
Ezio Melotti2623a372010-11-21 13:34:58 +0000545 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000546
547 def test_selfreferential_old_style_instance(self):
548 gdb_repr, gdb_output = \
549 self.get_gdb_repr('''
550class Foo:
551 pass
552foo = Foo()
553foo.an_attr = foo
554print foo''')
555 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
556 gdb_repr),
557 'Unexpected gdb representation: %r\n%s' % \
558 (gdb_repr, gdb_output))
559
560 def test_selfreferential_new_style_instance(self):
561 gdb_repr, gdb_output = \
562 self.get_gdb_repr('''
563class Foo(object):
564 pass
565foo = Foo()
566foo.an_attr = foo
567print foo''')
568 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
569 gdb_repr),
570 'Unexpected gdb representation: %r\n%s' % \
571 (gdb_repr, gdb_output))
572
573 gdb_repr, gdb_output = \
574 self.get_gdb_repr('''
575class Foo(object):
576 pass
577a = Foo()
578b = Foo()
579a.an_attr = b
580b.an_attr = a
581print a''')
582 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
583 gdb_repr),
584 'Unexpected gdb representation: %r\n%s' % \
585 (gdb_repr, gdb_output))
586
587 def test_truncation(self):
588 'Verify that very long output is truncated'
589 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)')
Ezio Melotti2623a372010-11-21 13:34:58 +0000590 self.assertEqual(gdb_repr,
591 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
592 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
593 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
594 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
595 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
596 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
597 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
598 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
599 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
600 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
601 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
602 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
603 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
604 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
605 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
606 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
607 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
608 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
609 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
610 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
611 "224, 225, 226...(truncated)")
612 self.assertEqual(len(gdb_repr),
613 1024 + len('...(truncated)'))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000614
615 def test_builtin_function(self):
616 gdb_repr, gdb_output = self.get_gdb_repr('print len')
Ezio Melotti2623a372010-11-21 13:34:58 +0000617 self.assertEqual(gdb_repr, '<built-in function len>')
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000618
619 def test_builtin_method(self):
620 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines')
621 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>',
622 gdb_repr),
623 'Unexpected gdb representation: %r\n%s' % \
624 (gdb_repr, gdb_output))
625
626 def test_frames(self):
627 gdb_output = self.get_stack_trace('''
628def foo(a, b, c):
629 pass
630
631foo(3, 4, 5)
632print foo.__code__''',
633 breakpoint='PyObject_Print',
634 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)']
635 )
R. David Murray0c080092010-04-05 16:28:49 +0000636 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
637 gdb_output,
638 re.DOTALL),
639 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000640
Victor Stinner99cff3f2011-12-19 13:59:58 +0100641@unittest.skipIf(python_is_optimized(),
642 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000643class PyListTests(DebuggerTests):
644 def assertListing(self, expected, actual):
645 self.assertEndsWith(actual, expected)
646
647 def test_basic_command(self):
648 'Verify that the "py-list" command works'
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'])
651
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000652 self.assertListing(' 5 \n'
653 ' 6 def bar(a, b, c):\n'
654 ' 7 baz(a, b, c)\n'
655 ' 8 \n'
656 ' 9 def baz(*args):\n'
657 ' >10 print(42)\n'
658 ' 11 \n'
659 ' 12 foo(1, 2, 3)\n',
660 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000661
662 def test_one_abs_arg(self):
663 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000664 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000665 cmds_after_breakpoint=['py-list 9'])
666
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000667 self.assertListing(' 9 def baz(*args):\n'
668 ' >10 print(42)\n'
669 ' 11 \n'
670 ' 12 foo(1, 2, 3)\n',
671 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000672
673 def test_two_abs_args(self):
674 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000675 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000676 cmds_after_breakpoint=['py-list 1,3'])
677
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000678 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
679 ' 2 \n'
680 ' 3 def foo(a, b, c):\n',
681 bt)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000682
683class StackNavigationTests(DebuggerTests):
Victor Stinnera92e81b2010-04-20 22:28:31 +0000684 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100685 @unittest.skipIf(python_is_optimized(),
686 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000687 def test_pyup_command(self):
688 'Verify that the "py-up" command works'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000689 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000690 cmds_after_breakpoint=['py-up'])
691 self.assertMultilineMatches(bt,
692 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000693#[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 +0000694 baz\(a, b, c\)
695$''')
696
Victor Stinnera92e81b2010-04-20 22:28:31 +0000697 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000698 def test_down_at_bottom(self):
699 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000700 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000701 cmds_after_breakpoint=['py-down'])
702 self.assertEndsWith(bt,
703 'Unable to find a newer python frame\n')
704
Victor Stinnera92e81b2010-04-20 22:28:31 +0000705 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000706 def test_up_at_top(self):
707 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000708 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000709 cmds_after_breakpoint=['py-up'] * 4)
710 self.assertEndsWith(bt,
711 'Unable to find an older python frame\n')
712
Victor Stinnera92e81b2010-04-20 22:28:31 +0000713 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
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_up_then_down(self):
717 'Verify "py-up" followed by "py-down"'
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000718 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000719 cmds_after_breakpoint=['py-up', 'py-down'])
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 10, in baz \(args=\(1, 2, 3\)\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000725 print\(42\)
726$''')
727
728class PyBtTests(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-bt" 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-bt'])
735 self.assertMultilineMatches(bt,
736 r'''^.*
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000737#[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 +0000738 baz\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000739#[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 +0000740 bar\(a, b, c\)
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000741#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinner99cff3f2011-12-19 13:59:58 +0100742 foo\(1, 2, 3\)
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000743''')
744
745class PyPrintTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100746 @unittest.skipIf(python_is_optimized(),
747 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000748 def test_basic_command(self):
749 'Verify that the "py-print" command works'
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 args'])
752 self.assertMultilineMatches(bt,
753 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
754
Victor Stinnera92e81b2010-04-20 22:28:31 +0000755 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100756 @unittest.skipIf(python_is_optimized(),
757 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000758 def test_print_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000759 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000760 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
761 self.assertMultilineMatches(bt,
762 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
763
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_printing_global(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-print __name__'])
769 self.assertMultilineMatches(bt,
770 r".*\nglobal '__name__' = '__main__'\n.*")
771
Victor Stinner99cff3f2011-12-19 13:59:58 +0100772 @unittest.skipIf(python_is_optimized(),
773 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000774 def test_printing_builtin(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000775 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000776 cmds_after_breakpoint=['py-print len'])
777 self.assertMultilineMatches(bt,
778 r".*\nbuiltin 'len' = <built-in function len>\n.*")
779
780class PyLocalsTests(DebuggerTests):
Victor Stinner99cff3f2011-12-19 13:59:58 +0100781 @unittest.skipIf(python_is_optimized(),
782 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000783 def test_basic_command(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000784 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000785 cmds_after_breakpoint=['py-locals'])
786 self.assertMultilineMatches(bt,
787 r".*\nargs = \(1, 2, 3\)\n.*")
788
Victor Stinnera92e81b2010-04-20 22:28:31 +0000789 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinner99cff3f2011-12-19 13:59:58 +0100790 @unittest.skipIf(python_is_optimized(),
791 "Python was compiled with optimizations")
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000792 def test_locals_after_up(self):
Martin v. Löwis24f09fd2010-04-17 22:40:40 +0000793 bt = self.get_stack_trace(script=self.get_sample_script(),
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000794 cmds_after_breakpoint=['py-up', 'py-locals'])
795 self.assertMultilineMatches(bt,
796 r".*\na = 1\nb = 2\nc = 3\n.*")
797
798def test_main():
Victor Stinner3c5ce402015-09-03 09:51:59 +0200799 if test_support.verbose:
800 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
801 for line in gdb_version.splitlines():
802 print(" " * 4 + line)
Martin v. Löwis5a965432010-04-12 05:22:25 +0000803 run_unittest(PrettyPrintTests,
804 PyListTests,
805 StackNavigationTests,
806 PyBtTests,
807 PyPrintTests,
808 PyLocalsTests
Martin v. Löwisbf0dfb32010-04-01 07:40:51 +0000809 )
810
811if __name__ == "__main__":
812 test_main()