blob: 3fe15e4507b1e6ce27a3d4cef7d79949422e2296 [file] [log] [blame]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +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
Antoine Pitroud0f3e072013-09-21 23:56:17 +02008import pprint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00009import subprocess
10import sys
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010011import sysconfig
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000012import unittest
Victor Stinner150016f2010-05-19 23:04:56 +000013import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000014
David Malcolm8d37ffa2012-06-27 14:15:34 -040015# Is this Python configured to support threads?
16try:
17 import _thread
18except ImportError:
19 _thread = None
20
Antoine Pitroud0f3e072013-09-21 23:56:17 +020021from test import support
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000022from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000023
Victor Stinner5b6b4a82015-09-02 23:19:55 +020024def get_gdb_version():
25 try:
26 proc = subprocess.Popen(["gdb", "-nx", "--version"],
27 stdout=subprocess.PIPE,
28 universal_newlines=True)
29 with proc:
30 version = proc.communicate()[0]
31 except OSError:
32 # This is what "no gdb" looks like. There may, however, be other
33 # errors that manifest this way too.
34 raise unittest.SkipTest("Couldn't find gdb on the path")
35
36 # Regex to parse:
37 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
38 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020039 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
40 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnera578eb32015-09-15 00:22:55 +020041 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020042 if match is None:
43 raise Exception("unable to parse GDB version: %r" % version)
44 return (version, int(match.group(1)), int(match.group(2)))
45
46gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040047if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020048 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
49 "embedding. Saw %s.%s:\n%s"
50 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020051 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000052
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010053if not sysconfig.is_python_build():
54 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
55
R David Murrayf9333022012-10-27 13:22:41 -040056# Location of custom hooks file in a repository checkout.
57checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
58 'python-gdb.py')
59
Victor Stinner51324932013-11-20 12:27:48 +010060PYTHONHASHSEED = '123'
61
R David Murrayf9333022012-10-27 13:22:41 -040062def run_gdb(*args, **env_vars):
63 """Runs gdb in --batch mode with the additional arguments given by *args.
64
65 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
66 """
67 if env_vars:
68 env = os.environ.copy()
69 env.update(env_vars)
70 else:
71 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020072 # -nx: Do not execute commands from any .gdbinit initialization files
73 # (issue #22188)
74 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040075 if (gdb_major_version, gdb_minor_version) >= (7, 4):
76 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020077 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000078 # Redirect stdin to prevent GDB from messing with
79 # the terminal settings
80 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020081 stdout=subprocess.PIPE,
82 stderr=subprocess.PIPE,
83 env=env)
84 with proc:
85 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040086 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
87
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000088# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010089gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040090if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000091 raise unittest.SkipTest("gdb not built with embedded python support")
92
Nick Coghlance346872013-09-22 19:38:16 +100093# Verify that "gdb" can load our custom hooks, as OS security settings may
94# disallow this without a customised .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040095_, gdbpy_errors = run_gdb('--args', sys.executable)
96if "auto-loading has been declined" in gdbpy_errors:
97 msg = "gdb security settings prevent use of custom hooks: "
98 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100099
Victor Stinner50eb60e2010-04-20 22:32:07 +0000100def gdb_has_frame_select():
101 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400102 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
103 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000104 if not m:
105 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400106 gdb_frame_dir = m.group(1).split(', ')
107 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000108
109HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000110
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000111BREAKPOINT_FN='builtin_id'
112
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000113class DebuggerTests(unittest.TestCase):
114
115 """Test that the debugger can debug Python."""
116
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000117 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000118 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000119 cmds_after_breakpoint=None,
120 import_site=False):
121 '''
122 Run 'python -c SOURCE' under gdb with a breakpoint.
123
124 Support injecting commands after the breakpoint is reached
125
126 Returns the stdout from gdb
127
128 cmds_after_breakpoint: if provided, a list of strings: gdb commands
129 '''
130 # We use "set breakpoint pending yes" to avoid blocking with a:
131 # Function "foo" not defined.
132 # Make breakpoint pending on future shared library load? (y or [n])
133 # error, which typically happens python is dynamically linked (the
134 # breakpoints of interest are to be found in the shared library)
135 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000136 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000137 # emitted to stderr each time, alas.
138
139 # Initially I had "--eval-command=continue" here, but removed it to
140 # avoid repeated print breakpoints when traversing hierarchical data
141 # structures
142
143 # Generate a list of commands in gdb's language:
144 commands = ['set breakpoint pending yes',
145 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200146
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200147 # The tests assume that the first frame of printed
148 # backtrace will not contain program counter,
149 # that is however not guaranteed by gdb
150 # therefore we need to use 'set print address off' to
151 # make sure the counter is not there. For example:
152 # #0 in PyObject_Print ...
153 # is assumed, but sometimes this can be e.g.
154 # #0 0x00003fffb7dd1798 in PyObject_Print ...
155 'set print address off',
156
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000157 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200158
159 # GDB as of 7.4 onwards can distinguish between the
160 # value of a variable at entry vs current value:
161 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
162 # which leads to the selftests failing with errors like this:
163 # AssertionError: 'v@entry=()' != '()'
164 # Disable this:
165 if (gdb_major_version, gdb_minor_version) >= (7, 4):
166 commands += ['set print entry-values no']
167
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000168 if cmds_after_breakpoint:
169 commands += cmds_after_breakpoint
170 else:
171 commands += ['backtrace']
172
173 # print commands
174
175 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000176 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000177 args += ["--args",
178 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100179 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000180
181 if not import_site:
182 # -S suppresses the default 'import site'
183 args += ["-S"]
184
185 if source:
186 args += ["-c", source]
187 elif script:
188 args += [script]
189
190 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100191 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000192
193 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100194 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000195
Antoine Pitrou81641d62013-05-01 00:15:44 +0200196 errlines = err.splitlines()
197 unexpected_errlines = []
198
199 # Ignore some benign messages on stderr.
200 ignore_patterns = (
201 'Function "%s" not defined.' % breakpoint,
202 "warning: no loadable sections found in added symbol-file"
203 " system-supplied DSO",
204 "warning: Unable to find libthread_db matching"
205 " inferior's thread library, thread debugging will"
206 " not be available.",
207 "warning: Cannot initialize thread debugging"
208 " library: Debugger service failed",
209 'warning: Could not load shared library symbols for '
210 'linux-vdso.so',
211 'warning: Could not load shared library symbols for '
212 'linux-gate.so',
Serhiy Storchaka6b688d82015-02-14 22:44:35 +0200213 'warning: Could not load shared library symbols for '
214 'linux-vdso64.so',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200215 'Do you need "set solib-search-path" or '
216 '"set sysroot"?',
Victor Stinner5ac1b932013-06-25 21:54:32 +0200217 'warning: Source file is more recent than executable.',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100218 # Issue #19753: missing symbols on System Z
Victor Stinnerf4a48982013-11-24 18:55:25 +0100219 'Missing separate debuginfo for ',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100220 'Try: zypper install -C ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200221 )
222 for line in errlines:
223 if not line.startswith(ignore_patterns):
224 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000225
226 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200227 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000228 return out
229
230 def get_gdb_repr(self, source,
231 cmds_after_breakpoint=None,
232 import_site=False):
233 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000234 # run "python -c'id(DATA)'" under gdb with a breakpoint on
235 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000236 # parameter, and verify that the gdb displays the same string
237 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000238 # Verify that the gdb displays the expected string
239 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000240 # For a nested structure, the first time we hit the breakpoint will
241 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100242
243 # NOTE: avoid decoding too much of the traceback as some
244 # undecodable characters may lurk there in optimized mode
245 # (issue #19743).
246 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000247 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000248 cmds_after_breakpoint=cmds_after_breakpoint,
249 import_site=import_site)
250 # gdb can insert additional '\n' and space characters in various places
251 # in its output, depending on the width of the terminal it's connected
252 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400253 m = re.match('.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000254 gdb_output, re.DOTALL)
255 if not m:
256 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
257 return m.group(1), gdb_output
258
259 def assertEndsWith(self, actual, exp_end):
260 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000261 self.assertTrue(actual.endswith(exp_end),
262 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000263
264 def assertMultilineMatches(self, actual, pattern):
265 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000266 if not m:
267 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000268
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000269 def get_sample_script(self):
270 return findfile('gdb_sample.py')
271
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000272class PrettyPrintTests(DebuggerTests):
273 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000274 gdb_output = self.get_stack_trace('id(42)')
275 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000276
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100277 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000278 # Ensure that gdb's rendering of the value in a debugged process
279 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100280 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000281 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100282 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000283 self.assertEqual(gdb_repr, exp_repr,
284 ('%r did not equal expected %r; full output was:\n%s'
285 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000286
287 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300288 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100289 self.assertGdbRepr(42)
290 self.assertGdbRepr(0)
291 self.assertGdbRepr(-7)
292 self.assertGdbRepr(1000000000000)
293 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000294
295 def test_singletons(self):
296 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100297 self.assertGdbRepr(True)
298 self.assertGdbRepr(False)
299 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000300
301 def test_dicts(self):
302 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100303 self.assertGdbRepr({})
304 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
Victor Stinner22756f12016-01-22 14:16:47 +0100305 # PYTHONHASHSEED is need to get the exact item order
306 if not sys.flags.ignore_environment:
307 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000308
309 def test_lists(self):
310 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100311 self.assertGdbRepr([])
312 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000313
314 def test_bytes(self):
315 'Verify the pretty-printing of bytes'
316 self.assertGdbRepr(b'')
317 self.assertGdbRepr(b'And now for something hopefully the same')
318 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
319 self.assertGdbRepr(b'this is a tab:\t'
320 b' this is a slash-N:\n'
321 b' this is a slash-R:\r'
322 )
323
324 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
325
326 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000327
328 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000329 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000330 encoding = locale.getpreferredencoding()
331 def check_repr(text):
332 try:
333 text.encode(encoding)
334 printable = True
335 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000336 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000337 else:
338 self.assertGdbRepr(text)
339
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000340 self.assertGdbRepr('')
341 self.assertGdbRepr('And now for something hopefully the same')
342 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000343
344 # Test printing a single character:
345 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000346 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000347
348 # Test printing a Japanese unicode string
349 # (I believe this reads "mojibake", using 3 characters from the CJK
350 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000351 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000352
353 # Test a character outside the BMP:
354 # U+1D121 MUSICAL SYMBOL C CLEF
355 # This is:
356 # UTF-8: 0xF0 0x9D 0x84 0xA1
357 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000358 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000359
360 def test_tuples(self):
361 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100362 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000363 self.assertGdbRepr((1,), '(1,)')
364 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000365
366 def test_sets(self):
367 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200368 if (gdb_major_version, gdb_minor_version) < (7, 3):
369 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100370 self.assertGdbRepr(set(), "set()")
371 self.assertGdbRepr(set(['a']), "{'a'}")
372 # PYTHONHASHSEED is need to get the exact frozenset item order
373 if not sys.flags.ignore_environment:
374 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
375 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000376
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000377 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000378 # which happens on deletion:
379 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100380s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000381id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000382 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000383
384 def test_frozensets(self):
385 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200386 if (gdb_major_version, gdb_minor_version) < (7, 3):
387 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100388 self.assertGdbRepr(frozenset(), "frozenset()")
389 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
390 # PYTHONHASHSEED is need to get the exact frozenset item order
391 if not sys.flags.ignore_environment:
392 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
393 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000394
395 def test_exceptions(self):
396 # Test a RuntimeError
397 gdb_repr, gdb_output = self.get_gdb_repr('''
398try:
399 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000400except RuntimeError as e:
401 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000402''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000403 self.assertEqual(gdb_repr,
404 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000405
406
407 # Test division by zero:
408 gdb_repr, gdb_output = self.get_gdb_repr('''
409try:
410 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000411except ZeroDivisionError as e:
412 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000413''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000414 self.assertEqual(gdb_repr,
415 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000416
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000417 def test_modern_class(self):
418 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000419 gdb_repr, gdb_output = self.get_gdb_repr('''
420class Foo:
421 pass
422foo = Foo()
423foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000424id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100425 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000426 self.assertTrue(m,
427 msg='Unexpected new-style class rendering %r' % gdb_repr)
428
429 def test_subclassing_list(self):
430 'Verify the pretty-printing of an instance of a list subclass'
431 gdb_repr, gdb_output = self.get_gdb_repr('''
432class Foo(list):
433 pass
434foo = Foo()
435foo += [1, 2, 3]
436foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000437id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100438 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000439
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000440 self.assertTrue(m,
441 msg='Unexpected new-style class rendering %r' % gdb_repr)
442
443 def test_subclassing_tuple(self):
444 'Verify the pretty-printing of an instance of a tuple subclass'
445 # This should exercise the negative tp_dictoffset code in the
446 # new-style class support
447 gdb_repr, gdb_output = self.get_gdb_repr('''
448class Foo(tuple):
449 pass
450foo = Foo((1, 2, 3))
451foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000452id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100453 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000454
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000455 self.assertTrue(m,
456 msg='Unexpected new-style class rendering %r' % gdb_repr)
457
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000458 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000459 '''Run Python under gdb, corrupting variables in the inferior process
460 immediately before taking a backtrace.
461
462 Verify that the variable's representation is the expected failsafe
463 representation'''
464 if corruption:
465 cmds_after_breakpoint=[corruption, 'backtrace']
466 else:
467 cmds_after_breakpoint=['backtrace']
468
469 gdb_repr, gdb_output = \
470 self.get_gdb_repr(source,
471 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000472 if exprepr:
473 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000474 # gdb managed to print the value in spite of the corruption;
475 # this is good (see http://bugs.python.org/issue8330)
476 return
477
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000478 # Match anything for the type name; 0xDEADBEEF could point to
479 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100480 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000481
482 m = re.match(pattern, gdb_repr)
483 if not m:
484 self.fail('Unexpected gdb representation: %r\n%s' % \
485 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000486
487 def test_NULL_ptr(self):
488 'Ensure that a NULL PyObject* is handled gracefully'
489 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000490 self.get_gdb_repr('id(42)',
491 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000492 'backtrace'])
493 )
494
Ezio Melottib3aedd42010-11-20 19:04:17 +0000495 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000496
497 def test_NULL_ob_type(self):
498 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000499 self.assertSane('id(42)',
500 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000501
502 def test_corrupt_ob_type(self):
503 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504 self.assertSane('id(42)',
505 'set v->ob_type=0xDEADBEEF',
506 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000507
508 def test_corrupt_tp_flags(self):
509 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000510 self.assertSane('id(42)',
511 'set v->ob_type->tp_flags=0x0',
512 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000513
514 def test_corrupt_tp_name(self):
515 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000516 self.assertSane('id(42)',
517 'set v->ob_type->tp_name=0xDEADBEEF',
518 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000519
520 def test_builtins_help(self):
521 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100522
523 if sys.flags.no_site:
524 self.skipTest("need site module, but -S option was used")
525
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000526 # (this was the issue causing tracebacks in
527 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000528 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000529
Antoine Pitrou4d098732011-11-26 01:42:03 +0100530 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000531 self.assertTrue(m,
532 msg='Unexpected rendering %r' % gdb_repr)
533
534 def test_selfreferential_list(self):
535 '''Ensure that a reference loop involving a list doesn't lead proxyval
536 into an infinite loop:'''
537 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000538 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000539 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000540
541 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000542 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000543 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000544
545 def test_selfreferential_dict(self):
546 '''Ensure that a reference loop involving a dict doesn't lead proxyval
547 into an infinite loop:'''
548 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000549 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000550
Ezio Melottib3aedd42010-11-20 19:04:17 +0000551 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000552
553 def test_selfreferential_old_style_instance(self):
554 gdb_repr, gdb_output = \
555 self.get_gdb_repr('''
556class Foo:
557 pass
558foo = Foo()
559foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000560id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100561 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000562 gdb_repr),
563 'Unexpected gdb representation: %r\n%s' % \
564 (gdb_repr, gdb_output))
565
566 def test_selfreferential_new_style_instance(self):
567 gdb_repr, gdb_output = \
568 self.get_gdb_repr('''
569class Foo(object):
570 pass
571foo = Foo()
572foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000573id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100574 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000575 gdb_repr),
576 'Unexpected gdb representation: %r\n%s' % \
577 (gdb_repr, gdb_output))
578
579 gdb_repr, gdb_output = \
580 self.get_gdb_repr('''
581class Foo(object):
582 pass
583a = Foo()
584b = Foo()
585a.an_attr = b
586b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000587id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100588 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000589 gdb_repr),
590 'Unexpected gdb representation: %r\n%s' % \
591 (gdb_repr, gdb_output))
592
593 def test_truncation(self):
594 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000595 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000596 self.assertEqual(gdb_repr,
597 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
598 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
599 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
600 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
601 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
602 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
603 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
604 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
605 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
606 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
607 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
608 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
609 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
610 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
611 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
612 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
613 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
614 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
615 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
616 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
617 "224, 225, 226...(truncated)")
618 self.assertEqual(len(gdb_repr),
619 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000620
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000621 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000622 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100623 self.assertTrue(re.match('<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000624 gdb_repr),
625 'Unexpected gdb representation: %r\n%s' % \
626 (gdb_repr, gdb_output))
627
628 def test_frames(self):
629 gdb_output = self.get_stack_trace('''
630def foo(a, b, c):
631 pass
632
633foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000634id(foo.__code__)''',
635 breakpoint='builtin_id',
636 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000637 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100638 self.assertTrue(re.match('.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000639 gdb_output,
640 re.DOTALL),
641 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
642
Victor Stinnerd2084162011-12-19 13:42:24 +0100643@unittest.skipIf(python_is_optimized(),
644 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000645class PyListTests(DebuggerTests):
646 def assertListing(self, expected, actual):
647 self.assertEndsWith(actual, expected)
648
649 def test_basic_command(self):
650 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000651 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000652 cmds_after_breakpoint=['py-list'])
653
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000654 self.assertListing(' 5 \n'
655 ' 6 def bar(a, b, c):\n'
656 ' 7 baz(a, b, c)\n'
657 ' 8 \n'
658 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000659 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000660 ' 11 \n'
661 ' 12 foo(1, 2, 3)\n',
662 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000663
664 def test_one_abs_arg(self):
665 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000666 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000667 cmds_after_breakpoint=['py-list 9'])
668
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000669 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000670 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000671 ' 11 \n'
672 ' 12 foo(1, 2, 3)\n',
673 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000674
675 def test_two_abs_args(self):
676 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000677 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 cmds_after_breakpoint=['py-list 1,3'])
679
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000680 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
681 ' 2 \n'
682 ' 3 def foo(a, b, c):\n',
683 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000684
685class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000686 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100687 @unittest.skipIf(python_is_optimized(),
688 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689 def test_pyup_command(self):
690 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000691 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000692 cmds_after_breakpoint=['py-up'])
693 self.assertMultilineMatches(bt,
694 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100695#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 baz\(a, b, c\)
697$''')
698
Victor Stinner50eb60e2010-04-20 22:32:07 +0000699 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000700 def test_down_at_bottom(self):
701 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000702 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000703 cmds_after_breakpoint=['py-down'])
704 self.assertEndsWith(bt,
705 'Unable to find a newer python frame\n')
706
Victor Stinner50eb60e2010-04-20 22:32:07 +0000707 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000708 def test_up_at_top(self):
709 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000710 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000711 cmds_after_breakpoint=['py-up'] * 4)
712 self.assertEndsWith(bt,
713 'Unable to find an older python frame\n')
714
Victor Stinner50eb60e2010-04-20 22:32:07 +0000715 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100716 @unittest.skipIf(python_is_optimized(),
717 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000718 def test_up_then_down(self):
719 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000720 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000721 cmds_after_breakpoint=['py-up', 'py-down'])
722 self.assertMultilineMatches(bt,
723 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100724#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100726#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000727 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000728$''')
729
730class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100731 @unittest.skipIf(python_is_optimized(),
732 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200733 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000734 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000735 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000736 cmds_after_breakpoint=['py-bt'])
737 self.assertMultilineMatches(bt,
738 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200739Traceback \(most recent call first\):
740 File ".*gdb_sample.py", line 10, in baz
741 id\(42\)
742 File ".*gdb_sample.py", line 7, in bar
743 baz\(a, b, c\)
744 File ".*gdb_sample.py", line 4, in foo
745 bar\(a, b, c\)
746 File ".*gdb_sample.py", line 12, in <module>
747 foo\(1, 2, 3\)
748''')
749
Victor Stinnerd2084162011-12-19 13:42:24 +0100750 @unittest.skipIf(python_is_optimized(),
751 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200752 def test_bt_full(self):
753 'Verify that the "py-bt-full" command works'
754 bt = self.get_stack_trace(script=self.get_sample_script(),
755 cmds_after_breakpoint=['py-bt-full'])
756 self.assertMultilineMatches(bt,
757 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100758#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000759 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100760#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000761 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100762#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100763 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000764''')
765
David Malcolm8d37ffa2012-06-27 14:15:34 -0400766 @unittest.skipUnless(_thread,
767 "Python was compiled without thread support")
768 def test_threads(self):
769 'Verify that "py-bt" indicates threads that are waiting for the GIL'
770 cmd = '''
771from threading import Thread
772
773class TestThread(Thread):
774 # These threads would run forever, but we'll interrupt things with the
775 # debugger
776 def run(self):
777 i = 0
778 while 1:
779 i += 1
780
781t = {}
782for i in range(4):
783 t[i] = TestThread()
784 t[i].start()
785
786# Trigger a breakpoint on the main thread
787id(42)
788
789'''
790 # Verify with "py-bt":
791 gdb_output = self.get_stack_trace(cmd,
792 cmds_after_breakpoint=['thread apply all py-bt'])
793 self.assertIn('Waiting for the GIL', gdb_output)
794
795 # Verify with "py-bt-full":
796 gdb_output = self.get_stack_trace(cmd,
797 cmds_after_breakpoint=['thread apply all py-bt-full'])
798 self.assertIn('Waiting for the GIL', gdb_output)
799
800 @unittest.skipIf(python_is_optimized(),
801 "Python was compiled with optimizations")
802 # Some older versions of gdb will fail with
803 # "Cannot find new threads: generic error"
804 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
805 @unittest.skipUnless(_thread,
806 "Python was compiled without thread support")
807 def test_gc(self):
808 'Verify that "py-bt" indicates if a thread is garbage-collecting'
809 cmd = ('from gc import collect\n'
810 'id(42)\n'
811 'def foo():\n'
812 ' collect()\n'
813 'def bar():\n'
814 ' foo()\n'
815 'bar()\n')
816 # Verify with "py-bt":
817 gdb_output = self.get_stack_trace(cmd,
818 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
819 )
820 self.assertIn('Garbage-collecting', gdb_output)
821
822 # Verify with "py-bt-full":
823 gdb_output = self.get_stack_trace(cmd,
824 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
825 )
826 self.assertIn('Garbage-collecting', gdb_output)
827
828 @unittest.skipIf(python_is_optimized(),
829 "Python was compiled with optimizations")
830 # Some older versions of gdb will fail with
831 # "Cannot find new threads: generic error"
832 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
833 @unittest.skipUnless(_thread,
834 "Python was compiled without thread support")
835 def test_pycfunction(self):
836 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100837 # Tested function must not be defined with METH_NOARGS or METH_O,
838 # otherwise call_function() doesn't call PyCFunction_Call()
839 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400840 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100841 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400842 'def bar():\n'
843 ' foo()\n'
844 'bar()\n')
845 # Verify with "py-bt":
846 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100847 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400848 cmds_after_breakpoint=['bt', 'py-bt'],
849 )
Victor Stinner79644f92015-03-27 15:42:37 +0100850 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400851
852 # Verify with "py-bt-full":
853 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100854 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400855 cmds_after_breakpoint=['py-bt-full'],
856 )
Victor Stinner79644f92015-03-27 15:42:37 +0100857 self.assertIn('#0 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400858
859
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000860class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100861 @unittest.skipIf(python_is_optimized(),
862 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000863 def test_basic_command(self):
864 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000865 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000866 cmds_after_breakpoint=['py-print args'])
867 self.assertMultilineMatches(bt,
868 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
869
Vinay Sajip2549f872012-01-04 12:07:30 +0000870 @unittest.skipIf(python_is_optimized(),
871 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000872 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000873 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000874 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000875 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
876 self.assertMultilineMatches(bt,
877 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
878
Victor Stinnerd2084162011-12-19 13:42:24 +0100879 @unittest.skipIf(python_is_optimized(),
880 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000881 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000882 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000883 cmds_after_breakpoint=['py-print __name__'])
884 self.assertMultilineMatches(bt,
885 r".*\nglobal '__name__' = '__main__'\n.*")
886
Victor Stinnerd2084162011-12-19 13:42:24 +0100887 @unittest.skipIf(python_is_optimized(),
888 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000889 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000890 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000891 cmds_after_breakpoint=['py-print len'])
892 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100893 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000894
895class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100896 @unittest.skipIf(python_is_optimized(),
897 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000898 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000899 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000900 cmds_after_breakpoint=['py-locals'])
901 self.assertMultilineMatches(bt,
902 r".*\nargs = \(1, 2, 3\)\n.*")
903
Victor Stinner50eb60e2010-04-20 22:32:07 +0000904 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000905 @unittest.skipIf(python_is_optimized(),
906 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000907 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000908 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000909 cmds_after_breakpoint=['py-up', 'py-locals'])
910 self.assertMultilineMatches(bt,
911 r".*\na = 1\nb = 2\nc = 3\n.*")
912
913def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200914 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200915 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200916 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200917 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000918 run_unittest(PrettyPrintTests,
919 PyListTests,
920 StackNavigationTests,
921 PyBtTests,
922 PyPrintTests,
923 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000924 )
925
926if __name__ == "__main__":
927 test_main()