blob: ff651903e91815f32a3da8ed30e4edd78ac68278 [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
8import subprocess
9import sys
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010010import sysconfig
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000011import unittest
Victor Stinner150016f2010-05-19 23:04:56 +000012import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000013
Victor Stinner742da042016-09-07 17:40:12 -070014# FIXME: issue #28023
15raise unittest.SkipTest("FIXME: issue #28023, compact dict (issue #27350) broke python-gdb.py")
16
David Malcolm8d37ffa2012-06-27 14:15:34 -040017# Is this Python configured to support threads?
18try:
19 import _thread
20except ImportError:
21 _thread = None
22
Antoine Pitroud0f3e072013-09-21 23:56:17 +020023from test import support
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000024from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000025
Victor Stinner5b6b4a82015-09-02 23:19:55 +020026def get_gdb_version():
27 try:
28 proc = subprocess.Popen(["gdb", "-nx", "--version"],
29 stdout=subprocess.PIPE,
Benjamin Petersoncbef66d2016-09-06 10:06:31 -070030 stderr=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020031 universal_newlines=True)
32 with proc:
33 version = proc.communicate()[0]
34 except OSError:
35 # This is what "no gdb" looks like. There may, however, be other
36 # errors that manifest this way too.
37 raise unittest.SkipTest("Couldn't find gdb on the path")
38
39 # Regex to parse:
40 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
41 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020042 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
43 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnera578eb32015-09-15 00:22:55 +020044 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020045 if match is None:
46 raise Exception("unable to parse GDB version: %r" % version)
47 return (version, int(match.group(1)), int(match.group(2)))
48
49gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040050if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020051 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
52 "embedding. Saw %s.%s:\n%s"
53 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020054 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000055
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010056if not sysconfig.is_python_build():
57 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
58
R David Murrayf9333022012-10-27 13:22:41 -040059# Location of custom hooks file in a repository checkout.
60checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
61 'python-gdb.py')
62
Victor Stinner51324932013-11-20 12:27:48 +010063PYTHONHASHSEED = '123'
64
R David Murrayf9333022012-10-27 13:22:41 -040065def run_gdb(*args, **env_vars):
66 """Runs gdb in --batch mode with the additional arguments given by *args.
67
68 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
69 """
70 if env_vars:
71 env = os.environ.copy()
72 env.update(env_vars)
73 else:
74 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020075 # -nx: Do not execute commands from any .gdbinit initialization files
76 # (issue #22188)
77 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040078 if (gdb_major_version, gdb_minor_version) >= (7, 4):
79 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020080 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000081 # Redirect stdin to prevent GDB from messing with
82 # the terminal settings
83 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020084 stdout=subprocess.PIPE,
85 stderr=subprocess.PIPE,
86 env=env)
87 with proc:
88 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040089 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
90
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000091# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010092gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040093if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000094 raise unittest.SkipTest("gdb not built with embedded python support")
95
Nick Coghlance346872013-09-22 19:38:16 +100096# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -070097# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040098_, gdbpy_errors = run_gdb('--args', sys.executable)
99if "auto-loading has been declined" in gdbpy_errors:
100 msg = "gdb security settings prevent use of custom hooks: "
101 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000102
Victor Stinner50eb60e2010-04-20 22:32:07 +0000103def gdb_has_frame_select():
104 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400105 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
106 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000107 if not m:
108 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400109 gdb_frame_dir = m.group(1).split(', ')
110 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000111
112HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000113
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000114BREAKPOINT_FN='builtin_id'
115
Benjamin Peterson437df902016-09-06 20:22:41 -0700116@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000117class DebuggerTests(unittest.TestCase):
118
119 """Test that the debugger can debug Python."""
120
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000121 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000122 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000123 cmds_after_breakpoint=None,
124 import_site=False):
125 '''
126 Run 'python -c SOURCE' under gdb with a breakpoint.
127
128 Support injecting commands after the breakpoint is reached
129
130 Returns the stdout from gdb
131
132 cmds_after_breakpoint: if provided, a list of strings: gdb commands
133 '''
134 # We use "set breakpoint pending yes" to avoid blocking with a:
135 # Function "foo" not defined.
136 # Make breakpoint pending on future shared library load? (y or [n])
137 # error, which typically happens python is dynamically linked (the
138 # breakpoints of interest are to be found in the shared library)
139 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000140 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000141 # emitted to stderr each time, alas.
142
143 # Initially I had "--eval-command=continue" here, but removed it to
144 # avoid repeated print breakpoints when traversing hierarchical data
145 # structures
146
147 # Generate a list of commands in gdb's language:
148 commands = ['set breakpoint pending yes',
149 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200150
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200151 # The tests assume that the first frame of printed
152 # backtrace will not contain program counter,
153 # that is however not guaranteed by gdb
154 # therefore we need to use 'set print address off' to
155 # make sure the counter is not there. For example:
156 # #0 in PyObject_Print ...
157 # is assumed, but sometimes this can be e.g.
158 # #0 0x00003fffb7dd1798 in PyObject_Print ...
159 'set print address off',
160
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000161 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200162
163 # GDB as of 7.4 onwards can distinguish between the
164 # value of a variable at entry vs current value:
165 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
166 # which leads to the selftests failing with errors like this:
167 # AssertionError: 'v@entry=()' != '()'
168 # Disable this:
169 if (gdb_major_version, gdb_minor_version) >= (7, 4):
170 commands += ['set print entry-values no']
171
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000172 if cmds_after_breakpoint:
173 commands += cmds_after_breakpoint
174 else:
175 commands += ['backtrace']
176
177 # print commands
178
179 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000180 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000181 args += ["--args",
182 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100183 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000184
185 if not import_site:
186 # -S suppresses the default 'import site'
187 args += ["-S"]
188
189 if source:
190 args += ["-c", source]
191 elif script:
192 args += [script]
193
194 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100195 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000196
197 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100198 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000199
Antoine Pitrou81641d62013-05-01 00:15:44 +0200200 errlines = err.splitlines()
201 unexpected_errlines = []
202
203 # Ignore some benign messages on stderr.
204 ignore_patterns = (
205 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200206 'Do you need "set solib-search-path" or '
207 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100208 # BFD: /usr/lib/debug/(...): unable to initialize decompress
209 # status for section .debug_aranges
210 'BFD: ',
211 # ignore all warnings
212 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200213 )
214 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100215 if not line:
216 continue
Antoine Pitrou81641d62013-05-01 00:15:44 +0200217 if not line.startswith(ignore_patterns):
218 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000219
220 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200221 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000222 return out
223
224 def get_gdb_repr(self, source,
225 cmds_after_breakpoint=None,
226 import_site=False):
227 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000228 # run "python -c'id(DATA)'" under gdb with a breakpoint on
229 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000230 # parameter, and verify that the gdb displays the same string
231 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000232 # Verify that the gdb displays the expected string
233 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000234 # For a nested structure, the first time we hit the breakpoint will
235 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100236
237 # NOTE: avoid decoding too much of the traceback as some
238 # undecodable characters may lurk there in optimized mode
239 # (issue #19743).
240 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000241 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000242 cmds_after_breakpoint=cmds_after_breakpoint,
243 import_site=import_site)
244 # gdb can insert additional '\n' and space characters in various places
245 # in its output, depending on the width of the terminal it's connected
246 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400247 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 +0000248 gdb_output, re.DOTALL)
249 if not m:
250 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
251 return m.group(1), gdb_output
252
253 def assertEndsWith(self, actual, exp_end):
254 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000255 self.assertTrue(actual.endswith(exp_end),
256 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000257
258 def assertMultilineMatches(self, actual, pattern):
259 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000260 if not m:
261 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000263 def get_sample_script(self):
264 return findfile('gdb_sample.py')
265
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266class PrettyPrintTests(DebuggerTests):
267 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000268 gdb_output = self.get_stack_trace('id(42)')
269 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000270
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100271 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000272 # Ensure that gdb's rendering of the value in a debugged process
273 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100274 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000275 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100276 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000277 self.assertEqual(gdb_repr, exp_repr,
278 ('%r did not equal expected %r; full output was:\n%s'
279 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000280
281 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300282 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100283 self.assertGdbRepr(42)
284 self.assertGdbRepr(0)
285 self.assertGdbRepr(-7)
286 self.assertGdbRepr(1000000000000)
287 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000288
289 def test_singletons(self):
290 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100291 self.assertGdbRepr(True)
292 self.assertGdbRepr(False)
293 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000294
295 def test_dicts(self):
296 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100297 self.assertGdbRepr({})
298 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
Victor Stinner22756f12016-01-22 14:16:47 +0100299 # PYTHONHASHSEED is need to get the exact item order
300 if not sys.flags.ignore_environment:
301 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000302
303 def test_lists(self):
304 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100305 self.assertGdbRepr([])
306 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000307
308 def test_bytes(self):
309 'Verify the pretty-printing of bytes'
310 self.assertGdbRepr(b'')
311 self.assertGdbRepr(b'And now for something hopefully the same')
312 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
313 self.assertGdbRepr(b'this is a tab:\t'
314 b' this is a slash-N:\n'
315 b' this is a slash-R:\r'
316 )
317
318 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
319
320 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000321
322 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000323 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000324 encoding = locale.getpreferredencoding()
325 def check_repr(text):
326 try:
327 text.encode(encoding)
328 printable = True
329 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000330 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000331 else:
332 self.assertGdbRepr(text)
333
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000334 self.assertGdbRepr('')
335 self.assertGdbRepr('And now for something hopefully the same')
336 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000337
338 # Test printing a single character:
339 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000340 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000341
342 # Test printing a Japanese unicode string
343 # (I believe this reads "mojibake", using 3 characters from the CJK
344 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000345 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000346
347 # Test a character outside the BMP:
348 # U+1D121 MUSICAL SYMBOL C CLEF
349 # This is:
350 # UTF-8: 0xF0 0x9D 0x84 0xA1
351 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000352 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000353
354 def test_tuples(self):
355 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100356 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000357 self.assertGdbRepr((1,), '(1,)')
358 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000359
360 def test_sets(self):
361 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200362 if (gdb_major_version, gdb_minor_version) < (7, 3):
363 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100364 self.assertGdbRepr(set(), "set()")
365 self.assertGdbRepr(set(['a']), "{'a'}")
366 # PYTHONHASHSEED is need to get the exact frozenset item order
367 if not sys.flags.ignore_environment:
368 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
369 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000370
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000371 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000372 # which happens on deletion:
373 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100374s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000375id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000376 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000377
378 def test_frozensets(self):
379 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200380 if (gdb_major_version, gdb_minor_version) < (7, 3):
381 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100382 self.assertGdbRepr(frozenset(), "frozenset()")
383 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
384 # PYTHONHASHSEED is need to get the exact frozenset item order
385 if not sys.flags.ignore_environment:
386 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
387 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000388
389 def test_exceptions(self):
390 # Test a RuntimeError
391 gdb_repr, gdb_output = self.get_gdb_repr('''
392try:
393 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000394except RuntimeError as e:
395 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000396''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000397 self.assertEqual(gdb_repr,
398 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000399
400
401 # Test division by zero:
402 gdb_repr, gdb_output = self.get_gdb_repr('''
403try:
404 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000405except ZeroDivisionError as e:
406 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000407''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000408 self.assertEqual(gdb_repr,
409 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000411 def test_modern_class(self):
412 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000413 gdb_repr, gdb_output = self.get_gdb_repr('''
414class Foo:
415 pass
416foo = Foo()
417foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000418id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100419 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000420 self.assertTrue(m,
421 msg='Unexpected new-style class rendering %r' % gdb_repr)
422
423 def test_subclassing_list(self):
424 'Verify the pretty-printing of an instance of a list subclass'
425 gdb_repr, gdb_output = self.get_gdb_repr('''
426class Foo(list):
427 pass
428foo = Foo()
429foo += [1, 2, 3]
430foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000431id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100432 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 +0000433
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000434 self.assertTrue(m,
435 msg='Unexpected new-style class rendering %r' % gdb_repr)
436
437 def test_subclassing_tuple(self):
438 'Verify the pretty-printing of an instance of a tuple subclass'
439 # This should exercise the negative tp_dictoffset code in the
440 # new-style class support
441 gdb_repr, gdb_output = self.get_gdb_repr('''
442class Foo(tuple):
443 pass
444foo = Foo((1, 2, 3))
445foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000446id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100447 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 +0000448
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000449 self.assertTrue(m,
450 msg='Unexpected new-style class rendering %r' % gdb_repr)
451
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000452 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000453 '''Run Python under gdb, corrupting variables in the inferior process
454 immediately before taking a backtrace.
455
456 Verify that the variable's representation is the expected failsafe
457 representation'''
458 if corruption:
459 cmds_after_breakpoint=[corruption, 'backtrace']
460 else:
461 cmds_after_breakpoint=['backtrace']
462
463 gdb_repr, gdb_output = \
464 self.get_gdb_repr(source,
465 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000466 if exprepr:
467 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000468 # gdb managed to print the value in spite of the corruption;
469 # this is good (see http://bugs.python.org/issue8330)
470 return
471
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000472 # Match anything for the type name; 0xDEADBEEF could point to
473 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100474 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000475
476 m = re.match(pattern, gdb_repr)
477 if not m:
478 self.fail('Unexpected gdb representation: %r\n%s' % \
479 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000480
481 def test_NULL_ptr(self):
482 'Ensure that a NULL PyObject* is handled gracefully'
483 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000484 self.get_gdb_repr('id(42)',
485 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000486 'backtrace'])
487 )
488
Ezio Melottib3aedd42010-11-20 19:04:17 +0000489 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000490
491 def test_NULL_ob_type(self):
492 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000493 self.assertSane('id(42)',
494 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000495
496 def test_corrupt_ob_type(self):
497 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000498 self.assertSane('id(42)',
499 'set v->ob_type=0xDEADBEEF',
500 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000501
502 def test_corrupt_tp_flags(self):
503 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504 self.assertSane('id(42)',
505 'set v->ob_type->tp_flags=0x0',
506 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000507
508 def test_corrupt_tp_name(self):
509 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000510 self.assertSane('id(42)',
511 'set v->ob_type->tp_name=0xDEADBEEF',
512 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000513
514 def test_builtins_help(self):
515 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100516
517 if sys.flags.no_site:
518 self.skipTest("need site module, but -S option was used")
519
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520 # (this was the issue causing tracebacks in
521 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000522 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000523
Antoine Pitrou4d098732011-11-26 01:42:03 +0100524 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000525 self.assertTrue(m,
526 msg='Unexpected rendering %r' % gdb_repr)
527
528 def test_selfreferential_list(self):
529 '''Ensure that a reference loop involving a list doesn't lead proxyval
530 into an infinite loop:'''
531 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000532 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000533 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000534
535 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000536 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000537 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000538
539 def test_selfreferential_dict(self):
540 '''Ensure that a reference loop involving a dict doesn't lead proxyval
541 into an infinite loop:'''
542 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000543 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000544
Ezio Melottib3aedd42010-11-20 19:04:17 +0000545 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000546
547 def test_selfreferential_old_style_instance(self):
548 gdb_repr, gdb_output = \
549 self.get_gdb_repr('''
550class Foo:
551 pass
552foo = Foo()
553foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000554id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100555 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000556 gdb_repr),
557 'Unexpected gdb representation: %r\n%s' % \
558 (gdb_repr, gdb_output))
559
560 def test_selfreferential_new_style_instance(self):
561 gdb_repr, gdb_output = \
562 self.get_gdb_repr('''
563class Foo(object):
564 pass
565foo = Foo()
566foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000567id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100568 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000569 gdb_repr),
570 'Unexpected gdb representation: %r\n%s' % \
571 (gdb_repr, gdb_output))
572
573 gdb_repr, gdb_output = \
574 self.get_gdb_repr('''
575class Foo(object):
576 pass
577a = Foo()
578b = Foo()
579a.an_attr = b
580b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000581id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100582 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 +0000583 gdb_repr),
584 'Unexpected gdb representation: %r\n%s' % \
585 (gdb_repr, gdb_output))
586
587 def test_truncation(self):
588 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000589 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000590 self.assertEqual(gdb_repr,
591 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
592 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
593 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
594 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
595 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
596 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
597 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
598 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
599 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
600 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
601 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
602 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
603 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
604 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
605 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
606 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
607 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
608 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
609 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
610 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
611 "224, 225, 226...(truncated)")
612 self.assertEqual(len(gdb_repr),
613 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000614
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000615 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000616 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100617 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 +0000618 gdb_repr),
619 'Unexpected gdb representation: %r\n%s' % \
620 (gdb_repr, gdb_output))
621
622 def test_frames(self):
623 gdb_output = self.get_stack_trace('''
624def foo(a, b, c):
625 pass
626
627foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000628id(foo.__code__)''',
629 breakpoint='builtin_id',
630 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000631 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100632 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 +0000633 gdb_output,
634 re.DOTALL),
635 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
636
Victor Stinnerd2084162011-12-19 13:42:24 +0100637@unittest.skipIf(python_is_optimized(),
638 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000639class PyListTests(DebuggerTests):
640 def assertListing(self, expected, actual):
641 self.assertEndsWith(actual, expected)
642
643 def test_basic_command(self):
644 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000645 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000646 cmds_after_breakpoint=['py-list'])
647
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000648 self.assertListing(' 5 \n'
649 ' 6 def bar(a, b, c):\n'
650 ' 7 baz(a, b, c)\n'
651 ' 8 \n'
652 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000653 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000654 ' 11 \n'
655 ' 12 foo(1, 2, 3)\n',
656 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000657
658 def test_one_abs_arg(self):
659 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000660 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000661 cmds_after_breakpoint=['py-list 9'])
662
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000663 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000664 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000665 ' 11 \n'
666 ' 12 foo(1, 2, 3)\n',
667 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000668
669 def test_two_abs_args(self):
670 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000671 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000672 cmds_after_breakpoint=['py-list 1,3'])
673
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000674 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
675 ' 2 \n'
676 ' 3 def foo(a, b, c):\n',
677 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678
679class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000680 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100681 @unittest.skipIf(python_is_optimized(),
682 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000683 def test_pyup_command(self):
684 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000685 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000686 cmds_after_breakpoint=['py-up'])
687 self.assertMultilineMatches(bt,
688 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100689#[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 +0000690 baz\(a, b, c\)
691$''')
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_down_at_bottom(self):
695 'Verify handling of "py-down" at the bottom 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-down'])
698 self.assertEndsWith(bt,
699 'Unable to find a newer python frame\n')
700
Victor Stinner50eb60e2010-04-20 22:32:07 +0000701 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000702 def test_up_at_top(self):
703 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000704 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000705 cmds_after_breakpoint=['py-up'] * 4)
706 self.assertEndsWith(bt,
707 'Unable to find an older python frame\n')
708
Victor Stinner50eb60e2010-04-20 22:32:07 +0000709 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100710 @unittest.skipIf(python_is_optimized(),
711 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000712 def test_up_then_down(self):
713 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000714 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000715 cmds_after_breakpoint=['py-up', 'py-down'])
716 self.assertMultilineMatches(bt,
717 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100718#[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 +0000719 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100720#[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 +0000721 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000722$''')
723
724class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100725 @unittest.skipIf(python_is_optimized(),
726 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200727 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000728 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000729 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000730 cmds_after_breakpoint=['py-bt'])
731 self.assertMultilineMatches(bt,
732 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200733Traceback \(most recent call first\):
734 File ".*gdb_sample.py", line 10, in baz
735 id\(42\)
736 File ".*gdb_sample.py", line 7, in bar
737 baz\(a, b, c\)
738 File ".*gdb_sample.py", line 4, in foo
739 bar\(a, b, c\)
740 File ".*gdb_sample.py", line 12, in <module>
741 foo\(1, 2, 3\)
742''')
743
Victor Stinnerd2084162011-12-19 13:42:24 +0100744 @unittest.skipIf(python_is_optimized(),
745 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200746 def test_bt_full(self):
747 'Verify that the "py-bt-full" command works'
748 bt = self.get_stack_trace(script=self.get_sample_script(),
749 cmds_after_breakpoint=['py-bt-full'])
750 self.assertMultilineMatches(bt,
751 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100752#[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 +0000753 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100754#[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 +0000755 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100756#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100757 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000758''')
759
David Malcolm8d37ffa2012-06-27 14:15:34 -0400760 @unittest.skipUnless(_thread,
761 "Python was compiled without thread support")
762 def test_threads(self):
763 'Verify that "py-bt" indicates threads that are waiting for the GIL'
764 cmd = '''
765from threading import Thread
766
767class TestThread(Thread):
768 # These threads would run forever, but we'll interrupt things with the
769 # debugger
770 def run(self):
771 i = 0
772 while 1:
773 i += 1
774
775t = {}
776for i in range(4):
777 t[i] = TestThread()
778 t[i].start()
779
780# Trigger a breakpoint on the main thread
781id(42)
782
783'''
784 # Verify with "py-bt":
785 gdb_output = self.get_stack_trace(cmd,
786 cmds_after_breakpoint=['thread apply all py-bt'])
787 self.assertIn('Waiting for the GIL', gdb_output)
788
789 # Verify with "py-bt-full":
790 gdb_output = self.get_stack_trace(cmd,
791 cmds_after_breakpoint=['thread apply all py-bt-full'])
792 self.assertIn('Waiting for the GIL', gdb_output)
793
794 @unittest.skipIf(python_is_optimized(),
795 "Python was compiled with optimizations")
796 # Some older versions of gdb will fail with
797 # "Cannot find new threads: generic error"
798 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
799 @unittest.skipUnless(_thread,
800 "Python was compiled without thread support")
801 def test_gc(self):
802 'Verify that "py-bt" indicates if a thread is garbage-collecting'
803 cmd = ('from gc import collect\n'
804 'id(42)\n'
805 'def foo():\n'
806 ' collect()\n'
807 'def bar():\n'
808 ' foo()\n'
809 'bar()\n')
810 # Verify with "py-bt":
811 gdb_output = self.get_stack_trace(cmd,
812 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
813 )
814 self.assertIn('Garbage-collecting', gdb_output)
815
816 # Verify with "py-bt-full":
817 gdb_output = self.get_stack_trace(cmd,
818 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
819 )
820 self.assertIn('Garbage-collecting', gdb_output)
821
822 @unittest.skipIf(python_is_optimized(),
823 "Python was compiled with optimizations")
824 # Some older versions of gdb will fail with
825 # "Cannot find new threads: generic error"
826 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
827 @unittest.skipUnless(_thread,
828 "Python was compiled without thread support")
829 def test_pycfunction(self):
830 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100831 # Tested function must not be defined with METH_NOARGS or METH_O,
832 # otherwise call_function() doesn't call PyCFunction_Call()
833 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400834 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100835 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400836 'def bar():\n'
837 ' foo()\n'
838 'bar()\n')
839 # Verify with "py-bt":
840 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100841 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400842 cmds_after_breakpoint=['bt', 'py-bt'],
843 )
Victor Stinner79644f92015-03-27 15:42:37 +0100844 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400845
846 # Verify with "py-bt-full":
847 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100848 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400849 cmds_after_breakpoint=['py-bt-full'],
850 )
Victor Stinner79644f92015-03-27 15:42:37 +0100851 self.assertIn('#0 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400852
853
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000854class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100855 @unittest.skipIf(python_is_optimized(),
856 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000857 def test_basic_command(self):
858 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000859 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000860 cmds_after_breakpoint=['py-print args'])
861 self.assertMultilineMatches(bt,
862 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
863
Vinay Sajip2549f872012-01-04 12:07:30 +0000864 @unittest.skipIf(python_is_optimized(),
865 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000866 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000867 def test_print_after_up(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-up', 'py-print c', 'py-print b', 'py-print a'])
870 self.assertMultilineMatches(bt,
871 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\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_global(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 __name__'])
878 self.assertMultilineMatches(bt,
879 r".*\nglobal '__name__' = '__main__'\n.*")
880
Victor Stinnerd2084162011-12-19 13:42:24 +0100881 @unittest.skipIf(python_is_optimized(),
882 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000883 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000884 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000885 cmds_after_breakpoint=['py-print len'])
886 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100887 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000888
889class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100890 @unittest.skipIf(python_is_optimized(),
891 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000892 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000893 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000894 cmds_after_breakpoint=['py-locals'])
895 self.assertMultilineMatches(bt,
896 r".*\nargs = \(1, 2, 3\)\n.*")
897
Victor Stinner50eb60e2010-04-20 22:32:07 +0000898 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000899 @unittest.skipIf(python_is_optimized(),
900 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000901 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000902 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000903 cmds_after_breakpoint=['py-up', 'py-locals'])
904 self.assertMultilineMatches(bt,
905 r".*\na = 1\nb = 2\nc = 3\n.*")
906
907def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200908 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200909 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200910 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200911 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000912 run_unittest(PrettyPrintTests,
913 PyListTests,
914 StackNavigationTests,
915 PyBtTests,
916 PyPrintTests,
917 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000918 )
919
920if __name__ == "__main__":
921 test_main()