blob: 0f950b23253391af67263a7d78b76e22352d11e8 [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
Victor Stinner61108332017-02-01 16:29:54 +01006import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00007import os
8import 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
R David Murrayf9333022012-10-27 13:22:41 -040051# Location of custom hooks file in a repository checkout.
52checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
53 'python-gdb.py')
54
Victor Stinner51324932013-11-20 12:27:48 +010055PYTHONHASHSEED = '123'
56
Victor Stinner79d21332018-10-09 16:54:04 +020057
58def cet_protection():
59 cflags = sysconfig.get_config_var('CFLAGS')
60 if not cflags:
61 return False
62 flags = cflags.split()
63 # True if "-mcet -fcf-protection" options are found, but false
64 # if "-fcf-protection=none" or "-fcf-protection=return" is found.
65 return (('-mcet' in flags)
66 and any((flag.startswith('-fcf-protection')
67 and not flag.endswith(("=none", "=return")))
68 for flag in flags))
69
70# Control-flow enforcement technology
71CET_PROTECTION = cet_protection()
72
73
R David Murrayf9333022012-10-27 13:22:41 -040074def run_gdb(*args, **env_vars):
75 """Runs gdb in --batch mode with the additional arguments given by *args.
76
77 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
78 """
79 if env_vars:
80 env = os.environ.copy()
81 env.update(env_vars)
82 else:
83 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020084 # -nx: Do not execute commands from any .gdbinit initialization files
85 # (issue #22188)
86 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040087 if (gdb_major_version, gdb_minor_version) >= (7, 4):
88 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020089 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000090 # Redirect stdin to prevent GDB from messing with
91 # the terminal settings
92 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020093 stdout=subprocess.PIPE,
94 stderr=subprocess.PIPE,
95 env=env)
96 with proc:
97 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040098 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
99
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000100# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +0100101gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -0400102if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000103 raise unittest.SkipTest("gdb not built with embedded python support")
104
Nick Coghlance346872013-09-22 19:38:16 +1000105# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -0700106# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -0400107_, gdbpy_errors = run_gdb('--args', sys.executable)
108if "auto-loading has been declined" in gdbpy_errors:
109 msg = "gdb security settings prevent use of custom hooks: "
110 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000111
Victor Stinner50eb60e2010-04-20 22:32:07 +0000112def gdb_has_frame_select():
113 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400114 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
115 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000116 if not m:
117 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400118 gdb_frame_dir = m.group(1).split(', ')
119 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000120
121HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000122
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000123BREAKPOINT_FN='builtin_id'
124
Benjamin Peterson437df902016-09-06 20:22:41 -0700125@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000126class DebuggerTests(unittest.TestCase):
127
128 """Test that the debugger can debug Python."""
129
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000130 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000131 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000132 cmds_after_breakpoint=None,
133 import_site=False):
134 '''
135 Run 'python -c SOURCE' under gdb with a breakpoint.
136
137 Support injecting commands after the breakpoint is reached
138
139 Returns the stdout from gdb
140
141 cmds_after_breakpoint: if provided, a list of strings: gdb commands
142 '''
143 # We use "set breakpoint pending yes" to avoid blocking with a:
144 # Function "foo" not defined.
145 # Make breakpoint pending on future shared library load? (y or [n])
146 # error, which typically happens python is dynamically linked (the
147 # breakpoints of interest are to be found in the shared library)
148 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000149 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000150 # emitted to stderr each time, alas.
151
152 # Initially I had "--eval-command=continue" here, but removed it to
153 # avoid repeated print breakpoints when traversing hierarchical data
154 # structures
155
156 # Generate a list of commands in gdb's language:
157 commands = ['set breakpoint pending yes',
158 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200159
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200160 # The tests assume that the first frame of printed
161 # backtrace will not contain program counter,
162 # that is however not guaranteed by gdb
163 # therefore we need to use 'set print address off' to
164 # make sure the counter is not there. For example:
165 # #0 in PyObject_Print ...
166 # is assumed, but sometimes this can be e.g.
167 # #0 0x00003fffb7dd1798 in PyObject_Print ...
168 'set print address off',
169
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000170 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200171
172 # GDB as of 7.4 onwards can distinguish between the
173 # value of a variable at entry vs current value:
174 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
175 # which leads to the selftests failing with errors like this:
176 # AssertionError: 'v@entry=()' != '()'
177 # Disable this:
178 if (gdb_major_version, gdb_minor_version) >= (7, 4):
179 commands += ['set print entry-values no']
180
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000181 if cmds_after_breakpoint:
Victor Stinner79d21332018-10-09 16:54:04 +0200182 if CET_PROTECTION:
183 # bpo-32962: When Python is compiled with -mcet
184 # -fcf-protection, function arguments are unusable before
185 # running the first instruction of the function entry point.
186 # The 'next' command makes the required first step.
187 commands += ['next']
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200188 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000189 else:
190 commands += ['backtrace']
191
192 # print commands
193
194 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000195 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000196 args += ["--args",
197 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100198 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000199
200 if not import_site:
201 # -S suppresses the default 'import site'
202 args += ["-S"]
203
204 if source:
205 args += ["-c", source]
206 elif script:
207 args += [script]
208
209 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100210 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000211
212 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100213 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000214
Antoine Pitrou81641d62013-05-01 00:15:44 +0200215 errlines = err.splitlines()
216 unexpected_errlines = []
217
218 # Ignore some benign messages on stderr.
219 ignore_patterns = (
220 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200221 'Do you need "set solib-search-path" or '
222 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100223 # BFD: /usr/lib/debug/(...): unable to initialize decompress
224 # status for section .debug_aranges
225 'BFD: ',
226 # ignore all warnings
227 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200228 )
229 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100230 if not line:
231 continue
Pablo Galindof2ef51f2018-08-31 23:04:47 +0100232 # bpo34007: Sometimes some versions of the shared libraries that
233 # are part of the traceback are compiled in optimised mode and the
234 # Program Counter (PC) is not present, not allowing gdb to walk the
235 # frames back. When this happens, the Python bindings of gdb raise
236 # an exception, making the test impossible to succeed.
237 if "PC not saved" in line:
238 raise unittest.SkipTest("gdb cannot walk the frame object"
239 " because the Program Counter is"
240 " not present")
Antoine Pitrou81641d62013-05-01 00:15:44 +0200241 if not line.startswith(ignore_patterns):
242 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000243
244 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200245 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000246 return out
247
248 def get_gdb_repr(self, source,
249 cmds_after_breakpoint=None,
250 import_site=False):
251 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000252 # run "python -c'id(DATA)'" under gdb with a breakpoint on
253 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000254 # parameter, and verify that the gdb displays the same string
255 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000256 # Verify that the gdb displays the expected string
257 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258 # For a nested structure, the first time we hit the breakpoint will
259 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100260
261 # NOTE: avoid decoding too much of the traceback as some
262 # undecodable characters may lurk there in optimized mode
263 # (issue #19743).
264 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000265 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266 cmds_after_breakpoint=cmds_after_breakpoint,
267 import_site=import_site)
268 # gdb can insert additional '\n' and space characters in various places
269 # in its output, depending on the width of the terminal it's connected
270 # to (using its "wrap_here" function)
R David Murray44b548d2016-09-08 13:59:53 -0400271 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 +0000272 gdb_output, re.DOTALL)
273 if not m:
274 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
275 return m.group(1), gdb_output
276
277 def assertEndsWith(self, actual, exp_end):
278 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000279 self.assertTrue(actual.endswith(exp_end),
280 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000281
282 def assertMultilineMatches(self, actual, pattern):
283 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000284 if not m:
285 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000286
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000287 def get_sample_script(self):
288 return findfile('gdb_sample.py')
289
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000290class PrettyPrintTests(DebuggerTests):
291 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000292 gdb_output = self.get_stack_trace('id(42)')
293 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000294
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100295 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000296 # Ensure that gdb's rendering of the value in a debugged process
297 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100298 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000299 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100300 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000301 self.assertEqual(gdb_repr, exp_repr,
302 ('%r did not equal expected %r; full output was:\n%s'
303 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000304
305 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300306 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100307 self.assertGdbRepr(42)
308 self.assertGdbRepr(0)
309 self.assertGdbRepr(-7)
310 self.assertGdbRepr(1000000000000)
311 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000312
313 def test_singletons(self):
314 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100315 self.assertGdbRepr(True)
316 self.assertGdbRepr(False)
317 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000318
319 def test_dicts(self):
320 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100321 self.assertGdbRepr({})
322 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900323 # Python preserves insertion order since 3.6
324 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000325
326 def test_lists(self):
327 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100328 self.assertGdbRepr([])
329 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000330
331 def test_bytes(self):
332 'Verify the pretty-printing of bytes'
333 self.assertGdbRepr(b'')
334 self.assertGdbRepr(b'And now for something hopefully the same')
335 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
336 self.assertGdbRepr(b'this is a tab:\t'
337 b' this is a slash-N:\n'
338 b' this is a slash-R:\r'
339 )
340
341 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
342
343 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000344
345 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000346 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400347 # We cannot simply call locale.getpreferredencoding() here,
348 # as GDB might have been linked against a different version
349 # of Python with a different encoding and coercion policy
350 # with respect to PEP 538 and PEP 540.
351 out, err = run_gdb(
352 '--eval-command',
353 'python import locale; print(locale.getpreferredencoding())')
354
355 encoding = out.rstrip()
356 if err or not encoding:
357 raise RuntimeError(
358 f'unable to determine the preferred encoding '
359 f'of embedded Python in GDB: {err}')
360
Victor Stinner150016f2010-05-19 23:04:56 +0000361 def check_repr(text):
362 try:
363 text.encode(encoding)
364 printable = True
365 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000366 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000367 else:
368 self.assertGdbRepr(text)
369
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000370 self.assertGdbRepr('')
371 self.assertGdbRepr('And now for something hopefully the same')
372 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000373
374 # Test printing a single character:
375 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000376 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000377
378 # Test printing a Japanese unicode string
379 # (I believe this reads "mojibake", using 3 characters from the CJK
380 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000381 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000382
383 # Test a character outside the BMP:
384 # U+1D121 MUSICAL SYMBOL C CLEF
385 # This is:
386 # UTF-8: 0xF0 0x9D 0x84 0xA1
387 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000388 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000389
390 def test_tuples(self):
391 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100392 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000393 self.assertGdbRepr((1,), '(1,)')
394 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000395
396 def test_sets(self):
397 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200398 if (gdb_major_version, gdb_minor_version) < (7, 3):
399 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100400 self.assertGdbRepr(set(), "set()")
401 self.assertGdbRepr(set(['a']), "{'a'}")
402 # PYTHONHASHSEED is need to get the exact frozenset item order
403 if not sys.flags.ignore_environment:
404 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
405 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000406
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000408 # which happens on deletion:
409 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100410s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000411id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000412 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000413
414 def test_frozensets(self):
415 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200416 if (gdb_major_version, gdb_minor_version) < (7, 3):
417 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100418 self.assertGdbRepr(frozenset(), "frozenset()")
419 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
420 # PYTHONHASHSEED is need to get the exact frozenset item order
421 if not sys.flags.ignore_environment:
422 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
423 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000424
425 def test_exceptions(self):
426 # Test a RuntimeError
427 gdb_repr, gdb_output = self.get_gdb_repr('''
428try:
429 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000430except RuntimeError as e:
431 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000432''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000433 self.assertEqual(gdb_repr,
434 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000435
436
437 # Test division by zero:
438 gdb_repr, gdb_output = self.get_gdb_repr('''
439try:
440 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000441except ZeroDivisionError as e:
442 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000443''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000444 self.assertEqual(gdb_repr,
445 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000446
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000447 def test_modern_class(self):
448 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000449 gdb_repr, gdb_output = self.get_gdb_repr('''
450class Foo:
451 pass
452foo = Foo()
453foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000454id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100455 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000456 self.assertTrue(m,
457 msg='Unexpected new-style class rendering %r' % gdb_repr)
458
459 def test_subclassing_list(self):
460 'Verify the pretty-printing of an instance of a list subclass'
461 gdb_repr, gdb_output = self.get_gdb_repr('''
462class Foo(list):
463 pass
464foo = Foo()
465foo += [1, 2, 3]
466foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000467id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100468 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 +0000469
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000470 self.assertTrue(m,
471 msg='Unexpected new-style class rendering %r' % gdb_repr)
472
473 def test_subclassing_tuple(self):
474 'Verify the pretty-printing of an instance of a tuple subclass'
475 # This should exercise the negative tp_dictoffset code in the
476 # new-style class support
477 gdb_repr, gdb_output = self.get_gdb_repr('''
478class Foo(tuple):
479 pass
480foo = Foo((1, 2, 3))
481foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000482id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100483 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 +0000484
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000485 self.assertTrue(m,
486 msg='Unexpected new-style class rendering %r' % gdb_repr)
487
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000488 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000489 '''Run Python under gdb, corrupting variables in the inferior process
490 immediately before taking a backtrace.
491
492 Verify that the variable's representation is the expected failsafe
493 representation'''
494 if corruption:
495 cmds_after_breakpoint=[corruption, 'backtrace']
496 else:
497 cmds_after_breakpoint=['backtrace']
498
499 gdb_repr, gdb_output = \
500 self.get_gdb_repr(source,
501 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000502 if exprepr:
503 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000504 # gdb managed to print the value in spite of the corruption;
505 # this is good (see http://bugs.python.org/issue8330)
506 return
507
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000508 # Match anything for the type name; 0xDEADBEEF could point to
509 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100510 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000511
512 m = re.match(pattern, gdb_repr)
513 if not m:
514 self.fail('Unexpected gdb representation: %r\n%s' % \
515 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000516
517 def test_NULL_ptr(self):
518 'Ensure that a NULL PyObject* is handled gracefully'
519 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000520 self.get_gdb_repr('id(42)',
521 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000522 'backtrace'])
523 )
524
Ezio Melottib3aedd42010-11-20 19:04:17 +0000525 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000526
527 def test_NULL_ob_type(self):
528 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000529 self.assertSane('id(42)',
530 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000531
532 def test_corrupt_ob_type(self):
533 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000534 self.assertSane('id(42)',
535 'set v->ob_type=0xDEADBEEF',
536 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000537
538 def test_corrupt_tp_flags(self):
539 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000540 self.assertSane('id(42)',
541 'set v->ob_type->tp_flags=0x0',
542 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000543
544 def test_corrupt_tp_name(self):
545 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000546 self.assertSane('id(42)',
547 'set v->ob_type->tp_name=0xDEADBEEF',
548 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000549
550 def test_builtins_help(self):
551 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100552
553 if sys.flags.no_site:
554 self.skipTest("need site module, but -S option was used")
555
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000556 # (this was the issue causing tracebacks in
557 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000558 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000559
Antoine Pitrou4d098732011-11-26 01:42:03 +0100560 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000561 self.assertTrue(m,
562 msg='Unexpected rendering %r' % gdb_repr)
563
564 def test_selfreferential_list(self):
565 '''Ensure that a reference loop involving a list doesn't lead proxyval
566 into an infinite loop:'''
567 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000568 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000569 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000570
571 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000572 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; 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 def test_selfreferential_dict(self):
576 '''Ensure that a reference loop involving a dict doesn't lead proxyval
577 into an infinite loop:'''
578 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000579 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000580
Ezio Melottib3aedd42010-11-20 19:04:17 +0000581 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000582
583 def test_selfreferential_old_style_instance(self):
584 gdb_repr, gdb_output = \
585 self.get_gdb_repr('''
586class Foo:
587 pass
588foo = Foo()
589foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000590id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400591 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000592 gdb_repr),
593 'Unexpected gdb representation: %r\n%s' % \
594 (gdb_repr, gdb_output))
595
596 def test_selfreferential_new_style_instance(self):
597 gdb_repr, gdb_output = \
598 self.get_gdb_repr('''
599class Foo(object):
600 pass
601foo = Foo()
602foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000603id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400604 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000605 gdb_repr),
606 'Unexpected gdb representation: %r\n%s' % \
607 (gdb_repr, gdb_output))
608
609 gdb_repr, gdb_output = \
610 self.get_gdb_repr('''
611class Foo(object):
612 pass
613a = Foo()
614b = Foo()
615a.an_attr = b
616b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000617id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400618 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 +0000619 gdb_repr),
620 'Unexpected gdb representation: %r\n%s' % \
621 (gdb_repr, gdb_output))
622
623 def test_truncation(self):
624 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000625 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000626 self.assertEqual(gdb_repr,
627 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
628 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
629 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
630 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
631 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
632 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
633 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
634 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
635 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
636 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
637 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
638 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
639 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
640 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
641 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
642 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
643 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
644 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
645 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
646 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
647 "224, 225, 226...(truncated)")
648 self.assertEqual(len(gdb_repr),
649 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000650
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000651 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000652 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400653 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 +0000654 gdb_repr),
655 'Unexpected gdb representation: %r\n%s' % \
656 (gdb_repr, gdb_output))
657
658 def test_frames(self):
659 gdb_output = self.get_stack_trace('''
660def foo(a, b, c):
661 pass
662
663foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000664id(foo.__code__)''',
665 breakpoint='builtin_id',
666 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000667 )
R David Murray44b548d2016-09-08 13:59:53 -0400668 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 +0000669 gdb_output,
670 re.DOTALL),
671 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
672
Victor Stinnerd2084162011-12-19 13:42:24 +0100673@unittest.skipIf(python_is_optimized(),
674 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000675class PyListTests(DebuggerTests):
676 def assertListing(self, expected, actual):
677 self.assertEndsWith(actual, expected)
678
679 def test_basic_command(self):
680 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000681 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000682 cmds_after_breakpoint=['py-list'])
683
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000684 self.assertListing(' 5 \n'
685 ' 6 def bar(a, b, c):\n'
686 ' 7 baz(a, b, c)\n'
687 ' 8 \n'
688 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000689 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000690 ' 11 \n'
691 ' 12 foo(1, 2, 3)\n',
692 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000693
694 def test_one_abs_arg(self):
695 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000696 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000697 cmds_after_breakpoint=['py-list 9'])
698
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000699 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000700 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000701 ' 11 \n'
702 ' 12 foo(1, 2, 3)\n',
703 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000704
705 def test_two_abs_args(self):
706 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000707 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000708 cmds_after_breakpoint=['py-list 1,3'])
709
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000710 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
711 ' 2 \n'
712 ' 3 def foo(a, b, c):\n',
713 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000714
715class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000716 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100717 @unittest.skipIf(python_is_optimized(),
718 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000719 def test_pyup_command(self):
720 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000721 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100722 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000723 self.assertMultilineMatches(bt,
724 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100725#[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 +0000726 baz\(a, b, c\)
727$''')
728
Victor Stinner50eb60e2010-04-20 22:32:07 +0000729 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000730 def test_down_at_bottom(self):
731 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000732 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000733 cmds_after_breakpoint=['py-down'])
734 self.assertEndsWith(bt,
735 'Unable to find a newer python frame\n')
736
Victor Stinner50eb60e2010-04-20 22:32:07 +0000737 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000738 def test_up_at_top(self):
739 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000740 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100741 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000742 self.assertEndsWith(bt,
743 'Unable to find an older python frame\n')
744
Victor Stinner50eb60e2010-04-20 22:32:07 +0000745 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100746 @unittest.skipIf(python_is_optimized(),
747 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000748 def test_up_then_down(self):
749 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000750 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100751 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000752 self.assertMultilineMatches(bt,
753 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100754#[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 +0000755 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100756#[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 +0000757 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000758$''')
759
760class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100761 @unittest.skipIf(python_is_optimized(),
762 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200763 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000764 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000765 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000766 cmds_after_breakpoint=['py-bt'])
767 self.assertMultilineMatches(bt,
768 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200769Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100770 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200771 File ".*gdb_sample.py", line 10, in baz
772 id\(42\)
773 File ".*gdb_sample.py", line 7, in bar
774 baz\(a, b, c\)
775 File ".*gdb_sample.py", line 4, in foo
776 bar\(a, b, c\)
777 File ".*gdb_sample.py", line 12, in <module>
778 foo\(1, 2, 3\)
779''')
780
Victor Stinnerd2084162011-12-19 13:42:24 +0100781 @unittest.skipIf(python_is_optimized(),
782 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200783 def test_bt_full(self):
784 'Verify that the "py-bt-full" command works'
785 bt = self.get_stack_trace(script=self.get_sample_script(),
786 cmds_after_breakpoint=['py-bt-full'])
787 self.assertMultilineMatches(bt,
788 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100789#[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 +0000790 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100791#[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 +0000792 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100793#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100794 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000795''')
796
David Malcolm8d37ffa2012-06-27 14:15:34 -0400797 def test_threads(self):
798 'Verify that "py-bt" indicates threads that are waiting for the GIL'
799 cmd = '''
800from threading import Thread
801
802class TestThread(Thread):
803 # These threads would run forever, but we'll interrupt things with the
804 # debugger
805 def run(self):
806 i = 0
807 while 1:
808 i += 1
809
810t = {}
811for i in range(4):
812 t[i] = TestThread()
813 t[i].start()
814
815# Trigger a breakpoint on the main thread
816id(42)
817
818'''
819 # Verify with "py-bt":
820 gdb_output = self.get_stack_trace(cmd,
821 cmds_after_breakpoint=['thread apply all py-bt'])
822 self.assertIn('Waiting for the GIL', gdb_output)
823
824 # Verify with "py-bt-full":
825 gdb_output = self.get_stack_trace(cmd,
826 cmds_after_breakpoint=['thread apply all py-bt-full'])
827 self.assertIn('Waiting for the GIL', gdb_output)
828
829 @unittest.skipIf(python_is_optimized(),
830 "Python was compiled with optimizations")
831 # Some older versions of gdb will fail with
832 # "Cannot find new threads: generic error"
833 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400834 def test_gc(self):
835 'Verify that "py-bt" indicates if a thread is garbage-collecting'
836 cmd = ('from gc import collect\n'
837 'id(42)\n'
838 'def foo():\n'
839 ' collect()\n'
840 'def bar():\n'
841 ' foo()\n'
842 'bar()\n')
843 # Verify with "py-bt":
844 gdb_output = self.get_stack_trace(cmd,
845 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
846 )
847 self.assertIn('Garbage-collecting', gdb_output)
848
849 # Verify with "py-bt-full":
850 gdb_output = self.get_stack_trace(cmd,
851 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
852 )
853 self.assertIn('Garbage-collecting', gdb_output)
854
855 @unittest.skipIf(python_is_optimized(),
856 "Python was compiled with optimizations")
857 # Some older versions of gdb will fail with
858 # "Cannot find new threads: generic error"
859 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400860 def test_pycfunction(self):
861 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100862 # Tested function must not be defined with METH_NOARGS or METH_O,
863 # otherwise call_function() doesn't call PyCFunction_Call()
864 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400865 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100866 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400867 'def bar():\n'
868 ' foo()\n'
869 'bar()\n')
870 # Verify with "py-bt":
871 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100872 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400873 cmds_after_breakpoint=['bt', 'py-bt'],
874 )
Victor Stinner79644f92015-03-27 15:42:37 +0100875 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400876
877 # Verify with "py-bt-full":
878 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100879 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400880 cmds_after_breakpoint=['py-bt-full'],
881 )
INADA Naoki5566bbb2017-02-03 07:43:03 +0900882 self.assertIn('#2 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400883
Victor Stinner61108332017-02-01 16:29:54 +0100884 @unittest.skipIf(python_is_optimized(),
885 "Python was compiled with optimizations")
886 def test_wrapper_call(self):
887 cmd = textwrap.dedent('''
888 class MyList(list):
889 def __init__(self):
890 super().__init__() # wrapper_call()
891
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100892 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100893 l = MyList()
894 ''')
Victor Stinner79d21332018-10-09 16:54:04 +0200895 cmds_after_breakpoint = ['break wrapper_call', 'continue']
896 if CET_PROTECTION:
897 # bpo-32962: same case as in get_stack_trace():
898 # we need an additional 'next' command in order to read
899 # arguments of the innermost function of the call stack.
900 cmds_after_breakpoint.append('next')
901 cmds_after_breakpoint.append('py-bt')
902
Victor Stinner61108332017-02-01 16:29:54 +0100903 # Verify with "py-bt":
904 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79d21332018-10-09 16:54:04 +0200905 cmds_after_breakpoint=cmds_after_breakpoint)
Victor Stinner72268ae2017-02-01 18:26:14 +0100906 self.assertRegex(gdb_output,
907 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100908
David Malcolm8d37ffa2012-06-27 14:15:34 -0400909
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000910class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100911 @unittest.skipIf(python_is_optimized(),
912 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000913 def test_basic_command(self):
914 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000915 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100916 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000917 self.assertMultilineMatches(bt,
918 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
919
Vinay Sajip2549f872012-01-04 12:07:30 +0000920 @unittest.skipIf(python_is_optimized(),
921 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000922 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000923 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000924 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100925 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000926 self.assertMultilineMatches(bt,
927 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
928
Victor Stinnerd2084162011-12-19 13:42:24 +0100929 @unittest.skipIf(python_is_optimized(),
930 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000931 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000932 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100933 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000934 self.assertMultilineMatches(bt,
935 r".*\nglobal '__name__' = '__main__'\n.*")
936
Victor Stinnerd2084162011-12-19 13:42:24 +0100937 @unittest.skipIf(python_is_optimized(),
938 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000939 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000940 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100941 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000942 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100943 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000944
945class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100946 @unittest.skipIf(python_is_optimized(),
947 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000948 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000949 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100950 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000951 self.assertMultilineMatches(bt,
952 r".*\nargs = \(1, 2, 3\)\n.*")
953
Victor Stinner50eb60e2010-04-20 22:32:07 +0000954 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000955 @unittest.skipIf(python_is_optimized(),
956 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000957 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000958 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100959 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000960 self.assertMultilineMatches(bt,
961 r".*\na = 1\nb = 2\nc = 3\n.*")
962
963def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200964 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200965 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200966 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200967 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000968 run_unittest(PrettyPrintTests,
969 PyListTests,
970 StackNavigationTests,
971 PyBtTests,
972 PyPrintTests,
973 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000974 )
975
976if __name__ == "__main__":
977 test_main()