blob: 8e3ccb0d6adfe5c9e31a35efd52fe68ad7e1b1e6 [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,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200202 'Do you need "set solib-search-path" or '
203 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100204 # BFD: /usr/lib/debug/(...): unable to initialize decompress
205 # status for section .debug_aranges
206 'BFD: ',
207 # ignore all warnings
208 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200209 )
210 for line in errlines:
211 if not line.startswith(ignore_patterns):
212 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000213
214 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200215 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000216 return out
217
218 def get_gdb_repr(self, source,
219 cmds_after_breakpoint=None,
220 import_site=False):
221 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000222 # run "python -c'id(DATA)'" under gdb with a breakpoint on
223 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000224 # parameter, and verify that the gdb displays the same string
225 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000226 # Verify that the gdb displays the expected string
227 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000228 # For a nested structure, the first time we hit the breakpoint will
229 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100230
231 # NOTE: avoid decoding too much of the traceback as some
232 # undecodable characters may lurk there in optimized mode
233 # (issue #19743).
234 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000235 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000236 cmds_after_breakpoint=cmds_after_breakpoint,
237 import_site=import_site)
238 # gdb can insert additional '\n' and space characters in various places
239 # in its output, depending on the width of the terminal it's connected
240 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400241 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 +0000242 gdb_output, re.DOTALL)
243 if not m:
244 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
245 return m.group(1), gdb_output
246
247 def assertEndsWith(self, actual, exp_end):
248 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000249 self.assertTrue(actual.endswith(exp_end),
250 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000251
252 def assertMultilineMatches(self, actual, pattern):
253 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000254 if not m:
255 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000256
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000257 def get_sample_script(self):
258 return findfile('gdb_sample.py')
259
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000260class PrettyPrintTests(DebuggerTests):
261 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000262 gdb_output = self.get_stack_trace('id(42)')
263 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000264
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100265 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266 # Ensure that gdb's rendering of the value in a debugged process
267 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100268 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000269 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100270 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000271 self.assertEqual(gdb_repr, exp_repr,
272 ('%r did not equal expected %r; full output was:\n%s'
273 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274
275 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300276 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100277 self.assertGdbRepr(42)
278 self.assertGdbRepr(0)
279 self.assertGdbRepr(-7)
280 self.assertGdbRepr(1000000000000)
281 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000282
283 def test_singletons(self):
284 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100285 self.assertGdbRepr(True)
286 self.assertGdbRepr(False)
287 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000288
289 def test_dicts(self):
290 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100291 self.assertGdbRepr({})
292 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
Victor Stinner22756f12016-01-22 14:16:47 +0100293 # PYTHONHASHSEED is need to get the exact item order
294 if not sys.flags.ignore_environment:
295 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000296
297 def test_lists(self):
298 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100299 self.assertGdbRepr([])
300 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000301
302 def test_bytes(self):
303 'Verify the pretty-printing of bytes'
304 self.assertGdbRepr(b'')
305 self.assertGdbRepr(b'And now for something hopefully the same')
306 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
307 self.assertGdbRepr(b'this is a tab:\t'
308 b' this is a slash-N:\n'
309 b' this is a slash-R:\r'
310 )
311
312 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
313
314 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000315
316 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000317 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000318 encoding = locale.getpreferredencoding()
319 def check_repr(text):
320 try:
321 text.encode(encoding)
322 printable = True
323 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000324 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000325 else:
326 self.assertGdbRepr(text)
327
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000328 self.assertGdbRepr('')
329 self.assertGdbRepr('And now for something hopefully the same')
330 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000331
332 # Test printing a single character:
333 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000334 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000335
336 # Test printing a Japanese unicode string
337 # (I believe this reads "mojibake", using 3 characters from the CJK
338 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000339 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000340
341 # Test a character outside the BMP:
342 # U+1D121 MUSICAL SYMBOL C CLEF
343 # This is:
344 # UTF-8: 0xF0 0x9D 0x84 0xA1
345 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000346 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000347
348 def test_tuples(self):
349 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100350 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000351 self.assertGdbRepr((1,), '(1,)')
352 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000353
354 def test_sets(self):
355 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200356 if (gdb_major_version, gdb_minor_version) < (7, 3):
357 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100358 self.assertGdbRepr(set(), "set()")
359 self.assertGdbRepr(set(['a']), "{'a'}")
360 # PYTHONHASHSEED is need to get the exact frozenset item order
361 if not sys.flags.ignore_environment:
362 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
363 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000364
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000365 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000366 # which happens on deletion:
367 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100368s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000369id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000370 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000371
372 def test_frozensets(self):
373 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200374 if (gdb_major_version, gdb_minor_version) < (7, 3):
375 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100376 self.assertGdbRepr(frozenset(), "frozenset()")
377 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
378 # PYTHONHASHSEED is need to get the exact frozenset item order
379 if not sys.flags.ignore_environment:
380 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
381 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000382
383 def test_exceptions(self):
384 # Test a RuntimeError
385 gdb_repr, gdb_output = self.get_gdb_repr('''
386try:
387 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000388except RuntimeError as e:
389 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000390''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000391 self.assertEqual(gdb_repr,
392 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000393
394
395 # Test division by zero:
396 gdb_repr, gdb_output = self.get_gdb_repr('''
397try:
398 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000399except ZeroDivisionError as e:
400 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000401''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000402 self.assertEqual(gdb_repr,
403 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000405 def test_modern_class(self):
406 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000407 gdb_repr, gdb_output = self.get_gdb_repr('''
408class Foo:
409 pass
410foo = Foo()
411foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000412id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100413 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000414 self.assertTrue(m,
415 msg='Unexpected new-style class rendering %r' % gdb_repr)
416
417 def test_subclassing_list(self):
418 'Verify the pretty-printing of an instance of a list subclass'
419 gdb_repr, gdb_output = self.get_gdb_repr('''
420class Foo(list):
421 pass
422foo = Foo()
423foo += [1, 2, 3]
424foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000425id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100426 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 +0000427
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000428 self.assertTrue(m,
429 msg='Unexpected new-style class rendering %r' % gdb_repr)
430
431 def test_subclassing_tuple(self):
432 'Verify the pretty-printing of an instance of a tuple subclass'
433 # This should exercise the negative tp_dictoffset code in the
434 # new-style class support
435 gdb_repr, gdb_output = self.get_gdb_repr('''
436class Foo(tuple):
437 pass
438foo = Foo((1, 2, 3))
439foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000440id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100441 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 +0000442
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000443 self.assertTrue(m,
444 msg='Unexpected new-style class rendering %r' % gdb_repr)
445
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000446 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000447 '''Run Python under gdb, corrupting variables in the inferior process
448 immediately before taking a backtrace.
449
450 Verify that the variable's representation is the expected failsafe
451 representation'''
452 if corruption:
453 cmds_after_breakpoint=[corruption, 'backtrace']
454 else:
455 cmds_after_breakpoint=['backtrace']
456
457 gdb_repr, gdb_output = \
458 self.get_gdb_repr(source,
459 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000460 if exprepr:
461 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000462 # gdb managed to print the value in spite of the corruption;
463 # this is good (see http://bugs.python.org/issue8330)
464 return
465
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000466 # Match anything for the type name; 0xDEADBEEF could point to
467 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100468 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000469
470 m = re.match(pattern, gdb_repr)
471 if not m:
472 self.fail('Unexpected gdb representation: %r\n%s' % \
473 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000474
475 def test_NULL_ptr(self):
476 'Ensure that a NULL PyObject* is handled gracefully'
477 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000478 self.get_gdb_repr('id(42)',
479 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000480 'backtrace'])
481 )
482
Ezio Melottib3aedd42010-11-20 19:04:17 +0000483 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000484
485 def test_NULL_ob_type(self):
486 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000487 self.assertSane('id(42)',
488 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000489
490 def test_corrupt_ob_type(self):
491 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000492 self.assertSane('id(42)',
493 'set v->ob_type=0xDEADBEEF',
494 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000495
496 def test_corrupt_tp_flags(self):
497 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000498 self.assertSane('id(42)',
499 'set v->ob_type->tp_flags=0x0',
500 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000501
502 def test_corrupt_tp_name(self):
503 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504 self.assertSane('id(42)',
505 'set v->ob_type->tp_name=0xDEADBEEF',
506 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000507
508 def test_builtins_help(self):
509 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100510
511 if sys.flags.no_site:
512 self.skipTest("need site module, but -S option was used")
513
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000514 # (this was the issue causing tracebacks in
515 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000516 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000517
Antoine Pitrou4d098732011-11-26 01:42:03 +0100518 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000519 self.assertTrue(m,
520 msg='Unexpected rendering %r' % gdb_repr)
521
522 def test_selfreferential_list(self):
523 '''Ensure that a reference loop involving a list 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 = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000527 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000528
529 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000530 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000531 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000532
533 def test_selfreferential_dict(self):
534 '''Ensure that a reference loop involving a dict doesn't lead proxyval
535 into an infinite loop:'''
536 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000537 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000538
Ezio Melottib3aedd42010-11-20 19:04:17 +0000539 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000540
541 def test_selfreferential_old_style_instance(self):
542 gdb_repr, gdb_output = \
543 self.get_gdb_repr('''
544class Foo:
545 pass
546foo = Foo()
547foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000548id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100549 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000550 gdb_repr),
551 'Unexpected gdb representation: %r\n%s' % \
552 (gdb_repr, gdb_output))
553
554 def test_selfreferential_new_style_instance(self):
555 gdb_repr, gdb_output = \
556 self.get_gdb_repr('''
557class Foo(object):
558 pass
559foo = Foo()
560foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000561id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100562 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000563 gdb_repr),
564 'Unexpected gdb representation: %r\n%s' % \
565 (gdb_repr, gdb_output))
566
567 gdb_repr, gdb_output = \
568 self.get_gdb_repr('''
569class Foo(object):
570 pass
571a = Foo()
572b = Foo()
573a.an_attr = b
574b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000575id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100576 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 +0000577 gdb_repr),
578 'Unexpected gdb representation: %r\n%s' % \
579 (gdb_repr, gdb_output))
580
581 def test_truncation(self):
582 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000583 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000584 self.assertEqual(gdb_repr,
585 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
586 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
587 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
588 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
589 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
590 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
591 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
592 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
593 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
594 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
595 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
596 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
597 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
598 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
599 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
600 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
601 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
602 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
603 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
604 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
605 "224, 225, 226...(truncated)")
606 self.assertEqual(len(gdb_repr),
607 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000608
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000610 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100611 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 +0000612 gdb_repr),
613 'Unexpected gdb representation: %r\n%s' % \
614 (gdb_repr, gdb_output))
615
616 def test_frames(self):
617 gdb_output = self.get_stack_trace('''
618def foo(a, b, c):
619 pass
620
621foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000622id(foo.__code__)''',
623 breakpoint='builtin_id',
624 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000625 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100626 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 +0000627 gdb_output,
628 re.DOTALL),
629 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
630
Victor Stinnerd2084162011-12-19 13:42:24 +0100631@unittest.skipIf(python_is_optimized(),
632 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000633class PyListTests(DebuggerTests):
634 def assertListing(self, expected, actual):
635 self.assertEndsWith(actual, expected)
636
637 def test_basic_command(self):
638 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000639 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000640 cmds_after_breakpoint=['py-list'])
641
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000642 self.assertListing(' 5 \n'
643 ' 6 def bar(a, b, c):\n'
644 ' 7 baz(a, b, c)\n'
645 ' 8 \n'
646 ' 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_one_abs_arg(self):
653 'Verify the "py-list" command with one absolute argument'
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 9'])
656
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000657 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000658 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000659 ' 11 \n'
660 ' 12 foo(1, 2, 3)\n',
661 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000662
663 def test_two_abs_args(self):
664 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000665 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000666 cmds_after_breakpoint=['py-list 1,3'])
667
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000668 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
669 ' 2 \n'
670 ' 3 def foo(a, b, c):\n',
671 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000672
673class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000674 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100675 @unittest.skipIf(python_is_optimized(),
676 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000677 def test_pyup_command(self):
678 'Verify that the "py-up" command works'
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-up'])
681 self.assertMultilineMatches(bt,
682 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100683#[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 +0000684 baz\(a, b, c\)
685$''')
686
Victor Stinner50eb60e2010-04-20 22:32:07 +0000687 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000688 def test_down_at_bottom(self):
689 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000690 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000691 cmds_after_breakpoint=['py-down'])
692 self.assertEndsWith(bt,
693 'Unable to find a newer python frame\n')
694
Victor Stinner50eb60e2010-04-20 22:32:07 +0000695 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 def test_up_at_top(self):
697 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000698 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000699 cmds_after_breakpoint=['py-up'] * 4)
700 self.assertEndsWith(bt,
701 'Unable to find an older python frame\n')
702
Victor Stinner50eb60e2010-04-20 22:32:07 +0000703 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100704 @unittest.skipIf(python_is_optimized(),
705 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000706 def test_up_then_down(self):
707 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000708 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000709 cmds_after_breakpoint=['py-up', 'py-down'])
710 self.assertMultilineMatches(bt,
711 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100712#[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 +0000713 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100714#[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 +0000715 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000716$''')
717
718class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100719 @unittest.skipIf(python_is_optimized(),
720 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200721 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000722 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000723 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000724 cmds_after_breakpoint=['py-bt'])
725 self.assertMultilineMatches(bt,
726 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200727Traceback \(most recent call first\):
728 File ".*gdb_sample.py", line 10, in baz
729 id\(42\)
730 File ".*gdb_sample.py", line 7, in bar
731 baz\(a, b, c\)
732 File ".*gdb_sample.py", line 4, in foo
733 bar\(a, b, c\)
734 File ".*gdb_sample.py", line 12, in <module>
735 foo\(1, 2, 3\)
736''')
737
Victor Stinnerd2084162011-12-19 13:42:24 +0100738 @unittest.skipIf(python_is_optimized(),
739 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200740 def test_bt_full(self):
741 'Verify that the "py-bt-full" command works'
742 bt = self.get_stack_trace(script=self.get_sample_script(),
743 cmds_after_breakpoint=['py-bt-full'])
744 self.assertMultilineMatches(bt,
745 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100746#[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 +0000747 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100748#[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 +0000749 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100750#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100751 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000752''')
753
David Malcolm8d37ffa2012-06-27 14:15:34 -0400754 @unittest.skipUnless(_thread,
755 "Python was compiled without thread support")
756 def test_threads(self):
757 'Verify that "py-bt" indicates threads that are waiting for the GIL'
758 cmd = '''
759from threading import Thread
760
761class TestThread(Thread):
762 # These threads would run forever, but we'll interrupt things with the
763 # debugger
764 def run(self):
765 i = 0
766 while 1:
767 i += 1
768
769t = {}
770for i in range(4):
771 t[i] = TestThread()
772 t[i].start()
773
774# Trigger a breakpoint on the main thread
775id(42)
776
777'''
778 # Verify with "py-bt":
779 gdb_output = self.get_stack_trace(cmd,
780 cmds_after_breakpoint=['thread apply all py-bt'])
781 self.assertIn('Waiting for the GIL', gdb_output)
782
783 # Verify with "py-bt-full":
784 gdb_output = self.get_stack_trace(cmd,
785 cmds_after_breakpoint=['thread apply all py-bt-full'])
786 self.assertIn('Waiting for the GIL', gdb_output)
787
788 @unittest.skipIf(python_is_optimized(),
789 "Python was compiled with optimizations")
790 # Some older versions of gdb will fail with
791 # "Cannot find new threads: generic error"
792 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
793 @unittest.skipUnless(_thread,
794 "Python was compiled without thread support")
795 def test_gc(self):
796 'Verify that "py-bt" indicates if a thread is garbage-collecting'
797 cmd = ('from gc import collect\n'
798 'id(42)\n'
799 'def foo():\n'
800 ' collect()\n'
801 'def bar():\n'
802 ' foo()\n'
803 'bar()\n')
804 # Verify with "py-bt":
805 gdb_output = self.get_stack_trace(cmd,
806 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
807 )
808 self.assertIn('Garbage-collecting', gdb_output)
809
810 # Verify with "py-bt-full":
811 gdb_output = self.get_stack_trace(cmd,
812 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
813 )
814 self.assertIn('Garbage-collecting', gdb_output)
815
816 @unittest.skipIf(python_is_optimized(),
817 "Python was compiled with optimizations")
818 # Some older versions of gdb will fail with
819 # "Cannot find new threads: generic error"
820 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
821 @unittest.skipUnless(_thread,
822 "Python was compiled without thread support")
823 def test_pycfunction(self):
824 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100825 # Tested function must not be defined with METH_NOARGS or METH_O,
826 # otherwise call_function() doesn't call PyCFunction_Call()
827 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400828 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100829 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400830 'def bar():\n'
831 ' foo()\n'
832 'bar()\n')
833 # Verify with "py-bt":
834 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100835 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400836 cmds_after_breakpoint=['bt', 'py-bt'],
837 )
Victor Stinner79644f92015-03-27 15:42:37 +0100838 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400839
840 # Verify with "py-bt-full":
841 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100842 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400843 cmds_after_breakpoint=['py-bt-full'],
844 )
Victor Stinner79644f92015-03-27 15:42:37 +0100845 self.assertIn('#0 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400846
847
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000848class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100849 @unittest.skipIf(python_is_optimized(),
850 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000851 def test_basic_command(self):
852 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000853 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000854 cmds_after_breakpoint=['py-print args'])
855 self.assertMultilineMatches(bt,
856 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
857
Vinay Sajip2549f872012-01-04 12:07:30 +0000858 @unittest.skipIf(python_is_optimized(),
859 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000860 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000861 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000862 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000863 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
864 self.assertMultilineMatches(bt,
865 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
866
Victor Stinnerd2084162011-12-19 13:42:24 +0100867 @unittest.skipIf(python_is_optimized(),
868 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000869 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000870 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000871 cmds_after_breakpoint=['py-print __name__'])
872 self.assertMultilineMatches(bt,
873 r".*\nglobal '__name__' = '__main__'\n.*")
874
Victor Stinnerd2084162011-12-19 13:42:24 +0100875 @unittest.skipIf(python_is_optimized(),
876 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000877 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000878 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000879 cmds_after_breakpoint=['py-print len'])
880 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100881 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000882
883class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100884 @unittest.skipIf(python_is_optimized(),
885 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000886 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000887 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000888 cmds_after_breakpoint=['py-locals'])
889 self.assertMultilineMatches(bt,
890 r".*\nargs = \(1, 2, 3\)\n.*")
891
Victor Stinner50eb60e2010-04-20 22:32:07 +0000892 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000893 @unittest.skipIf(python_is_optimized(),
894 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000895 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000896 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000897 cmds_after_breakpoint=['py-up', 'py-locals'])
898 self.assertMultilineMatches(bt,
899 r".*\na = 1\nb = 2\nc = 3\n.*")
900
901def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200902 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200903 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200904 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200905 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000906 run_unittest(PrettyPrintTests,
907 PyListTests,
908 StackNavigationTests,
909 PyBtTests,
910 PyPrintTests,
911 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000912 )
913
914if __name__ == "__main__":
915 test_main()