blob: 4d1ce4ed96c06d2d441c24bb4735421384077d63 [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:
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
R David Murrayf9333022012-10-27 13:22:41 -040055# Location of custom hooks file in a repository checkout.
56checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
57 'python-gdb.py')
58
Victor Stinner51324932013-11-20 12:27:48 +010059PYTHONHASHSEED = '123'
60
Victor Stinner79d21332018-10-09 16:54:04 +020061
62def cet_protection():
63 cflags = sysconfig.get_config_var('CFLAGS')
64 if not cflags:
65 return False
66 flags = cflags.split()
67 # True if "-mcet -fcf-protection" options are found, but false
68 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
69 return (('-mcet' in flags)
70 and any((flag.startswith('-fcf-protection')
71 and not flag.endswith(("=none", "=return")))
72 for flag in flags))
73
74# Control-flow enforcement technology
75CET_PROTECTION = cet_protection()
76
77
R David Murrayf9333022012-10-27 13:22:41 -040078def run_gdb(*args, **env_vars):
79 """Runs gdb in --batch mode with the additional arguments given by *args.
80
81 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
82 """
83 if env_vars:
84 env = os.environ.copy()
85 env.update(env_vars)
86 else:
87 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020088 # -nx: Do not execute commands from any .gdbinit initialization files
89 # (issue #22188)
90 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040091 if (gdb_major_version, gdb_minor_version) >= (7, 4):
92 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020093 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000094 # Redirect stdin to prevent GDB from messing with
95 # the terminal settings
96 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020097 stdout=subprocess.PIPE,
98 stderr=subprocess.PIPE,
99 env=env)
100 with proc:
101 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -0400102 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
103
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000104# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +0100105gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -0400106if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000107 raise unittest.SkipTest("gdb not built with embedded python support")
108
Nick Coghlance346872013-09-22 19:38:16 +1000109# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -0700110# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -0400111_, gdbpy_errors = run_gdb('--args', sys.executable)
112if "auto-loading has been declined" in gdbpy_errors:
113 msg = "gdb security settings prevent use of custom hooks: "
114 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000115
Victor Stinner50eb60e2010-04-20 22:32:07 +0000116def gdb_has_frame_select():
117 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400118 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
119 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000120 if not m:
121 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400122 gdb_frame_dir = m.group(1).split(', ')
123 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000124
125HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000126
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000127BREAKPOINT_FN='builtin_id'
128
Benjamin Peterson437df902016-09-06 20:22:41 -0700129@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000130class DebuggerTests(unittest.TestCase):
131
132 """Test that the debugger can debug Python."""
133
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000134 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000135 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000136 cmds_after_breakpoint=None,
137 import_site=False):
138 '''
139 Run 'python -c SOURCE' under gdb with a breakpoint.
140
141 Support injecting commands after the breakpoint is reached
142
143 Returns the stdout from gdb
144
145 cmds_after_breakpoint: if provided, a list of strings: gdb commands
146 '''
147 # We use "set breakpoint pending yes" to avoid blocking with a:
148 # Function "foo" not defined.
149 # Make breakpoint pending on future shared library load? (y or [n])
150 # error, which typically happens python is dynamically linked (the
151 # breakpoints of interest are to be found in the shared library)
152 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000153 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000154 # emitted to stderr each time, alas.
155
156 # Initially I had "--eval-command=continue" here, but removed it to
157 # avoid repeated print breakpoints when traversing hierarchical data
158 # structures
159
160 # Generate a list of commands in gdb's language:
161 commands = ['set breakpoint pending yes',
162 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200163
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200164 # The tests assume that the first frame of printed
165 # backtrace will not contain program counter,
166 # that is however not guaranteed by gdb
167 # therefore we need to use 'set print address off' to
168 # make sure the counter is not there. For example:
169 # #0 in PyObject_Print ...
170 # is assumed, but sometimes this can be e.g.
171 # #0 0x00003fffb7dd1798 in PyObject_Print ...
172 'set print address off',
173
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000174 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200175
176 # GDB as of 7.4 onwards can distinguish between the
177 # value of a variable at entry vs current value:
178 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
179 # which leads to the selftests failing with errors like this:
180 # AssertionError: 'v@entry=()' != '()'
181 # Disable this:
182 if (gdb_major_version, gdb_minor_version) >= (7, 4):
183 commands += ['set print entry-values no']
184
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000185 if cmds_after_breakpoint:
Victor Stinner79d21332018-10-09 16:54:04 +0200186 if CET_PROTECTION:
187 # bpo-32962: When Python is compiled with -mcet
188 # -fcf-protection, function arguments are unusable before
189 # running the first instruction of the function entry point.
190 # The 'next' command makes the required first step.
191 commands += ['next']
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200192 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000193 else:
194 commands += ['backtrace']
195
196 # print commands
197
198 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000199 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000200 args += ["--args",
201 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100202 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203
204 if not import_site:
205 # -S suppresses the default 'import site'
206 args += ["-S"]
207
208 if source:
209 args += ["-c", source]
210 elif script:
211 args += [script]
212
213 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100214 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000215
216 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100217 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000218
Antoine Pitrou81641d62013-05-01 00:15:44 +0200219 errlines = err.splitlines()
220 unexpected_errlines = []
221
222 # Ignore some benign messages on stderr.
223 ignore_patterns = (
224 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200225 'Do you need "set solib-search-path" or '
226 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100227 # BFD: /usr/lib/debug/(...): unable to initialize decompress
228 # status for section .debug_aranges
229 'BFD: ',
230 # ignore all warnings
231 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200232 )
233 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100234 if not line:
235 continue
Pablo Galindof2ef51f2018-08-31 23:04:47 +0100236 # bpo34007: Sometimes some versions of the shared libraries that
237 # are part of the traceback are compiled in optimised mode and the
238 # Program Counter (PC) is not present, not allowing gdb to walk the
239 # frames back. When this happens, the Python bindings of gdb raise
240 # an exception, making the test impossible to succeed.
241 if "PC not saved" in line:
242 raise unittest.SkipTest("gdb cannot walk the frame object"
243 " because the Program Counter is"
244 " not present")
Antoine Pitrou81641d62013-05-01 00:15:44 +0200245 if not line.startswith(ignore_patterns):
246 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000247
248 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200249 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000250 return out
251
252 def get_gdb_repr(self, source,
253 cmds_after_breakpoint=None,
254 import_site=False):
255 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000256 # run "python -c'id(DATA)'" under gdb with a breakpoint on
257 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258 # parameter, and verify that the gdb displays the same string
259 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000260 # Verify that the gdb displays the expected string
261 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262 # For a nested structure, the first time we hit the breakpoint will
263 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100264
265 # NOTE: avoid decoding too much of the traceback as some
266 # undecodable characters may lurk there in optimized mode
267 # (issue #19743).
268 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000269 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000270 cmds_after_breakpoint=cmds_after_breakpoint,
271 import_site=import_site)
272 # gdb can insert additional '\n' and space characters in various places
273 # in its output, depending on the width of the terminal it's connected
274 # to (using its "wrap_here" function)
R David Murray44b548d2016-09-08 13:59:53 -0400275 m = re.match(r'.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000276 gdb_output, re.DOTALL)
277 if not m:
278 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
279 return m.group(1), gdb_output
280
281 def assertEndsWith(self, actual, exp_end):
282 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000283 self.assertTrue(actual.endswith(exp_end),
284 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000285
286 def assertMultilineMatches(self, actual, pattern):
287 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000288 if not m:
289 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000290
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000291 def get_sample_script(self):
292 return findfile('gdb_sample.py')
293
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000294class PrettyPrintTests(DebuggerTests):
295 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000296 gdb_output = self.get_stack_trace('id(42)')
297 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000298
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100299 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000300 # Ensure that gdb's rendering of the value in a debugged process
301 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100302 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000303 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100304 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000305 self.assertEqual(gdb_repr, exp_repr,
306 ('%r did not equal expected %r; full output was:\n%s'
307 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000308
309 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300310 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100311 self.assertGdbRepr(42)
312 self.assertGdbRepr(0)
313 self.assertGdbRepr(-7)
314 self.assertGdbRepr(1000000000000)
315 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000316
317 def test_singletons(self):
318 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100319 self.assertGdbRepr(True)
320 self.assertGdbRepr(False)
321 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000322
323 def test_dicts(self):
324 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100325 self.assertGdbRepr({})
326 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900327 # Python preserves insertion order since 3.6
328 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000329
330 def test_lists(self):
331 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100332 self.assertGdbRepr([])
333 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000334
335 def test_bytes(self):
336 'Verify the pretty-printing of bytes'
337 self.assertGdbRepr(b'')
338 self.assertGdbRepr(b'And now for something hopefully the same')
339 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
340 self.assertGdbRepr(b'this is a tab:\t'
341 b' this is a slash-N:\n'
342 b' this is a slash-R:\r'
343 )
344
345 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
346
347 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000348
349 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000350 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400351 # We cannot simply call locale.getpreferredencoding() here,
352 # as GDB might have been linked against a different version
353 # of Python with a different encoding and coercion policy
354 # with respect to PEP 538 and PEP 540.
355 out, err = run_gdb(
356 '--eval-command',
357 'python import locale; print(locale.getpreferredencoding())')
358
359 encoding = out.rstrip()
360 if err or not encoding:
361 raise RuntimeError(
362 f'unable to determine the preferred encoding '
363 f'of embedded Python in GDB: {err}')
364
Victor Stinner150016f2010-05-19 23:04:56 +0000365 def check_repr(text):
366 try:
367 text.encode(encoding)
368 printable = True
369 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000370 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000371 else:
372 self.assertGdbRepr(text)
373
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000374 self.assertGdbRepr('')
375 self.assertGdbRepr('And now for something hopefully the same')
376 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000377
378 # Test printing a single character:
379 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000380 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000381
382 # Test printing a Japanese unicode string
383 # (I believe this reads "mojibake", using 3 characters from the CJK
384 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000385 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000386
387 # Test a character outside the BMP:
388 # U+1D121 MUSICAL SYMBOL C CLEF
389 # This is:
390 # UTF-8: 0xF0 0x9D 0x84 0xA1
391 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000392 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000393
394 def test_tuples(self):
395 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100396 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000397 self.assertGdbRepr((1,), '(1,)')
398 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000399
400 def test_sets(self):
401 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200402 if (gdb_major_version, gdb_minor_version) < (7, 3):
403 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100404 self.assertGdbRepr(set(), "set()")
405 self.assertGdbRepr(set(['a']), "{'a'}")
406 # PYTHONHASHSEED is need to get the exact frozenset item order
407 if not sys.flags.ignore_environment:
408 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
409 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000411 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000412 # which happens on deletion:
413 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100414s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000415id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000416 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000417
418 def test_frozensets(self):
419 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200420 if (gdb_major_version, gdb_minor_version) < (7, 3):
421 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100422 self.assertGdbRepr(frozenset(), "frozenset()")
423 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
424 # PYTHONHASHSEED is need to get the exact frozenset item order
425 if not sys.flags.ignore_environment:
426 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
427 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000428
429 def test_exceptions(self):
430 # Test a RuntimeError
431 gdb_repr, gdb_output = self.get_gdb_repr('''
432try:
433 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000434except RuntimeError as e:
435 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000436''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000437 self.assertEqual(gdb_repr,
438 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000439
440
441 # Test division by zero:
442 gdb_repr, gdb_output = self.get_gdb_repr('''
443try:
444 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000445except ZeroDivisionError as e:
446 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000447''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000448 self.assertEqual(gdb_repr,
449 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000450
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000451 def test_modern_class(self):
452 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000453 gdb_repr, gdb_output = self.get_gdb_repr('''
454class Foo:
455 pass
456foo = Foo()
457foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000458id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100459 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000460 self.assertTrue(m,
461 msg='Unexpected new-style class rendering %r' % gdb_repr)
462
463 def test_subclassing_list(self):
464 'Verify the pretty-printing of an instance of a list subclass'
465 gdb_repr, gdb_output = self.get_gdb_repr('''
466class Foo(list):
467 pass
468foo = Foo()
469foo += [1, 2, 3]
470foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000471id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100472 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 +0000473
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000474 self.assertTrue(m,
475 msg='Unexpected new-style class rendering %r' % gdb_repr)
476
477 def test_subclassing_tuple(self):
478 'Verify the pretty-printing of an instance of a tuple subclass'
479 # This should exercise the negative tp_dictoffset code in the
480 # new-style class support
481 gdb_repr, gdb_output = self.get_gdb_repr('''
482class Foo(tuple):
483 pass
484foo = Foo((1, 2, 3))
485foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000486id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100487 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 +0000488
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000489 self.assertTrue(m,
490 msg='Unexpected new-style class rendering %r' % gdb_repr)
491
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000492 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000493 '''Run Python under gdb, corrupting variables in the inferior process
494 immediately before taking a backtrace.
495
496 Verify that the variable's representation is the expected failsafe
497 representation'''
498 if corruption:
499 cmds_after_breakpoint=[corruption, 'backtrace']
500 else:
501 cmds_after_breakpoint=['backtrace']
502
503 gdb_repr, gdb_output = \
504 self.get_gdb_repr(source,
505 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000506 if exprepr:
507 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000508 # gdb managed to print the value in spite of the corruption;
509 # this is good (see http://bugs.python.org/issue8330)
510 return
511
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000512 # Match anything for the type name; 0xDEADBEEF could point to
513 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100514 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000515
516 m = re.match(pattern, gdb_repr)
517 if not m:
518 self.fail('Unexpected gdb representation: %r\n%s' % \
519 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520
521 def test_NULL_ptr(self):
522 'Ensure that a NULL PyObject* is handled gracefully'
523 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000524 self.get_gdb_repr('id(42)',
525 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000526 'backtrace'])
527 )
528
Ezio Melottib3aedd42010-11-20 19:04:17 +0000529 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000530
531 def test_NULL_ob_type(self):
532 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000533 self.assertSane('id(42)',
534 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000535
536 def test_corrupt_ob_type(self):
537 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000538 self.assertSane('id(42)',
539 'set v->ob_type=0xDEADBEEF',
540 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000541
542 def test_corrupt_tp_flags(self):
543 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000544 self.assertSane('id(42)',
545 'set v->ob_type->tp_flags=0x0',
546 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000547
548 def test_corrupt_tp_name(self):
549 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000550 self.assertSane('id(42)',
551 'set v->ob_type->tp_name=0xDEADBEEF',
552 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000553
554 def test_builtins_help(self):
555 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100556
557 if sys.flags.no_site:
558 self.skipTest("need site module, but -S option was used")
559
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000560 # (this was the issue causing tracebacks in
561 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000562 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000563
Antoine Pitrou4d098732011-11-26 01:42:03 +0100564 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000565 self.assertTrue(m,
566 msg='Unexpected rendering %r' % gdb_repr)
567
568 def test_selfreferential_list(self):
569 '''Ensure that a reference loop involving a list doesn't lead proxyval
570 into an infinite loop:'''
571 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000572 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000573 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000574
575 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000576 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000577 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000578
579 def test_selfreferential_dict(self):
580 '''Ensure that a reference loop involving a dict doesn't lead proxyval
581 into an infinite loop:'''
582 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000583 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000584
Ezio Melottib3aedd42010-11-20 19:04:17 +0000585 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000586
587 def test_selfreferential_old_style_instance(self):
588 gdb_repr, gdb_output = \
589 self.get_gdb_repr('''
590class Foo:
591 pass
592foo = Foo()
593foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000594id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400595 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000596 gdb_repr),
597 'Unexpected gdb representation: %r\n%s' % \
598 (gdb_repr, gdb_output))
599
600 def test_selfreferential_new_style_instance(self):
601 gdb_repr, gdb_output = \
602 self.get_gdb_repr('''
603class Foo(object):
604 pass
605foo = Foo()
606foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000607id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400608 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609 gdb_repr),
610 'Unexpected gdb representation: %r\n%s' % \
611 (gdb_repr, gdb_output))
612
613 gdb_repr, gdb_output = \
614 self.get_gdb_repr('''
615class Foo(object):
616 pass
617a = Foo()
618b = Foo()
619a.an_attr = b
620b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000621id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400622 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 +0000623 gdb_repr),
624 'Unexpected gdb representation: %r\n%s' % \
625 (gdb_repr, gdb_output))
626
627 def test_truncation(self):
628 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000629 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000630 self.assertEqual(gdb_repr,
631 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
632 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
633 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
634 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
635 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
636 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
637 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
638 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
639 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
640 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
641 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
642 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
643 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
644 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
645 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
646 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
647 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
648 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
649 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
650 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
651 "224, 225, 226...(truncated)")
652 self.assertEqual(len(gdb_repr),
653 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000654
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000655 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000656 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400657 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 +0000658 gdb_repr),
659 'Unexpected gdb representation: %r\n%s' % \
660 (gdb_repr, gdb_output))
661
662 def test_frames(self):
663 gdb_output = self.get_stack_trace('''
664def foo(a, b, c):
665 pass
666
667foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000668id(foo.__code__)''',
669 breakpoint='builtin_id',
670 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000671 )
R David Murray44b548d2016-09-08 13:59:53 -0400672 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 +0000673 gdb_output,
674 re.DOTALL),
675 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
676
Victor Stinnerd2084162011-12-19 13:42:24 +0100677@unittest.skipIf(python_is_optimized(),
678 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000679class PyListTests(DebuggerTests):
680 def assertListing(self, expected, actual):
681 self.assertEndsWith(actual, expected)
682
683 def test_basic_command(self):
684 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000685 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000686 cmds_after_breakpoint=['py-list'])
687
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000688 self.assertListing(' 5 \n'
689 ' 6 def bar(a, b, c):\n'
690 ' 7 baz(a, b, c)\n'
691 ' 8 \n'
692 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000693 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000694 ' 11 \n'
695 ' 12 foo(1, 2, 3)\n',
696 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000697
698 def test_one_abs_arg(self):
699 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000700 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000701 cmds_after_breakpoint=['py-list 9'])
702
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000703 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000704 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000705 ' 11 \n'
706 ' 12 foo(1, 2, 3)\n',
707 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000708
709 def test_two_abs_args(self):
710 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000711 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000712 cmds_after_breakpoint=['py-list 1,3'])
713
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000714 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
715 ' 2 \n'
716 ' 3 def foo(a, b, c):\n',
717 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000718
719class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000720 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100721 @unittest.skipIf(python_is_optimized(),
722 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000723 def test_pyup_command(self):
724 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000725 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100726 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000727 self.assertMultilineMatches(bt,
728 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100729#[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 +0000730 baz\(a, b, c\)
731$''')
732
Victor Stinner50eb60e2010-04-20 22:32:07 +0000733 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000734 def test_down_at_bottom(self):
735 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000736 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000737 cmds_after_breakpoint=['py-down'])
738 self.assertEndsWith(bt,
739 'Unable to find a newer python frame\n')
740
Victor Stinner50eb60e2010-04-20 22:32:07 +0000741 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000742 def test_up_at_top(self):
743 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000744 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100745 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000746 self.assertEndsWith(bt,
747 'Unable to find an older python frame\n')
748
Victor Stinner50eb60e2010-04-20 22:32:07 +0000749 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100750 @unittest.skipIf(python_is_optimized(),
751 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000752 def test_up_then_down(self):
753 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000754 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100755 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000756 self.assertMultilineMatches(bt,
757 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100758#[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 +0000759 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100760#[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 +0000761 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000762$''')
763
764class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100765 @unittest.skipIf(python_is_optimized(),
766 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200767 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000768 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000769 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000770 cmds_after_breakpoint=['py-bt'])
771 self.assertMultilineMatches(bt,
772 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200773Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100774 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200775 File ".*gdb_sample.py", line 10, in baz
776 id\(42\)
777 File ".*gdb_sample.py", line 7, in bar
778 baz\(a, b, c\)
779 File ".*gdb_sample.py", line 4, in foo
780 bar\(a, b, c\)
781 File ".*gdb_sample.py", line 12, in <module>
782 foo\(1, 2, 3\)
783''')
784
Victor Stinnerd2084162011-12-19 13:42:24 +0100785 @unittest.skipIf(python_is_optimized(),
786 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200787 def test_bt_full(self):
788 'Verify that the "py-bt-full" command works'
789 bt = self.get_stack_trace(script=self.get_sample_script(),
790 cmds_after_breakpoint=['py-bt-full'])
791 self.assertMultilineMatches(bt,
792 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100793#[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 +0000794 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100795#[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 +0000796 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100797#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100798 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000799''')
800
David Malcolm8d37ffa2012-06-27 14:15:34 -0400801 def test_threads(self):
802 'Verify that "py-bt" indicates threads that are waiting for the GIL'
803 cmd = '''
804from threading import Thread
805
806class TestThread(Thread):
807 # These threads would run forever, but we'll interrupt things with the
808 # debugger
809 def run(self):
810 i = 0
811 while 1:
812 i += 1
813
814t = {}
815for i in range(4):
816 t[i] = TestThread()
817 t[i].start()
818
819# Trigger a breakpoint on the main thread
820id(42)
821
822'''
823 # Verify with "py-bt":
824 gdb_output = self.get_stack_trace(cmd,
825 cmds_after_breakpoint=['thread apply all py-bt'])
826 self.assertIn('Waiting for the GIL', gdb_output)
827
828 # Verify with "py-bt-full":
829 gdb_output = self.get_stack_trace(cmd,
830 cmds_after_breakpoint=['thread apply all py-bt-full'])
831 self.assertIn('Waiting for the GIL', gdb_output)
832
833 @unittest.skipIf(python_is_optimized(),
834 "Python was compiled with optimizations")
835 # Some older versions of gdb will fail with
836 # "Cannot find new threads: generic error"
837 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400838 def test_gc(self):
839 'Verify that "py-bt" indicates if a thread is garbage-collecting'
840 cmd = ('from gc import collect\n'
841 'id(42)\n'
842 'def foo():\n'
843 ' collect()\n'
844 'def bar():\n'
845 ' foo()\n'
846 'bar()\n')
847 # Verify with "py-bt":
848 gdb_output = self.get_stack_trace(cmd,
849 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
850 )
851 self.assertIn('Garbage-collecting', gdb_output)
852
853 # Verify with "py-bt-full":
854 gdb_output = self.get_stack_trace(cmd,
855 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
856 )
857 self.assertIn('Garbage-collecting', gdb_output)
858
859 @unittest.skipIf(python_is_optimized(),
860 "Python was compiled with optimizations")
861 # Some older versions of gdb will fail with
862 # "Cannot find new threads: generic error"
863 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400864 def test_pycfunction(self):
865 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100866 # Tested function must not be defined with METH_NOARGS or METH_O,
867 # otherwise call_function() doesn't call PyCFunction_Call()
868 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400869 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100870 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400871 'def bar():\n'
872 ' foo()\n'
873 'bar()\n')
874 # Verify with "py-bt":
875 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100876 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400877 cmds_after_breakpoint=['bt', 'py-bt'],
878 )
Victor Stinner79644f92015-03-27 15:42:37 +0100879 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400880
881 # Verify with "py-bt-full":
882 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100883 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400884 cmds_after_breakpoint=['py-bt-full'],
885 )
INADA Naoki5566bbb2017-02-03 07:43:03 +0900886 self.assertIn('#2 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400887
Victor Stinner61108332017-02-01 16:29:54 +0100888 @unittest.skipIf(python_is_optimized(),
889 "Python was compiled with optimizations")
890 def test_wrapper_call(self):
891 cmd = textwrap.dedent('''
892 class MyList(list):
893 def __init__(self):
894 super().__init__() # wrapper_call()
895
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100896 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100897 l = MyList()
898 ''')
Victor Stinner79d21332018-10-09 16:54:04 +0200899 cmds_after_breakpoint = ['break wrapper_call', 'continue']
900 if CET_PROTECTION:
901 # bpo-32962: same case as in get_stack_trace():
902 # we need an additional 'next' command in order to read
903 # arguments of the innermost function of the call stack.
904 cmds_after_breakpoint.append('next')
905 cmds_after_breakpoint.append('py-bt')
906
Victor Stinner61108332017-02-01 16:29:54 +0100907 # Verify with "py-bt":
908 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79d21332018-10-09 16:54:04 +0200909 cmds_after_breakpoint=cmds_after_breakpoint)
Victor Stinner72268ae2017-02-01 18:26:14 +0100910 self.assertRegex(gdb_output,
911 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100912
David Malcolm8d37ffa2012-06-27 14:15:34 -0400913
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000914class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100915 @unittest.skipIf(python_is_optimized(),
916 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000917 def test_basic_command(self):
918 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000919 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100920 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000921 self.assertMultilineMatches(bt,
922 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
923
Vinay Sajip2549f872012-01-04 12:07:30 +0000924 @unittest.skipIf(python_is_optimized(),
925 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000926 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000927 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000928 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100929 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000930 self.assertMultilineMatches(bt,
931 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
932
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_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000936 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100937 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000938 self.assertMultilineMatches(bt,
939 r".*\nglobal '__name__' = '__main__'\n.*")
940
Victor Stinnerd2084162011-12-19 13:42:24 +0100941 @unittest.skipIf(python_is_optimized(),
942 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000943 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000944 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100945 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000946 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100947 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000948
949class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100950 @unittest.skipIf(python_is_optimized(),
951 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000952 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000953 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100954 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000955 self.assertMultilineMatches(bt,
956 r".*\nargs = \(1, 2, 3\)\n.*")
957
Victor Stinner50eb60e2010-04-20 22:32:07 +0000958 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000959 @unittest.skipIf(python_is_optimized(),
960 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000961 def test_locals_after_up(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-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000964 self.assertMultilineMatches(bt,
965 r".*\na = 1\nb = 2\nc = 3\n.*")
966
967def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200968 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200969 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200970 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200971 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000972 run_unittest(PrettyPrintTests,
973 PyListTests,
974 StackNavigationTests,
975 PyBtTests,
976 PyPrintTests,
977 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000978 )
979
980if __name__ == "__main__":
981 test_main()