blob: f043c9256e02fd7a905706c420c296275d3172c0 [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
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000016from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000017
Victor Stinner5b6b4a82015-09-02 23:19:55 +020018def get_gdb_version():
19 try:
Miss Islington (bot)d9e90492020-04-29 08:30:01 -070020 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:
Miss Islington (bot)d9e90492020-04-29 08:30:01 -070026 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 Stinnera578eb32015-09-15 00:22:55 +020042 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020043 if match is None:
44 raise Exception("unable to parse GDB version: %r" % version)
45 return (version, int(match.group(1)), int(match.group(2)))
46
47gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040048if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020049 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
50 "embedding. Saw %s.%s:\n%s"
51 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020052 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000053
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010054if not sysconfig.is_python_build():
55 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
56
Lysandros Nikolaou59668aa2018-11-04 22:21:28 +010057if 'Clang' in platform.python_compiler() and sys.platform == 'darwin':
58 raise unittest.SkipTest("test_gdb doesn't work correctly when python is"
59 " built with LLVM clang")
60
Steve Dower6de45742019-05-24 13:00:04 -070061if ((sysconfig.get_config_var('PGO_PROF_USE_FLAG') or 'xxx') in
62 (sysconfig.get_config_var('PY_CORE_CFLAGS') or '')):
63 raise unittest.SkipTest("test_gdb is not reliable on PGO builds")
64
R David Murrayf9333022012-10-27 13:22:41 -040065# Location of custom hooks file in a repository checkout.
66checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
67 'python-gdb.py')
68
Victor Stinner51324932013-11-20 12:27:48 +010069PYTHONHASHSEED = '123'
70
Victor Stinner79d21332018-10-09 16:54:04 +020071
72def cet_protection():
73 cflags = sysconfig.get_config_var('CFLAGS')
74 if not cflags:
75 return False
76 flags = cflags.split()
77 # True if "-mcet -fcf-protection" options are found, but false
78 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
79 return (('-mcet' in flags)
80 and any((flag.startswith('-fcf-protection')
81 and not flag.endswith(("=none", "=return")))
82 for flag in flags))
83
84# Control-flow enforcement technology
85CET_PROTECTION = cet_protection()
86
87
R David Murrayf9333022012-10-27 13:22:41 -040088def run_gdb(*args, **env_vars):
89 """Runs gdb in --batch mode with the additional arguments given by *args.
90
91 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
92 """
93 if env_vars:
94 env = os.environ.copy()
95 env.update(env_vars)
96 else:
97 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020098 # -nx: Do not execute commands from any .gdbinit initialization files
99 # (issue #22188)
100 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -0400101 if (gdb_major_version, gdb_minor_version) >= (7, 4):
102 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200103 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +0000104 # Redirect stdin to prevent GDB from messing with
105 # the terminal settings
106 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200107 stdout=subprocess.PIPE,
108 stderr=subprocess.PIPE,
109 env=env)
110 with proc:
111 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -0400112 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
113
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000114# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +0100115gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -0400116if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000117 raise unittest.SkipTest("gdb not built with embedded python support")
118
Nick Coghlance346872013-09-22 19:38:16 +1000119# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -0700120# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -0400121_, gdbpy_errors = run_gdb('--args', sys.executable)
122if "auto-loading has been declined" in gdbpy_errors:
123 msg = "gdb security settings prevent use of custom hooks: "
124 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000125
Victor Stinner50eb60e2010-04-20 22:32:07 +0000126def gdb_has_frame_select():
127 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400128 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
129 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000130 if not m:
131 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400132 gdb_frame_dir = m.group(1).split(', ')
133 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000134
135HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000136
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000137BREAKPOINT_FN='builtin_id'
138
Benjamin Peterson437df902016-09-06 20:22:41 -0700139@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000140class DebuggerTests(unittest.TestCase):
141
142 """Test that the debugger can debug Python."""
143
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000144 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000145 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000146 cmds_after_breakpoint=None,
147 import_site=False):
148 '''
149 Run 'python -c SOURCE' under gdb with a breakpoint.
150
151 Support injecting commands after the breakpoint is reached
152
153 Returns the stdout from gdb
154
155 cmds_after_breakpoint: if provided, a list of strings: gdb commands
156 '''
157 # We use "set breakpoint pending yes" to avoid blocking with a:
158 # Function "foo" not defined.
159 # Make breakpoint pending on future shared library load? (y or [n])
160 # error, which typically happens python is dynamically linked (the
161 # breakpoints of interest are to be found in the shared library)
162 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000163 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000164 # emitted to stderr each time, alas.
165
166 # Initially I had "--eval-command=continue" here, but removed it to
167 # avoid repeated print breakpoints when traversing hierarchical data
168 # structures
169
170 # Generate a list of commands in gdb's language:
171 commands = ['set breakpoint pending yes',
172 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200173
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200174 # The tests assume that the first frame of printed
175 # backtrace will not contain program counter,
176 # that is however not guaranteed by gdb
177 # therefore we need to use 'set print address off' to
178 # make sure the counter is not there. For example:
179 # #0 in PyObject_Print ...
180 # is assumed, but sometimes this can be e.g.
181 # #0 0x00003fffb7dd1798 in PyObject_Print ...
182 'set print address off',
183
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000184 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200185
186 # GDB as of 7.4 onwards can distinguish between the
187 # value of a variable at entry vs current value:
188 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
189 # which leads to the selftests failing with errors like this:
190 # AssertionError: 'v@entry=()' != '()'
191 # Disable this:
192 if (gdb_major_version, gdb_minor_version) >= (7, 4):
193 commands += ['set print entry-values no']
194
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000195 if cmds_after_breakpoint:
Victor Stinner79d21332018-10-09 16:54:04 +0200196 if CET_PROTECTION:
197 # bpo-32962: When Python is compiled with -mcet
198 # -fcf-protection, function arguments are unusable before
199 # running the first instruction of the function entry point.
200 # The 'next' command makes the required first step.
201 commands += ['next']
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200202 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203 else:
204 commands += ['backtrace']
205
206 # print commands
207
208 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000209 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000210 args += ["--args",
211 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100212 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000213
214 if not import_site:
215 # -S suppresses the default 'import site'
216 args += ["-S"]
217
218 if source:
219 args += ["-c", source]
220 elif script:
221 args += [script]
222
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000223 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100224 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000225
Miss Islington (bot)3523e0c2019-06-21 14:39:58 -0700226 for line in err.splitlines():
227 print(line, file=sys.stderr)
Antoine Pitrou81641d62013-05-01 00:15:44 +0200228
Miss Islington (bot)3523e0c2019-06-21 14:39:58 -0700229 # bpo-34007: Sometimes some versions of the shared libraries that
230 # are part of the traceback are compiled in optimised mode and the
231 # Program Counter (PC) is not present, not allowing gdb to walk the
232 # frames back. When this happens, the Python bindings of gdb raise
233 # an exception, making the test impossible to succeed.
234 if "PC not saved" in err:
235 raise unittest.SkipTest("gdb cannot walk the frame object"
236 " because the Program Counter is"
237 " not present")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000238
Miss Islington (bot)4ced9a72020-03-31 10:27:41 -0700239 # bpo-40019: Skip the test if gdb failed to read debug information
240 # because the Python binary is optimized.
241 for pattern in (
242 '(frame information optimized out)',
243 'Unable to read information on python frame',
244 ):
245 if pattern in out:
246 raise unittest.SkipTest(f"{pattern!r} found in gdb output")
247
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000248 return out
249
250 def get_gdb_repr(self, source,
251 cmds_after_breakpoint=None,
252 import_site=False):
253 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000254 # run "python -c'id(DATA)'" under gdb with a breakpoint on
255 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000256 # parameter, and verify that the gdb displays the same string
257 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000258 # Verify that the gdb displays the expected string
259 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000260 # For a nested structure, the first time we hit the breakpoint will
261 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100262
263 # NOTE: avoid decoding too much of the traceback as some
264 # undecodable characters may lurk there in optimized mode
265 # (issue #19743).
266 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000267 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000268 cmds_after_breakpoint=cmds_after_breakpoint,
269 import_site=import_site)
270 # gdb can insert additional '\n' and space characters in various places
271 # in its output, depending on the width of the terminal it's connected
272 # to (using its "wrap_here" function)
Miss Islington (bot)c9893402019-09-26 08:13:39 -0700273 m = re.search(
274 # Match '#0 builtin_id(self=..., v=...)'
275 r'#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)?\)'
276 # Match ' at Python/bltinmodule.c'.
277 # bpo-38239: builtin_id() is defined in Python/bltinmodule.c,
278 # but accept any "Directory\file.c" to support Link Time
279 # Optimization (LTO).
280 r'\s+at\s+\S*[A-Za-z]+/[A-Za-z0-9_-]+\.c',
281 gdb_output, re.DOTALL)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000282 if not m:
283 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
284 return m.group(1), gdb_output
285
286 def assertEndsWith(self, actual, exp_end):
287 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000288 self.assertTrue(actual.endswith(exp_end),
289 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000290
291 def assertMultilineMatches(self, actual, pattern):
292 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000293 if not m:
294 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000295
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000296 def get_sample_script(self):
297 return findfile('gdb_sample.py')
298
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000299class PrettyPrintTests(DebuggerTests):
300 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000301 gdb_output = self.get_stack_trace('id(42)')
302 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000303
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100304 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000305 # Ensure that gdb's rendering of the value in a debugged process
306 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100307 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000308 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100309 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000310 self.assertEqual(gdb_repr, exp_repr,
311 ('%r did not equal expected %r; full output was:\n%s'
312 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000313
314 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300315 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100316 self.assertGdbRepr(42)
317 self.assertGdbRepr(0)
318 self.assertGdbRepr(-7)
319 self.assertGdbRepr(1000000000000)
320 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000321
322 def test_singletons(self):
323 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100324 self.assertGdbRepr(True)
325 self.assertGdbRepr(False)
326 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000327
328 def test_dicts(self):
329 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100330 self.assertGdbRepr({})
331 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900332 # Python preserves insertion order since 3.6
333 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000334
335 def test_lists(self):
336 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100337 self.assertGdbRepr([])
338 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000339
340 def test_bytes(self):
341 'Verify the pretty-printing of bytes'
342 self.assertGdbRepr(b'')
343 self.assertGdbRepr(b'And now for something hopefully the same')
344 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
345 self.assertGdbRepr(b'this is a tab:\t'
346 b' this is a slash-N:\n'
347 b' this is a slash-R:\r'
348 )
349
350 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
351
352 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000353
354 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000355 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400356 # We cannot simply call locale.getpreferredencoding() here,
357 # as GDB might have been linked against a different version
358 # of Python with a different encoding and coercion policy
359 # with respect to PEP 538 and PEP 540.
360 out, err = run_gdb(
361 '--eval-command',
362 'python import locale; print(locale.getpreferredencoding())')
363
364 encoding = out.rstrip()
365 if err or not encoding:
366 raise RuntimeError(
367 f'unable to determine the preferred encoding '
368 f'of embedded Python in GDB: {err}')
369
Victor Stinner150016f2010-05-19 23:04:56 +0000370 def check_repr(text):
371 try:
372 text.encode(encoding)
373 printable = True
374 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000375 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000376 else:
377 self.assertGdbRepr(text)
378
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000379 self.assertGdbRepr('')
380 self.assertGdbRepr('And now for something hopefully the same')
381 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000382
383 # Test printing a single character:
384 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000385 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000386
387 # Test printing a Japanese unicode string
388 # (I believe this reads "mojibake", using 3 characters from the CJK
389 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000390 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000391
392 # Test a character outside the BMP:
393 # U+1D121 MUSICAL SYMBOL C CLEF
394 # This is:
395 # UTF-8: 0xF0 0x9D 0x84 0xA1
396 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000397 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000398
399 def test_tuples(self):
400 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100401 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000402 self.assertGdbRepr((1,), '(1,)')
403 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404
405 def test_sets(self):
406 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200407 if (gdb_major_version, gdb_minor_version) < (7, 3):
408 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100409 self.assertGdbRepr(set(), "set()")
410 self.assertGdbRepr(set(['a']), "{'a'}")
411 # PYTHONHASHSEED is need to get the exact frozenset item order
412 if not sys.flags.ignore_environment:
413 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
414 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000415
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000416 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000417 # which happens on deletion:
418 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100419s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000420id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000421 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000422
423 def test_frozensets(self):
424 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200425 if (gdb_major_version, gdb_minor_version) < (7, 3):
426 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100427 self.assertGdbRepr(frozenset(), "frozenset()")
428 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
429 # PYTHONHASHSEED is need to get the exact frozenset item order
430 if not sys.flags.ignore_environment:
431 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
432 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000433
434 def test_exceptions(self):
435 # Test a RuntimeError
436 gdb_repr, gdb_output = self.get_gdb_repr('''
437try:
438 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000439except RuntimeError as e:
440 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000441''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000442 self.assertEqual(gdb_repr,
443 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000444
445
446 # Test division by zero:
447 gdb_repr, gdb_output = self.get_gdb_repr('''
448try:
449 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000450except ZeroDivisionError as e:
451 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000452''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000453 self.assertEqual(gdb_repr,
454 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000455
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000456 def test_modern_class(self):
457 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000458 gdb_repr, gdb_output = self.get_gdb_repr('''
459class Foo:
460 pass
461foo = Foo()
462foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000463id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100464 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000465 self.assertTrue(m,
466 msg='Unexpected new-style class rendering %r' % gdb_repr)
467
468 def test_subclassing_list(self):
469 'Verify the pretty-printing of an instance of a list subclass'
470 gdb_repr, gdb_output = self.get_gdb_repr('''
471class Foo(list):
472 pass
473foo = Foo()
474foo += [1, 2, 3]
475foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000476id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100477 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 +0000478
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000479 self.assertTrue(m,
480 msg='Unexpected new-style class rendering %r' % gdb_repr)
481
482 def test_subclassing_tuple(self):
483 'Verify the pretty-printing of an instance of a tuple subclass'
484 # This should exercise the negative tp_dictoffset code in the
485 # new-style class support
486 gdb_repr, gdb_output = self.get_gdb_repr('''
487class Foo(tuple):
488 pass
489foo = Foo((1, 2, 3))
490foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000491id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100492 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 +0000493
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000494 self.assertTrue(m,
495 msg='Unexpected new-style class rendering %r' % gdb_repr)
496
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000497 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000498 '''Run Python under gdb, corrupting variables in the inferior process
499 immediately before taking a backtrace.
500
501 Verify that the variable's representation is the expected failsafe
502 representation'''
503 if corruption:
504 cmds_after_breakpoint=[corruption, 'backtrace']
505 else:
506 cmds_after_breakpoint=['backtrace']
507
508 gdb_repr, gdb_output = \
509 self.get_gdb_repr(source,
510 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000511 if exprepr:
512 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000513 # gdb managed to print the value in spite of the corruption;
514 # this is good (see http://bugs.python.org/issue8330)
515 return
516
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000517 # Match anything for the type name; 0xDEADBEEF could point to
518 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100519 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000520
521 m = re.match(pattern, gdb_repr)
522 if not m:
523 self.fail('Unexpected gdb representation: %r\n%s' % \
524 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000525
526 def test_NULL_ptr(self):
527 'Ensure that a NULL PyObject* is handled gracefully'
528 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000529 self.get_gdb_repr('id(42)',
530 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000531 'backtrace'])
532 )
533
Ezio Melottib3aedd42010-11-20 19:04:17 +0000534 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000535
536 def test_NULL_ob_type(self):
537 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000538 self.assertSane('id(42)',
539 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000540
541 def test_corrupt_ob_type(self):
542 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000543 self.assertSane('id(42)',
544 'set v->ob_type=0xDEADBEEF',
545 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000546
547 def test_corrupt_tp_flags(self):
548 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000549 self.assertSane('id(42)',
550 'set v->ob_type->tp_flags=0x0',
551 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000552
553 def test_corrupt_tp_name(self):
554 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000555 self.assertSane('id(42)',
556 'set v->ob_type->tp_name=0xDEADBEEF',
557 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000558
559 def test_builtins_help(self):
560 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100561
562 if sys.flags.no_site:
563 self.skipTest("need site module, but -S option was used")
564
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000565 # (this was the issue causing tracebacks in
566 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000567 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000568
Antoine Pitrou4d098732011-11-26 01:42:03 +0100569 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000570 self.assertTrue(m,
571 msg='Unexpected rendering %r' % gdb_repr)
572
573 def test_selfreferential_list(self):
574 '''Ensure that a reference loop involving a list doesn't lead proxyval
575 into an infinite loop:'''
576 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000577 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000578 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000579
580 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000581 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000582 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000583
584 def test_selfreferential_dict(self):
585 '''Ensure that a reference loop involving a dict doesn't lead proxyval
586 into an infinite loop:'''
587 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000588 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000589
Ezio Melottib3aedd42010-11-20 19:04:17 +0000590 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000591
592 def test_selfreferential_old_style_instance(self):
593 gdb_repr, gdb_output = \
594 self.get_gdb_repr('''
595class Foo:
596 pass
597foo = Foo()
598foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000599id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400600 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000601 gdb_repr),
602 'Unexpected gdb representation: %r\n%s' % \
603 (gdb_repr, gdb_output))
604
605 def test_selfreferential_new_style_instance(self):
606 gdb_repr, gdb_output = \
607 self.get_gdb_repr('''
608class Foo(object):
609 pass
610foo = Foo()
611foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000612id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400613 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000614 gdb_repr),
615 'Unexpected gdb representation: %r\n%s' % \
616 (gdb_repr, gdb_output))
617
618 gdb_repr, gdb_output = \
619 self.get_gdb_repr('''
620class Foo(object):
621 pass
622a = Foo()
623b = Foo()
624a.an_attr = b
625b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000626id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400627 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 +0000628 gdb_repr),
629 'Unexpected gdb representation: %r\n%s' % \
630 (gdb_repr, gdb_output))
631
632 def test_truncation(self):
633 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000634 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000635 self.assertEqual(gdb_repr,
636 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
637 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
638 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
639 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
640 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
641 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
642 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
643 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
644 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
645 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
646 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
647 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
648 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
649 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
650 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
651 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
652 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
653 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
654 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
655 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
656 "224, 225, 226...(truncated)")
657 self.assertEqual(len(gdb_repr),
658 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000659
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000660 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000661 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400662 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 +0000663 gdb_repr),
664 'Unexpected gdb representation: %r\n%s' % \
665 (gdb_repr, gdb_output))
666
667 def test_frames(self):
668 gdb_output = self.get_stack_trace('''
669def foo(a, b, c):
670 pass
671
672foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000673id(foo.__code__)''',
674 breakpoint='builtin_id',
675 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000676 )
R David Murray44b548d2016-09-08 13:59:53 -0400677 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 +0000678 gdb_output,
679 re.DOTALL),
680 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
681
Victor Stinnerd2084162011-12-19 13:42:24 +0100682@unittest.skipIf(python_is_optimized(),
683 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000684class PyListTests(DebuggerTests):
685 def assertListing(self, expected, actual):
686 self.assertEndsWith(actual, expected)
687
688 def test_basic_command(self):
689 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000690 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000691 cmds_after_breakpoint=['py-list'])
692
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000693 self.assertListing(' 5 \n'
694 ' 6 def bar(a, b, c):\n'
695 ' 7 baz(a, b, c)\n'
696 ' 8 \n'
697 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000698 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000699 ' 11 \n'
700 ' 12 foo(1, 2, 3)\n',
701 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000702
703 def test_one_abs_arg(self):
704 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000705 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000706 cmds_after_breakpoint=['py-list 9'])
707
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000708 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000709 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000710 ' 11 \n'
711 ' 12 foo(1, 2, 3)\n',
712 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000713
714 def test_two_abs_args(self):
715 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000716 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000717 cmds_after_breakpoint=['py-list 1,3'])
718
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000719 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
720 ' 2 \n'
721 ' 3 def foo(a, b, c):\n',
722 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000723
724class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000725 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100726 @unittest.skipIf(python_is_optimized(),
727 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000728 def test_pyup_command(self):
729 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000730 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100731 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000732 self.assertMultilineMatches(bt,
733 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100734#[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 +0000735 baz\(a, b, c\)
736$''')
737
Victor Stinner50eb60e2010-04-20 22:32:07 +0000738 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000739 def test_down_at_bottom(self):
740 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000741 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000742 cmds_after_breakpoint=['py-down'])
743 self.assertEndsWith(bt,
744 'Unable to find a newer python frame\n')
745
Victor Stinner50eb60e2010-04-20 22:32:07 +0000746 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000747 def test_up_at_top(self):
748 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000749 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100750 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000751 self.assertEndsWith(bt,
752 'Unable to find an older python frame\n')
753
Victor Stinner50eb60e2010-04-20 22:32:07 +0000754 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100755 @unittest.skipIf(python_is_optimized(),
756 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000757 def test_up_then_down(self):
758 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000759 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100760 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000761 self.assertMultilineMatches(bt,
762 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100763#[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 +0000764 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100765#[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 +0000766 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000767$''')
768
769class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100770 @unittest.skipIf(python_is_optimized(),
771 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200772 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000773 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000774 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000775 cmds_after_breakpoint=['py-bt'])
776 self.assertMultilineMatches(bt,
777 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200778Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100779 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200780 File ".*gdb_sample.py", line 10, in baz
781 id\(42\)
782 File ".*gdb_sample.py", line 7, in bar
783 baz\(a, b, c\)
784 File ".*gdb_sample.py", line 4, in foo
785 bar\(a, b, c\)
786 File ".*gdb_sample.py", line 12, in <module>
787 foo\(1, 2, 3\)
788''')
789
Victor Stinnerd2084162011-12-19 13:42:24 +0100790 @unittest.skipIf(python_is_optimized(),
791 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200792 def test_bt_full(self):
793 'Verify that the "py-bt-full" command works'
794 bt = self.get_stack_trace(script=self.get_sample_script(),
795 cmds_after_breakpoint=['py-bt-full'])
796 self.assertMultilineMatches(bt,
797 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100798#[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 +0000799 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100800#[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 +0000801 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100802#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100803 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000804''')
805
David Malcolm8d37ffa2012-06-27 14:15:34 -0400806 def test_threads(self):
807 'Verify that "py-bt" indicates threads that are waiting for the GIL'
808 cmd = '''
809from threading import Thread
810
811class TestThread(Thread):
812 # These threads would run forever, but we'll interrupt things with the
813 # debugger
814 def run(self):
815 i = 0
816 while 1:
817 i += 1
818
819t = {}
820for i in range(4):
821 t[i] = TestThread()
822 t[i].start()
823
824# Trigger a breakpoint on the main thread
825id(42)
826
827'''
828 # Verify with "py-bt":
829 gdb_output = self.get_stack_trace(cmd,
830 cmds_after_breakpoint=['thread apply all py-bt'])
831 self.assertIn('Waiting for the GIL', gdb_output)
832
833 # Verify with "py-bt-full":
834 gdb_output = self.get_stack_trace(cmd,
835 cmds_after_breakpoint=['thread apply all py-bt-full'])
836 self.assertIn('Waiting for the GIL', gdb_output)
837
838 @unittest.skipIf(python_is_optimized(),
839 "Python was compiled with optimizations")
840 # Some older versions of gdb will fail with
841 # "Cannot find new threads: generic error"
842 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400843 def test_gc(self):
844 'Verify that "py-bt" indicates if a thread is garbage-collecting'
845 cmd = ('from gc import collect\n'
846 'id(42)\n'
847 'def foo():\n'
848 ' collect()\n'
849 'def bar():\n'
850 ' foo()\n'
851 'bar()\n')
852 # Verify with "py-bt":
853 gdb_output = self.get_stack_trace(cmd,
854 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
855 )
856 self.assertIn('Garbage-collecting', gdb_output)
857
858 # Verify with "py-bt-full":
859 gdb_output = self.get_stack_trace(cmd,
860 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
861 )
862 self.assertIn('Garbage-collecting', gdb_output)
863
864 @unittest.skipIf(python_is_optimized(),
865 "Python was compiled with optimizations")
866 # Some older versions of gdb will fail with
867 # "Cannot find new threads: generic error"
868 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
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.
873 for py_name, py_args, c_name, expected_frame_number in (
874 ('gmtime', '', 'time_gmtime', 1), # METH_VARARGS
Jeroen Demeyerbf8e82f2019-07-23 12:39:51 +0200875 ('len', '[]', 'builtin_len', 1), # METH_O
876 ('locals', '', 'builtin_locals', 1), # METH_NOARGS
877 ('iter', '[]', 'builtin_iter', 1), # METH_FASTCALL
878 ('sorted', '[]', 'builtin_sorted', 1), # METH_FASTCALL|METH_KEYWORDS
Petr Viktorin64e2c642019-06-02 23:11:24 +0200879 ):
880 with self.subTest(c_name):
881 cmd = ('from time import gmtime\n' # (not always needed)
882 'def foo():\n'
883 f' {py_name}({py_args})\n'
884 'def bar():\n'
885 ' foo()\n'
886 'bar()\n')
887 # Verify with "py-bt":
888 gdb_output = self.get_stack_trace(
889 cmd,
890 breakpoint=c_name,
891 cmds_after_breakpoint=['bt', 'py-bt'],
892 )
893 self.assertIn(f'<built-in method {py_name}', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400894
Petr Viktorin64e2c642019-06-02 23:11:24 +0200895 # Verify with "py-bt-full":
896 gdb_output = self.get_stack_trace(
897 cmd,
898 breakpoint=c_name,
899 cmds_after_breakpoint=['py-bt-full'],
900 )
901 self.assertIn(
902 f'#{expected_frame_number} <built-in method {py_name}',
903 gdb_output,
904 )
David Malcolm8d37ffa2012-06-27 14:15:34 -0400905
Victor Stinner61108332017-02-01 16:29:54 +0100906 @unittest.skipIf(python_is_optimized(),
907 "Python was compiled with optimizations")
908 def test_wrapper_call(self):
909 cmd = textwrap.dedent('''
910 class MyList(list):
911 def __init__(self):
912 super().__init__() # wrapper_call()
913
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100914 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100915 l = MyList()
916 ''')
Victor Stinner79d21332018-10-09 16:54:04 +0200917 cmds_after_breakpoint = ['break wrapper_call', 'continue']
918 if CET_PROTECTION:
919 # bpo-32962: same case as in get_stack_trace():
920 # we need an additional 'next' command in order to read
921 # arguments of the innermost function of the call stack.
922 cmds_after_breakpoint.append('next')
923 cmds_after_breakpoint.append('py-bt')
924
Victor Stinner61108332017-02-01 16:29:54 +0100925 # Verify with "py-bt":
926 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79d21332018-10-09 16:54:04 +0200927 cmds_after_breakpoint=cmds_after_breakpoint)
Victor Stinner72268ae2017-02-01 18:26:14 +0100928 self.assertRegex(gdb_output,
929 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100930
David Malcolm8d37ffa2012-06-27 14:15:34 -0400931
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000932class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100933 @unittest.skipIf(python_is_optimized(),
934 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000935 def test_basic_command(self):
936 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000937 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100938 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000939 self.assertMultilineMatches(bt,
940 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
941
Vinay Sajip2549f872012-01-04 12:07:30 +0000942 @unittest.skipIf(python_is_optimized(),
943 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000944 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000945 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000946 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100947 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000948 self.assertMultilineMatches(bt,
949 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
950
Victor Stinnerd2084162011-12-19 13:42:24 +0100951 @unittest.skipIf(python_is_optimized(),
952 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000953 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000954 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100955 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000956 self.assertMultilineMatches(bt,
957 r".*\nglobal '__name__' = '__main__'\n.*")
958
Victor Stinnerd2084162011-12-19 13:42:24 +0100959 @unittest.skipIf(python_is_optimized(),
960 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000961 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000962 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100963 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000964 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100965 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000966
967class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100968 @unittest.skipIf(python_is_optimized(),
969 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000970 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000971 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100972 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000973 self.assertMultilineMatches(bt,
974 r".*\nargs = \(1, 2, 3\)\n.*")
975
Victor Stinner50eb60e2010-04-20 22:32:07 +0000976 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000977 @unittest.skipIf(python_is_optimized(),
978 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000979 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000980 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100981 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000982 self.assertMultilineMatches(bt,
983 r".*\na = 1\nb = 2\nc = 3\n.*")
984
985def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200986 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200987 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200988 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200989 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000990 run_unittest(PrettyPrintTests,
991 PyListTests,
992 StackNavigationTests,
993 PyBtTests,
994 PyPrintTests,
995 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000996 )
997
998if __name__ == "__main__":
999 test_main()