blob: 44cb9a0f07b75dc1f26abf6eac8e687a5a6b2fe2 [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))
Victor Stinnere27a51c2020-08-07 17:57:56 +020054if (gdb_major_version, gdb_minor_version) >= (9, 2):
55 # gdb 9.2 on Fedora Rawhide is not reliable, see:
56 # * https://bugs.python.org/issue41473
57 # * https://bugzilla.redhat.com/show_bug.cgi?id=1866884
58 raise unittest.SkipTest("https://bugzilla.redhat.com/show_bug.cgi?id=1866884")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000059
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010060if not sysconfig.is_python_build():
61 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
62
Lysandros Nikolaou59668aa2018-11-04 22:21:28 +010063if 'Clang' in platform.python_compiler() and sys.platform == 'darwin':
64 raise unittest.SkipTest("test_gdb doesn't work correctly when python is"
65 " built with LLVM clang")
66
Steve Dower6de45742019-05-24 13:00:04 -070067if ((sysconfig.get_config_var('PGO_PROF_USE_FLAG') or 'xxx') in
68 (sysconfig.get_config_var('PY_CORE_CFLAGS') or '')):
69 raise unittest.SkipTest("test_gdb is not reliable on PGO builds")
70
R David Murrayf9333022012-10-27 13:22:41 -040071# Location of custom hooks file in a repository checkout.
72checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
73 'python-gdb.py')
74
Victor Stinner51324932013-11-20 12:27:48 +010075PYTHONHASHSEED = '123'
76
Victor Stinner79d21332018-10-09 16:54:04 +020077
78def cet_protection():
79 cflags = sysconfig.get_config_var('CFLAGS')
80 if not cflags:
81 return False
82 flags = cflags.split()
83 # True if "-mcet -fcf-protection" options are found, but false
84 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
85 return (('-mcet' in flags)
86 and any((flag.startswith('-fcf-protection')
87 and not flag.endswith(("=none", "=return")))
88 for flag in flags))
89
90# Control-flow enforcement technology
91CET_PROTECTION = cet_protection()
92
93
R David Murrayf9333022012-10-27 13:22:41 -040094def run_gdb(*args, **env_vars):
95 """Runs gdb in --batch mode with the additional arguments given by *args.
96
97 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
98 """
99 if env_vars:
100 env = os.environ.copy()
101 env.update(env_vars)
102 else:
103 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +0200104 # -nx: Do not execute commands from any .gdbinit initialization files
105 # (issue #22188)
106 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -0400107 if (gdb_major_version, gdb_minor_version) >= (7, 4):
108 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200109 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +0000110 # Redirect stdin to prevent GDB from messing with
111 # the terminal settings
112 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200113 stdout=subprocess.PIPE,
114 stderr=subprocess.PIPE,
115 env=env)
116 with proc:
117 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -0400118 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
119
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000120# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +0100121gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -0400122if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000123 raise unittest.SkipTest("gdb not built with embedded python support")
124
Nick Coghlance346872013-09-22 19:38:16 +1000125# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -0700126# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -0400127_, gdbpy_errors = run_gdb('--args', sys.executable)
128if "auto-loading has been declined" in gdbpy_errors:
129 msg = "gdb security settings prevent use of custom hooks: "
130 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000131
Victor Stinner50eb60e2010-04-20 22:32:07 +0000132def gdb_has_frame_select():
133 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400134 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
135 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000136 if not m:
137 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400138 gdb_frame_dir = m.group(1).split(', ')
139 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000140
141HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000142
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000143BREAKPOINT_FN='builtin_id'
144
Benjamin Peterson437df902016-09-06 20:22:41 -0700145@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000146class DebuggerTests(unittest.TestCase):
147
148 """Test that the debugger can debug Python."""
149
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000150 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000151 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000152 cmds_after_breakpoint=None,
153 import_site=False):
154 '''
155 Run 'python -c SOURCE' under gdb with a breakpoint.
156
157 Support injecting commands after the breakpoint is reached
158
159 Returns the stdout from gdb
160
161 cmds_after_breakpoint: if provided, a list of strings: gdb commands
162 '''
163 # We use "set breakpoint pending yes" to avoid blocking with a:
164 # Function "foo" not defined.
165 # Make breakpoint pending on future shared library load? (y or [n])
166 # error, which typically happens python is dynamically linked (the
167 # breakpoints of interest are to be found in the shared library)
168 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000169 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000170 # emitted to stderr each time, alas.
171
172 # Initially I had "--eval-command=continue" here, but removed it to
173 # avoid repeated print breakpoints when traversing hierarchical data
174 # structures
175
176 # Generate a list of commands in gdb's language:
177 commands = ['set breakpoint pending yes',
178 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200179
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200180 # The tests assume that the first frame of printed
181 # backtrace will not contain program counter,
182 # that is however not guaranteed by gdb
183 # therefore we need to use 'set print address off' to
184 # make sure the counter is not there. For example:
185 # #0 in PyObject_Print ...
186 # is assumed, but sometimes this can be e.g.
187 # #0 0x00003fffb7dd1798 in PyObject_Print ...
188 'set print address off',
189
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000190 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200191
192 # GDB as of 7.4 onwards can distinguish between the
193 # value of a variable at entry vs current value:
194 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
195 # which leads to the selftests failing with errors like this:
196 # AssertionError: 'v@entry=()' != '()'
197 # Disable this:
198 if (gdb_major_version, gdb_minor_version) >= (7, 4):
199 commands += ['set print entry-values no']
200
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000201 if cmds_after_breakpoint:
Victor Stinner79d21332018-10-09 16:54:04 +0200202 if CET_PROTECTION:
203 # bpo-32962: When Python is compiled with -mcet
204 # -fcf-protection, function arguments are unusable before
205 # running the first instruction of the function entry point.
206 # The 'next' command makes the required first step.
207 commands += ['next']
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200208 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000209 else:
210 commands += ['backtrace']
211
212 # print commands
213
214 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000215 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000216 args += ["--args",
217 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100218 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000219
220 if not import_site:
221 # -S suppresses the default 'import site'
222 args += ["-S"]
223
224 if source:
225 args += ["-c", source]
226 elif script:
227 args += [script]
228
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000229 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100230 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000231
Victor Stinnere56a1232019-06-21 23:17:30 +0200232 for line in err.splitlines():
233 print(line, file=sys.stderr)
Antoine Pitrou81641d62013-05-01 00:15:44 +0200234
Victor Stinnere56a1232019-06-21 23:17:30 +0200235 # bpo-34007: Sometimes some versions of the shared libraries that
236 # are part of the traceback are compiled in optimised mode and the
237 # Program Counter (PC) is not present, not allowing gdb to walk the
238 # frames back. When this happens, the Python bindings of gdb raise
239 # an exception, making the test impossible to succeed.
240 if "PC not saved" in err:
241 raise unittest.SkipTest("gdb cannot walk the frame object"
242 " because the Program Counter is"
243 " not present")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000244
Victor Stinner7bf069b2020-03-20 08:23:26 +0100245 # bpo-40019: Skip the test if gdb failed to read debug information
246 # because the Python binary is optimized.
247 for pattern in (
248 '(frame information optimized out)',
249 'Unable to read information on python frame',
250 ):
251 if pattern in out:
252 raise unittest.SkipTest(f"{pattern!r} found in gdb output")
253
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000254 return out
255
256 def get_gdb_repr(self, source,
257 cmds_after_breakpoint=None,
258 import_site=False):
259 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000260 # run "python -c'id(DATA)'" under gdb with a breakpoint on
261 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262 # parameter, and verify that the gdb displays the same string
263 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000264 # Verify that the gdb displays the expected string
265 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266 # For a nested structure, the first time we hit the breakpoint will
267 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100268
269 # NOTE: avoid decoding too much of the traceback as some
270 # undecodable characters may lurk there in optimized mode
271 # (issue #19743).
272 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000273 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274 cmds_after_breakpoint=cmds_after_breakpoint,
275 import_site=import_site)
276 # gdb can insert additional '\n' and space characters in various places
277 # in its output, depending on the width of the terminal it's connected
278 # to (using its "wrap_here" function)
Victor Stinner64b4a3a2019-09-26 16:54:13 +0200279 m = re.search(
280 # Match '#0 builtin_id(self=..., v=...)'
281 r'#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)?\)'
282 # Match ' at Python/bltinmodule.c'.
283 # bpo-38239: builtin_id() is defined in Python/bltinmodule.c,
284 # but accept any "Directory\file.c" to support Link Time
285 # Optimization (LTO).
286 r'\s+at\s+\S*[A-Za-z]+/[A-Za-z0-9_-]+\.c',
287 gdb_output, re.DOTALL)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000288 if not m:
289 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
290 return m.group(1), gdb_output
291
292 def assertEndsWith(self, actual, exp_end):
293 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000294 self.assertTrue(actual.endswith(exp_end),
295 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000296
297 def assertMultilineMatches(self, actual, pattern):
298 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000299 if not m:
300 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000301
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000302 def get_sample_script(self):
303 return findfile('gdb_sample.py')
304
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000305class PrettyPrintTests(DebuggerTests):
306 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000307 gdb_output = self.get_stack_trace('id(42)')
308 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000309
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100310 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000311 # Ensure that gdb's rendering of the value in a debugged process
312 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100313 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000314 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100315 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000316 self.assertEqual(gdb_repr, exp_repr,
317 ('%r did not equal expected %r; full output was:\n%s'
318 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000319
320 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300321 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100322 self.assertGdbRepr(42)
323 self.assertGdbRepr(0)
324 self.assertGdbRepr(-7)
325 self.assertGdbRepr(1000000000000)
326 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000327
328 def test_singletons(self):
329 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100330 self.assertGdbRepr(True)
331 self.assertGdbRepr(False)
332 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000333
334 def test_dicts(self):
335 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100336 self.assertGdbRepr({})
337 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900338 # Python preserves insertion order since 3.6
339 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000340
341 def test_lists(self):
342 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100343 self.assertGdbRepr([])
344 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000345
346 def test_bytes(self):
347 'Verify the pretty-printing of bytes'
348 self.assertGdbRepr(b'')
349 self.assertGdbRepr(b'And now for something hopefully the same')
350 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
351 self.assertGdbRepr(b'this is a tab:\t'
352 b' this is a slash-N:\n'
353 b' this is a slash-R:\r'
354 )
355
356 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
357
358 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000359
360 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000361 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400362 # We cannot simply call locale.getpreferredencoding() here,
363 # as GDB might have been linked against a different version
364 # of Python with a different encoding and coercion policy
365 # with respect to PEP 538 and PEP 540.
366 out, err = run_gdb(
367 '--eval-command',
368 'python import locale; print(locale.getpreferredencoding())')
369
370 encoding = out.rstrip()
371 if err or not encoding:
372 raise RuntimeError(
373 f'unable to determine the preferred encoding '
374 f'of embedded Python in GDB: {err}')
375
Victor Stinner150016f2010-05-19 23:04:56 +0000376 def check_repr(text):
377 try:
378 text.encode(encoding)
Victor Stinner150016f2010-05-19 23:04:56 +0000379 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000380 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000381 else:
382 self.assertGdbRepr(text)
383
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000384 self.assertGdbRepr('')
385 self.assertGdbRepr('And now for something hopefully the same')
386 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000387
388 # Test printing a single character:
389 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000390 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000391
392 # Test printing a Japanese unicode string
393 # (I believe this reads "mojibake", using 3 characters from the CJK
394 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000395 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000396
397 # Test a character outside the BMP:
398 # U+1D121 MUSICAL SYMBOL C CLEF
399 # This is:
400 # UTF-8: 0xF0 0x9D 0x84 0xA1
401 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000402 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000403
404 def test_tuples(self):
405 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100406 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407 self.assertGdbRepr((1,), '(1,)')
408 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000409
410 def test_sets(self):
411 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200412 if (gdb_major_version, gdb_minor_version) < (7, 3):
413 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100414 self.assertGdbRepr(set(), "set()")
415 self.assertGdbRepr(set(['a']), "{'a'}")
416 # PYTHONHASHSEED is need to get the exact frozenset item order
417 if not sys.flags.ignore_environment:
418 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
419 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000420
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000421 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000422 # which happens on deletion:
423 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100424s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000425id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000426 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000427
428 def test_frozensets(self):
429 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200430 if (gdb_major_version, gdb_minor_version) < (7, 3):
431 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100432 self.assertGdbRepr(frozenset(), "frozenset()")
433 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
434 # PYTHONHASHSEED is need to get the exact frozenset item order
435 if not sys.flags.ignore_environment:
436 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
437 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000438
439 def test_exceptions(self):
440 # Test a RuntimeError
441 gdb_repr, gdb_output = self.get_gdb_repr('''
442try:
443 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000444except RuntimeError as e:
445 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000446''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000447 self.assertEqual(gdb_repr,
448 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000449
450
451 # Test division by zero:
452 gdb_repr, gdb_output = self.get_gdb_repr('''
453try:
454 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000455except ZeroDivisionError as e:
456 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000457''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000458 self.assertEqual(gdb_repr,
459 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000460
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000461 def test_modern_class(self):
462 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000463 gdb_repr, gdb_output = self.get_gdb_repr('''
464class Foo:
465 pass
466foo = Foo()
467foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000468id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100469 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000470 self.assertTrue(m,
471 msg='Unexpected new-style class rendering %r' % gdb_repr)
472
473 def test_subclassing_list(self):
474 'Verify the pretty-printing of an instance of a list subclass'
475 gdb_repr, gdb_output = self.get_gdb_repr('''
476class Foo(list):
477 pass
478foo = Foo()
479foo += [1, 2, 3]
480foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000481id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100482 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 +0000483
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000484 self.assertTrue(m,
485 msg='Unexpected new-style class rendering %r' % gdb_repr)
486
487 def test_subclassing_tuple(self):
488 'Verify the pretty-printing of an instance of a tuple subclass'
489 # This should exercise the negative tp_dictoffset code in the
490 # new-style class support
491 gdb_repr, gdb_output = self.get_gdb_repr('''
492class Foo(tuple):
493 pass
494foo = Foo((1, 2, 3))
495foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000496id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100497 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 +0000498
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000499 self.assertTrue(m,
500 msg='Unexpected new-style class rendering %r' % gdb_repr)
501
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000502 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000503 '''Run Python under gdb, corrupting variables in the inferior process
504 immediately before taking a backtrace.
505
506 Verify that the variable's representation is the expected failsafe
507 representation'''
508 if corruption:
509 cmds_after_breakpoint=[corruption, 'backtrace']
510 else:
511 cmds_after_breakpoint=['backtrace']
512
513 gdb_repr, gdb_output = \
514 self.get_gdb_repr(source,
515 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000516 if exprepr:
517 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000518 # gdb managed to print the value in spite of the corruption;
519 # this is good (see http://bugs.python.org/issue8330)
520 return
521
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000522 # Match anything for the type name; 0xDEADBEEF could point to
523 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100524 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000525
526 m = re.match(pattern, gdb_repr)
527 if not m:
528 self.fail('Unexpected gdb representation: %r\n%s' % \
529 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000530
531 def test_NULL_ptr(self):
532 'Ensure that a NULL PyObject* is handled gracefully'
533 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000534 self.get_gdb_repr('id(42)',
535 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000536 'backtrace'])
537 )
538
Ezio Melottib3aedd42010-11-20 19:04:17 +0000539 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000540
541 def test_NULL_ob_type(self):
542 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000543 self.assertSane('id(42)',
544 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000545
546 def test_corrupt_ob_type(self):
547 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000548 self.assertSane('id(42)',
549 'set v->ob_type=0xDEADBEEF',
550 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000551
552 def test_corrupt_tp_flags(self):
553 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000554 self.assertSane('id(42)',
555 'set v->ob_type->tp_flags=0x0',
556 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000557
558 def test_corrupt_tp_name(self):
559 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000560 self.assertSane('id(42)',
561 'set v->ob_type->tp_name=0xDEADBEEF',
562 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000563
564 def test_builtins_help(self):
565 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100566
567 if sys.flags.no_site:
568 self.skipTest("need site module, but -S option was used")
569
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000570 # (this was the issue causing tracebacks in
571 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000572 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000573
Antoine Pitrou4d098732011-11-26 01:42:03 +0100574 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000575 self.assertTrue(m,
576 msg='Unexpected rendering %r' % gdb_repr)
577
578 def test_selfreferential_list(self):
579 '''Ensure that a reference loop involving a list doesn't lead proxyval
580 into an infinite loop:'''
581 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000582 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000583 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000584
585 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000586 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000587 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000588
589 def test_selfreferential_dict(self):
590 '''Ensure that a reference loop involving a dict doesn't lead proxyval
591 into an infinite loop:'''
592 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000593 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000594
Ezio Melottib3aedd42010-11-20 19:04:17 +0000595 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000596
597 def test_selfreferential_old_style_instance(self):
598 gdb_repr, gdb_output = \
599 self.get_gdb_repr('''
600class Foo:
601 pass
602foo = Foo()
603foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000604id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400605 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000606 gdb_repr),
607 'Unexpected gdb representation: %r\n%s' % \
608 (gdb_repr, gdb_output))
609
610 def test_selfreferential_new_style_instance(self):
611 gdb_repr, gdb_output = \
612 self.get_gdb_repr('''
613class Foo(object):
614 pass
615foo = Foo()
616foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000617id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400618 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000619 gdb_repr),
620 'Unexpected gdb representation: %r\n%s' % \
621 (gdb_repr, gdb_output))
622
623 gdb_repr, gdb_output = \
624 self.get_gdb_repr('''
625class Foo(object):
626 pass
627a = Foo()
628b = Foo()
629a.an_attr = b
630b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000631id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400632 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 +0000633 gdb_repr),
634 'Unexpected gdb representation: %r\n%s' % \
635 (gdb_repr, gdb_output))
636
637 def test_truncation(self):
638 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000639 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000640 self.assertEqual(gdb_repr,
641 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
642 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
643 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
644 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
645 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
646 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
647 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
648 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
649 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
650 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
651 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
652 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
653 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
654 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
655 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
656 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
657 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
658 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
659 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
660 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
661 "224, 225, 226...(truncated)")
662 self.assertEqual(len(gdb_repr),
663 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000664
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000665 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000666 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400667 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 +0000668 gdb_repr),
669 'Unexpected gdb representation: %r\n%s' % \
670 (gdb_repr, gdb_output))
671
672 def test_frames(self):
673 gdb_output = self.get_stack_trace('''
674def foo(a, b, c):
675 pass
676
677foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000678id(foo.__code__)''',
679 breakpoint='builtin_id',
680 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000681 )
R David Murray44b548d2016-09-08 13:59:53 -0400682 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 +0000683 gdb_output,
684 re.DOTALL),
685 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
686
Victor Stinnerd2084162011-12-19 13:42:24 +0100687@unittest.skipIf(python_is_optimized(),
688 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689class PyListTests(DebuggerTests):
690 def assertListing(self, expected, actual):
691 self.assertEndsWith(actual, expected)
692
693 def test_basic_command(self):
694 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000695 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 cmds_after_breakpoint=['py-list'])
697
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000698 self.assertListing(' 5 \n'
699 ' 6 def bar(a, b, c):\n'
700 ' 7 baz(a, b, c)\n'
701 ' 8 \n'
702 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000703 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000704 ' 11 \n'
705 ' 12 foo(1, 2, 3)\n',
706 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000707
708 def test_one_abs_arg(self):
709 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000710 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000711 cmds_after_breakpoint=['py-list 9'])
712
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000713 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000714 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000715 ' 11 \n'
716 ' 12 foo(1, 2, 3)\n',
717 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000718
719 def test_two_abs_args(self):
720 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000721 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000722 cmds_after_breakpoint=['py-list 1,3'])
723
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000724 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
725 ' 2 \n'
726 ' 3 def foo(a, b, c):\n',
727 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000728
729class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000730 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100731 @unittest.skipIf(python_is_optimized(),
732 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000733 def test_pyup_command(self):
734 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000735 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100736 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000737 self.assertMultilineMatches(bt,
738 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100739#[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 +0000740 baz\(a, b, c\)
741$''')
742
Victor Stinner50eb60e2010-04-20 22:32:07 +0000743 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000744 def test_down_at_bottom(self):
745 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000746 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000747 cmds_after_breakpoint=['py-down'])
748 self.assertEndsWith(bt,
749 'Unable to find a newer python frame\n')
750
Victor Stinner50eb60e2010-04-20 22:32:07 +0000751 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000752 def test_up_at_top(self):
753 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000754 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100755 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000756 self.assertEndsWith(bt,
757 'Unable to find an older python frame\n')
758
Victor Stinner50eb60e2010-04-20 22:32:07 +0000759 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100760 @unittest.skipIf(python_is_optimized(),
761 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000762 def test_up_then_down(self):
763 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000764 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100765 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000766 self.assertMultilineMatches(bt,
767 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100768#[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 +0000769 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100770#[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 +0000771 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000772$''')
773
774class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100775 @unittest.skipIf(python_is_optimized(),
776 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200777 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000778 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000779 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000780 cmds_after_breakpoint=['py-bt'])
781 self.assertMultilineMatches(bt,
782 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200783Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100784 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200785 File ".*gdb_sample.py", line 10, in baz
786 id\(42\)
787 File ".*gdb_sample.py", line 7, in bar
788 baz\(a, b, c\)
789 File ".*gdb_sample.py", line 4, in foo
790 bar\(a, b, c\)
791 File ".*gdb_sample.py", line 12, in <module>
792 foo\(1, 2, 3\)
793''')
794
Victor Stinnerd2084162011-12-19 13:42:24 +0100795 @unittest.skipIf(python_is_optimized(),
796 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200797 def test_bt_full(self):
798 'Verify that the "py-bt-full" command works'
799 bt = self.get_stack_trace(script=self.get_sample_script(),
800 cmds_after_breakpoint=['py-bt-full'])
801 self.assertMultilineMatches(bt,
802 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100803#[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 +0000804 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100805#[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 +0000806 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100807#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100808 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000809''')
810
David Malcolm8d37ffa2012-06-27 14:15:34 -0400811 def test_threads(self):
812 'Verify that "py-bt" indicates threads that are waiting for the GIL'
813 cmd = '''
814from threading import Thread
815
816class TestThread(Thread):
817 # These threads would run forever, but we'll interrupt things with the
818 # debugger
819 def run(self):
820 i = 0
821 while 1:
822 i += 1
823
824t = {}
825for i in range(4):
826 t[i] = TestThread()
827 t[i].start()
828
829# Trigger a breakpoint on the main thread
830id(42)
831
832'''
833 # Verify with "py-bt":
834 gdb_output = self.get_stack_trace(cmd,
835 cmds_after_breakpoint=['thread apply all py-bt'])
836 self.assertIn('Waiting for the GIL', gdb_output)
837
838 # Verify with "py-bt-full":
839 gdb_output = self.get_stack_trace(cmd,
840 cmds_after_breakpoint=['thread apply all py-bt-full'])
841 self.assertIn('Waiting for the GIL', gdb_output)
842
843 @unittest.skipIf(python_is_optimized(),
844 "Python was compiled with optimizations")
845 # Some older versions of gdb will fail with
846 # "Cannot find new threads: generic error"
847 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400848 def test_gc(self):
849 'Verify that "py-bt" indicates if a thread is garbage-collecting'
850 cmd = ('from gc import collect\n'
851 'id(42)\n'
852 'def foo():\n'
853 ' collect()\n'
854 'def bar():\n'
855 ' foo()\n'
856 'bar()\n')
857 # Verify with "py-bt":
858 gdb_output = self.get_stack_trace(cmd,
859 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
860 )
861 self.assertIn('Garbage-collecting', gdb_output)
862
863 # Verify with "py-bt-full":
864 gdb_output = self.get_stack_trace(cmd,
865 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
866 )
867 self.assertIn('Garbage-collecting', gdb_output)
868
Petr Viktorinf9583772019-09-10 12:21:09 +0100869
David Malcolm8d37ffa2012-06-27 14:15:34 -0400870 @unittest.skipIf(python_is_optimized(),
871 "Python was compiled with optimizations")
872 # Some older versions of gdb will fail with
873 # "Cannot find new threads: generic error"
874 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
Petr Viktorinf9583772019-09-10 12:21:09 +0100875 #
876 # gdb will also generate many erroneous errors such as:
877 # Function "meth_varargs" not defined.
878 # This is because we are calling functions from an "external" module
879 # (_testcapimodule) rather than compiled-in functions. It seems difficult
880 # to suppress these. See also the comment in DebuggerTests.get_stack_trace
David Malcolm8d37ffa2012-06-27 14:15:34 -0400881 def test_pycfunction(self):
882 'Verify that "py-bt" displays invocations of PyCFunction instances'
Petr Viktorin64e2c642019-06-02 23:11:24 +0200883 # Various optimizations multiply the code paths by which these are
884 # called, so test a variety of calling conventions.
Petr Viktorinf9583772019-09-10 12:21:09 +0100885 for func_name, args, expected_frame in (
886 ('meth_varargs', '', 1),
887 ('meth_varargs_keywords', '', 1),
888 ('meth_o', '[]', 1),
889 ('meth_noargs', '', 1),
890 ('meth_fastcall', '', 1),
891 ('meth_fastcall_keywords', '', 1),
Petr Viktorin64e2c642019-06-02 23:11:24 +0200892 ):
Petr Viktorinf9583772019-09-10 12:21:09 +0100893 for obj in (
894 '_testcapi',
895 '_testcapi.MethClass',
896 '_testcapi.MethClass()',
897 '_testcapi.MethStatic()',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400898
Petr Viktorinf9583772019-09-10 12:21:09 +0100899 # XXX: bound methods don't yet give nice tracebacks
900 # '_testcapi.MethInstance()',
901 ):
902 with self.subTest(f'{obj}.{func_name}'):
903 cmd = textwrap.dedent(f'''
904 import _testcapi
905 def foo():
906 {obj}.{func_name}({args})
907 def bar():
908 foo()
909 bar()
910 ''')
911 # Verify with "py-bt":
912 gdb_output = self.get_stack_trace(
913 cmd,
914 breakpoint=func_name,
915 cmds_after_breakpoint=['bt', 'py-bt'],
916 )
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'],
924 )
925 self.assertIn(
926 f'#{expected_frame} <built-in method {func_name}',
927 gdb_output,
928 )
David Malcolm8d37ffa2012-06-27 14:15:34 -0400929
Victor Stinner61108332017-02-01 16:29:54 +0100930 @unittest.skipIf(python_is_optimized(),
931 "Python was compiled with optimizations")
932 def test_wrapper_call(self):
933 cmd = textwrap.dedent('''
934 class MyList(list):
935 def __init__(self):
936 super().__init__() # wrapper_call()
937
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100938 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100939 l = MyList()
940 ''')
Victor Stinner79d21332018-10-09 16:54:04 +0200941 cmds_after_breakpoint = ['break wrapper_call', 'continue']
942 if CET_PROTECTION:
943 # bpo-32962: same case as in get_stack_trace():
944 # we need an additional 'next' command in order to read
945 # arguments of the innermost function of the call stack.
946 cmds_after_breakpoint.append('next')
947 cmds_after_breakpoint.append('py-bt')
948
Victor Stinner61108332017-02-01 16:29:54 +0100949 # Verify with "py-bt":
950 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79d21332018-10-09 16:54:04 +0200951 cmds_after_breakpoint=cmds_after_breakpoint)
Victor Stinner72268ae2017-02-01 18:26:14 +0100952 self.assertRegex(gdb_output,
953 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100954
David Malcolm8d37ffa2012-06-27 14:15:34 -0400955
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000956class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100957 @unittest.skipIf(python_is_optimized(),
958 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000959 def test_basic_command(self):
960 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000961 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100962 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000963 self.assertMultilineMatches(bt,
964 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
965
Vinay Sajip2549f872012-01-04 12:07:30 +0000966 @unittest.skipIf(python_is_optimized(),
967 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000968 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000969 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000970 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100971 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000972 self.assertMultilineMatches(bt,
973 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
974
Victor Stinnerd2084162011-12-19 13:42:24 +0100975 @unittest.skipIf(python_is_optimized(),
976 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000977 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000978 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100979 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000980 self.assertMultilineMatches(bt,
981 r".*\nglobal '__name__' = '__main__'\n.*")
982
Victor Stinnerd2084162011-12-19 13:42:24 +0100983 @unittest.skipIf(python_is_optimized(),
984 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000985 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000986 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100987 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000988 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100989 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000990
991class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100992 @unittest.skipIf(python_is_optimized(),
993 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000994 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000995 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100996 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000997 self.assertMultilineMatches(bt,
998 r".*\nargs = \(1, 2, 3\)\n.*")
999
Victor Stinner50eb60e2010-04-20 22:32:07 +00001000 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +00001001 @unittest.skipIf(python_is_optimized(),
1002 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001003 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +00001004 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +01001005 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001006 self.assertMultilineMatches(bt,
1007 r".*\na = 1\nb = 2\nc = 3\n.*")
1008
Victor Stinner81446fd2019-08-23 11:28:27 +01001009
1010def setUpModule():
Antoine Pitroud0f3e072013-09-21 23:56:17 +02001011 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +02001012 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +02001013 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +02001014 print(" " * 4 + line)
Victor Stinner81446fd2019-08-23 11:28:27 +01001015
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001016
1017if __name__ == "__main__":
Victor Stinner81446fd2019-08-23 11:28:27 +01001018 unittest.main()