blob: d341a17f1fec80f88be2c025b0320ee5d85e80ed [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
Victor Stinner61108332017-02-01 16:29:54 +01006import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00007import os
8import re
9import subprocess
10import sys
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010011import sysconfig
Victor Stinner61108332017-02-01 16:29:54 +010012import textwrap
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000013import unittest
14
Antoine Pitroud0f3e072013-09-21 23:56:17 +020015from test import support
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000016from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000017
Victor Stinner5b6b4a82015-09-02 23:19:55 +020018def get_gdb_version():
19 try:
20 proc = subprocess.Popen(["gdb", "-nx", "--version"],
21 stdout=subprocess.PIPE,
Benjamin Petersoncbef66d2016-09-06 10:06:31 -070022 stderr=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020023 universal_newlines=True)
24 with proc:
25 version = proc.communicate()[0]
26 except OSError:
27 # This is what "no gdb" looks like. There may, however, be other
28 # errors that manifest this way too.
29 raise unittest.SkipTest("Couldn't find gdb on the path")
30
31 # Regex to parse:
32 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
33 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020034 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
35 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnera578eb32015-09-15 00:22:55 +020036 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020037 if match is None:
38 raise Exception("unable to parse GDB version: %r" % version)
39 return (version, int(match.group(1)), int(match.group(2)))
40
41gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040042if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020043 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
44 "embedding. Saw %s.%s:\n%s"
45 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020046 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000047
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010048if not sysconfig.is_python_build():
49 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
50
R David Murrayf9333022012-10-27 13:22:41 -040051# Location of custom hooks file in a repository checkout.
52checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
53 'python-gdb.py')
54
Victor Stinner51324932013-11-20 12:27:48 +010055PYTHONHASHSEED = '123'
56
R David Murrayf9333022012-10-27 13:22:41 -040057def run_gdb(*args, **env_vars):
58 """Runs gdb in --batch mode with the additional arguments given by *args.
59
60 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
61 """
62 if env_vars:
63 env = os.environ.copy()
64 env.update(env_vars)
65 else:
66 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020067 # -nx: Do not execute commands from any .gdbinit initialization files
68 # (issue #22188)
69 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040070 if (gdb_major_version, gdb_minor_version) >= (7, 4):
71 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020072 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000073 # Redirect stdin to prevent GDB from messing with
74 # the terminal settings
75 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020076 stdout=subprocess.PIPE,
77 stderr=subprocess.PIPE,
78 env=env)
79 with proc:
80 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040081 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
82
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000083# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010084gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040085if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000086 raise unittest.SkipTest("gdb not built with embedded python support")
87
Nick Coghlance346872013-09-22 19:38:16 +100088# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -070089# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040090_, gdbpy_errors = run_gdb('--args', sys.executable)
91if "auto-loading has been declined" in gdbpy_errors:
92 msg = "gdb security settings prevent use of custom hooks: "
93 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100094
Victor Stinner50eb60e2010-04-20 22:32:07 +000095def gdb_has_frame_select():
96 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -040097 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
98 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +000099 if not m:
100 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400101 gdb_frame_dir = m.group(1).split(', ')
102 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000103
104HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000105
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000106BREAKPOINT_FN='builtin_id'
107
Benjamin Peterson437df902016-09-06 20:22:41 -0700108@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000109class DebuggerTests(unittest.TestCase):
110
111 """Test that the debugger can debug Python."""
112
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000113 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000114 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000115 cmds_after_breakpoint=None,
116 import_site=False):
117 '''
118 Run 'python -c SOURCE' under gdb with a breakpoint.
119
120 Support injecting commands after the breakpoint is reached
121
122 Returns the stdout from gdb
123
124 cmds_after_breakpoint: if provided, a list of strings: gdb commands
125 '''
126 # We use "set breakpoint pending yes" to avoid blocking with a:
127 # Function "foo" not defined.
128 # Make breakpoint pending on future shared library load? (y or [n])
129 # error, which typically happens python is dynamically linked (the
130 # breakpoints of interest are to be found in the shared library)
131 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000132 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000133 # emitted to stderr each time, alas.
134
135 # Initially I had "--eval-command=continue" here, but removed it to
136 # avoid repeated print breakpoints when traversing hierarchical data
137 # structures
138
139 # Generate a list of commands in gdb's language:
140 commands = ['set breakpoint pending yes',
141 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200142
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200143 # The tests assume that the first frame of printed
144 # backtrace will not contain program counter,
145 # that is however not guaranteed by gdb
146 # therefore we need to use 'set print address off' to
147 # make sure the counter is not there. For example:
148 # #0 in PyObject_Print ...
149 # is assumed, but sometimes this can be e.g.
150 # #0 0x00003fffb7dd1798 in PyObject_Print ...
151 'set print address off',
152
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000153 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200154
155 # GDB as of 7.4 onwards can distinguish between the
156 # value of a variable at entry vs current value:
157 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
158 # which leads to the selftests failing with errors like this:
159 # AssertionError: 'v@entry=()' != '()'
160 # Disable this:
161 if (gdb_major_version, gdb_minor_version) >= (7, 4):
162 commands += ['set print entry-values no']
163
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000164 if cmds_after_breakpoint:
Marcel Plch9b7c74c2018-06-15 17:56:24 +0200165 # bpo-32962: When Python is compiled with -mcet -fcf-protection,
166 # arguments are unusable before running the first instruction
167 # of the function entry point. The 'next' command makes the
168 # required first step.
169 commands += ['next'] + cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000170 else:
171 commands += ['backtrace']
172
173 # print commands
174
175 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000176 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000177 args += ["--args",
178 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100179 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000180
181 if not import_site:
182 # -S suppresses the default 'import site'
183 args += ["-S"]
184
185 if source:
186 args += ["-c", source]
187 elif script:
188 args += [script]
189
190 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100191 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000192
193 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100194 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000195
Antoine Pitrou81641d62013-05-01 00:15:44 +0200196 errlines = err.splitlines()
197 unexpected_errlines = []
198
199 # Ignore some benign messages on stderr.
200 ignore_patterns = (
201 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200202 'Do you need "set solib-search-path" or '
203 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100204 # BFD: /usr/lib/debug/(...): unable to initialize decompress
205 # status for section .debug_aranges
206 'BFD: ',
207 # ignore all warnings
208 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200209 )
210 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100211 if not line:
212 continue
Antoine Pitrou81641d62013-05-01 00:15:44 +0200213 if not line.startswith(ignore_patterns):
214 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000215
216 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200217 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000218 return out
219
220 def get_gdb_repr(self, source,
221 cmds_after_breakpoint=None,
222 import_site=False):
223 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000224 # run "python -c'id(DATA)'" under gdb with a breakpoint on
225 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000226 # parameter, and verify that the gdb displays the same string
227 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000228 # Verify that the gdb displays the expected string
229 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000230 # For a nested structure, the first time we hit the breakpoint will
231 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100232
233 # NOTE: avoid decoding too much of the traceback as some
234 # undecodable characters may lurk there in optimized mode
235 # (issue #19743).
236 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000237 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000238 cmds_after_breakpoint=cmds_after_breakpoint,
239 import_site=import_site)
240 # gdb can insert additional '\n' and space characters in various places
241 # in its output, depending on the width of the terminal it's connected
242 # to (using its "wrap_here" function)
R David Murray44b548d2016-09-08 13:59:53 -0400243 m = re.match(r'.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000244 gdb_output, re.DOTALL)
245 if not m:
246 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
247 return m.group(1), gdb_output
248
249 def assertEndsWith(self, actual, exp_end):
250 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000251 self.assertTrue(actual.endswith(exp_end),
252 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000253
254 def assertMultilineMatches(self, actual, pattern):
255 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000256 if not m:
257 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000259 def get_sample_script(self):
260 return findfile('gdb_sample.py')
261
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262class PrettyPrintTests(DebuggerTests):
263 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000264 gdb_output = self.get_stack_trace('id(42)')
265 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100267 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000268 # Ensure that gdb's rendering of the value in a debugged process
269 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100270 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000271 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100272 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000273 self.assertEqual(gdb_repr, exp_repr,
274 ('%r did not equal expected %r; full output was:\n%s'
275 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000276
277 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300278 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100279 self.assertGdbRepr(42)
280 self.assertGdbRepr(0)
281 self.assertGdbRepr(-7)
282 self.assertGdbRepr(1000000000000)
283 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000284
285 def test_singletons(self):
286 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100287 self.assertGdbRepr(True)
288 self.assertGdbRepr(False)
289 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000290
291 def test_dicts(self):
292 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100293 self.assertGdbRepr({})
294 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900295 # Python preserves insertion order since 3.6
296 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000297
298 def test_lists(self):
299 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100300 self.assertGdbRepr([])
301 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000302
303 def test_bytes(self):
304 'Verify the pretty-printing of bytes'
305 self.assertGdbRepr(b'')
306 self.assertGdbRepr(b'And now for something hopefully the same')
307 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
308 self.assertGdbRepr(b'this is a tab:\t'
309 b' this is a slash-N:\n'
310 b' this is a slash-R:\r'
311 )
312
313 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
314
315 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000316
317 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000318 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000319 encoding = locale.getpreferredencoding()
320 def check_repr(text):
321 try:
322 text.encode(encoding)
323 printable = True
324 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000325 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000326 else:
327 self.assertGdbRepr(text)
328
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000329 self.assertGdbRepr('')
330 self.assertGdbRepr('And now for something hopefully the same')
331 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000332
333 # Test printing a single character:
334 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000335 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000336
337 # Test printing a Japanese unicode string
338 # (I believe this reads "mojibake", using 3 characters from the CJK
339 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000340 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000341
342 # Test a character outside the BMP:
343 # U+1D121 MUSICAL SYMBOL C CLEF
344 # This is:
345 # UTF-8: 0xF0 0x9D 0x84 0xA1
346 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000347 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000348
349 def test_tuples(self):
350 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100351 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000352 self.assertGdbRepr((1,), '(1,)')
353 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000354
355 def test_sets(self):
356 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200357 if (gdb_major_version, gdb_minor_version) < (7, 3):
358 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100359 self.assertGdbRepr(set(), "set()")
360 self.assertGdbRepr(set(['a']), "{'a'}")
361 # PYTHONHASHSEED is need to get the exact frozenset item order
362 if not sys.flags.ignore_environment:
363 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
364 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000365
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000366 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000367 # which happens on deletion:
368 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100369s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000370id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000371 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000372
373 def test_frozensets(self):
374 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200375 if (gdb_major_version, gdb_minor_version) < (7, 3):
376 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100377 self.assertGdbRepr(frozenset(), "frozenset()")
378 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
379 # PYTHONHASHSEED is need to get the exact frozenset item order
380 if not sys.flags.ignore_environment:
381 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
382 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000383
384 def test_exceptions(self):
385 # Test a RuntimeError
386 gdb_repr, gdb_output = self.get_gdb_repr('''
387try:
388 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000389except RuntimeError as e:
390 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000391''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000392 self.assertEqual(gdb_repr,
393 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000394
395
396 # Test division by zero:
397 gdb_repr, gdb_output = self.get_gdb_repr('''
398try:
399 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000400except ZeroDivisionError as e:
401 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000402''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000403 self.assertEqual(gdb_repr,
404 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000405
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000406 def test_modern_class(self):
407 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000408 gdb_repr, gdb_output = self.get_gdb_repr('''
409class Foo:
410 pass
411foo = Foo()
412foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000413id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100414 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000415 self.assertTrue(m,
416 msg='Unexpected new-style class rendering %r' % gdb_repr)
417
418 def test_subclassing_list(self):
419 'Verify the pretty-printing of an instance of a list subclass'
420 gdb_repr, gdb_output = self.get_gdb_repr('''
421class Foo(list):
422 pass
423foo = Foo()
424foo += [1, 2, 3]
425foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000426id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100427 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 +0000428
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000429 self.assertTrue(m,
430 msg='Unexpected new-style class rendering %r' % gdb_repr)
431
432 def test_subclassing_tuple(self):
433 'Verify the pretty-printing of an instance of a tuple subclass'
434 # This should exercise the negative tp_dictoffset code in the
435 # new-style class support
436 gdb_repr, gdb_output = self.get_gdb_repr('''
437class Foo(tuple):
438 pass
439foo = Foo((1, 2, 3))
440foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000441id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100442 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 +0000443
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000444 self.assertTrue(m,
445 msg='Unexpected new-style class rendering %r' % gdb_repr)
446
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000447 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000448 '''Run Python under gdb, corrupting variables in the inferior process
449 immediately before taking a backtrace.
450
451 Verify that the variable's representation is the expected failsafe
452 representation'''
453 if corruption:
454 cmds_after_breakpoint=[corruption, 'backtrace']
455 else:
456 cmds_after_breakpoint=['backtrace']
457
458 gdb_repr, gdb_output = \
459 self.get_gdb_repr(source,
460 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000461 if exprepr:
462 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000463 # gdb managed to print the value in spite of the corruption;
464 # this is good (see http://bugs.python.org/issue8330)
465 return
466
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000467 # Match anything for the type name; 0xDEADBEEF could point to
468 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100469 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000470
471 m = re.match(pattern, gdb_repr)
472 if not m:
473 self.fail('Unexpected gdb representation: %r\n%s' % \
474 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000475
476 def test_NULL_ptr(self):
477 'Ensure that a NULL PyObject* is handled gracefully'
478 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000479 self.get_gdb_repr('id(42)',
480 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000481 'backtrace'])
482 )
483
Ezio Melottib3aedd42010-11-20 19:04:17 +0000484 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000485
486 def test_NULL_ob_type(self):
487 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000488 self.assertSane('id(42)',
489 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000490
491 def test_corrupt_ob_type(self):
492 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000493 self.assertSane('id(42)',
494 'set v->ob_type=0xDEADBEEF',
495 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000496
497 def test_corrupt_tp_flags(self):
498 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000499 self.assertSane('id(42)',
500 'set v->ob_type->tp_flags=0x0',
501 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000502
503 def test_corrupt_tp_name(self):
504 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000505 self.assertSane('id(42)',
506 'set v->ob_type->tp_name=0xDEADBEEF',
507 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000508
509 def test_builtins_help(self):
510 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100511
512 if sys.flags.no_site:
513 self.skipTest("need site module, but -S option was used")
514
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000515 # (this was the issue causing tracebacks in
516 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000517 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000518
Antoine Pitrou4d098732011-11-26 01:42:03 +0100519 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520 self.assertTrue(m,
521 msg='Unexpected rendering %r' % gdb_repr)
522
523 def test_selfreferential_list(self):
524 '''Ensure that a reference loop involving a list doesn't lead proxyval
525 into an infinite loop:'''
526 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000527 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000528 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000529
530 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000531 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000532 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000533
534 def test_selfreferential_dict(self):
535 '''Ensure that a reference loop involving a dict doesn't lead proxyval
536 into an infinite loop:'''
537 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000538 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000539
Ezio Melottib3aedd42010-11-20 19:04:17 +0000540 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000541
542 def test_selfreferential_old_style_instance(self):
543 gdb_repr, gdb_output = \
544 self.get_gdb_repr('''
545class Foo:
546 pass
547foo = Foo()
548foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000549id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400550 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000551 gdb_repr),
552 'Unexpected gdb representation: %r\n%s' % \
553 (gdb_repr, gdb_output))
554
555 def test_selfreferential_new_style_instance(self):
556 gdb_repr, gdb_output = \
557 self.get_gdb_repr('''
558class Foo(object):
559 pass
560foo = Foo()
561foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000562id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400563 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000564 gdb_repr),
565 'Unexpected gdb representation: %r\n%s' % \
566 (gdb_repr, gdb_output))
567
568 gdb_repr, gdb_output = \
569 self.get_gdb_repr('''
570class Foo(object):
571 pass
572a = Foo()
573b = Foo()
574a.an_attr = b
575b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000576id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400577 self.assertTrue(re.match(r'<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 +0000578 gdb_repr),
579 'Unexpected gdb representation: %r\n%s' % \
580 (gdb_repr, gdb_output))
581
582 def test_truncation(self):
583 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000584 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000585 self.assertEqual(gdb_repr,
586 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
587 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
588 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
589 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
590 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
591 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
592 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
593 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
594 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
595 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
596 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
597 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
598 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
599 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
600 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
601 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
602 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
603 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
604 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
605 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
606 "224, 225, 226...(truncated)")
607 self.assertEqual(len(gdb_repr),
608 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000610 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000611 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400612 self.assertTrue(re.match(r'<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000613 gdb_repr),
614 'Unexpected gdb representation: %r\n%s' % \
615 (gdb_repr, gdb_output))
616
617 def test_frames(self):
618 gdb_output = self.get_stack_trace('''
619def foo(a, b, c):
620 pass
621
622foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000623id(foo.__code__)''',
624 breakpoint='builtin_id',
625 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000626 )
R David Murray44b548d2016-09-08 13:59:53 -0400627 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000628 gdb_output,
629 re.DOTALL),
630 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
631
Victor Stinnerd2084162011-12-19 13:42:24 +0100632@unittest.skipIf(python_is_optimized(),
633 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000634class PyListTests(DebuggerTests):
635 def assertListing(self, expected, actual):
636 self.assertEndsWith(actual, expected)
637
638 def test_basic_command(self):
639 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000640 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000641 cmds_after_breakpoint=['py-list'])
642
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000643 self.assertListing(' 5 \n'
644 ' 6 def bar(a, b, c):\n'
645 ' 7 baz(a, b, c)\n'
646 ' 8 \n'
647 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000648 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000649 ' 11 \n'
650 ' 12 foo(1, 2, 3)\n',
651 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000652
653 def test_one_abs_arg(self):
654 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000655 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000656 cmds_after_breakpoint=['py-list 9'])
657
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000658 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000659 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000660 ' 11 \n'
661 ' 12 foo(1, 2, 3)\n',
662 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000663
664 def test_two_abs_args(self):
665 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000666 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000667 cmds_after_breakpoint=['py-list 1,3'])
668
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000669 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
670 ' 2 \n'
671 ' 3 def foo(a, b, c):\n',
672 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000673
674class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000675 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100676 @unittest.skipIf(python_is_optimized(),
677 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 def test_pyup_command(self):
679 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000680 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100681 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000682 self.assertMultilineMatches(bt,
683 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100684#[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 +0000685 baz\(a, b, c\)
686$''')
687
Victor Stinner50eb60e2010-04-20 22:32:07 +0000688 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689 def test_down_at_bottom(self):
690 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000691 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000692 cmds_after_breakpoint=['py-down'])
693 self.assertEndsWith(bt,
694 'Unable to find a newer python frame\n')
695
Victor Stinner50eb60e2010-04-20 22:32:07 +0000696 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000697 def test_up_at_top(self):
698 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000699 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100700 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000701 self.assertEndsWith(bt,
702 'Unable to find an older python frame\n')
703
Victor Stinner50eb60e2010-04-20 22:32:07 +0000704 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100705 @unittest.skipIf(python_is_optimized(),
706 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000707 def test_up_then_down(self):
708 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000709 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100710 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000711 self.assertMultilineMatches(bt,
712 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100713#[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 +0000714 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100715#[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 +0000716 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000717$''')
718
719class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100720 @unittest.skipIf(python_is_optimized(),
721 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200722 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000723 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000724 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725 cmds_after_breakpoint=['py-bt'])
726 self.assertMultilineMatches(bt,
727 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200728Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100729 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200730 File ".*gdb_sample.py", line 10, in baz
731 id\(42\)
732 File ".*gdb_sample.py", line 7, in bar
733 baz\(a, b, c\)
734 File ".*gdb_sample.py", line 4, in foo
735 bar\(a, b, c\)
736 File ".*gdb_sample.py", line 12, in <module>
737 foo\(1, 2, 3\)
738''')
739
Victor Stinnerd2084162011-12-19 13:42:24 +0100740 @unittest.skipIf(python_is_optimized(),
741 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200742 def test_bt_full(self):
743 'Verify that the "py-bt-full" command works'
744 bt = self.get_stack_trace(script=self.get_sample_script(),
745 cmds_after_breakpoint=['py-bt-full'])
746 self.assertMultilineMatches(bt,
747 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100748#[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 +0000749 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100750#[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 +0000751 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100752#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100753 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000754''')
755
David Malcolm8d37ffa2012-06-27 14:15:34 -0400756 def test_threads(self):
757 'Verify that "py-bt" indicates threads that are waiting for the GIL'
758 cmd = '''
759from threading import Thread
760
761class TestThread(Thread):
762 # These threads would run forever, but we'll interrupt things with the
763 # debugger
764 def run(self):
765 i = 0
766 while 1:
767 i += 1
768
769t = {}
770for i in range(4):
771 t[i] = TestThread()
772 t[i].start()
773
774# Trigger a breakpoint on the main thread
775id(42)
776
777'''
778 # Verify with "py-bt":
779 gdb_output = self.get_stack_trace(cmd,
780 cmds_after_breakpoint=['thread apply all py-bt'])
781 self.assertIn('Waiting for the GIL', gdb_output)
782
783 # Verify with "py-bt-full":
784 gdb_output = self.get_stack_trace(cmd,
785 cmds_after_breakpoint=['thread apply all py-bt-full'])
786 self.assertIn('Waiting for the GIL', gdb_output)
787
788 @unittest.skipIf(python_is_optimized(),
789 "Python was compiled with optimizations")
790 # Some older versions of gdb will fail with
791 # "Cannot find new threads: generic error"
792 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400793 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
David Malcolm8d37ffa2012-06-27 14:15:34 -0400819 def test_pycfunction(self):
820 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100821 # Tested function must not be defined with METH_NOARGS or METH_O,
822 # otherwise call_function() doesn't call PyCFunction_Call()
823 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400824 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100825 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400826 'def bar():\n'
827 ' foo()\n'
828 'bar()\n')
829 # Verify with "py-bt":
830 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100831 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400832 cmds_after_breakpoint=['bt', 'py-bt'],
833 )
Victor Stinner79644f92015-03-27 15:42:37 +0100834 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400835
836 # Verify with "py-bt-full":
837 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100838 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400839 cmds_after_breakpoint=['py-bt-full'],
840 )
INADA Naoki5566bbb2017-02-03 07:43:03 +0900841 self.assertIn('#2 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400842
Victor Stinner61108332017-02-01 16:29:54 +0100843 @unittest.skipIf(python_is_optimized(),
844 "Python was compiled with optimizations")
845 def test_wrapper_call(self):
846 cmd = textwrap.dedent('''
847 class MyList(list):
848 def __init__(self):
849 super().__init__() # wrapper_call()
850
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100851 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100852 l = MyList()
853 ''')
Marcel Plch9b7c74c2018-06-15 17:56:24 +0200854 # bpo-32962: same case as in get_stack_trace():
855 # we need an additional 'next' command in order to read
856 # arguments of the innermost function of the call stack.
Victor Stinner61108332017-02-01 16:29:54 +0100857 # Verify with "py-bt":
858 gdb_output = self.get_stack_trace(cmd,
Marcel Plch9b7c74c2018-06-15 17:56:24 +0200859 cmds_after_breakpoint=['break wrapper_call', 'continue', 'next', 'py-bt'])
Victor Stinner72268ae2017-02-01 18:26:14 +0100860 self.assertRegex(gdb_output,
861 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100862
David Malcolm8d37ffa2012-06-27 14:15:34 -0400863
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000864class PyPrintTests(DebuggerTests):
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_basic_command(self):
868 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000869 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100870 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000871 self.assertMultilineMatches(bt,
872 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
873
Vinay Sajip2549f872012-01-04 12:07:30 +0000874 @unittest.skipIf(python_is_optimized(),
875 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000876 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000877 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000878 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100879 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000880 self.assertMultilineMatches(bt,
881 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
882
Victor Stinnerd2084162011-12-19 13:42:24 +0100883 @unittest.skipIf(python_is_optimized(),
884 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000885 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000886 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100887 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000888 self.assertMultilineMatches(bt,
889 r".*\nglobal '__name__' = '__main__'\n.*")
890
Victor Stinnerd2084162011-12-19 13:42:24 +0100891 @unittest.skipIf(python_is_optimized(),
892 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000893 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000894 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100895 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000896 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100897 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000898
899class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100900 @unittest.skipIf(python_is_optimized(),
901 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000902 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000903 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100904 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000905 self.assertMultilineMatches(bt,
906 r".*\nargs = \(1, 2, 3\)\n.*")
907
Victor Stinner50eb60e2010-04-20 22:32:07 +0000908 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000909 @unittest.skipIf(python_is_optimized(),
910 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000911 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000912 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100913 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000914 self.assertMultilineMatches(bt,
915 r".*\na = 1\nb = 2\nc = 3\n.*")
916
917def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200918 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200919 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200920 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200921 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000922 run_unittest(PrettyPrintTests,
923 PyListTests,
924 StackNavigationTests,
925 PyBtTests,
926 PyPrintTests,
927 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000928 )
929
930if __name__ == "__main__":
931 test_main()