blob: 93a2c7dd57587e1b642efd7b930088069682bf69 [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
R David Murrayf9333022012-10-27 13:22:41 -040057def run_gdb(*args, **env_vars):
58 """Runs gdb in --batch mode with the additional arguments given by *args.
59
60 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
61 """
62 if env_vars:
63 env = os.environ.copy()
64 env.update(env_vars)
65 else:
66 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020067 # -nx: Do not execute commands from any .gdbinit initialization files
68 # (issue #22188)
69 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040070 if (gdb_major_version, gdb_minor_version) >= (7, 4):
71 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020072 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000073 # Redirect stdin to prevent GDB from messing with
74 # the terminal settings
75 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020076 stdout=subprocess.PIPE,
77 stderr=subprocess.PIPE,
78 env=env)
79 with proc:
80 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040081 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
82
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000083# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010084gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040085if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000086 raise unittest.SkipTest("gdb not built with embedded python support")
87
Nick Coghlance346872013-09-22 19:38:16 +100088# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -070089# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040090_, gdbpy_errors = run_gdb('--args', sys.executable)
91if "auto-loading has been declined" in gdbpy_errors:
92 msg = "gdb security settings prevent use of custom hooks: "
93 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100094
Victor Stinner50eb60e2010-04-20 22:32:07 +000095def gdb_has_frame_select():
96 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -040097 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
98 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +000099 if not m:
100 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400101 gdb_frame_dir = m.group(1).split(', ')
102 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000103
104HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000105
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000106BREAKPOINT_FN='builtin_id'
107
Benjamin Peterson437df902016-09-06 20:22:41 -0700108@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000109class DebuggerTests(unittest.TestCase):
110
111 """Test that the debugger can debug Python."""
112
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000113 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000114 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000115 cmds_after_breakpoint=None,
116 import_site=False):
117 '''
118 Run 'python -c SOURCE' under gdb with a breakpoint.
119
120 Support injecting commands after the breakpoint is reached
121
122 Returns the stdout from gdb
123
124 cmds_after_breakpoint: if provided, a list of strings: gdb commands
125 '''
126 # We use "set breakpoint pending yes" to avoid blocking with a:
127 # Function "foo" not defined.
128 # Make breakpoint pending on future shared library load? (y or [n])
129 # error, which typically happens python is dynamically linked (the
130 # breakpoints of interest are to be found in the shared library)
131 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000132 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000133 # emitted to stderr each time, alas.
134
135 # Initially I had "--eval-command=continue" here, but removed it to
136 # avoid repeated print breakpoints when traversing hierarchical data
137 # structures
138
139 # Generate a list of commands in gdb's language:
140 commands = ['set breakpoint pending yes',
141 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200142
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200143 # The tests assume that the first frame of printed
144 # backtrace will not contain program counter,
145 # that is however not guaranteed by gdb
146 # therefore we need to use 'set print address off' to
147 # make sure the counter is not there. For example:
148 # #0 in PyObject_Print ...
149 # is assumed, but sometimes this can be e.g.
150 # #0 0x00003fffb7dd1798 in PyObject_Print ...
151 'set print address off',
152
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000153 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200154
155 # GDB as of 7.4 onwards can distinguish between the
156 # value of a variable at entry vs current value:
157 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
158 # which leads to the selftests failing with errors like this:
159 # AssertionError: 'v@entry=()' != '()'
160 # Disable this:
161 if (gdb_major_version, gdb_minor_version) >= (7, 4):
162 commands += ['set print entry-values no']
163
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000164 if cmds_after_breakpoint:
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200165 commands += cmds_after_breakpoint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000166 else:
167 commands += ['backtrace']
168
169 # print commands
170
171 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000172 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000173 args += ["--args",
174 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100175 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000176
177 if not import_site:
178 # -S suppresses the default 'import site'
179 args += ["-S"]
180
181 if source:
182 args += ["-c", source]
183 elif script:
184 args += [script]
185
186 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100187 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000188
189 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100190 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000191
Antoine Pitrou81641d62013-05-01 00:15:44 +0200192 errlines = err.splitlines()
193 unexpected_errlines = []
194
195 # Ignore some benign messages on stderr.
196 ignore_patterns = (
197 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200198 'Do you need "set solib-search-path" or '
199 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100200 # BFD: /usr/lib/debug/(...): unable to initialize decompress
201 # status for section .debug_aranges
202 'BFD: ',
203 # ignore all warnings
204 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200205 )
206 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100207 if not line:
208 continue
Pablo Galindof2ef51f2018-08-31 23:04:47 +0100209 # bpo34007: Sometimes some versions of the shared libraries that
210 # are part of the traceback are compiled in optimised mode and the
211 # Program Counter (PC) is not present, not allowing gdb to walk the
212 # frames back. When this happens, the Python bindings of gdb raise
213 # an exception, making the test impossible to succeed.
214 if "PC not saved" in line:
215 raise unittest.SkipTest("gdb cannot walk the frame object"
216 " because the Program Counter is"
217 " not present")
Antoine Pitrou81641d62013-05-01 00:15:44 +0200218 if not line.startswith(ignore_patterns):
219 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000220
221 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200222 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000223 return out
224
225 def get_gdb_repr(self, source,
226 cmds_after_breakpoint=None,
227 import_site=False):
228 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000229 # run "python -c'id(DATA)'" under gdb with a breakpoint on
230 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000231 # parameter, and verify that the gdb displays the same string
232 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000233 # Verify that the gdb displays the expected string
234 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000235 # For a nested structure, the first time we hit the breakpoint will
236 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100237
238 # NOTE: avoid decoding too much of the traceback as some
239 # undecodable characters may lurk there in optimized mode
240 # (issue #19743).
241 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000242 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000243 cmds_after_breakpoint=cmds_after_breakpoint,
244 import_site=import_site)
245 # gdb can insert additional '\n' and space characters in various places
246 # in its output, depending on the width of the terminal it's connected
247 # to (using its "wrap_here" function)
R David Murray44b548d2016-09-08 13:59:53 -0400248 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 +0000249 gdb_output, re.DOTALL)
250 if not m:
251 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
252 return m.group(1), gdb_output
253
254 def assertEndsWith(self, actual, exp_end):
255 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000256 self.assertTrue(actual.endswith(exp_end),
257 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258
259 def assertMultilineMatches(self, actual, pattern):
260 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000261 if not m:
262 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000263
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000264 def get_sample_script(self):
265 return findfile('gdb_sample.py')
266
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000267class PrettyPrintTests(DebuggerTests):
268 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000269 gdb_output = self.get_stack_trace('id(42)')
270 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000271
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100272 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000273 # Ensure that gdb's rendering of the value in a debugged process
274 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100275 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000276 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100277 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000278 self.assertEqual(gdb_repr, exp_repr,
279 ('%r did not equal expected %r; full output was:\n%s'
280 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000281
282 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300283 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100284 self.assertGdbRepr(42)
285 self.assertGdbRepr(0)
286 self.assertGdbRepr(-7)
287 self.assertGdbRepr(1000000000000)
288 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000289
290 def test_singletons(self):
291 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100292 self.assertGdbRepr(True)
293 self.assertGdbRepr(False)
294 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000295
296 def test_dicts(self):
297 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100298 self.assertGdbRepr({})
299 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900300 # Python preserves insertion order since 3.6
301 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000302
303 def test_lists(self):
304 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100305 self.assertGdbRepr([])
306 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000307
308 def test_bytes(self):
309 'Verify the pretty-printing of bytes'
310 self.assertGdbRepr(b'')
311 self.assertGdbRepr(b'And now for something hopefully the same')
312 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
313 self.assertGdbRepr(b'this is a tab:\t'
314 b' this is a slash-N:\n'
315 b' this is a slash-R:\r'
316 )
317
318 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
319
320 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000321
322 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000323 'Verify the pretty-printing of unicode strings'
Elvis Pranskevichus7279b512018-09-21 21:13:16 -0400324 # We cannot simply call locale.getpreferredencoding() here,
325 # as GDB might have been linked against a different version
326 # of Python with a different encoding and coercion policy
327 # with respect to PEP 538 and PEP 540.
328 out, err = run_gdb(
329 '--eval-command',
330 'python import locale; print(locale.getpreferredencoding())')
331
332 encoding = out.rstrip()
333 if err or not encoding:
334 raise RuntimeError(
335 f'unable to determine the preferred encoding '
336 f'of embedded Python in GDB: {err}')
337
Victor Stinner150016f2010-05-19 23:04:56 +0000338 def check_repr(text):
339 try:
340 text.encode(encoding)
341 printable = True
342 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000343 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000344 else:
345 self.assertGdbRepr(text)
346
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000347 self.assertGdbRepr('')
348 self.assertGdbRepr('And now for something hopefully the same')
349 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000350
351 # Test printing a single character:
352 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000353 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000354
355 # Test printing a Japanese unicode string
356 # (I believe this reads "mojibake", using 3 characters from the CJK
357 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000358 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000359
360 # Test a character outside the BMP:
361 # U+1D121 MUSICAL SYMBOL C CLEF
362 # This is:
363 # UTF-8: 0xF0 0x9D 0x84 0xA1
364 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000365 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000366
367 def test_tuples(self):
368 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100369 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000370 self.assertGdbRepr((1,), '(1,)')
371 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000372
373 def test_sets(self):
374 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200375 if (gdb_major_version, gdb_minor_version) < (7, 3):
376 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100377 self.assertGdbRepr(set(), "set()")
378 self.assertGdbRepr(set(['a']), "{'a'}")
379 # PYTHONHASHSEED is need to get the exact frozenset item order
380 if not sys.flags.ignore_environment:
381 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
382 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000383
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000384 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000385 # which happens on deletion:
386 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100387s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000388id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000389 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000390
391 def test_frozensets(self):
392 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200393 if (gdb_major_version, gdb_minor_version) < (7, 3):
394 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100395 self.assertGdbRepr(frozenset(), "frozenset()")
396 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
397 # PYTHONHASHSEED is need to get the exact frozenset item order
398 if not sys.flags.ignore_environment:
399 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
400 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000401
402 def test_exceptions(self):
403 # Test a RuntimeError
404 gdb_repr, gdb_output = self.get_gdb_repr('''
405try:
406 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407except RuntimeError as e:
408 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000409''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000410 self.assertEqual(gdb_repr,
411 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000412
413
414 # Test division by zero:
415 gdb_repr, gdb_output = self.get_gdb_repr('''
416try:
417 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000418except ZeroDivisionError as e:
419 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000420''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000421 self.assertEqual(gdb_repr,
422 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000423
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000424 def test_modern_class(self):
425 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000426 gdb_repr, gdb_output = self.get_gdb_repr('''
427class Foo:
428 pass
429foo = Foo()
430foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000431id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100432 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000433 self.assertTrue(m,
434 msg='Unexpected new-style class rendering %r' % gdb_repr)
435
436 def test_subclassing_list(self):
437 'Verify the pretty-printing of an instance of a list subclass'
438 gdb_repr, gdb_output = self.get_gdb_repr('''
439class Foo(list):
440 pass
441foo = Foo()
442foo += [1, 2, 3]
443foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000444id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100445 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 +0000446
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000447 self.assertTrue(m,
448 msg='Unexpected new-style class rendering %r' % gdb_repr)
449
450 def test_subclassing_tuple(self):
451 'Verify the pretty-printing of an instance of a tuple subclass'
452 # This should exercise the negative tp_dictoffset code in the
453 # new-style class support
454 gdb_repr, gdb_output = self.get_gdb_repr('''
455class Foo(tuple):
456 pass
457foo = Foo((1, 2, 3))
458foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000459id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100460 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 +0000461
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000462 self.assertTrue(m,
463 msg='Unexpected new-style class rendering %r' % gdb_repr)
464
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000465 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000466 '''Run Python under gdb, corrupting variables in the inferior process
467 immediately before taking a backtrace.
468
469 Verify that the variable's representation is the expected failsafe
470 representation'''
471 if corruption:
472 cmds_after_breakpoint=[corruption, 'backtrace']
473 else:
474 cmds_after_breakpoint=['backtrace']
475
476 gdb_repr, gdb_output = \
477 self.get_gdb_repr(source,
478 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000479 if exprepr:
480 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000481 # gdb managed to print the value in spite of the corruption;
482 # this is good (see http://bugs.python.org/issue8330)
483 return
484
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000485 # Match anything for the type name; 0xDEADBEEF could point to
486 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100487 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000488
489 m = re.match(pattern, gdb_repr)
490 if not m:
491 self.fail('Unexpected gdb representation: %r\n%s' % \
492 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000493
494 def test_NULL_ptr(self):
495 'Ensure that a NULL PyObject* is handled gracefully'
496 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000497 self.get_gdb_repr('id(42)',
498 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000499 'backtrace'])
500 )
501
Ezio Melottib3aedd42010-11-20 19:04:17 +0000502 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000503
504 def test_NULL_ob_type(self):
505 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000506 self.assertSane('id(42)',
507 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000508
509 def test_corrupt_ob_type(self):
510 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000511 self.assertSane('id(42)',
512 'set v->ob_type=0xDEADBEEF',
513 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000514
515 def test_corrupt_tp_flags(self):
516 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000517 self.assertSane('id(42)',
518 'set v->ob_type->tp_flags=0x0',
519 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520
521 def test_corrupt_tp_name(self):
522 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000523 self.assertSane('id(42)',
524 'set v->ob_type->tp_name=0xDEADBEEF',
525 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000526
527 def test_builtins_help(self):
528 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100529
530 if sys.flags.no_site:
531 self.skipTest("need site module, but -S option was used")
532
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000533 # (this was the issue causing tracebacks in
534 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000535 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000536
Antoine Pitrou4d098732011-11-26 01:42:03 +0100537 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000538 self.assertTrue(m,
539 msg='Unexpected rendering %r' % gdb_repr)
540
541 def test_selfreferential_list(self):
542 '''Ensure that a reference loop involving a list doesn't lead proxyval
543 into an infinite loop:'''
544 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000545 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000546 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000547
548 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000549 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000550 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000551
552 def test_selfreferential_dict(self):
553 '''Ensure that a reference loop involving a dict doesn't lead proxyval
554 into an infinite loop:'''
555 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000556 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000557
Ezio Melottib3aedd42010-11-20 19:04:17 +0000558 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000559
560 def test_selfreferential_old_style_instance(self):
561 gdb_repr, gdb_output = \
562 self.get_gdb_repr('''
563class Foo:
564 pass
565foo = Foo()
566foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000567id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400568 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000569 gdb_repr),
570 'Unexpected gdb representation: %r\n%s' % \
571 (gdb_repr, gdb_output))
572
573 def test_selfreferential_new_style_instance(self):
574 gdb_repr, gdb_output = \
575 self.get_gdb_repr('''
576class Foo(object):
577 pass
578foo = Foo()
579foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000580id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400581 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000582 gdb_repr),
583 'Unexpected gdb representation: %r\n%s' % \
584 (gdb_repr, gdb_output))
585
586 gdb_repr, gdb_output = \
587 self.get_gdb_repr('''
588class Foo(object):
589 pass
590a = Foo()
591b = Foo()
592a.an_attr = b
593b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000594id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400595 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 +0000596 gdb_repr),
597 'Unexpected gdb representation: %r\n%s' % \
598 (gdb_repr, gdb_output))
599
600 def test_truncation(self):
601 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000602 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000603 self.assertEqual(gdb_repr,
604 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
605 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
606 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
607 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
608 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
609 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
610 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
611 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
612 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
613 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
614 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
615 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
616 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
617 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
618 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
619 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
620 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
621 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
622 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
623 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
624 "224, 225, 226...(truncated)")
625 self.assertEqual(len(gdb_repr),
626 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000627
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000628 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000629 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400630 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 +0000631 gdb_repr),
632 'Unexpected gdb representation: %r\n%s' % \
633 (gdb_repr, gdb_output))
634
635 def test_frames(self):
636 gdb_output = self.get_stack_trace('''
637def foo(a, b, c):
638 pass
639
640foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000641id(foo.__code__)''',
642 breakpoint='builtin_id',
643 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000644 )
R David Murray44b548d2016-09-08 13:59:53 -0400645 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 +0000646 gdb_output,
647 re.DOTALL),
648 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
649
Victor Stinnerd2084162011-12-19 13:42:24 +0100650@unittest.skipIf(python_is_optimized(),
651 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000652class PyListTests(DebuggerTests):
653 def assertListing(self, expected, actual):
654 self.assertEndsWith(actual, expected)
655
656 def test_basic_command(self):
657 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000658 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000659 cmds_after_breakpoint=['py-list'])
660
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000661 self.assertListing(' 5 \n'
662 ' 6 def bar(a, b, c):\n'
663 ' 7 baz(a, b, c)\n'
664 ' 8 \n'
665 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000666 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000667 ' 11 \n'
668 ' 12 foo(1, 2, 3)\n',
669 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000670
671 def test_one_abs_arg(self):
672 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000673 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000674 cmds_after_breakpoint=['py-list 9'])
675
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000676 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000677 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000678 ' 11 \n'
679 ' 12 foo(1, 2, 3)\n',
680 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000681
682 def test_two_abs_args(self):
683 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000684 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000685 cmds_after_breakpoint=['py-list 1,3'])
686
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000687 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
688 ' 2 \n'
689 ' 3 def foo(a, b, c):\n',
690 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000691
692class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000693 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100694 @unittest.skipIf(python_is_optimized(),
695 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 def test_pyup_command(self):
697 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000698 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100699 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000700 self.assertMultilineMatches(bt,
701 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100702#[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 +0000703 baz\(a, b, c\)
704$''')
705
Victor Stinner50eb60e2010-04-20 22:32:07 +0000706 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000707 def test_down_at_bottom(self):
708 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000709 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000710 cmds_after_breakpoint=['py-down'])
711 self.assertEndsWith(bt,
712 'Unable to find a newer python frame\n')
713
Victor Stinner50eb60e2010-04-20 22:32:07 +0000714 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000715 def test_up_at_top(self):
716 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000717 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100718 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000719 self.assertEndsWith(bt,
720 'Unable to find an older python frame\n')
721
Victor Stinner50eb60e2010-04-20 22:32:07 +0000722 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100723 @unittest.skipIf(python_is_optimized(),
724 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725 def test_up_then_down(self):
726 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000727 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100728 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000729 self.assertMultilineMatches(bt,
730 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100731#[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 +0000732 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100733#[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 +0000734 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000735$''')
736
737class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100738 @unittest.skipIf(python_is_optimized(),
739 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200740 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000741 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000742 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000743 cmds_after_breakpoint=['py-bt'])
744 self.assertMultilineMatches(bt,
745 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200746Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100747 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200748 File ".*gdb_sample.py", line 10, in baz
749 id\(42\)
750 File ".*gdb_sample.py", line 7, in bar
751 baz\(a, b, c\)
752 File ".*gdb_sample.py", line 4, in foo
753 bar\(a, b, c\)
754 File ".*gdb_sample.py", line 12, in <module>
755 foo\(1, 2, 3\)
756''')
757
Victor Stinnerd2084162011-12-19 13:42:24 +0100758 @unittest.skipIf(python_is_optimized(),
759 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200760 def test_bt_full(self):
761 'Verify that the "py-bt-full" command works'
762 bt = self.get_stack_trace(script=self.get_sample_script(),
763 cmds_after_breakpoint=['py-bt-full'])
764 self.assertMultilineMatches(bt,
765 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100766#[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 +0000767 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100768#[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 +0000769 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100770#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100771 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000772''')
773
David Malcolm8d37ffa2012-06-27 14:15:34 -0400774 def test_threads(self):
775 'Verify that "py-bt" indicates threads that are waiting for the GIL'
776 cmd = '''
777from threading import Thread
778
779class TestThread(Thread):
780 # These threads would run forever, but we'll interrupt things with the
781 # debugger
782 def run(self):
783 i = 0
784 while 1:
785 i += 1
786
787t = {}
788for i in range(4):
789 t[i] = TestThread()
790 t[i].start()
791
792# Trigger a breakpoint on the main thread
793id(42)
794
795'''
796 # Verify with "py-bt":
797 gdb_output = self.get_stack_trace(cmd,
798 cmds_after_breakpoint=['thread apply all py-bt'])
799 self.assertIn('Waiting for the GIL', gdb_output)
800
801 # Verify with "py-bt-full":
802 gdb_output = self.get_stack_trace(cmd,
803 cmds_after_breakpoint=['thread apply all py-bt-full'])
804 self.assertIn('Waiting for the GIL', gdb_output)
805
806 @unittest.skipIf(python_is_optimized(),
807 "Python was compiled with optimizations")
808 # Some older versions of gdb will fail with
809 # "Cannot find new threads: generic error"
810 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400811 def test_gc(self):
812 'Verify that "py-bt" indicates if a thread is garbage-collecting'
813 cmd = ('from gc import collect\n'
814 'id(42)\n'
815 'def foo():\n'
816 ' collect()\n'
817 'def bar():\n'
818 ' foo()\n'
819 'bar()\n')
820 # Verify with "py-bt":
821 gdb_output = self.get_stack_trace(cmd,
822 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
823 )
824 self.assertIn('Garbage-collecting', gdb_output)
825
826 # Verify with "py-bt-full":
827 gdb_output = self.get_stack_trace(cmd,
828 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
829 )
830 self.assertIn('Garbage-collecting', gdb_output)
831
832 @unittest.skipIf(python_is_optimized(),
833 "Python was compiled with optimizations")
834 # Some older versions of gdb will fail with
835 # "Cannot find new threads: generic error"
836 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400837 def test_pycfunction(self):
838 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100839 # Tested function must not be defined with METH_NOARGS or METH_O,
840 # otherwise call_function() doesn't call PyCFunction_Call()
841 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400842 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100843 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400844 'def bar():\n'
845 ' foo()\n'
846 'bar()\n')
847 # Verify with "py-bt":
848 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100849 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400850 cmds_after_breakpoint=['bt', 'py-bt'],
851 )
Victor Stinner79644f92015-03-27 15:42:37 +0100852 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400853
854 # Verify with "py-bt-full":
855 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100856 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400857 cmds_after_breakpoint=['py-bt-full'],
858 )
INADA Naoki5566bbb2017-02-03 07:43:03 +0900859 self.assertIn('#2 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400860
Victor Stinner61108332017-02-01 16:29:54 +0100861 @unittest.skipIf(python_is_optimized(),
862 "Python was compiled with optimizations")
863 def test_wrapper_call(self):
864 cmd = textwrap.dedent('''
865 class MyList(list):
866 def __init__(self):
867 super().__init__() # wrapper_call()
868
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100869 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100870 l = MyList()
871 ''')
872 # Verify with "py-bt":
873 gdb_output = self.get_stack_trace(cmd,
Victor Stinner2f9cbaa2018-06-15 22:54:35 +0200874 cmds_after_breakpoint=['break wrapper_call', 'continue', 'py-bt'])
Victor Stinner72268ae2017-02-01 18:26:14 +0100875 self.assertRegex(gdb_output,
876 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100877
David Malcolm8d37ffa2012-06-27 14:15:34 -0400878
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000879class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100880 @unittest.skipIf(python_is_optimized(),
881 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000882 def test_basic_command(self):
883 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000884 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100885 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000886 self.assertMultilineMatches(bt,
887 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
888
Vinay Sajip2549f872012-01-04 12:07:30 +0000889 @unittest.skipIf(python_is_optimized(),
890 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000891 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000892 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000893 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100894 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000895 self.assertMultilineMatches(bt,
896 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
897
Victor Stinnerd2084162011-12-19 13:42:24 +0100898 @unittest.skipIf(python_is_optimized(),
899 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000900 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000901 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100902 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000903 self.assertMultilineMatches(bt,
904 r".*\nglobal '__name__' = '__main__'\n.*")
905
Victor Stinnerd2084162011-12-19 13:42:24 +0100906 @unittest.skipIf(python_is_optimized(),
907 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000908 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000909 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100910 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000911 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100912 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000913
914class PyLocalsTests(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):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000918 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100919 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000920 self.assertMultilineMatches(bt,
921 r".*\nargs = \(1, 2, 3\)\n.*")
922
Victor Stinner50eb60e2010-04-20 22:32:07 +0000923 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000924 @unittest.skipIf(python_is_optimized(),
925 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000926 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000927 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100928 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000929 self.assertMultilineMatches(bt,
930 r".*\na = 1\nb = 2\nc = 3\n.*")
931
932def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200933 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200934 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200935 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200936 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000937 run_unittest(PrettyPrintTests,
938 PyListTests,
939 StackNavigationTests,
940 PyBtTests,
941 PyPrintTests,
942 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000943 )
944
945if __name__ == "__main__":
946 test_main()