blob: 5f554897f86a0b33de53e59a53e1263e0a7d0b32 [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
Lysandros Nikolaou59668aa2018-11-04 22:21:28 +01007import platform
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00008import 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
Victor Stinner81446fd2019-08-23 11:28:27 +010016from test.support import 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:
Victor Stinnerec9bea42020-04-29 17:11:48 +020020 cmd = ["gdb", "-nx", "--version"]
21 proc = subprocess.Popen(cmd,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020022 stdout=subprocess.PIPE,
Benjamin Petersoncbef66d2016-09-06 10:06:31 -070023 stderr=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020024 universal_newlines=True)
25 with proc:
Victor Stinnerec9bea42020-04-29 17:11:48 +020026 version, stderr = proc.communicate()
27
28 if proc.returncode:
29 raise Exception(f"Command {' '.join(cmd)!r} failed "
30 f"with exit code {proc.returncode}: "
31 f"stdout={version!r} stderr={stderr!r}")
Victor Stinner5b6b4a82015-09-02 23:19:55 +020032 except OSError:
33 # This is what "no gdb" looks like. There may, however, be other
34 # errors that manifest this way too.
35 raise unittest.SkipTest("Couldn't find gdb on the path")
36
37 # Regex to parse:
38 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
39 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020040 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
41 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnerb2dca492020-06-11 15:48:03 +020042 # 'HP gdb 6.7 for HP Itanium (32 or 64 bit) and target HP-UX 11iv2 and 11iv3.\n' -> 6.7
43 match = re.search(r"^(?:GNU|HP) gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020044 if match is None:
45 raise Exception("unable to parse GDB version: %r" % version)
46 return (version, int(match.group(1)), int(match.group(2)))
47
48gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040049if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020050 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
51 "embedding. Saw %s.%s:\n%s"
52 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020053 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000054
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010055if not sysconfig.is_python_build():
56 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
57
Lysandros Nikolaou59668aa2018-11-04 22:21:28 +010058if 'Clang' in platform.python_compiler() and sys.platform == 'darwin':
59 raise unittest.SkipTest("test_gdb doesn't work correctly when python is"
60 " built with LLVM clang")
61
Steve Dower6de45742019-05-24 13:00:04 -070062if ((sysconfig.get_config_var('PGO_PROF_USE_FLAG') or 'xxx') in
63 (sysconfig.get_config_var('PY_CORE_CFLAGS') or '')):
64 raise unittest.SkipTest("test_gdb is not reliable on PGO builds")
65
R David Murrayf9333022012-10-27 13:22:41 -040066# Location of custom hooks file in a repository checkout.
67checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
68 'python-gdb.py')
69
Victor Stinner51324932013-11-20 12:27:48 +010070PYTHONHASHSEED = '123'
71
Victor Stinner79d21332018-10-09 16:54:04 +020072
73def cet_protection():
74 cflags = sysconfig.get_config_var('CFLAGS')
75 if not cflags:
76 return False
77 flags = cflags.split()
78 # True if "-mcet -fcf-protection" options are found, but false
79 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
80 return (('-mcet' in flags)
81 and any((flag.startswith('-fcf-protection')
82 and not flag.endswith(("=none", "=return")))
83 for flag in flags))
84
85# Control-flow enforcement technology
86CET_PROTECTION = cet_protection()
87
88
R David Murrayf9333022012-10-27 13:22:41 -040089def run_gdb(*args, **env_vars):
90 """Runs gdb in --batch mode with the additional arguments given by *args.
91
92 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
93 """
94 if env_vars:
95 env = os.environ.copy()
96 env.update(env_vars)
97 else:
98 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020099 # -nx: Do not execute commands from any .gdbinit initialization files
100 # (issue #22188)
101 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -0400102 if (gdb_major_version, gdb_minor_version) >= (7, 4):
103 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200104 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +0000105 # Redirect stdin to prevent GDB from messing with
106 # the terminal settings
107 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200108 stdout=subprocess.PIPE,
109 stderr=subprocess.PIPE,
110 env=env)
111 with proc:
112 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -0400113 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
114
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000115# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +0100116gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -0400117if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000118 raise unittest.SkipTest("gdb not built with embedded python support")
119
Nick Coghlance346872013-09-22 19:38:16 +1000120# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -0700121# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -0400122_, gdbpy_errors = run_gdb('--args', sys.executable)
123if "auto-loading has been declined" in gdbpy_errors:
124 msg = "gdb security settings prevent use of custom hooks: "
125 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000126
Victor Stinner50eb60e2010-04-20 22:32:07 +0000127def gdb_has_frame_select():
128 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400129 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
130 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000131 if not m:
132 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400133 gdb_frame_dir = m.group(1).split(', ')
134 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000135
136HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000137
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000138BREAKPOINT_FN='builtin_id'
139
Benjamin Peterson437df902016-09-06 20:22:41 -0700140@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000141class DebuggerTests(unittest.TestCase):
142
143 """Test that the debugger can debug Python."""
144
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000145 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000146 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000147 cmds_after_breakpoint=None,
Miss Islington (bot)bbaf5c22021-09-15 12:10:33 -0700148 import_site=False,
149 ignore_stderr=False):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000150 '''
151 Run 'python -c SOURCE' under gdb with a breakpoint.
152
153 Support injecting commands after the breakpoint is reached
154
155 Returns the stdout from gdb
156
157 cmds_after_breakpoint: if provided, a list of strings: gdb commands
158 '''
159 # We use "set breakpoint pending yes" to avoid blocking with a:
160 # Function "foo" not defined.
161 # Make breakpoint pending on future shared library load? (y or [n])
162 # error, which typically happens python is dynamically linked (the
163 # breakpoints of interest are to be found in the shared library)
164 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000165 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000166 # emitted to stderr each time, alas.
167
168 # Initially I had "--eval-command=continue" here, but removed it to
169 # avoid repeated print breakpoints when traversing hierarchical data
170 # structures
171
172 # Generate a list of commands in gdb's language:
173 commands = ['set breakpoint pending yes',
174 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200175
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200176 # The tests assume that the first frame of printed
177 # backtrace will not contain program counter,
178 # that is however not guaranteed by gdb
179 # therefore we need to use 'set print address off' to
180 # make sure the counter is not there. For example:
181 # #0 in PyObject_Print ...
182 # is assumed, but sometimes this can be e.g.
183 # #0 0x00003fffb7dd1798 in PyObject_Print ...
184 'set print address off',
185
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000186 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200187
188 # GDB as of 7.4 onwards can distinguish between the
189 # value of a variable at entry vs current value:
190 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
191 # which leads to the selftests failing with errors like this:
192 # AssertionError: 'v@entry=()' != '()'
193 # Disable this:
194 if (gdb_major_version, gdb_minor_version) >= (7, 4):
195 commands += ['set print entry-values no']
196
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000197 if cmds_after_breakpoint:
Victor Stinner79d21332018-10-09 16:54:04 +0200198 if CET_PROTECTION:
199 # bpo-32962: When Python is compiled with -mcet
200 # -fcf-protection, function arguments are unusable before
201 # running the first instruction of the function entry point.
202 # The 'next' command makes the required first step.
203 commands += ['next']
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200204 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000205 else:
206 commands += ['backtrace']
207
208 # print commands
209
210 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000211 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000212 args += ["--args",
213 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100214 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000215
216 if not import_site:
217 # -S suppresses the default 'import site'
218 args += ["-S"]
219
220 if source:
221 args += ["-c", source]
222 elif script:
223 args += [script]
224
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000225 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100226 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000227
Miss Islington (bot)bbaf5c22021-09-15 12:10:33 -0700228 if not ignore_stderr:
229 for line in err.splitlines():
230 print(line, file=sys.stderr)
Antoine Pitrou81641d62013-05-01 00:15:44 +0200231
Victor Stinnere56a1232019-06-21 23:17:30 +0200232 # bpo-34007: Sometimes some versions of the shared libraries that
233 # are part of the traceback are compiled in optimised mode and the
234 # Program Counter (PC) is not present, not allowing gdb to walk the
235 # frames back. When this happens, the Python bindings of gdb raise
236 # an exception, making the test impossible to succeed.
237 if "PC not saved" in err:
238 raise unittest.SkipTest("gdb cannot walk the frame object"
239 " because the Program Counter is"
240 " not present")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000241
Victor Stinner7bf069b2020-03-20 08:23:26 +0100242 # bpo-40019: Skip the test if gdb failed to read debug information
243 # because the Python binary is optimized.
244 for pattern in (
245 '(frame information optimized out)',
246 'Unable to read information on python frame',
247 ):
248 if pattern in out:
249 raise unittest.SkipTest(f"{pattern!r} found in gdb output")
250
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000251 return out
252
253 def get_gdb_repr(self, source,
254 cmds_after_breakpoint=None,
255 import_site=False):
256 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000257 # run "python -c'id(DATA)'" under gdb with a breakpoint on
258 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000259 # parameter, and verify that the gdb displays the same string
260 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000261 # Verify that the gdb displays the expected string
262 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000263 # For a nested structure, the first time we hit the breakpoint will
264 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100265
266 # NOTE: avoid decoding too much of the traceback as some
267 # undecodable characters may lurk there in optimized mode
268 # (issue #19743).
269 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000270 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000271 cmds_after_breakpoint=cmds_after_breakpoint,
272 import_site=import_site)
273 # gdb can insert additional '\n' and space characters in various places
274 # in its output, depending on the width of the terminal it's connected
275 # to (using its "wrap_here" function)
Victor Stinner64b4a3a2019-09-26 16:54:13 +0200276 m = re.search(
277 # Match '#0 builtin_id(self=..., v=...)'
278 r'#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)?\)'
279 # Match ' at Python/bltinmodule.c'.
280 # bpo-38239: builtin_id() is defined in Python/bltinmodule.c,
281 # but accept any "Directory\file.c" to support Link Time
282 # Optimization (LTO).
283 r'\s+at\s+\S*[A-Za-z]+/[A-Za-z0-9_-]+\.c',
284 gdb_output, re.DOTALL)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000285 if not m:
286 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
287 return m.group(1), gdb_output
288
289 def assertEndsWith(self, actual, exp_end):
290 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000291 self.assertTrue(actual.endswith(exp_end),
292 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000293
294 def assertMultilineMatches(self, actual, pattern):
295 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000296 if not m:
297 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000298
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000299 def get_sample_script(self):
300 return findfile('gdb_sample.py')
301
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000302class PrettyPrintTests(DebuggerTests):
303 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000304 gdb_output = self.get_stack_trace('id(42)')
305 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000306
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100307 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000308 # Ensure that gdb's rendering of the value in a debugged process
309 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100310 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000311 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100312 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000313 self.assertEqual(gdb_repr, exp_repr,
314 ('%r did not equal expected %r; full output was:\n%s'
315 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000316
317 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300318 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100319 self.assertGdbRepr(42)
320 self.assertGdbRepr(0)
321 self.assertGdbRepr(-7)
322 self.assertGdbRepr(1000000000000)
323 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000324
325 def test_singletons(self):
326 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100327 self.assertGdbRepr(True)
328 self.assertGdbRepr(False)
329 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000330
331 def test_dicts(self):
332 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100333 self.assertGdbRepr({})
334 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900335 # Python preserves insertion order since 3.6
336 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000337
338 def test_lists(self):
339 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100340 self.assertGdbRepr([])
341 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000342
343 def test_bytes(self):
344 'Verify the pretty-printing of bytes'
345 self.assertGdbRepr(b'')
346 self.assertGdbRepr(b'And now for something hopefully the same')
347 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
348 self.assertGdbRepr(b'this is a tab:\t'
349 b' this is a slash-N:\n'
350 b' this is a slash-R:\r'
351 )
352
353 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
354
355 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000356
357 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000358 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400359 # We cannot simply call locale.getpreferredencoding() here,
360 # as GDB might have been linked against a different version
361 # of Python with a different encoding and coercion policy
362 # with respect to PEP 538 and PEP 540.
363 out, err = run_gdb(
364 '--eval-command',
365 'python import locale; print(locale.getpreferredencoding())')
366
367 encoding = out.rstrip()
368 if err or not encoding:
369 raise RuntimeError(
370 f'unable to determine the preferred encoding '
371 f'of embedded Python in GDB: {err}')
372
Victor Stinner150016f2010-05-19 23:04:56 +0000373 def check_repr(text):
374 try:
375 text.encode(encoding)
Victor Stinner150016f2010-05-19 23:04:56 +0000376 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000377 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000378 else:
379 self.assertGdbRepr(text)
380
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000381 self.assertGdbRepr('')
382 self.assertGdbRepr('And now for something hopefully the same')
383 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000384
385 # Test printing a single character:
386 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000387 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000388
389 # Test printing a Japanese unicode string
390 # (I believe this reads "mojibake", using 3 characters from the CJK
391 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000392 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000393
394 # Test a character outside the BMP:
395 # U+1D121 MUSICAL SYMBOL C CLEF
396 # This is:
397 # UTF-8: 0xF0 0x9D 0x84 0xA1
398 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000399 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000400
401 def test_tuples(self):
402 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100403 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000404 self.assertGdbRepr((1,), '(1,)')
405 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000406
407 def test_sets(self):
408 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200409 if (gdb_major_version, gdb_minor_version) < (7, 3):
410 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100411 self.assertGdbRepr(set(), "set()")
412 self.assertGdbRepr(set(['a']), "{'a'}")
413 # PYTHONHASHSEED is need to get the exact frozenset item order
414 if not sys.flags.ignore_environment:
415 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
416 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000417
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000418 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000419 # which happens on deletion:
420 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100421s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000422id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000423 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000424
425 def test_frozensets(self):
426 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200427 if (gdb_major_version, gdb_minor_version) < (7, 3):
428 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100429 self.assertGdbRepr(frozenset(), "frozenset()")
430 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
431 # PYTHONHASHSEED is need to get the exact frozenset item order
432 if not sys.flags.ignore_environment:
433 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
434 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000435
436 def test_exceptions(self):
437 # Test a RuntimeError
438 gdb_repr, gdb_output = self.get_gdb_repr('''
439try:
440 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000441except RuntimeError as e:
442 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000443''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000444 self.assertEqual(gdb_repr,
445 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000446
447
448 # Test division by zero:
449 gdb_repr, gdb_output = self.get_gdb_repr('''
450try:
451 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000452except ZeroDivisionError as e:
453 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000454''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000455 self.assertEqual(gdb_repr,
456 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000457
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000458 def test_modern_class(self):
459 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000460 gdb_repr, gdb_output = self.get_gdb_repr('''
461class Foo:
462 pass
463foo = Foo()
464foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000465id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100466 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000467 self.assertTrue(m,
468 msg='Unexpected new-style class rendering %r' % gdb_repr)
469
470 def test_subclassing_list(self):
471 'Verify the pretty-printing of an instance of a list subclass'
472 gdb_repr, gdb_output = self.get_gdb_repr('''
473class Foo(list):
474 pass
475foo = Foo()
476foo += [1, 2, 3]
477foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000478id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100479 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 +0000480
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000481 self.assertTrue(m,
482 msg='Unexpected new-style class rendering %r' % gdb_repr)
483
484 def test_subclassing_tuple(self):
485 'Verify the pretty-printing of an instance of a tuple subclass'
486 # This should exercise the negative tp_dictoffset code in the
487 # new-style class support
488 gdb_repr, gdb_output = self.get_gdb_repr('''
489class Foo(tuple):
490 pass
491foo = Foo((1, 2, 3))
492foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000493id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100494 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 +0000495
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000496 self.assertTrue(m,
497 msg='Unexpected new-style class rendering %r' % gdb_repr)
498
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000499 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000500 '''Run Python under gdb, corrupting variables in the inferior process
501 immediately before taking a backtrace.
502
503 Verify that the variable's representation is the expected failsafe
504 representation'''
505 if corruption:
506 cmds_after_breakpoint=[corruption, 'backtrace']
507 else:
508 cmds_after_breakpoint=['backtrace']
509
510 gdb_repr, gdb_output = \
511 self.get_gdb_repr(source,
512 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000513 if exprepr:
514 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000515 # gdb managed to print the value in spite of the corruption;
516 # this is good (see http://bugs.python.org/issue8330)
517 return
518
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000519 # Match anything for the type name; 0xDEADBEEF could point to
520 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100521 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000522
523 m = re.match(pattern, gdb_repr)
524 if not m:
525 self.fail('Unexpected gdb representation: %r\n%s' % \
526 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000527
528 def test_NULL_ptr(self):
529 'Ensure that a NULL PyObject* is handled gracefully'
530 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000531 self.get_gdb_repr('id(42)',
532 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000533 'backtrace'])
534 )
535
Ezio Melottib3aedd42010-11-20 19:04:17 +0000536 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000537
538 def test_NULL_ob_type(self):
539 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000540 self.assertSane('id(42)',
541 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000542
543 def test_corrupt_ob_type(self):
544 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000545 self.assertSane('id(42)',
546 'set v->ob_type=0xDEADBEEF',
547 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000548
549 def test_corrupt_tp_flags(self):
550 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000551 self.assertSane('id(42)',
552 'set v->ob_type->tp_flags=0x0',
553 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000554
555 def test_corrupt_tp_name(self):
556 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000557 self.assertSane('id(42)',
558 'set v->ob_type->tp_name=0xDEADBEEF',
559 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000560
561 def test_builtins_help(self):
562 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100563
564 if sys.flags.no_site:
565 self.skipTest("need site module, but -S option was used")
566
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000567 # (this was the issue causing tracebacks in
568 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000569 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000570
Antoine Pitrou4d098732011-11-26 01:42:03 +0100571 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000572 self.assertTrue(m,
573 msg='Unexpected rendering %r' % gdb_repr)
574
575 def test_selfreferential_list(self):
576 '''Ensure that a reference loop involving a list doesn't lead proxyval
577 into an infinite loop:'''
578 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000579 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000580 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000581
582 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000583 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000584 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000585
586 def test_selfreferential_dict(self):
587 '''Ensure that a reference loop involving a dict doesn't lead proxyval
588 into an infinite loop:'''
589 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000590 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000591
Ezio Melottib3aedd42010-11-20 19:04:17 +0000592 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000593
594 def test_selfreferential_old_style_instance(self):
595 gdb_repr, gdb_output = \
596 self.get_gdb_repr('''
597class Foo:
598 pass
599foo = Foo()
600foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000601id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400602 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000603 gdb_repr),
604 'Unexpected gdb representation: %r\n%s' % \
605 (gdb_repr, gdb_output))
606
607 def test_selfreferential_new_style_instance(self):
608 gdb_repr, gdb_output = \
609 self.get_gdb_repr('''
610class Foo(object):
611 pass
612foo = Foo()
613foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000614id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400615 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000616 gdb_repr),
617 'Unexpected gdb representation: %r\n%s' % \
618 (gdb_repr, gdb_output))
619
620 gdb_repr, gdb_output = \
621 self.get_gdb_repr('''
622class Foo(object):
623 pass
624a = Foo()
625b = Foo()
626a.an_attr = b
627b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000628id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400629 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 +0000630 gdb_repr),
631 'Unexpected gdb representation: %r\n%s' % \
632 (gdb_repr, gdb_output))
633
634 def test_truncation(self):
635 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000636 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000637 self.assertEqual(gdb_repr,
638 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
639 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
640 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
641 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
642 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
643 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
644 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
645 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
646 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
647 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
648 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
649 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
650 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
651 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
652 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
653 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
654 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
655 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
656 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
657 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
658 "224, 225, 226...(truncated)")
659 self.assertEqual(len(gdb_repr),
660 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000661
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000662 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000663 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400664 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 +0000665 gdb_repr),
666 'Unexpected gdb representation: %r\n%s' % \
667 (gdb_repr, gdb_output))
668
669 def test_frames(self):
670 gdb_output = self.get_stack_trace('''
671def foo(a, b, c):
672 pass
673
674foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000675id(foo.__code__)''',
676 breakpoint='builtin_id',
677 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 )
R David Murray44b548d2016-09-08 13:59:53 -0400679 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 +0000680 gdb_output,
681 re.DOTALL),
682 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
683
Victor Stinnerd2084162011-12-19 13:42:24 +0100684@unittest.skipIf(python_is_optimized(),
685 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000686class PyListTests(DebuggerTests):
687 def assertListing(self, expected, actual):
688 self.assertEndsWith(actual, expected)
689
690 def test_basic_command(self):
691 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000692 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000693 cmds_after_breakpoint=['py-list'])
694
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000695 self.assertListing(' 5 \n'
696 ' 6 def bar(a, b, c):\n'
697 ' 7 baz(a, b, c)\n'
698 ' 8 \n'
699 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000700 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000701 ' 11 \n'
702 ' 12 foo(1, 2, 3)\n',
703 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000704
705 def test_one_abs_arg(self):
706 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000707 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000708 cmds_after_breakpoint=['py-list 9'])
709
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000710 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000711 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000712 ' 11 \n'
713 ' 12 foo(1, 2, 3)\n',
714 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000715
716 def test_two_abs_args(self):
717 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000718 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000719 cmds_after_breakpoint=['py-list 1,3'])
720
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000721 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
722 ' 2 \n'
723 ' 3 def foo(a, b, c):\n',
724 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725
726class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000727 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100728 @unittest.skipIf(python_is_optimized(),
729 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000730 def test_pyup_command(self):
731 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000732 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100733 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000734 self.assertMultilineMatches(bt,
735 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100736#[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 +0000737 baz\(a, b, c\)
738$''')
739
Victor Stinner50eb60e2010-04-20 22:32:07 +0000740 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000741 def test_down_at_bottom(self):
742 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000743 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000744 cmds_after_breakpoint=['py-down'])
745 self.assertEndsWith(bt,
746 'Unable to find a newer python frame\n')
747
Victor Stinner50eb60e2010-04-20 22:32:07 +0000748 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000749 def test_up_at_top(self):
750 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000751 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100752 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000753 self.assertEndsWith(bt,
754 'Unable to find an older python frame\n')
755
Victor Stinner50eb60e2010-04-20 22:32:07 +0000756 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100757 @unittest.skipIf(python_is_optimized(),
758 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000759 def test_up_then_down(self):
760 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000761 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100762 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000763 self.assertMultilineMatches(bt,
764 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100765#[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 +0000766 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100767#[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 +0000768 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000769$''')
770
771class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100772 @unittest.skipIf(python_is_optimized(),
773 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200774 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000775 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000776 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000777 cmds_after_breakpoint=['py-bt'])
778 self.assertMultilineMatches(bt,
779 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200780Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100781 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200782 File ".*gdb_sample.py", line 10, in baz
783 id\(42\)
784 File ".*gdb_sample.py", line 7, in bar
785 baz\(a, b, c\)
786 File ".*gdb_sample.py", line 4, in foo
787 bar\(a, b, c\)
788 File ".*gdb_sample.py", line 12, in <module>
789 foo\(1, 2, 3\)
790''')
791
Victor Stinnerd2084162011-12-19 13:42:24 +0100792 @unittest.skipIf(python_is_optimized(),
793 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200794 def test_bt_full(self):
795 'Verify that the "py-bt-full" command works'
796 bt = self.get_stack_trace(script=self.get_sample_script(),
797 cmds_after_breakpoint=['py-bt-full'])
798 self.assertMultilineMatches(bt,
799 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100800#[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 +0000801 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100802#[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 +0000803 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100804#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100805 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000806''')
807
David Malcolm8d37ffa2012-06-27 14:15:34 -0400808 def test_threads(self):
809 'Verify that "py-bt" indicates threads that are waiting for the GIL'
810 cmd = '''
811from threading import Thread
812
813class TestThread(Thread):
814 # These threads would run forever, but we'll interrupt things with the
815 # debugger
816 def run(self):
817 i = 0
818 while 1:
819 i += 1
820
821t = {}
822for i in range(4):
823 t[i] = TestThread()
824 t[i].start()
825
826# Trigger a breakpoint on the main thread
827id(42)
828
829'''
830 # Verify with "py-bt":
831 gdb_output = self.get_stack_trace(cmd,
832 cmds_after_breakpoint=['thread apply all py-bt'])
833 self.assertIn('Waiting for the GIL', gdb_output)
834
835 # Verify with "py-bt-full":
836 gdb_output = self.get_stack_trace(cmd,
837 cmds_after_breakpoint=['thread apply all py-bt-full'])
838 self.assertIn('Waiting for the GIL', gdb_output)
839
840 @unittest.skipIf(python_is_optimized(),
841 "Python was compiled with optimizations")
842 # Some older versions of gdb will fail with
843 # "Cannot find new threads: generic error"
844 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400845 def test_gc(self):
846 'Verify that "py-bt" indicates if a thread is garbage-collecting'
847 cmd = ('from gc import collect\n'
848 'id(42)\n'
849 'def foo():\n'
850 ' collect()\n'
851 'def bar():\n'
852 ' foo()\n'
853 'bar()\n')
854 # Verify with "py-bt":
855 gdb_output = self.get_stack_trace(cmd,
856 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
857 )
858 self.assertIn('Garbage-collecting', gdb_output)
859
860 # Verify with "py-bt-full":
861 gdb_output = self.get_stack_trace(cmd,
862 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
863 )
864 self.assertIn('Garbage-collecting', gdb_output)
865
Petr Viktorinf9583772019-09-10 12:21:09 +0100866
David Malcolm8d37ffa2012-06-27 14:15:34 -0400867 @unittest.skipIf(python_is_optimized(),
868 "Python was compiled with optimizations")
869 # Some older versions of gdb will fail with
870 # "Cannot find new threads: generic error"
871 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
Petr Viktorinf9583772019-09-10 12:21:09 +0100872 #
873 # gdb will also generate many erroneous errors such as:
874 # Function "meth_varargs" not defined.
875 # This is because we are calling functions from an "external" module
876 # (_testcapimodule) rather than compiled-in functions. It seems difficult
877 # to suppress these. See also the comment in DebuggerTests.get_stack_trace
David Malcolm8d37ffa2012-06-27 14:15:34 -0400878 def test_pycfunction(self):
879 'Verify that "py-bt" displays invocations of PyCFunction instances'
Petr Viktorin64e2c642019-06-02 23:11:24 +0200880 # Various optimizations multiply the code paths by which these are
881 # called, so test a variety of calling conventions.
Petr Viktorinf9583772019-09-10 12:21:09 +0100882 for func_name, args, expected_frame in (
883 ('meth_varargs', '', 1),
884 ('meth_varargs_keywords', '', 1),
885 ('meth_o', '[]', 1),
886 ('meth_noargs', '', 1),
887 ('meth_fastcall', '', 1),
888 ('meth_fastcall_keywords', '', 1),
Petr Viktorin64e2c642019-06-02 23:11:24 +0200889 ):
Petr Viktorinf9583772019-09-10 12:21:09 +0100890 for obj in (
891 '_testcapi',
892 '_testcapi.MethClass',
893 '_testcapi.MethClass()',
894 '_testcapi.MethStatic()',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400895
Petr Viktorinf9583772019-09-10 12:21:09 +0100896 # XXX: bound methods don't yet give nice tracebacks
897 # '_testcapi.MethInstance()',
898 ):
899 with self.subTest(f'{obj}.{func_name}'):
900 cmd = textwrap.dedent(f'''
901 import _testcapi
902 def foo():
903 {obj}.{func_name}({args})
904 def bar():
905 foo()
906 bar()
907 ''')
908 # Verify with "py-bt":
909 gdb_output = self.get_stack_trace(
910 cmd,
911 breakpoint=func_name,
912 cmds_after_breakpoint=['bt', 'py-bt'],
Miss Islington (bot)bbaf5c22021-09-15 12:10:33 -0700913 # bpo-45207: Ignore 'Function "meth_varargs" not
914 # defined.' message in stderr.
915 ignore_stderr=True,
Petr Viktorinf9583772019-09-10 12:21:09 +0100916 )
917 self.assertIn(f'<built-in method {func_name}', gdb_output)
918
919 # Verify with "py-bt-full":
920 gdb_output = self.get_stack_trace(
921 cmd,
922 breakpoint=func_name,
923 cmds_after_breakpoint=['py-bt-full'],
Miss Islington (bot)bbaf5c22021-09-15 12:10:33 -0700924 # bpo-45207: Ignore 'Function "meth_varargs" not
925 # defined.' message in stderr.
926 ignore_stderr=True,
Petr Viktorinf9583772019-09-10 12:21:09 +0100927 )
928 self.assertIn(
929 f'#{expected_frame} <built-in method {func_name}',
930 gdb_output,
931 )
David Malcolm8d37ffa2012-06-27 14:15:34 -0400932
Victor Stinner61108332017-02-01 16:29:54 +0100933 @unittest.skipIf(python_is_optimized(),
934 "Python was compiled with optimizations")
935 def test_wrapper_call(self):
936 cmd = textwrap.dedent('''
937 class MyList(list):
938 def __init__(self):
939 super().__init__() # wrapper_call()
940
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100941 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100942 l = MyList()
943 ''')
Victor Stinner79d21332018-10-09 16:54:04 +0200944 cmds_after_breakpoint = ['break wrapper_call', 'continue']
945 if CET_PROTECTION:
946 # bpo-32962: same case as in get_stack_trace():
947 # we need an additional 'next' command in order to read
948 # arguments of the innermost function of the call stack.
949 cmds_after_breakpoint.append('next')
950 cmds_after_breakpoint.append('py-bt')
951
Victor Stinner61108332017-02-01 16:29:54 +0100952 # Verify with "py-bt":
953 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79d21332018-10-09 16:54:04 +0200954 cmds_after_breakpoint=cmds_after_breakpoint)
Victor Stinner72268ae2017-02-01 18:26:14 +0100955 self.assertRegex(gdb_output,
956 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100957
David Malcolm8d37ffa2012-06-27 14:15:34 -0400958
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000959class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100960 @unittest.skipIf(python_is_optimized(),
961 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000962 def test_basic_command(self):
963 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000964 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100965 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000966 self.assertMultilineMatches(bt,
967 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
968
Vinay Sajip2549f872012-01-04 12:07:30 +0000969 @unittest.skipIf(python_is_optimized(),
970 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000971 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000972 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000973 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100974 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000975 self.assertMultilineMatches(bt,
976 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
977
Victor Stinnerd2084162011-12-19 13:42:24 +0100978 @unittest.skipIf(python_is_optimized(),
979 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000980 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000981 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100982 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000983 self.assertMultilineMatches(bt,
984 r".*\nglobal '__name__' = '__main__'\n.*")
985
Victor Stinnerd2084162011-12-19 13:42:24 +0100986 @unittest.skipIf(python_is_optimized(),
987 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000988 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000989 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100990 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000991 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100992 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000993
994class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100995 @unittest.skipIf(python_is_optimized(),
996 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000997 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000998 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100999 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001000 self.assertMultilineMatches(bt,
1001 r".*\nargs = \(1, 2, 3\)\n.*")
1002
Victor Stinner50eb60e2010-04-20 22:32:07 +00001003 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +00001004 @unittest.skipIf(python_is_optimized(),
1005 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001006 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001007 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +01001008 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001009 self.assertMultilineMatches(bt,
1010 r".*\na = 1\nb = 2\nc = 3\n.*")
1011
Victor Stinner81446fd2019-08-23 11:28:27 +01001012
1013def setUpModule():
Antoine Pitroud0f3e072013-09-21 23:56:17 +02001014 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +02001015 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +02001016 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +02001017 print(" " * 4 + line)
Victor Stinner81446fd2019-08-23 11:28:27 +01001018
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001019
1020if __name__ == "__main__":
Victor Stinner81446fd2019-08-23 11:28:27 +01001021 unittest.main()