blob: fb1480145a7e1a0e0bb146256cfaabf40a84e44e [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:
20 proc = subprocess.Popen(["gdb", "-nx", "--version"],
21 stdout=subprocess.PIPE,
Benjamin Petersoncbef66d2016-09-06 10:06:31 -070022 stderr=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020023 universal_newlines=True)
24 with proc:
25 version = proc.communicate()[0]
26 except OSError:
27 # This is what "no gdb" looks like. There may, however, be other
28 # errors that manifest this way too.
29 raise unittest.SkipTest("Couldn't find gdb on the path")
30
31 # Regex to parse:
32 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
33 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020034 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
35 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnera578eb32015-09-15 00:22:55 +020036 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020037 if match is None:
38 raise Exception("unable to parse GDB version: %r" % version)
39 return (version, int(match.group(1)), int(match.group(2)))
40
41gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040042if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020043 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
44 "embedding. Saw %s.%s:\n%s"
45 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020046 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000047
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010048if not sysconfig.is_python_build():
49 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
50
Lysandros Nikolaou59668aa2018-11-04 22:21:28 +010051if 'Clang' in platform.python_compiler() and sys.platform == 'darwin':
52 raise unittest.SkipTest("test_gdb doesn't work correctly when python is"
53 " built with LLVM clang")
54
Steve Dower6de45742019-05-24 13:00:04 -070055if ((sysconfig.get_config_var('PGO_PROF_USE_FLAG') or 'xxx') in
56 (sysconfig.get_config_var('PY_CORE_CFLAGS') or '')):
57 raise unittest.SkipTest("test_gdb is not reliable on PGO builds")
58
R David Murrayf9333022012-10-27 13:22:41 -040059# Location of custom hooks file in a repository checkout.
60checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
61 'python-gdb.py')
62
Victor Stinner51324932013-11-20 12:27:48 +010063PYTHONHASHSEED = '123'
64
Victor Stinner79d21332018-10-09 16:54:04 +020065
66def cet_protection():
67 cflags = sysconfig.get_config_var('CFLAGS')
68 if not cflags:
69 return False
70 flags = cflags.split()
71 # True if "-mcet -fcf-protection" options are found, but false
72 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
73 return (('-mcet' in flags)
74 and any((flag.startswith('-fcf-protection')
75 and not flag.endswith(("=none", "=return")))
76 for flag in flags))
77
78# Control-flow enforcement technology
79CET_PROTECTION = cet_protection()
80
81
R David Murrayf9333022012-10-27 13:22:41 -040082def run_gdb(*args, **env_vars):
83 """Runs gdb in --batch mode with the additional arguments given by *args.
84
85 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
86 """
87 if env_vars:
88 env = os.environ.copy()
89 env.update(env_vars)
90 else:
91 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020092 # -nx: Do not execute commands from any .gdbinit initialization files
93 # (issue #22188)
94 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040095 if (gdb_major_version, gdb_minor_version) >= (7, 4):
96 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020097 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000098 # Redirect stdin to prevent GDB from messing with
99 # the terminal settings
100 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200101 stdout=subprocess.PIPE,
102 stderr=subprocess.PIPE,
103 env=env)
104 with proc:
105 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -0400106 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
107
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000108# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +0100109gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -0400110if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000111 raise unittest.SkipTest("gdb not built with embedded python support")
112
Nick Coghlance346872013-09-22 19:38:16 +1000113# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -0700114# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -0400115_, gdbpy_errors = run_gdb('--args', sys.executable)
116if "auto-loading has been declined" in gdbpy_errors:
117 msg = "gdb security settings prevent use of custom hooks: "
118 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000119
Victor Stinner50eb60e2010-04-20 22:32:07 +0000120def gdb_has_frame_select():
121 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400122 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
123 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000124 if not m:
125 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400126 gdb_frame_dir = m.group(1).split(', ')
127 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000128
129HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000130
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000131BREAKPOINT_FN='builtin_id'
132
Benjamin Peterson437df902016-09-06 20:22:41 -0700133@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000134class DebuggerTests(unittest.TestCase):
135
136 """Test that the debugger can debug Python."""
137
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000138 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000139 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000140 cmds_after_breakpoint=None,
141 import_site=False):
142 '''
143 Run 'python -c SOURCE' under gdb with a breakpoint.
144
145 Support injecting commands after the breakpoint is reached
146
147 Returns the stdout from gdb
148
149 cmds_after_breakpoint: if provided, a list of strings: gdb commands
150 '''
151 # We use "set breakpoint pending yes" to avoid blocking with a:
152 # Function "foo" not defined.
153 # Make breakpoint pending on future shared library load? (y or [n])
154 # error, which typically happens python is dynamically linked (the
155 # breakpoints of interest are to be found in the shared library)
156 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000157 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000158 # emitted to stderr each time, alas.
159
160 # Initially I had "--eval-command=continue" here, but removed it to
161 # avoid repeated print breakpoints when traversing hierarchical data
162 # structures
163
164 # Generate a list of commands in gdb's language:
165 commands = ['set breakpoint pending yes',
166 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200167
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200168 # The tests assume that the first frame of printed
169 # backtrace will not contain program counter,
170 # that is however not guaranteed by gdb
171 # therefore we need to use 'set print address off' to
172 # make sure the counter is not there. For example:
173 # #0 in PyObject_Print ...
174 # is assumed, but sometimes this can be e.g.
175 # #0 0x00003fffb7dd1798 in PyObject_Print ...
176 'set print address off',
177
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000178 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200179
180 # GDB as of 7.4 onwards can distinguish between the
181 # value of a variable at entry vs current value:
182 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
183 # which leads to the selftests failing with errors like this:
184 # AssertionError: 'v@entry=()' != '()'
185 # Disable this:
186 if (gdb_major_version, gdb_minor_version) >= (7, 4):
187 commands += ['set print entry-values no']
188
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000189 if cmds_after_breakpoint:
Victor Stinner79d21332018-10-09 16:54:04 +0200190 if CET_PROTECTION:
191 # bpo-32962: When Python is compiled with -mcet
192 # -fcf-protection, function arguments are unusable before
193 # running the first instruction of the function entry point.
194 # The 'next' command makes the required first step.
195 commands += ['next']
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200196 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000197 else:
198 commands += ['backtrace']
199
200 # print commands
201
202 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000203 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000204 args += ["--args",
205 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100206 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000207
208 if not import_site:
209 # -S suppresses the default 'import site'
210 args += ["-S"]
211
212 if source:
213 args += ["-c", source]
214 elif script:
215 args += [script]
216
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000217 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100218 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000219
Victor Stinnere56a1232019-06-21 23:17:30 +0200220 for line in err.splitlines():
221 print(line, file=sys.stderr)
Antoine Pitrou81641d62013-05-01 00:15:44 +0200222
Victor Stinnere56a1232019-06-21 23:17:30 +0200223 # bpo-34007: Sometimes some versions of the shared libraries that
224 # are part of the traceback are compiled in optimised mode and the
225 # Program Counter (PC) is not present, not allowing gdb to walk the
226 # frames back. When this happens, the Python bindings of gdb raise
227 # an exception, making the test impossible to succeed.
228 if "PC not saved" in err:
229 raise unittest.SkipTest("gdb cannot walk the frame object"
230 " because the Program Counter is"
231 " not present")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000232
Victor Stinner7bf069b2020-03-20 08:23:26 +0100233 # bpo-40019: Skip the test if gdb failed to read debug information
234 # because the Python binary is optimized.
235 for pattern in (
236 '(frame information optimized out)',
237 'Unable to read information on python frame',
238 ):
239 if pattern in out:
240 raise unittest.SkipTest(f"{pattern!r} found in gdb output")
241
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000242 return out
243
244 def get_gdb_repr(self, source,
245 cmds_after_breakpoint=None,
246 import_site=False):
247 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000248 # run "python -c'id(DATA)'" under gdb with a breakpoint on
249 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000250 # parameter, and verify that the gdb displays the same string
251 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000252 # Verify that the gdb displays the expected string
253 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000254 # For a nested structure, the first time we hit the breakpoint will
255 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100256
257 # NOTE: avoid decoding too much of the traceback as some
258 # undecodable characters may lurk there in optimized mode
259 # (issue #19743).
260 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000261 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262 cmds_after_breakpoint=cmds_after_breakpoint,
263 import_site=import_site)
264 # gdb can insert additional '\n' and space characters in various places
265 # in its output, depending on the width of the terminal it's connected
266 # to (using its "wrap_here" function)
Victor Stinner64b4a3a2019-09-26 16:54:13 +0200267 m = re.search(
268 # Match '#0 builtin_id(self=..., v=...)'
269 r'#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)?\)'
270 # Match ' at Python/bltinmodule.c'.
271 # bpo-38239: builtin_id() is defined in Python/bltinmodule.c,
272 # but accept any "Directory\file.c" to support Link Time
273 # Optimization (LTO).
274 r'\s+at\s+\S*[A-Za-z]+/[A-Za-z0-9_-]+\.c',
275 gdb_output, re.DOTALL)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000276 if not m:
277 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
278 return m.group(1), gdb_output
279
280 def assertEndsWith(self, actual, exp_end):
281 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000282 self.assertTrue(actual.endswith(exp_end),
283 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000284
285 def assertMultilineMatches(self, actual, pattern):
286 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000287 if not m:
288 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000289
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000290 def get_sample_script(self):
291 return findfile('gdb_sample.py')
292
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000293class PrettyPrintTests(DebuggerTests):
294 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000295 gdb_output = self.get_stack_trace('id(42)')
296 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000297
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100298 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000299 # Ensure that gdb's rendering of the value in a debugged process
300 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100301 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000302 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100303 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000304 self.assertEqual(gdb_repr, exp_repr,
305 ('%r did not equal expected %r; full output was:\n%s'
306 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000307
308 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300309 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100310 self.assertGdbRepr(42)
311 self.assertGdbRepr(0)
312 self.assertGdbRepr(-7)
313 self.assertGdbRepr(1000000000000)
314 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000315
316 def test_singletons(self):
317 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100318 self.assertGdbRepr(True)
319 self.assertGdbRepr(False)
320 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000321
322 def test_dicts(self):
323 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100324 self.assertGdbRepr({})
325 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900326 # Python preserves insertion order since 3.6
327 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000328
329 def test_lists(self):
330 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100331 self.assertGdbRepr([])
332 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000333
334 def test_bytes(self):
335 'Verify the pretty-printing of bytes'
336 self.assertGdbRepr(b'')
337 self.assertGdbRepr(b'And now for something hopefully the same')
338 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
339 self.assertGdbRepr(b'this is a tab:\t'
340 b' this is a slash-N:\n'
341 b' this is a slash-R:\r'
342 )
343
344 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
345
346 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000347
348 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000349 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400350 # We cannot simply call locale.getpreferredencoding() here,
351 # as GDB might have been linked against a different version
352 # of Python with a different encoding and coercion policy
353 # with respect to PEP 538 and PEP 540.
354 out, err = run_gdb(
355 '--eval-command',
356 'python import locale; print(locale.getpreferredencoding())')
357
358 encoding = out.rstrip()
359 if err or not encoding:
360 raise RuntimeError(
361 f'unable to determine the preferred encoding '
362 f'of embedded Python in GDB: {err}')
363
Victor Stinner150016f2010-05-19 23:04:56 +0000364 def check_repr(text):
365 try:
366 text.encode(encoding)
Victor Stinner150016f2010-05-19 23:04:56 +0000367 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000368 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000369 else:
370 self.assertGdbRepr(text)
371
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000372 self.assertGdbRepr('')
373 self.assertGdbRepr('And now for something hopefully the same')
374 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000375
376 # Test printing a single character:
377 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000378 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000379
380 # Test printing a Japanese unicode string
381 # (I believe this reads "mojibake", using 3 characters from the CJK
382 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000383 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000384
385 # Test a character outside the BMP:
386 # U+1D121 MUSICAL SYMBOL C CLEF
387 # This is:
388 # UTF-8: 0xF0 0x9D 0x84 0xA1
389 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000390 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000391
392 def test_tuples(self):
393 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100394 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000395 self.assertGdbRepr((1,), '(1,)')
396 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000397
398 def test_sets(self):
399 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200400 if (gdb_major_version, gdb_minor_version) < (7, 3):
401 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100402 self.assertGdbRepr(set(), "set()")
403 self.assertGdbRepr(set(['a']), "{'a'}")
404 # PYTHONHASHSEED is need to get the exact frozenset item order
405 if not sys.flags.ignore_environment:
406 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
407 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000408
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000409 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410 # which happens on deletion:
411 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100412s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000413id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000414 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000415
416 def test_frozensets(self):
417 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200418 if (gdb_major_version, gdb_minor_version) < (7, 3):
419 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100420 self.assertGdbRepr(frozenset(), "frozenset()")
421 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
422 # PYTHONHASHSEED is need to get the exact frozenset item order
423 if not sys.flags.ignore_environment:
424 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
425 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000426
427 def test_exceptions(self):
428 # Test a RuntimeError
429 gdb_repr, gdb_output = self.get_gdb_repr('''
430try:
431 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000432except RuntimeError as e:
433 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000434''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000435 self.assertEqual(gdb_repr,
436 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000437
438
439 # Test division by zero:
440 gdb_repr, gdb_output = self.get_gdb_repr('''
441try:
442 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000443except ZeroDivisionError as e:
444 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000445''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000446 self.assertEqual(gdb_repr,
447 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000448
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000449 def test_modern_class(self):
450 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000451 gdb_repr, gdb_output = self.get_gdb_repr('''
452class Foo:
453 pass
454foo = Foo()
455foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000456id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100457 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000458 self.assertTrue(m,
459 msg='Unexpected new-style class rendering %r' % gdb_repr)
460
461 def test_subclassing_list(self):
462 'Verify the pretty-printing of an instance of a list subclass'
463 gdb_repr, gdb_output = self.get_gdb_repr('''
464class Foo(list):
465 pass
466foo = Foo()
467foo += [1, 2, 3]
468foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000469id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100470 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 +0000471
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000472 self.assertTrue(m,
473 msg='Unexpected new-style class rendering %r' % gdb_repr)
474
475 def test_subclassing_tuple(self):
476 'Verify the pretty-printing of an instance of a tuple subclass'
477 # This should exercise the negative tp_dictoffset code in the
478 # new-style class support
479 gdb_repr, gdb_output = self.get_gdb_repr('''
480class Foo(tuple):
481 pass
482foo = Foo((1, 2, 3))
483foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000484id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100485 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 +0000486
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000487 self.assertTrue(m,
488 msg='Unexpected new-style class rendering %r' % gdb_repr)
489
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000490 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000491 '''Run Python under gdb, corrupting variables in the inferior process
492 immediately before taking a backtrace.
493
494 Verify that the variable's representation is the expected failsafe
495 representation'''
496 if corruption:
497 cmds_after_breakpoint=[corruption, 'backtrace']
498 else:
499 cmds_after_breakpoint=['backtrace']
500
501 gdb_repr, gdb_output = \
502 self.get_gdb_repr(source,
503 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504 if exprepr:
505 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000506 # gdb managed to print the value in spite of the corruption;
507 # this is good (see http://bugs.python.org/issue8330)
508 return
509
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000510 # Match anything for the type name; 0xDEADBEEF could point to
511 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100512 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000513
514 m = re.match(pattern, gdb_repr)
515 if not m:
516 self.fail('Unexpected gdb representation: %r\n%s' % \
517 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000518
519 def test_NULL_ptr(self):
520 'Ensure that a NULL PyObject* is handled gracefully'
521 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000522 self.get_gdb_repr('id(42)',
523 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000524 'backtrace'])
525 )
526
Ezio Melottib3aedd42010-11-20 19:04:17 +0000527 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000528
529 def test_NULL_ob_type(self):
530 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000531 self.assertSane('id(42)',
532 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000533
534 def test_corrupt_ob_type(self):
535 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000536 self.assertSane('id(42)',
537 'set v->ob_type=0xDEADBEEF',
538 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000539
540 def test_corrupt_tp_flags(self):
541 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000542 self.assertSane('id(42)',
543 'set v->ob_type->tp_flags=0x0',
544 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000545
546 def test_corrupt_tp_name(self):
547 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000548 self.assertSane('id(42)',
549 'set v->ob_type->tp_name=0xDEADBEEF',
550 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000551
552 def test_builtins_help(self):
553 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100554
555 if sys.flags.no_site:
556 self.skipTest("need site module, but -S option was used")
557
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000558 # (this was the issue causing tracebacks in
559 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000560 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000561
Antoine Pitrou4d098732011-11-26 01:42:03 +0100562 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000563 self.assertTrue(m,
564 msg='Unexpected rendering %r' % gdb_repr)
565
566 def test_selfreferential_list(self):
567 '''Ensure that a reference loop involving a list doesn't lead proxyval
568 into an infinite loop:'''
569 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000570 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000571 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000572
573 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000574 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000575 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000576
577 def test_selfreferential_dict(self):
578 '''Ensure that a reference loop involving a dict doesn't lead proxyval
579 into an infinite loop:'''
580 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000581 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000582
Ezio Melottib3aedd42010-11-20 19:04:17 +0000583 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000584
585 def test_selfreferential_old_style_instance(self):
586 gdb_repr, gdb_output = \
587 self.get_gdb_repr('''
588class Foo:
589 pass
590foo = Foo()
591foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000592id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400593 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000594 gdb_repr),
595 'Unexpected gdb representation: %r\n%s' % \
596 (gdb_repr, gdb_output))
597
598 def test_selfreferential_new_style_instance(self):
599 gdb_repr, gdb_output = \
600 self.get_gdb_repr('''
601class Foo(object):
602 pass
603foo = Foo()
604foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000605id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400606 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000607 gdb_repr),
608 'Unexpected gdb representation: %r\n%s' % \
609 (gdb_repr, gdb_output))
610
611 gdb_repr, gdb_output = \
612 self.get_gdb_repr('''
613class Foo(object):
614 pass
615a = Foo()
616b = Foo()
617a.an_attr = b
618b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000619id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400620 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 +0000621 gdb_repr),
622 'Unexpected gdb representation: %r\n%s' % \
623 (gdb_repr, gdb_output))
624
625 def test_truncation(self):
626 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000627 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000628 self.assertEqual(gdb_repr,
629 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
630 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
631 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
632 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
633 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
634 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
635 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
636 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
637 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
638 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
639 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
640 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
641 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
642 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
643 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
644 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
645 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
646 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
647 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
648 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
649 "224, 225, 226...(truncated)")
650 self.assertEqual(len(gdb_repr),
651 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000652
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000653 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000654 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400655 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 +0000656 gdb_repr),
657 'Unexpected gdb representation: %r\n%s' % \
658 (gdb_repr, gdb_output))
659
660 def test_frames(self):
661 gdb_output = self.get_stack_trace('''
662def foo(a, b, c):
663 pass
664
665foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000666id(foo.__code__)''',
667 breakpoint='builtin_id',
668 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000669 )
R David Murray44b548d2016-09-08 13:59:53 -0400670 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 +0000671 gdb_output,
672 re.DOTALL),
673 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
674
Victor Stinnerd2084162011-12-19 13:42:24 +0100675@unittest.skipIf(python_is_optimized(),
676 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000677class PyListTests(DebuggerTests):
678 def assertListing(self, expected, actual):
679 self.assertEndsWith(actual, expected)
680
681 def test_basic_command(self):
682 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000683 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000684 cmds_after_breakpoint=['py-list'])
685
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000686 self.assertListing(' 5 \n'
687 ' 6 def bar(a, b, c):\n'
688 ' 7 baz(a, b, c)\n'
689 ' 8 \n'
690 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000691 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000692 ' 11 \n'
693 ' 12 foo(1, 2, 3)\n',
694 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000695
696 def test_one_abs_arg(self):
697 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000698 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000699 cmds_after_breakpoint=['py-list 9'])
700
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000701 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000702 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000703 ' 11 \n'
704 ' 12 foo(1, 2, 3)\n',
705 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000706
707 def test_two_abs_args(self):
708 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000709 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000710 cmds_after_breakpoint=['py-list 1,3'])
711
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000712 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
713 ' 2 \n'
714 ' 3 def foo(a, b, c):\n',
715 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000716
717class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000718 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100719 @unittest.skipIf(python_is_optimized(),
720 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000721 def test_pyup_command(self):
722 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000723 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100724 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725 self.assertMultilineMatches(bt,
726 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100727#[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 +0000728 baz\(a, b, c\)
729$''')
730
Victor Stinner50eb60e2010-04-20 22:32:07 +0000731 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000732 def test_down_at_bottom(self):
733 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000734 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000735 cmds_after_breakpoint=['py-down'])
736 self.assertEndsWith(bt,
737 'Unable to find a newer python frame\n')
738
Victor Stinner50eb60e2010-04-20 22:32:07 +0000739 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000740 def test_up_at_top(self):
741 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000742 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100743 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000744 self.assertEndsWith(bt,
745 'Unable to find an older python frame\n')
746
Victor Stinner50eb60e2010-04-20 22:32:07 +0000747 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100748 @unittest.skipIf(python_is_optimized(),
749 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000750 def test_up_then_down(self):
751 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000752 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100753 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000754 self.assertMultilineMatches(bt,
755 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100756#[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 +0000757 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100758#[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 +0000759 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000760$''')
761
762class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100763 @unittest.skipIf(python_is_optimized(),
764 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200765 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000766 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000767 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000768 cmds_after_breakpoint=['py-bt'])
769 self.assertMultilineMatches(bt,
770 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200771Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100772 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200773 File ".*gdb_sample.py", line 10, in baz
774 id\(42\)
775 File ".*gdb_sample.py", line 7, in bar
776 baz\(a, b, c\)
777 File ".*gdb_sample.py", line 4, in foo
778 bar\(a, b, c\)
779 File ".*gdb_sample.py", line 12, in <module>
780 foo\(1, 2, 3\)
781''')
782
Victor Stinnerd2084162011-12-19 13:42:24 +0100783 @unittest.skipIf(python_is_optimized(),
784 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200785 def test_bt_full(self):
786 'Verify that the "py-bt-full" command works'
787 bt = self.get_stack_trace(script=self.get_sample_script(),
788 cmds_after_breakpoint=['py-bt-full'])
789 self.assertMultilineMatches(bt,
790 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100791#[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 +0000792 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100793#[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 +0000794 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100795#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100796 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000797''')
798
David Malcolm8d37ffa2012-06-27 14:15:34 -0400799 def test_threads(self):
800 'Verify that "py-bt" indicates threads that are waiting for the GIL'
801 cmd = '''
802from threading import Thread
803
804class TestThread(Thread):
805 # These threads would run forever, but we'll interrupt things with the
806 # debugger
807 def run(self):
808 i = 0
809 while 1:
810 i += 1
811
812t = {}
813for i in range(4):
814 t[i] = TestThread()
815 t[i].start()
816
817# Trigger a breakpoint on the main thread
818id(42)
819
820'''
821 # Verify with "py-bt":
822 gdb_output = self.get_stack_trace(cmd,
823 cmds_after_breakpoint=['thread apply all py-bt'])
824 self.assertIn('Waiting for the GIL', gdb_output)
825
826 # Verify with "py-bt-full":
827 gdb_output = self.get_stack_trace(cmd,
828 cmds_after_breakpoint=['thread apply all py-bt-full'])
829 self.assertIn('Waiting for the GIL', gdb_output)
830
831 @unittest.skipIf(python_is_optimized(),
832 "Python was compiled with optimizations")
833 # Some older versions of gdb will fail with
834 # "Cannot find new threads: generic error"
835 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400836 def test_gc(self):
837 'Verify that "py-bt" indicates if a thread is garbage-collecting'
838 cmd = ('from gc import collect\n'
839 'id(42)\n'
840 'def foo():\n'
841 ' collect()\n'
842 'def bar():\n'
843 ' foo()\n'
844 'bar()\n')
845 # Verify with "py-bt":
846 gdb_output = self.get_stack_trace(cmd,
847 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
848 )
849 self.assertIn('Garbage-collecting', gdb_output)
850
851 # Verify with "py-bt-full":
852 gdb_output = self.get_stack_trace(cmd,
853 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
854 )
855 self.assertIn('Garbage-collecting', gdb_output)
856
Petr Viktorinf9583772019-09-10 12:21:09 +0100857
David Malcolm8d37ffa2012-06-27 14:15:34 -0400858 @unittest.skipIf(python_is_optimized(),
859 "Python was compiled with optimizations")
860 # Some older versions of gdb will fail with
861 # "Cannot find new threads: generic error"
862 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
Petr Viktorinf9583772019-09-10 12:21:09 +0100863 #
864 # gdb will also generate many erroneous errors such as:
865 # Function "meth_varargs" not defined.
866 # This is because we are calling functions from an "external" module
867 # (_testcapimodule) rather than compiled-in functions. It seems difficult
868 # to suppress these. See also the comment in DebuggerTests.get_stack_trace
David Malcolm8d37ffa2012-06-27 14:15:34 -0400869 def test_pycfunction(self):
870 'Verify that "py-bt" displays invocations of PyCFunction instances'
Petr Viktorin64e2c642019-06-02 23:11:24 +0200871 # Various optimizations multiply the code paths by which these are
872 # called, so test a variety of calling conventions.
Petr Viktorinf9583772019-09-10 12:21:09 +0100873 for func_name, args, expected_frame in (
874 ('meth_varargs', '', 1),
875 ('meth_varargs_keywords', '', 1),
876 ('meth_o', '[]', 1),
877 ('meth_noargs', '', 1),
878 ('meth_fastcall', '', 1),
879 ('meth_fastcall_keywords', '', 1),
Petr Viktorin64e2c642019-06-02 23:11:24 +0200880 ):
Petr Viktorinf9583772019-09-10 12:21:09 +0100881 for obj in (
882 '_testcapi',
883 '_testcapi.MethClass',
884 '_testcapi.MethClass()',
885 '_testcapi.MethStatic()',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400886
Petr Viktorinf9583772019-09-10 12:21:09 +0100887 # XXX: bound methods don't yet give nice tracebacks
888 # '_testcapi.MethInstance()',
889 ):
890 with self.subTest(f'{obj}.{func_name}'):
891 cmd = textwrap.dedent(f'''
892 import _testcapi
893 def foo():
894 {obj}.{func_name}({args})
895 def bar():
896 foo()
897 bar()
898 ''')
899 # Verify with "py-bt":
900 gdb_output = self.get_stack_trace(
901 cmd,
902 breakpoint=func_name,
903 cmds_after_breakpoint=['bt', 'py-bt'],
904 )
905 self.assertIn(f'<built-in method {func_name}', gdb_output)
906
907 # Verify with "py-bt-full":
908 gdb_output = self.get_stack_trace(
909 cmd,
910 breakpoint=func_name,
911 cmds_after_breakpoint=['py-bt-full'],
912 )
913 self.assertIn(
914 f'#{expected_frame} <built-in method {func_name}',
915 gdb_output,
916 )
David Malcolm8d37ffa2012-06-27 14:15:34 -0400917
Victor Stinner61108332017-02-01 16:29:54 +0100918 @unittest.skipIf(python_is_optimized(),
919 "Python was compiled with optimizations")
920 def test_wrapper_call(self):
921 cmd = textwrap.dedent('''
922 class MyList(list):
923 def __init__(self):
924 super().__init__() # wrapper_call()
925
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100926 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100927 l = MyList()
928 ''')
Victor Stinner79d21332018-10-09 16:54:04 +0200929 cmds_after_breakpoint = ['break wrapper_call', 'continue']
930 if CET_PROTECTION:
931 # bpo-32962: same case as in get_stack_trace():
932 # we need an additional 'next' command in order to read
933 # arguments of the innermost function of the call stack.
934 cmds_after_breakpoint.append('next')
935 cmds_after_breakpoint.append('py-bt')
936
Victor Stinner61108332017-02-01 16:29:54 +0100937 # Verify with "py-bt":
938 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79d21332018-10-09 16:54:04 +0200939 cmds_after_breakpoint=cmds_after_breakpoint)
Victor Stinner72268ae2017-02-01 18:26:14 +0100940 self.assertRegex(gdb_output,
941 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100942
David Malcolm8d37ffa2012-06-27 14:15:34 -0400943
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000944class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100945 @unittest.skipIf(python_is_optimized(),
946 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000947 def test_basic_command(self):
948 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000949 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100950 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000951 self.assertMultilineMatches(bt,
952 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
953
Vinay Sajip2549f872012-01-04 12:07:30 +0000954 @unittest.skipIf(python_is_optimized(),
955 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000956 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000957 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000958 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100959 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000960 self.assertMultilineMatches(bt,
961 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
962
Victor Stinnerd2084162011-12-19 13:42:24 +0100963 @unittest.skipIf(python_is_optimized(),
964 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000965 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000966 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100967 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000968 self.assertMultilineMatches(bt,
969 r".*\nglobal '__name__' = '__main__'\n.*")
970
Victor Stinnerd2084162011-12-19 13:42:24 +0100971 @unittest.skipIf(python_is_optimized(),
972 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000973 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000974 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100975 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000976 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100977 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000978
979class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100980 @unittest.skipIf(python_is_optimized(),
981 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000982 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000983 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100984 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000985 self.assertMultilineMatches(bt,
986 r".*\nargs = \(1, 2, 3\)\n.*")
987
Victor Stinner50eb60e2010-04-20 22:32:07 +0000988 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000989 @unittest.skipIf(python_is_optimized(),
990 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000991 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000992 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100993 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000994 self.assertMultilineMatches(bt,
995 r".*\na = 1\nb = 2\nc = 3\n.*")
996
Victor Stinner81446fd2019-08-23 11:28:27 +0100997
998def setUpModule():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200999 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +02001000 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +02001001 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +02001002 print(" " * 4 + line)
Victor Stinner81446fd2019-08-23 11:28:27 +01001003
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001004
1005if __name__ == "__main__":
Victor Stinner81446fd2019-08-23 11:28:27 +01001006 unittest.main()