blob: cd7d2925f47c31cd58c820f1a4a63f373c3a2259 [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]
179
180 if not import_site:
181 # -S suppresses the default 'import site'
182 args += ["-S"]
183
184 if source:
185 args += ["-c", source]
186 elif script:
187 args += [script]
188
189 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100190 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000191
192 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100193 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194
Antoine Pitrou81641d62013-05-01 00:15:44 +0200195 errlines = err.splitlines()
196 unexpected_errlines = []
197
198 # Ignore some benign messages on stderr.
199 ignore_patterns = (
200 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200201 'Do you need "set solib-search-path" or '
202 '"set sysroot"?',
Victor Stinner0d88c652016-04-20 00:30:14 +0200203 # BFD: /usr/lib/debug/(...): unable to initialize decompress
204 # status for section .debug_aranges
205 'BFD: ',
206 # ignore all warnings
207 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200208 )
209 for line in errlines:
Victor Stinner0d88c652016-04-20 00:30:14 +0200210 if not line:
211 continue
Antoine Pitrou81641d62013-05-01 00:15:44 +0200212 if not line.startswith(ignore_patterns):
213 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000214
215 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200216 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000217 return out
218
219 def get_gdb_repr(self, source,
220 cmds_after_breakpoint=None,
221 import_site=False):
222 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000223 # run "python -c'id(DATA)'" under gdb with a breakpoint on
224 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000225 # parameter, and verify that the gdb displays the same string
226 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000227 # Verify that the gdb displays the expected string
228 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000229 # For a nested structure, the first time we hit the breakpoint will
230 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100231
232 # NOTE: avoid decoding too much of the traceback as some
233 # undecodable characters may lurk there in optimized mode
234 # (issue #19743).
235 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000236 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000237 cmds_after_breakpoint=cmds_after_breakpoint,
238 import_site=import_site)
239 # gdb can insert additional '\n' and space characters in various places
240 # in its output, depending on the width of the terminal it's connected
241 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400242 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 +0000243 gdb_output, re.DOTALL)
244 if not m:
245 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
246 return m.group(1), gdb_output
247
248 def assertEndsWith(self, actual, exp_end):
249 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000250 self.assertTrue(actual.endswith(exp_end),
251 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000252
253 def assertMultilineMatches(self, actual, pattern):
254 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000255 if not m:
256 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000257
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000258 def get_sample_script(self):
259 return findfile('gdb_sample.py')
260
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000261class PrettyPrintTests(DebuggerTests):
262 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000263 gdb_output = self.get_stack_trace('id(42)')
264 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000265
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100266 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000267 # Ensure that gdb's rendering of the value in a debugged process
268 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100269 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000270 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100271 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000272 self.assertEqual(gdb_repr, exp_repr,
273 ('%r did not equal expected %r; full output was:\n%s'
274 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000275
276 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300277 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100278 self.assertGdbRepr(42)
279 self.assertGdbRepr(0)
280 self.assertGdbRepr(-7)
281 self.assertGdbRepr(1000000000000)
282 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000283
284 def test_singletons(self):
285 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100286 self.assertGdbRepr(True)
287 self.assertGdbRepr(False)
288 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000289
290 def test_dicts(self):
291 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100292 self.assertGdbRepr({})
293 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
294 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000295
296 def test_lists(self):
297 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100298 self.assertGdbRepr([])
299 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000300
301 def test_bytes(self):
302 'Verify the pretty-printing of bytes'
303 self.assertGdbRepr(b'')
304 self.assertGdbRepr(b'And now for something hopefully the same')
305 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
306 self.assertGdbRepr(b'this is a tab:\t'
307 b' this is a slash-N:\n'
308 b' this is a slash-R:\r'
309 )
310
311 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
312
313 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000314
315 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000316 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000317 encoding = locale.getpreferredencoding()
318 def check_repr(text):
319 try:
320 text.encode(encoding)
321 printable = True
322 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000323 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000324 else:
325 self.assertGdbRepr(text)
326
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000327 self.assertGdbRepr('')
328 self.assertGdbRepr('And now for something hopefully the same')
329 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000330
331 # Test printing a single character:
332 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000333 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000334
335 # Test printing a Japanese unicode string
336 # (I believe this reads "mojibake", using 3 characters from the CJK
337 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000338 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000339
340 # Test a character outside the BMP:
341 # U+1D121 MUSICAL SYMBOL C CLEF
342 # This is:
343 # UTF-8: 0xF0 0x9D 0x84 0xA1
344 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000345 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000346
347 def test_tuples(self):
348 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100349 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000350 self.assertGdbRepr((1,), '(1,)')
351 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000352
353 def test_sets(self):
354 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200355 if (gdb_major_version, gdb_minor_version) < (7, 3):
356 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100357 self.assertGdbRepr(set(), 'set()')
358 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
359 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000360
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000361 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000362 # which happens on deletion:
363 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100364s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000365id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000366 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000367
368 def test_frozensets(self):
369 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200370 if (gdb_major_version, gdb_minor_version) < (7, 3):
371 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100372 self.assertGdbRepr(frozenset(), 'frozenset()')
373 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
374 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000375
376 def test_exceptions(self):
377 # Test a RuntimeError
378 gdb_repr, gdb_output = self.get_gdb_repr('''
379try:
380 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000381except RuntimeError as e:
382 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000383''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000384 self.assertEqual(gdb_repr,
385 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000386
387
388 # Test division by zero:
389 gdb_repr, gdb_output = self.get_gdb_repr('''
390try:
391 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000392except ZeroDivisionError as e:
393 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000394''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000395 self.assertEqual(gdb_repr,
396 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000397
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000398 def test_modern_class(self):
399 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000400 gdb_repr, gdb_output = self.get_gdb_repr('''
401class Foo:
402 pass
403foo = Foo()
404foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000405id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100406 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000407 self.assertTrue(m,
408 msg='Unexpected new-style class rendering %r' % gdb_repr)
409
410 def test_subclassing_list(self):
411 'Verify the pretty-printing of an instance of a list subclass'
412 gdb_repr, gdb_output = self.get_gdb_repr('''
413class Foo(list):
414 pass
415foo = Foo()
416foo += [1, 2, 3]
417foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000418id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100419 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 +0000420
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000421 self.assertTrue(m,
422 msg='Unexpected new-style class rendering %r' % gdb_repr)
423
424 def test_subclassing_tuple(self):
425 'Verify the pretty-printing of an instance of a tuple subclass'
426 # This should exercise the negative tp_dictoffset code in the
427 # new-style class support
428 gdb_repr, gdb_output = self.get_gdb_repr('''
429class Foo(tuple):
430 pass
431foo = Foo((1, 2, 3))
432foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000433id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100434 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 +0000435
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000436 self.assertTrue(m,
437 msg='Unexpected new-style class rendering %r' % gdb_repr)
438
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000439 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +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öwis5ae68102010-04-21 22:38:42 +0000453 if exprepr:
454 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000455 # gdb managed to print the value in spite of the corruption;
456 # this is good (see http://bugs.python.org/issue8330)
457 return
458
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000459 # Match anything for the type name; 0xDEADBEEF could point to
460 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100461 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000462
463 m = re.match(pattern, gdb_repr)
464 if not m:
465 self.fail('Unexpected gdb representation: %r\n%s' % \
466 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000467
468 def test_NULL_ptr(self):
469 'Ensure that a NULL PyObject* is handled gracefully'
470 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000471 self.get_gdb_repr('id(42)',
472 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000473 'backtrace'])
474 )
475
Ezio Melottib3aedd42010-11-20 19:04:17 +0000476 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000477
478 def test_NULL_ob_type(self):
479 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000480 self.assertSane('id(42)',
481 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000482
483 def test_corrupt_ob_type(self):
484 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000485 self.assertSane('id(42)',
486 'set v->ob_type=0xDEADBEEF',
487 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000488
489 def test_corrupt_tp_flags(self):
490 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000491 self.assertSane('id(42)',
492 'set v->ob_type->tp_flags=0x0',
493 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000494
495 def test_corrupt_tp_name(self):
496 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000497 self.assertSane('id(42)',
498 'set v->ob_type->tp_name=0xDEADBEEF',
499 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +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 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000505 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000506
Antoine Pitrou4d098732011-11-26 01:42:03 +0100507 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000508 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 = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000515 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000516 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000517
518 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000519 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000520 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000521
522 def test_selfreferential_dict(self):
523 '''Ensure that a reference loop involving a dict doesn't lead proxyval
524 into an infinite loop:'''
525 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000526 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000527
Ezio Melottib3aedd42010-11-20 19:04:17 +0000528 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000529
530 def test_selfreferential_old_style_instance(self):
531 gdb_repr, gdb_output = \
532 self.get_gdb_repr('''
533class Foo:
534 pass
535foo = Foo()
536foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000537id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100538 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000539 gdb_repr),
540 'Unexpected gdb representation: %r\n%s' % \
541 (gdb_repr, gdb_output))
542
543 def test_selfreferential_new_style_instance(self):
544 gdb_repr, gdb_output = \
545 self.get_gdb_repr('''
546class Foo(object):
547 pass
548foo = Foo()
549foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000550id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100551 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000552 gdb_repr),
553 'Unexpected gdb representation: %r\n%s' % \
554 (gdb_repr, gdb_output))
555
556 gdb_repr, gdb_output = \
557 self.get_gdb_repr('''
558class Foo(object):
559 pass
560a = Foo()
561b = Foo()
562a.an_attr = b
563b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000564id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100565 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 +0000566 gdb_repr),
567 'Unexpected gdb representation: %r\n%s' % \
568 (gdb_repr, gdb_output))
569
570 def test_truncation(self):
571 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000572 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000573 self.assertEqual(gdb_repr,
574 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
575 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
576 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
577 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
578 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
579 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
580 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
581 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
582 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
583 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
584 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
585 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
586 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
587 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
588 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
589 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
590 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
591 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
592 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
593 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
594 "224, 225, 226...(truncated)")
595 self.assertEqual(len(gdb_repr),
596 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000597
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000598 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000599 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100600 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 +0000601 gdb_repr),
602 'Unexpected gdb representation: %r\n%s' % \
603 (gdb_repr, gdb_output))
604
605 def test_frames(self):
606 gdb_output = self.get_stack_trace('''
607def foo(a, b, c):
608 pass
609
610foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000611id(foo.__code__)''',
612 breakpoint='builtin_id',
613 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000614 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100615 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 +0000616 gdb_output,
617 re.DOTALL),
618 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
619
Victor Stinnerd2084162011-12-19 13:42:24 +0100620@unittest.skipIf(python_is_optimized(),
621 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000622class PyListTests(DebuggerTests):
623 def assertListing(self, expected, actual):
624 self.assertEndsWith(actual, expected)
625
626 def test_basic_command(self):
627 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000628 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000629 cmds_after_breakpoint=['py-list'])
630
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000631 self.assertListing(' 5 \n'
632 ' 6 def bar(a, b, c):\n'
633 ' 7 baz(a, b, c)\n'
634 ' 8 \n'
635 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000636 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000637 ' 11 \n'
638 ' 12 foo(1, 2, 3)\n',
639 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000640
641 def test_one_abs_arg(self):
642 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000643 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000644 cmds_after_breakpoint=['py-list 9'])
645
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000646 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000647 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000648 ' 11 \n'
649 ' 12 foo(1, 2, 3)\n',
650 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000651
652 def test_two_abs_args(self):
653 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000654 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000655 cmds_after_breakpoint=['py-list 1,3'])
656
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000657 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
658 ' 2 \n'
659 ' 3 def foo(a, b, c):\n',
660 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000661
662class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000663 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100664 @unittest.skipIf(python_is_optimized(),
665 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000666 def test_pyup_command(self):
667 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000668 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000669 cmds_after_breakpoint=['py-up'])
670 self.assertMultilineMatches(bt,
671 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100672#[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 +0000673 baz\(a, b, c\)
674$''')
675
Victor Stinner50eb60e2010-04-20 22:32:07 +0000676 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000677 def test_down_at_bottom(self):
678 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000679 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000680 cmds_after_breakpoint=['py-down'])
681 self.assertEndsWith(bt,
682 'Unable to find a newer python frame\n')
683
Victor Stinner50eb60e2010-04-20 22:32:07 +0000684 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000685 def test_up_at_top(self):
686 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000687 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000688 cmds_after_breakpoint=['py-up'] * 4)
689 self.assertEndsWith(bt,
690 'Unable to find an older python frame\n')
691
Victor Stinner50eb60e2010-04-20 22:32:07 +0000692 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100693 @unittest.skipIf(python_is_optimized(),
694 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000695 def test_up_then_down(self):
696 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000697 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000698 cmds_after_breakpoint=['py-up', 'py-down'])
699 self.assertMultilineMatches(bt,
700 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100701#[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 +0000702 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100703#[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 +0000704 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000705$''')
706
707class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100708 @unittest.skipIf(python_is_optimized(),
709 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200710 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000711 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000712 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000713 cmds_after_breakpoint=['py-bt'])
714 self.assertMultilineMatches(bt,
715 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200716Traceback \(most recent call first\):
717 File ".*gdb_sample.py", line 10, in baz
718 id\(42\)
719 File ".*gdb_sample.py", line 7, in bar
720 baz\(a, b, c\)
721 File ".*gdb_sample.py", line 4, in foo
722 bar\(a, b, c\)
723 File ".*gdb_sample.py", line 12, in <module>
724 foo\(1, 2, 3\)
725''')
726
Victor Stinnerd2084162011-12-19 13:42:24 +0100727 @unittest.skipIf(python_is_optimized(),
728 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200729 def test_bt_full(self):
730 'Verify that the "py-bt-full" command works'
731 bt = self.get_stack_trace(script=self.get_sample_script(),
732 cmds_after_breakpoint=['py-bt-full'])
733 self.assertMultilineMatches(bt,
734 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100735#[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 +0000736 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100737#[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 +0000738 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100739#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100740 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000741''')
742
David Malcolm8d37ffa2012-06-27 14:15:34 -0400743 @unittest.skipUnless(_thread,
744 "Python was compiled without thread support")
745 def test_threads(self):
746 'Verify that "py-bt" indicates threads that are waiting for the GIL'
747 cmd = '''
748from threading import Thread
749
750class TestThread(Thread):
751 # These threads would run forever, but we'll interrupt things with the
752 # debugger
753 def run(self):
754 i = 0
755 while 1:
756 i += 1
757
758t = {}
759for i in range(4):
760 t[i] = TestThread()
761 t[i].start()
762
763# Trigger a breakpoint on the main thread
764id(42)
765
766'''
767 # Verify with "py-bt":
768 gdb_output = self.get_stack_trace(cmd,
769 cmds_after_breakpoint=['thread apply all py-bt'])
770 self.assertIn('Waiting for the GIL', gdb_output)
771
772 # Verify with "py-bt-full":
773 gdb_output = self.get_stack_trace(cmd,
774 cmds_after_breakpoint=['thread apply all py-bt-full'])
775 self.assertIn('Waiting for the GIL', gdb_output)
776
777 @unittest.skipIf(python_is_optimized(),
778 "Python was compiled with optimizations")
779 # Some older versions of gdb will fail with
780 # "Cannot find new threads: generic error"
781 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
782 @unittest.skipUnless(_thread,
783 "Python was compiled without thread support")
784 def test_gc(self):
785 'Verify that "py-bt" indicates if a thread is garbage-collecting'
786 cmd = ('from gc import collect\n'
787 'id(42)\n'
788 'def foo():\n'
789 ' collect()\n'
790 'def bar():\n'
791 ' foo()\n'
792 'bar()\n')
793 # Verify with "py-bt":
794 gdb_output = self.get_stack_trace(cmd,
795 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
796 )
797 self.assertIn('Garbage-collecting', gdb_output)
798
799 # Verify with "py-bt-full":
800 gdb_output = self.get_stack_trace(cmd,
801 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
802 )
803 self.assertIn('Garbage-collecting', gdb_output)
804
805 @unittest.skipIf(python_is_optimized(),
806 "Python was compiled with optimizations")
807 # Some older versions of gdb will fail with
808 # "Cannot find new threads: generic error"
809 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
810 @unittest.skipUnless(_thread,
811 "Python was compiled without thread support")
812 def test_pycfunction(self):
813 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100814 # Tested function must not be defined with METH_NOARGS or METH_O,
815 # otherwise call_function() doesn't call PyCFunction_Call()
816 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400817 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100818 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400819 'def bar():\n'
820 ' foo()\n'
821 'bar()\n')
822 # Verify with "py-bt":
823 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100824 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400825 cmds_after_breakpoint=['bt', 'py-bt'],
826 )
Victor Stinner79644f92015-03-27 15:42:37 +0100827 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400828
829 # Verify with "py-bt-full":
830 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100831 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400832 cmds_after_breakpoint=['py-bt-full'],
833 )
Victor Stinner79644f92015-03-27 15:42:37 +0100834 self.assertIn('#0 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400835
836
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000837class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100838 @unittest.skipIf(python_is_optimized(),
839 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000840 def test_basic_command(self):
841 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000842 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000843 cmds_after_breakpoint=['py-print args'])
844 self.assertMultilineMatches(bt,
845 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
846
Vinay Sajip2549f872012-01-04 12:07:30 +0000847 @unittest.skipIf(python_is_optimized(),
848 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000849 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000850 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000851 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000852 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
853 self.assertMultilineMatches(bt,
854 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
855
Victor Stinnerd2084162011-12-19 13:42:24 +0100856 @unittest.skipIf(python_is_optimized(),
857 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000858 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000859 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000860 cmds_after_breakpoint=['py-print __name__'])
861 self.assertMultilineMatches(bt,
862 r".*\nglobal '__name__' = '__main__'\n.*")
863
Victor Stinnerd2084162011-12-19 13:42:24 +0100864 @unittest.skipIf(python_is_optimized(),
865 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000866 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000867 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000868 cmds_after_breakpoint=['py-print len'])
869 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100870 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000871
872class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100873 @unittest.skipIf(python_is_optimized(),
874 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000875 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000876 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000877 cmds_after_breakpoint=['py-locals'])
878 self.assertMultilineMatches(bt,
879 r".*\nargs = \(1, 2, 3\)\n.*")
880
Victor Stinner50eb60e2010-04-20 22:32:07 +0000881 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000882 @unittest.skipIf(python_is_optimized(),
883 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000884 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000885 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000886 cmds_after_breakpoint=['py-up', 'py-locals'])
887 self.assertMultilineMatches(bt,
888 r".*\na = 1\nb = 2\nc = 3\n.*")
889
890def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200891 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200892 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200893 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200894 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000895 run_unittest(PrettyPrintTests,
896 PyListTests,
897 StackNavigationTests,
898 PyBtTests,
899 PyPrintTests,
900 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000901 )
902
903if __name__ == "__main__":
904 test_main()