blob: 46736f62d584ab656bf5f5648cea565a78730148 [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
David Malcolm8d37ffa2012-06-27 14:15:34 -040015# Is this Python configured to support threads?
16try:
17 import _thread
18except ImportError:
19 _thread = None
20
Antoine Pitroud0f3e072013-09-21 23:56:17 +020021from test import support
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000022from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000023
Victor Stinner5b6b4a82015-09-02 23:19:55 +020024def get_gdb_version():
25 try:
26 proc = subprocess.Popen(["gdb", "-nx", "--version"],
27 stdout=subprocess.PIPE,
Benjamin Petersoncbef66d2016-09-06 10:06:31 -070028 stderr=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020029 universal_newlines=True)
30 with proc:
31 version = proc.communicate()[0]
32 except OSError:
33 # This is what "no gdb" looks like. There may, however, be other
34 # errors that manifest this way too.
35 raise unittest.SkipTest("Couldn't find gdb on the path")
36
37 # Regex to parse:
38 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
39 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020040 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
41 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnera578eb32015-09-15 00:22:55 +020042 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020043 if match is None:
44 raise Exception("unable to parse GDB version: %r" % version)
45 return (version, int(match.group(1)), int(match.group(2)))
46
47gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040048if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020049 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
50 "embedding. Saw %s.%s:\n%s"
51 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020052 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000053
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010054if not sysconfig.is_python_build():
55 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
56
R David Murrayf9333022012-10-27 13:22:41 -040057# Location of custom hooks file in a repository checkout.
58checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
59 'python-gdb.py')
60
Victor Stinner51324932013-11-20 12:27:48 +010061PYTHONHASHSEED = '123'
62
R David Murrayf9333022012-10-27 13:22:41 -040063def run_gdb(*args, **env_vars):
64 """Runs gdb in --batch mode with the additional arguments given by *args.
65
66 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
67 """
68 if env_vars:
69 env = os.environ.copy()
70 env.update(env_vars)
71 else:
72 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020073 # -nx: Do not execute commands from any .gdbinit initialization files
74 # (issue #22188)
75 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040076 if (gdb_major_version, gdb_minor_version) >= (7, 4):
77 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020078 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000079 # Redirect stdin to prevent GDB from messing with
80 # the terminal settings
81 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020082 stdout=subprocess.PIPE,
83 stderr=subprocess.PIPE,
84 env=env)
85 with proc:
86 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040087 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
88
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000089# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010090gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040091if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000092 raise unittest.SkipTest("gdb not built with embedded python support")
93
Nick Coghlance346872013-09-22 19:38:16 +100094# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -070095# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040096_, gdbpy_errors = run_gdb('--args', sys.executable)
97if "auto-loading has been declined" in gdbpy_errors:
98 msg = "gdb security settings prevent use of custom hooks: "
99 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +1000100
Victor Stinner50eb60e2010-04-20 22:32:07 +0000101def gdb_has_frame_select():
102 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -0400103 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
104 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +0000105 if not m:
106 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400107 gdb_frame_dir = m.group(1).split(', ')
108 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000109
110HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000111
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000112BREAKPOINT_FN='builtin_id'
113
Benjamin Peterson437df902016-09-06 20:22:41 -0700114@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000115class DebuggerTests(unittest.TestCase):
116
117 """Test that the debugger can debug Python."""
118
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000119 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000120 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000121 cmds_after_breakpoint=None,
122 import_site=False):
123 '''
124 Run 'python -c SOURCE' under gdb with a breakpoint.
125
126 Support injecting commands after the breakpoint is reached
127
128 Returns the stdout from gdb
129
130 cmds_after_breakpoint: if provided, a list of strings: gdb commands
131 '''
132 # We use "set breakpoint pending yes" to avoid blocking with a:
133 # Function "foo" not defined.
134 # Make breakpoint pending on future shared library load? (y or [n])
135 # error, which typically happens python is dynamically linked (the
136 # breakpoints of interest are to be found in the shared library)
137 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000138 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000139 # emitted to stderr each time, alas.
140
141 # Initially I had "--eval-command=continue" here, but removed it to
142 # avoid repeated print breakpoints when traversing hierarchical data
143 # structures
144
145 # Generate a list of commands in gdb's language:
146 commands = ['set breakpoint pending yes',
147 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200148
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200149 # The tests assume that the first frame of printed
150 # backtrace will not contain program counter,
151 # that is however not guaranteed by gdb
152 # therefore we need to use 'set print address off' to
153 # make sure the counter is not there. For example:
154 # #0 in PyObject_Print ...
155 # is assumed, but sometimes this can be e.g.
156 # #0 0x00003fffb7dd1798 in PyObject_Print ...
157 'set print address off',
158
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000159 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200160
161 # GDB as of 7.4 onwards can distinguish between the
162 # value of a variable at entry vs current value:
163 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
164 # which leads to the selftests failing with errors like this:
165 # AssertionError: 'v@entry=()' != '()'
166 # Disable this:
167 if (gdb_major_version, gdb_minor_version) >= (7, 4):
168 commands += ['set print entry-values no']
169
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000170 if cmds_after_breakpoint:
171 commands += cmds_after_breakpoint
172 else:
173 commands += ['backtrace']
174
175 # print commands
176
177 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000178 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000179 args += ["--args",
180 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100181 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000182
183 if not import_site:
184 # -S suppresses the default 'import site'
185 args += ["-S"]
186
187 if source:
188 args += ["-c", source]
189 elif script:
190 args += [script]
191
192 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100193 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194
195 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100196 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000197
Antoine Pitrou81641d62013-05-01 00:15:44 +0200198 errlines = err.splitlines()
199 unexpected_errlines = []
200
201 # Ignore some benign messages on stderr.
202 ignore_patterns = (
203 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200204 'Do you need "set solib-search-path" or '
205 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100206 # BFD: /usr/lib/debug/(...): unable to initialize decompress
207 # status for section .debug_aranges
208 'BFD: ',
209 # ignore all warnings
210 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200211 )
212 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100213 if not line:
214 continue
Antoine Pitrou81641d62013-05-01 00:15:44 +0200215 if not line.startswith(ignore_patterns):
216 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000217
218 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200219 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000220 return out
221
222 def get_gdb_repr(self, source,
223 cmds_after_breakpoint=None,
224 import_site=False):
225 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000226 # run "python -c'id(DATA)'" under gdb with a breakpoint on
227 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000228 # parameter, and verify that the gdb displays the same string
229 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000230 # Verify that the gdb displays the expected string
231 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000232 # For a nested structure, the first time we hit the breakpoint will
233 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100234
235 # NOTE: avoid decoding too much of the traceback as some
236 # undecodable characters may lurk there in optimized mode
237 # (issue #19743).
238 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000239 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000240 cmds_after_breakpoint=cmds_after_breakpoint,
241 import_site=import_site)
242 # gdb can insert additional '\n' and space characters in various places
243 # in its output, depending on the width of the terminal it's connected
244 # to (using its "wrap_here" function)
R David Murray44b548d2016-09-08 13:59:53 -0400245 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 +0000246 gdb_output, re.DOTALL)
247 if not m:
248 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
249 return m.group(1), gdb_output
250
251 def assertEndsWith(self, actual, exp_end):
252 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000253 self.assertTrue(actual.endswith(exp_end),
254 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000255
256 def assertMultilineMatches(self, actual, pattern):
257 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000258 if not m:
259 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000260
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000261 def get_sample_script(self):
262 return findfile('gdb_sample.py')
263
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000264class PrettyPrintTests(DebuggerTests):
265 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000266 gdb_output = self.get_stack_trace('id(42)')
267 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000268
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100269 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000270 # Ensure that gdb's rendering of the value in a debugged process
271 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100272 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000273 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100274 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000275 self.assertEqual(gdb_repr, exp_repr,
276 ('%r did not equal expected %r; full output was:\n%s'
277 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000278
279 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300280 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100281 self.assertGdbRepr(42)
282 self.assertGdbRepr(0)
283 self.assertGdbRepr(-7)
284 self.assertGdbRepr(1000000000000)
285 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000286
287 def test_singletons(self):
288 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100289 self.assertGdbRepr(True)
290 self.assertGdbRepr(False)
291 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000292
293 def test_dicts(self):
294 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100295 self.assertGdbRepr({})
296 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900297 # Python preserves insertion order since 3.6
298 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000299
300 def test_lists(self):
301 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100302 self.assertGdbRepr([])
303 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000304
305 def test_bytes(self):
306 'Verify the pretty-printing of bytes'
307 self.assertGdbRepr(b'')
308 self.assertGdbRepr(b'And now for something hopefully the same')
309 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
310 self.assertGdbRepr(b'this is a tab:\t'
311 b' this is a slash-N:\n'
312 b' this is a slash-R:\r'
313 )
314
315 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
316
317 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000318
319 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000320 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000321 encoding = locale.getpreferredencoding()
322 def check_repr(text):
323 try:
324 text.encode(encoding)
325 printable = True
326 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000327 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000328 else:
329 self.assertGdbRepr(text)
330
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000331 self.assertGdbRepr('')
332 self.assertGdbRepr('And now for something hopefully the same')
333 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000334
335 # Test printing a single character:
336 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000337 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000338
339 # Test printing a Japanese unicode string
340 # (I believe this reads "mojibake", using 3 characters from the CJK
341 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000342 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000343
344 # Test a character outside the BMP:
345 # U+1D121 MUSICAL SYMBOL C CLEF
346 # This is:
347 # UTF-8: 0xF0 0x9D 0x84 0xA1
348 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000349 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000350
351 def test_tuples(self):
352 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100353 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000354 self.assertGdbRepr((1,), '(1,)')
355 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000356
357 def test_sets(self):
358 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200359 if (gdb_major_version, gdb_minor_version) < (7, 3):
360 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100361 self.assertGdbRepr(set(), "set()")
362 self.assertGdbRepr(set(['a']), "{'a'}")
363 # PYTHONHASHSEED is need to get the exact frozenset item order
364 if not sys.flags.ignore_environment:
365 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
366 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000367
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000368 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000369 # which happens on deletion:
370 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100371s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000372id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000373 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000374
375 def test_frozensets(self):
376 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200377 if (gdb_major_version, gdb_minor_version) < (7, 3):
378 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100379 self.assertGdbRepr(frozenset(), "frozenset()")
380 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
381 # PYTHONHASHSEED is need to get the exact frozenset item order
382 if not sys.flags.ignore_environment:
383 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
384 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000385
386 def test_exceptions(self):
387 # Test a RuntimeError
388 gdb_repr, gdb_output = self.get_gdb_repr('''
389try:
390 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000391except RuntimeError as e:
392 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000393''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000394 self.assertEqual(gdb_repr,
395 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000396
397
398 # Test division by zero:
399 gdb_repr, gdb_output = self.get_gdb_repr('''
400try:
401 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000402except ZeroDivisionError as e:
403 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000405 self.assertEqual(gdb_repr,
406 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000407
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000408 def test_modern_class(self):
409 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410 gdb_repr, gdb_output = self.get_gdb_repr('''
411class Foo:
412 pass
413foo = Foo()
414foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000415id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100416 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000417 self.assertTrue(m,
418 msg='Unexpected new-style class rendering %r' % gdb_repr)
419
420 def test_subclassing_list(self):
421 'Verify the pretty-printing of an instance of a list subclass'
422 gdb_repr, gdb_output = self.get_gdb_repr('''
423class Foo(list):
424 pass
425foo = Foo()
426foo += [1, 2, 3]
427foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000428id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100429 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 +0000430
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000431 self.assertTrue(m,
432 msg='Unexpected new-style class rendering %r' % gdb_repr)
433
434 def test_subclassing_tuple(self):
435 'Verify the pretty-printing of an instance of a tuple subclass'
436 # This should exercise the negative tp_dictoffset code in the
437 # new-style class support
438 gdb_repr, gdb_output = self.get_gdb_repr('''
439class Foo(tuple):
440 pass
441foo = Foo((1, 2, 3))
442foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000443id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100444 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 +0000445
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000446 self.assertTrue(m,
447 msg='Unexpected new-style class rendering %r' % gdb_repr)
448
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000449 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000450 '''Run Python under gdb, corrupting variables in the inferior process
451 immediately before taking a backtrace.
452
453 Verify that the variable's representation is the expected failsafe
454 representation'''
455 if corruption:
456 cmds_after_breakpoint=[corruption, 'backtrace']
457 else:
458 cmds_after_breakpoint=['backtrace']
459
460 gdb_repr, gdb_output = \
461 self.get_gdb_repr(source,
462 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000463 if exprepr:
464 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000465 # gdb managed to print the value in spite of the corruption;
466 # this is good (see http://bugs.python.org/issue8330)
467 return
468
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000469 # Match anything for the type name; 0xDEADBEEF could point to
470 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100471 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000472
473 m = re.match(pattern, gdb_repr)
474 if not m:
475 self.fail('Unexpected gdb representation: %r\n%s' % \
476 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000477
478 def test_NULL_ptr(self):
479 'Ensure that a NULL PyObject* is handled gracefully'
480 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000481 self.get_gdb_repr('id(42)',
482 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000483 'backtrace'])
484 )
485
Ezio Melottib3aedd42010-11-20 19:04:17 +0000486 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000487
488 def test_NULL_ob_type(self):
489 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000490 self.assertSane('id(42)',
491 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000492
493 def test_corrupt_ob_type(self):
494 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000495 self.assertSane('id(42)',
496 'set v->ob_type=0xDEADBEEF',
497 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000498
499 def test_corrupt_tp_flags(self):
500 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000501 self.assertSane('id(42)',
502 'set v->ob_type->tp_flags=0x0',
503 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000504
505 def test_corrupt_tp_name(self):
506 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000507 self.assertSane('id(42)',
508 'set v->ob_type->tp_name=0xDEADBEEF',
509 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000510
511 def test_builtins_help(self):
512 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100513
514 if sys.flags.no_site:
515 self.skipTest("need site module, but -S option was used")
516
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000517 # (this was the issue causing tracebacks in
518 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000519 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520
Antoine Pitrou4d098732011-11-26 01:42:03 +0100521 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000522 self.assertTrue(m,
523 msg='Unexpected rendering %r' % gdb_repr)
524
525 def test_selfreferential_list(self):
526 '''Ensure that a reference loop involving a list doesn't lead proxyval
527 into an infinite loop:'''
528 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000529 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000530 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000531
532 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000533 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000534 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000535
536 def test_selfreferential_dict(self):
537 '''Ensure that a reference loop involving a dict doesn't lead proxyval
538 into an infinite loop:'''
539 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000540 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000541
Ezio Melottib3aedd42010-11-20 19:04:17 +0000542 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000543
544 def test_selfreferential_old_style_instance(self):
545 gdb_repr, gdb_output = \
546 self.get_gdb_repr('''
547class Foo:
548 pass
549foo = Foo()
550foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000551id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400552 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000553 gdb_repr),
554 'Unexpected gdb representation: %r\n%s' % \
555 (gdb_repr, gdb_output))
556
557 def test_selfreferential_new_style_instance(self):
558 gdb_repr, gdb_output = \
559 self.get_gdb_repr('''
560class Foo(object):
561 pass
562foo = Foo()
563foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000564id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400565 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000566 gdb_repr),
567 'Unexpected gdb representation: %r\n%s' % \
568 (gdb_repr, gdb_output))
569
570 gdb_repr, gdb_output = \
571 self.get_gdb_repr('''
572class Foo(object):
573 pass
574a = Foo()
575b = Foo()
576a.an_attr = b
577b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000578id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400579 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 +0000580 gdb_repr),
581 'Unexpected gdb representation: %r\n%s' % \
582 (gdb_repr, gdb_output))
583
584 def test_truncation(self):
585 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000586 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000587 self.assertEqual(gdb_repr,
588 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
589 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
590 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
591 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
592 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
593 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
594 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
595 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
596 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
597 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
598 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
599 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
600 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
601 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
602 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
603 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
604 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
605 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
606 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
607 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
608 "224, 225, 226...(truncated)")
609 self.assertEqual(len(gdb_repr),
610 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000611
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000612 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000613 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400614 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 +0000615 gdb_repr),
616 'Unexpected gdb representation: %r\n%s' % \
617 (gdb_repr, gdb_output))
618
619 def test_frames(self):
620 gdb_output = self.get_stack_trace('''
621def foo(a, b, c):
622 pass
623
624foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000625id(foo.__code__)''',
626 breakpoint='builtin_id',
627 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000628 )
R David Murray44b548d2016-09-08 13:59:53 -0400629 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 +0000630 gdb_output,
631 re.DOTALL),
632 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
633
Victor Stinnerd2084162011-12-19 13:42:24 +0100634@unittest.skipIf(python_is_optimized(),
635 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000636class PyListTests(DebuggerTests):
637 def assertListing(self, expected, actual):
638 self.assertEndsWith(actual, expected)
639
640 def test_basic_command(self):
641 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000642 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000643 cmds_after_breakpoint=['py-list'])
644
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000645 self.assertListing(' 5 \n'
646 ' 6 def bar(a, b, c):\n'
647 ' 7 baz(a, b, c)\n'
648 ' 8 \n'
649 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000650 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000651 ' 11 \n'
652 ' 12 foo(1, 2, 3)\n',
653 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000654
655 def test_one_abs_arg(self):
656 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000657 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000658 cmds_after_breakpoint=['py-list 9'])
659
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000660 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000661 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000662 ' 11 \n'
663 ' 12 foo(1, 2, 3)\n',
664 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000665
666 def test_two_abs_args(self):
667 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000668 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000669 cmds_after_breakpoint=['py-list 1,3'])
670
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000671 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
672 ' 2 \n'
673 ' 3 def foo(a, b, c):\n',
674 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000675
676class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000677 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100678 @unittest.skipIf(python_is_optimized(),
679 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000680 def test_pyup_command(self):
681 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000682 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100683 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000684 self.assertMultilineMatches(bt,
685 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100686#[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 +0000687 baz\(a, b, c\)
688$''')
689
Victor Stinner50eb60e2010-04-20 22:32:07 +0000690 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000691 def test_down_at_bottom(self):
692 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000693 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000694 cmds_after_breakpoint=['py-down'])
695 self.assertEndsWith(bt,
696 'Unable to find a newer python frame\n')
697
Victor Stinner50eb60e2010-04-20 22:32:07 +0000698 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000699 def test_up_at_top(self):
700 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000701 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100702 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000703 self.assertEndsWith(bt,
704 'Unable to find an older python frame\n')
705
Victor Stinner50eb60e2010-04-20 22:32:07 +0000706 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100707 @unittest.skipIf(python_is_optimized(),
708 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000709 def test_up_then_down(self):
710 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000711 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100712 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000713 self.assertMultilineMatches(bt,
714 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100715#[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 +0000716 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100717#[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 +0000718 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000719$''')
720
721class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100722 @unittest.skipIf(python_is_optimized(),
723 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200724 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000726 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000727 cmds_after_breakpoint=['py-bt'])
728 self.assertMultilineMatches(bt,
729 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200730Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100731 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200732 File ".*gdb_sample.py", line 10, in baz
733 id\(42\)
734 File ".*gdb_sample.py", line 7, in bar
735 baz\(a, b, c\)
736 File ".*gdb_sample.py", line 4, in foo
737 bar\(a, b, c\)
738 File ".*gdb_sample.py", line 12, in <module>
739 foo\(1, 2, 3\)
740''')
741
Victor Stinnerd2084162011-12-19 13:42:24 +0100742 @unittest.skipIf(python_is_optimized(),
743 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200744 def test_bt_full(self):
745 'Verify that the "py-bt-full" command works'
746 bt = self.get_stack_trace(script=self.get_sample_script(),
747 cmds_after_breakpoint=['py-bt-full'])
748 self.assertMultilineMatches(bt,
749 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100750#[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 +0000751 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100752#[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 +0000753 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100754#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100755 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000756''')
757
David Malcolm8d37ffa2012-06-27 14:15:34 -0400758 @unittest.skipUnless(_thread,
759 "Python was compiled without thread support")
760 def test_threads(self):
761 'Verify that "py-bt" indicates threads that are waiting for the GIL'
762 cmd = '''
763from threading import Thread
764
765class TestThread(Thread):
766 # These threads would run forever, but we'll interrupt things with the
767 # debugger
768 def run(self):
769 i = 0
770 while 1:
771 i += 1
772
773t = {}
774for i in range(4):
775 t[i] = TestThread()
776 t[i].start()
777
778# Trigger a breakpoint on the main thread
779id(42)
780
781'''
782 # Verify with "py-bt":
783 gdb_output = self.get_stack_trace(cmd,
784 cmds_after_breakpoint=['thread apply all py-bt'])
785 self.assertIn('Waiting for the GIL', gdb_output)
786
787 # Verify with "py-bt-full":
788 gdb_output = self.get_stack_trace(cmd,
789 cmds_after_breakpoint=['thread apply all py-bt-full'])
790 self.assertIn('Waiting for the GIL', gdb_output)
791
792 @unittest.skipIf(python_is_optimized(),
793 "Python was compiled with optimizations")
794 # Some older versions of gdb will fail with
795 # "Cannot find new threads: generic error"
796 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
797 @unittest.skipUnless(_thread,
798 "Python was compiled without thread support")
799 def test_gc(self):
800 'Verify that "py-bt" indicates if a thread is garbage-collecting'
801 cmd = ('from gc import collect\n'
802 'id(42)\n'
803 'def foo():\n'
804 ' collect()\n'
805 'def bar():\n'
806 ' foo()\n'
807 'bar()\n')
808 # Verify with "py-bt":
809 gdb_output = self.get_stack_trace(cmd,
810 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
811 )
812 self.assertIn('Garbage-collecting', gdb_output)
813
814 # Verify with "py-bt-full":
815 gdb_output = self.get_stack_trace(cmd,
816 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
817 )
818 self.assertIn('Garbage-collecting', gdb_output)
819
820 @unittest.skipIf(python_is_optimized(),
821 "Python was compiled with optimizations")
822 # Some older versions of gdb will fail with
823 # "Cannot find new threads: generic error"
824 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
825 @unittest.skipUnless(_thread,
826 "Python was compiled without thread support")
827 def test_pycfunction(self):
828 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100829 # Tested function must not be defined with METH_NOARGS or METH_O,
830 # otherwise call_function() doesn't call PyCFunction_Call()
831 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400832 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100833 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400834 'def bar():\n'
835 ' foo()\n'
836 'bar()\n')
837 # Verify with "py-bt":
838 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100839 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400840 cmds_after_breakpoint=['bt', 'py-bt'],
841 )
Victor Stinner79644f92015-03-27 15:42:37 +0100842 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400843
844 # Verify with "py-bt-full":
845 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100846 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400847 cmds_after_breakpoint=['py-bt-full'],
848 )
INADA Naoki5566bbb2017-02-03 07:43:03 +0900849 self.assertIn('#2 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400850
Victor Stinner61108332017-02-01 16:29:54 +0100851 @unittest.skipIf(python_is_optimized(),
852 "Python was compiled with optimizations")
853 def test_wrapper_call(self):
854 cmd = textwrap.dedent('''
855 class MyList(list):
856 def __init__(self):
857 super().__init__() # wrapper_call()
858
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100859 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100860 l = MyList()
861 ''')
862 # Verify with "py-bt":
863 gdb_output = self.get_stack_trace(cmd,
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100864 cmds_after_breakpoint=['break wrapper_call', 'continue', 'py-bt'])
Victor Stinner72268ae2017-02-01 18:26:14 +0100865 self.assertRegex(gdb_output,
866 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100867
David Malcolm8d37ffa2012-06-27 14:15:34 -0400868
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000869class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100870 @unittest.skipIf(python_is_optimized(),
871 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000872 def test_basic_command(self):
873 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000874 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100875 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000876 self.assertMultilineMatches(bt,
877 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
878
Vinay Sajip2549f872012-01-04 12:07:30 +0000879 @unittest.skipIf(python_is_optimized(),
880 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000881 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000882 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000883 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100884 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000885 self.assertMultilineMatches(bt,
886 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
887
Victor Stinnerd2084162011-12-19 13:42:24 +0100888 @unittest.skipIf(python_is_optimized(),
889 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000890 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000891 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100892 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000893 self.assertMultilineMatches(bt,
894 r".*\nglobal '__name__' = '__main__'\n.*")
895
Victor Stinnerd2084162011-12-19 13:42:24 +0100896 @unittest.skipIf(python_is_optimized(),
897 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000898 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000899 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100900 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000901 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100902 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000903
904class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100905 @unittest.skipIf(python_is_optimized(),
906 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000907 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000908 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100909 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000910 self.assertMultilineMatches(bt,
911 r".*\nargs = \(1, 2, 3\)\n.*")
912
Victor Stinner50eb60e2010-04-20 22:32:07 +0000913 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000914 @unittest.skipIf(python_is_optimized(),
915 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000916 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000917 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100918 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000919 self.assertMultilineMatches(bt,
920 r".*\na = 1\nb = 2\nc = 3\n.*")
921
922def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200923 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200924 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200925 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200926 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000927 run_unittest(PrettyPrintTests,
928 PyListTests,
929 StackNavigationTests,
930 PyBtTests,
931 PyPrintTests,
932 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000933 )
934
935if __name__ == "__main__":
936 test_main()