blob: 6c4a34894011f67372124f4f3d093f72fb445d90 [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,
78 stdout=subprocess.PIPE,
79 stderr=subprocess.PIPE,
80 env=env)
81 with proc:
82 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040083 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
84
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000085# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010086gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040087if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000088 raise unittest.SkipTest("gdb not built with embedded python support")
89
Nick Coghlance346872013-09-22 19:38:16 +100090# Verify that "gdb" can load our custom hooks, as OS security settings may
91# disallow this without a customised .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040092cmd = ['--args', sys.executable]
93_, gdbpy_errors = run_gdb('--args', sys.executable)
94if "auto-loading has been declined" in gdbpy_errors:
95 msg = "gdb security settings prevent use of custom hooks: "
96 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100097
Victor Stinner50eb60e2010-04-20 22:32:07 +000098def gdb_has_frame_select():
99 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400100 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
101 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000102 if not m:
103 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400104 gdb_frame_dir = m.group(1).split(', ')
105 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000106
107HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000108
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000109BREAKPOINT_FN='builtin_id'
110
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000111class DebuggerTests(unittest.TestCase):
112
113 """Test that the debugger can debug Python."""
114
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000115 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000116 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000117 cmds_after_breakpoint=None,
118 import_site=False):
119 '''
120 Run 'python -c SOURCE' under gdb with a breakpoint.
121
122 Support injecting commands after the breakpoint is reached
123
124 Returns the stdout from gdb
125
126 cmds_after_breakpoint: if provided, a list of strings: gdb commands
127 '''
128 # We use "set breakpoint pending yes" to avoid blocking with a:
129 # Function "foo" not defined.
130 # Make breakpoint pending on future shared library load? (y or [n])
131 # error, which typically happens python is dynamically linked (the
132 # breakpoints of interest are to be found in the shared library)
133 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000134 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000135 # emitted to stderr each time, alas.
136
137 # Initially I had "--eval-command=continue" here, but removed it to
138 # avoid repeated print breakpoints when traversing hierarchical data
139 # structures
140
141 # Generate a list of commands in gdb's language:
142 commands = ['set breakpoint pending yes',
143 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200144
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200145 # The tests assume that the first frame of printed
146 # backtrace will not contain program counter,
147 # that is however not guaranteed by gdb
148 # therefore we need to use 'set print address off' to
149 # make sure the counter is not there. For example:
150 # #0 in PyObject_Print ...
151 # is assumed, but sometimes this can be e.g.
152 # #0 0x00003fffb7dd1798 in PyObject_Print ...
153 'set print address off',
154
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000155 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200156
157 # GDB as of 7.4 onwards can distinguish between the
158 # value of a variable at entry vs current value:
159 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
160 # which leads to the selftests failing with errors like this:
161 # AssertionError: 'v@entry=()' != '()'
162 # Disable this:
163 if (gdb_major_version, gdb_minor_version) >= (7, 4):
164 commands += ['set print entry-values no']
165
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000166 if cmds_after_breakpoint:
167 commands += cmds_after_breakpoint
168 else:
169 commands += ['backtrace']
170
171 # print commands
172
173 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner7869a4e2014-08-16 14:38:02 +0200174 args = ["gdb", "--batch", "-nx"]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000175 args += ['--eval-command=%s' % cmd for cmd in commands]
176 args += ["--args",
177 sys.executable]
178
179 if not import_site:
180 # -S suppresses the default 'import site'
181 args += ["-S"]
182
183 if source:
184 args += ["-c", source]
185 elif script:
186 args += [script]
187
188 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100189 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000190
191 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100192 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000193
Antoine Pitrou81641d62013-05-01 00:15:44 +0200194 errlines = err.splitlines()
195 unexpected_errlines = []
196
197 # Ignore some benign messages on stderr.
198 ignore_patterns = (
199 'Function "%s" not defined.' % breakpoint,
200 "warning: no loadable sections found in added symbol-file"
201 " system-supplied DSO",
202 "warning: Unable to find libthread_db matching"
203 " inferior's thread library, thread debugging will"
204 " not be available.",
205 "warning: Cannot initialize thread debugging"
206 " library: Debugger service failed",
207 'warning: Could not load shared library symbols for '
208 'linux-vdso.so',
209 'warning: Could not load shared library symbols for '
210 'linux-gate.so',
Serhiy Storchaka6b688d82015-02-14 22:44:35 +0200211 'warning: Could not load shared library symbols for '
212 'linux-vdso64.so',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200213 'Do you need "set solib-search-path" or '
214 '"set sysroot"?',
Victor Stinner5ac1b932013-06-25 21:54:32 +0200215 'warning: Source file is more recent than executable.',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100216 # Issue #19753: missing symbols on System Z
Victor Stinnerf4a48982013-11-24 18:55:25 +0100217 'Missing separate debuginfo for ',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100218 'Try: zypper install -C ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200219 )
220 for line in errlines:
221 if not line.startswith(ignore_patterns):
222 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000223
224 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200225 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000226 return out
227
228 def get_gdb_repr(self, source,
229 cmds_after_breakpoint=None,
230 import_site=False):
231 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000232 # run "python -c'id(DATA)'" under gdb with a breakpoint on
233 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000234 # parameter, and verify that the gdb displays the same string
235 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000236 # Verify that the gdb displays the expected string
237 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000238 # For a nested structure, the first time we hit the breakpoint will
239 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100240
241 # NOTE: avoid decoding too much of the traceback as some
242 # undecodable characters may lurk there in optimized mode
243 # (issue #19743).
244 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000245 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000246 cmds_after_breakpoint=cmds_after_breakpoint,
247 import_site=import_site)
248 # gdb can insert additional '\n' and space characters in various places
249 # in its output, depending on the width of the terminal it's connected
250 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400251 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 +0000252 gdb_output, re.DOTALL)
253 if not m:
254 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
255 return m.group(1), gdb_output
256
257 def assertEndsWith(self, actual, exp_end):
258 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000259 self.assertTrue(actual.endswith(exp_end),
260 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000261
262 def assertMultilineMatches(self, actual, pattern):
263 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000264 if not m:
265 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000267 def get_sample_script(self):
268 return findfile('gdb_sample.py')
269
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000270class PrettyPrintTests(DebuggerTests):
271 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000272 gdb_output = self.get_stack_trace('id(42)')
273 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100275 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000276 # Ensure that gdb's rendering of the value in a debugged process
277 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100278 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000279 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100280 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000281 self.assertEqual(gdb_repr, exp_repr,
282 ('%r did not equal expected %r; full output was:\n%s'
283 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000284
285 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300286 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100287 self.assertGdbRepr(42)
288 self.assertGdbRepr(0)
289 self.assertGdbRepr(-7)
290 self.assertGdbRepr(1000000000000)
291 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000292
293 def test_singletons(self):
294 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100295 self.assertGdbRepr(True)
296 self.assertGdbRepr(False)
297 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000298
299 def test_dicts(self):
300 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100301 self.assertGdbRepr({})
302 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
303 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000304
305 def test_lists(self):
306 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100307 self.assertGdbRepr([])
308 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000309
310 def test_bytes(self):
311 'Verify the pretty-printing of bytes'
312 self.assertGdbRepr(b'')
313 self.assertGdbRepr(b'And now for something hopefully the same')
314 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
315 self.assertGdbRepr(b'this is a tab:\t'
316 b' this is a slash-N:\n'
317 b' this is a slash-R:\r'
318 )
319
320 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
321
322 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000323
324 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000325 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000326 encoding = locale.getpreferredencoding()
327 def check_repr(text):
328 try:
329 text.encode(encoding)
330 printable = True
331 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000332 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000333 else:
334 self.assertGdbRepr(text)
335
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000336 self.assertGdbRepr('')
337 self.assertGdbRepr('And now for something hopefully the same')
338 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000339
340 # Test printing a single character:
341 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000342 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000343
344 # Test printing a Japanese unicode string
345 # (I believe this reads "mojibake", using 3 characters from the CJK
346 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000347 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000348
349 # Test a character outside the BMP:
350 # U+1D121 MUSICAL SYMBOL C CLEF
351 # This is:
352 # UTF-8: 0xF0 0x9D 0x84 0xA1
353 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000354 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000355
356 def test_tuples(self):
357 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100358 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000359 self.assertGdbRepr((1,), '(1,)')
360 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000361
362 def test_sets(self):
363 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200364 if (gdb_major_version, gdb_minor_version) < (7, 3):
365 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100366 self.assertGdbRepr(set(), 'set()')
367 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
368 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000369
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000370 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000371 # which happens on deletion:
372 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100373s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000374id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000375 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000376
377 def test_frozensets(self):
378 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200379 if (gdb_major_version, gdb_minor_version) < (7, 3):
380 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100381 self.assertGdbRepr(frozenset(), 'frozenset()')
382 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
383 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000384
385 def test_exceptions(self):
386 # Test a RuntimeError
387 gdb_repr, gdb_output = self.get_gdb_repr('''
388try:
389 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000390except RuntimeError as e:
391 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000392''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000393 self.assertEqual(gdb_repr,
394 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000395
396
397 # Test division by zero:
398 gdb_repr, gdb_output = self.get_gdb_repr('''
399try:
400 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000401except ZeroDivisionError as e:
402 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000403''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000404 self.assertEqual(gdb_repr,
405 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000406
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407 def test_modern_class(self):
408 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000409 gdb_repr, gdb_output = self.get_gdb_repr('''
410class Foo:
411 pass
412foo = Foo()
413foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000414id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100415 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000416 self.assertTrue(m,
417 msg='Unexpected new-style class rendering %r' % gdb_repr)
418
419 def test_subclassing_list(self):
420 'Verify the pretty-printing of an instance of a list subclass'
421 gdb_repr, gdb_output = self.get_gdb_repr('''
422class Foo(list):
423 pass
424foo = Foo()
425foo += [1, 2, 3]
426foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000427id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100428 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 +0000429
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000430 self.assertTrue(m,
431 msg='Unexpected new-style class rendering %r' % gdb_repr)
432
433 def test_subclassing_tuple(self):
434 'Verify the pretty-printing of an instance of a tuple subclass'
435 # This should exercise the negative tp_dictoffset code in the
436 # new-style class support
437 gdb_repr, gdb_output = self.get_gdb_repr('''
438class Foo(tuple):
439 pass
440foo = Foo((1, 2, 3))
441foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000442id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100443 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 +0000444
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000445 self.assertTrue(m,
446 msg='Unexpected new-style class rendering %r' % gdb_repr)
447
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000448 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000449 '''Run Python under gdb, corrupting variables in the inferior process
450 immediately before taking a backtrace.
451
452 Verify that the variable's representation is the expected failsafe
453 representation'''
454 if corruption:
455 cmds_after_breakpoint=[corruption, 'backtrace']
456 else:
457 cmds_after_breakpoint=['backtrace']
458
459 gdb_repr, gdb_output = \
460 self.get_gdb_repr(source,
461 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000462 if exprepr:
463 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000464 # gdb managed to print the value in spite of the corruption;
465 # this is good (see http://bugs.python.org/issue8330)
466 return
467
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000468 # Match anything for the type name; 0xDEADBEEF could point to
469 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100470 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000471
472 m = re.match(pattern, gdb_repr)
473 if not m:
474 self.fail('Unexpected gdb representation: %r\n%s' % \
475 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000476
477 def test_NULL_ptr(self):
478 'Ensure that a NULL PyObject* is handled gracefully'
479 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000480 self.get_gdb_repr('id(42)',
481 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000482 'backtrace'])
483 )
484
Ezio Melottib3aedd42010-11-20 19:04:17 +0000485 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000486
487 def test_NULL_ob_type(self):
488 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000489 self.assertSane('id(42)',
490 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000491
492 def test_corrupt_ob_type(self):
493 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000494 self.assertSane('id(42)',
495 'set v->ob_type=0xDEADBEEF',
496 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000497
498 def test_corrupt_tp_flags(self):
499 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000500 self.assertSane('id(42)',
501 'set v->ob_type->tp_flags=0x0',
502 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000503
504 def test_corrupt_tp_name(self):
505 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000506 self.assertSane('id(42)',
507 'set v->ob_type->tp_name=0xDEADBEEF',
508 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000509
510 def test_builtins_help(self):
511 'Ensure that the new-style class _Helper in site.py can be handled'
512 # (this was the issue causing tracebacks in
513 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000514 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000515
Antoine Pitrou4d098732011-11-26 01:42:03 +0100516 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000517 self.assertTrue(m,
518 msg='Unexpected rendering %r' % gdb_repr)
519
520 def test_selfreferential_list(self):
521 '''Ensure that a reference loop involving a list doesn't lead proxyval
522 into an infinite loop:'''
523 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000524 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000525 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000526
527 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000528 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000529 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000530
531 def test_selfreferential_dict(self):
532 '''Ensure that a reference loop involving a dict doesn't lead proxyval
533 into an infinite loop:'''
534 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000535 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000536
Ezio Melottib3aedd42010-11-20 19:04:17 +0000537 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000538
539 def test_selfreferential_old_style_instance(self):
540 gdb_repr, gdb_output = \
541 self.get_gdb_repr('''
542class Foo:
543 pass
544foo = Foo()
545foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000546id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100547 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000548 gdb_repr),
549 'Unexpected gdb representation: %r\n%s' % \
550 (gdb_repr, gdb_output))
551
552 def test_selfreferential_new_style_instance(self):
553 gdb_repr, gdb_output = \
554 self.get_gdb_repr('''
555class Foo(object):
556 pass
557foo = Foo()
558foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000559id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100560 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000561 gdb_repr),
562 'Unexpected gdb representation: %r\n%s' % \
563 (gdb_repr, gdb_output))
564
565 gdb_repr, gdb_output = \
566 self.get_gdb_repr('''
567class Foo(object):
568 pass
569a = Foo()
570b = Foo()
571a.an_attr = b
572b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000573id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100574 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 +0000575 gdb_repr),
576 'Unexpected gdb representation: %r\n%s' % \
577 (gdb_repr, gdb_output))
578
579 def test_truncation(self):
580 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000581 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000582 self.assertEqual(gdb_repr,
583 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
584 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
585 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
586 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
587 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
588 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
589 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
590 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
591 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
592 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
593 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
594 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
595 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
596 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
597 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
598 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
599 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
600 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
601 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
602 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
603 "224, 225, 226...(truncated)")
604 self.assertEqual(len(gdb_repr),
605 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000606
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000607 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000608 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100609 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 +0000610 gdb_repr),
611 'Unexpected gdb representation: %r\n%s' % \
612 (gdb_repr, gdb_output))
613
614 def test_frames(self):
615 gdb_output = self.get_stack_trace('''
616def foo(a, b, c):
617 pass
618
619foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000620id(foo.__code__)''',
621 breakpoint='builtin_id',
622 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000623 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100624 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 +0000625 gdb_output,
626 re.DOTALL),
627 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
628
Victor Stinnerd2084162011-12-19 13:42:24 +0100629@unittest.skipIf(python_is_optimized(),
630 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000631class PyListTests(DebuggerTests):
632 def assertListing(self, expected, actual):
633 self.assertEndsWith(actual, expected)
634
635 def test_basic_command(self):
636 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000637 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000638 cmds_after_breakpoint=['py-list'])
639
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000640 self.assertListing(' 5 \n'
641 ' 6 def bar(a, b, c):\n'
642 ' 7 baz(a, b, c)\n'
643 ' 8 \n'
644 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000645 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000646 ' 11 \n'
647 ' 12 foo(1, 2, 3)\n',
648 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000649
650 def test_one_abs_arg(self):
651 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000652 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000653 cmds_after_breakpoint=['py-list 9'])
654
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000655 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000656 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000657 ' 11 \n'
658 ' 12 foo(1, 2, 3)\n',
659 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000660
661 def test_two_abs_args(self):
662 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000663 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000664 cmds_after_breakpoint=['py-list 1,3'])
665
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000666 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
667 ' 2 \n'
668 ' 3 def foo(a, b, c):\n',
669 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000670
671class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000672 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100673 @unittest.skipIf(python_is_optimized(),
674 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000675 def test_pyup_command(self):
676 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000677 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 cmds_after_breakpoint=['py-up'])
679 self.assertMultilineMatches(bt,
680 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100681#[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 +0000682 baz\(a, b, c\)
683$''')
684
Victor Stinner50eb60e2010-04-20 22:32:07 +0000685 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000686 def test_down_at_bottom(self):
687 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000688 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689 cmds_after_breakpoint=['py-down'])
690 self.assertEndsWith(bt,
691 'Unable to find a newer python frame\n')
692
Victor Stinner50eb60e2010-04-20 22:32:07 +0000693 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000694 def test_up_at_top(self):
695 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000696 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000697 cmds_after_breakpoint=['py-up'] * 4)
698 self.assertEndsWith(bt,
699 'Unable to find an older python frame\n')
700
Victor Stinner50eb60e2010-04-20 22:32:07 +0000701 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100702 @unittest.skipIf(python_is_optimized(),
703 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000704 def test_up_then_down(self):
705 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000706 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000707 cmds_after_breakpoint=['py-up', 'py-down'])
708 self.assertMultilineMatches(bt,
709 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100710#[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 +0000711 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100712#[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 +0000713 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000714$''')
715
716class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100717 @unittest.skipIf(python_is_optimized(),
718 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200719 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000720 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000721 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000722 cmds_after_breakpoint=['py-bt'])
723 self.assertMultilineMatches(bt,
724 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200725Traceback \(most recent call first\):
726 File ".*gdb_sample.py", line 10, in baz
727 id\(42\)
728 File ".*gdb_sample.py", line 7, in bar
729 baz\(a, b, c\)
730 File ".*gdb_sample.py", line 4, in foo
731 bar\(a, b, c\)
732 File ".*gdb_sample.py", line 12, in <module>
733 foo\(1, 2, 3\)
734''')
735
Victor Stinnerd2084162011-12-19 13:42:24 +0100736 @unittest.skipIf(python_is_optimized(),
737 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200738 def test_bt_full(self):
739 'Verify that the "py-bt-full" command works'
740 bt = self.get_stack_trace(script=self.get_sample_script(),
741 cmds_after_breakpoint=['py-bt-full'])
742 self.assertMultilineMatches(bt,
743 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100744#[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 +0000745 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100746#[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 +0000747 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100748#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100749 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000750''')
751
David Malcolm8d37ffa2012-06-27 14:15:34 -0400752 @unittest.skipUnless(_thread,
753 "Python was compiled without thread support")
754 def test_threads(self):
755 'Verify that "py-bt" indicates threads that are waiting for the GIL'
756 cmd = '''
757from threading import Thread
758
759class TestThread(Thread):
760 # These threads would run forever, but we'll interrupt things with the
761 # debugger
762 def run(self):
763 i = 0
764 while 1:
765 i += 1
766
767t = {}
768for i in range(4):
769 t[i] = TestThread()
770 t[i].start()
771
772# Trigger a breakpoint on the main thread
773id(42)
774
775'''
776 # Verify with "py-bt":
777 gdb_output = self.get_stack_trace(cmd,
778 cmds_after_breakpoint=['thread apply all py-bt'])
779 self.assertIn('Waiting for the GIL', gdb_output)
780
781 # Verify with "py-bt-full":
782 gdb_output = self.get_stack_trace(cmd,
783 cmds_after_breakpoint=['thread apply all py-bt-full'])
784 self.assertIn('Waiting for the GIL', gdb_output)
785
786 @unittest.skipIf(python_is_optimized(),
787 "Python was compiled with optimizations")
788 # Some older versions of gdb will fail with
789 # "Cannot find new threads: generic error"
790 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
791 @unittest.skipUnless(_thread,
792 "Python was compiled without thread support")
793 def test_gc(self):
794 'Verify that "py-bt" indicates if a thread is garbage-collecting'
795 cmd = ('from gc import collect\n'
796 'id(42)\n'
797 'def foo():\n'
798 ' collect()\n'
799 'def bar():\n'
800 ' foo()\n'
801 'bar()\n')
802 # Verify with "py-bt":
803 gdb_output = self.get_stack_trace(cmd,
804 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
805 )
806 self.assertIn('Garbage-collecting', gdb_output)
807
808 # Verify with "py-bt-full":
809 gdb_output = self.get_stack_trace(cmd,
810 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
811 )
812 self.assertIn('Garbage-collecting', gdb_output)
813
814 @unittest.skipIf(python_is_optimized(),
815 "Python was compiled with optimizations")
816 # Some older versions of gdb will fail with
817 # "Cannot find new threads: generic error"
818 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
819 @unittest.skipUnless(_thread,
820 "Python was compiled without thread support")
821 def test_pycfunction(self):
822 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100823 # Tested function must not be defined with METH_NOARGS or METH_O,
824 # otherwise call_function() doesn't call PyCFunction_Call()
825 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400826 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100827 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400828 'def bar():\n'
829 ' foo()\n'
830 'bar()\n')
831 # Verify with "py-bt":
832 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100833 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400834 cmds_after_breakpoint=['bt', 'py-bt'],
835 )
Victor Stinner79644f92015-03-27 15:42:37 +0100836 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400837
838 # Verify with "py-bt-full":
839 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100840 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400841 cmds_after_breakpoint=['py-bt-full'],
842 )
Victor Stinner79644f92015-03-27 15:42:37 +0100843 self.assertIn('#0 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400844
845
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000846class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100847 @unittest.skipIf(python_is_optimized(),
848 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000849 def test_basic_command(self):
850 'Verify that the "py-print" command works'
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-print args'])
853 self.assertMultilineMatches(bt,
854 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
855
Vinay Sajip2549f872012-01-04 12:07:30 +0000856 @unittest.skipIf(python_is_optimized(),
857 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000858 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000859 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000860 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000861 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
862 self.assertMultilineMatches(bt,
863 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
864
Victor Stinnerd2084162011-12-19 13:42:24 +0100865 @unittest.skipIf(python_is_optimized(),
866 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000867 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000868 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000869 cmds_after_breakpoint=['py-print __name__'])
870 self.assertMultilineMatches(bt,
871 r".*\nglobal '__name__' = '__main__'\n.*")
872
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_printing_builtin(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-print len'])
878 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100879 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000880
881class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100882 @unittest.skipIf(python_is_optimized(),
883 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000884 def test_basic_command(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-locals'])
887 self.assertMultilineMatches(bt,
888 r".*\nargs = \(1, 2, 3\)\n.*")
889
Victor Stinner50eb60e2010-04-20 22:32:07 +0000890 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000891 @unittest.skipIf(python_is_optimized(),
892 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000893 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000894 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000895 cmds_after_breakpoint=['py-up', 'py-locals'])
896 self.assertMultilineMatches(bt,
897 r".*\na = 1\nb = 2\nc = 3\n.*")
898
899def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200900 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200901 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200902 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200903 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000904 run_unittest(PrettyPrintTests,
905 PyListTests,
906 StackNavigationTests,
907 PyBtTests,
908 PyPrintTests,
909 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000910 )
911
912if __name__ == "__main__":
913 test_main()