blob: 0322677793a52488434ae8893d246307183c406e [file] [log] [blame]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00001# Verify that gdb can pretty-print the various PyObject* types
2#
3# The code for testing gdb was adapted from similar work in Unladen Swallow's
4# Lib/test/test_jit_gdb.py
5
6import os
7import re
Antoine Pitroud0f3e072013-09-21 23:56:17 +02008import pprint
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00009import subprocess
10import sys
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010011import sysconfig
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000012import unittest
Victor Stinner150016f2010-05-19 23:04:56 +000013import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000014
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
24try:
Victor Stinner7869a4e2014-08-16 14:38:02 +020025 gdb_version, _ = subprocess.Popen(["gdb", "-nx", "--version"],
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000026 stdout=subprocess.PIPE).communicate()
27except OSError:
28 # This is what "no gdb" looks like. There may, however, be other
29 # errors that manifest this way too.
30 raise unittest.SkipTest("Couldn't find gdb on the path")
R David Murrayf9333022012-10-27 13:22:41 -040031gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
32gdb_major_version = int(gdb_version_number.group(1))
33gdb_minor_version = int(gdb_version_number.group(2))
34if gdb_major_version < 7:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000035 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
Antoine Pitrou6a45e9d2010-04-11 22:47:34 +000036 " Saw:\n" + gdb_version.decode('ascii', 'replace'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000037
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010038if not sysconfig.is_python_build():
39 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
40
R David Murrayf9333022012-10-27 13:22:41 -040041# Location of custom hooks file in a repository checkout.
42checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
43 'python-gdb.py')
44
Victor Stinner51324932013-11-20 12:27:48 +010045PYTHONHASHSEED = '123'
46
R David Murrayf9333022012-10-27 13:22:41 -040047def run_gdb(*args, **env_vars):
48 """Runs gdb in --batch mode with the additional arguments given by *args.
49
50 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
51 """
52 if env_vars:
53 env = os.environ.copy()
54 env.update(env_vars)
55 else:
56 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020057 # -nx: Do not execute commands from any .gdbinit initialization files
58 # (issue #22188)
59 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040060 if (gdb_major_version, gdb_minor_version) >= (7, 4):
61 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
62 out, err = subprocess.Popen(base_cmd + args,
63 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
64 ).communicate()
65 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
66
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000067# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010068gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040069if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000070 raise unittest.SkipTest("gdb not built with embedded python support")
71
Nick Coghlance346872013-09-22 19:38:16 +100072# Verify that "gdb" can load our custom hooks, as OS security settings may
73# disallow this without a customised .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040074cmd = ['--args', sys.executable]
75_, gdbpy_errors = run_gdb('--args', sys.executable)
76if "auto-loading has been declined" in gdbpy_errors:
77 msg = "gdb security settings prevent use of custom hooks: "
78 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100079
Victor Stinner50eb60e2010-04-20 22:32:07 +000080def gdb_has_frame_select():
81 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -040082 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
83 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +000084 if not m:
85 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -040086 gdb_frame_dir = m.group(1).split(', ')
87 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +000088
89HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000090
Martin v. Löwis5ae68102010-04-21 22:38:42 +000091BREAKPOINT_FN='builtin_id'
92
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000093class DebuggerTests(unittest.TestCase):
94
95 """Test that the debugger can debug Python."""
96
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000097 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000098 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000099 cmds_after_breakpoint=None,
100 import_site=False):
101 '''
102 Run 'python -c SOURCE' under gdb with a breakpoint.
103
104 Support injecting commands after the breakpoint is reached
105
106 Returns the stdout from gdb
107
108 cmds_after_breakpoint: if provided, a list of strings: gdb commands
109 '''
110 # We use "set breakpoint pending yes" to avoid blocking with a:
111 # Function "foo" not defined.
112 # Make breakpoint pending on future shared library load? (y or [n])
113 # error, which typically happens python is dynamically linked (the
114 # breakpoints of interest are to be found in the shared library)
115 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000116 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000117 # emitted to stderr each time, alas.
118
119 # Initially I had "--eval-command=continue" here, but removed it to
120 # avoid repeated print breakpoints when traversing hierarchical data
121 # structures
122
123 # Generate a list of commands in gdb's language:
124 commands = ['set breakpoint pending yes',
125 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200126
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200127 # The tests assume that the first frame of printed
128 # backtrace will not contain program counter,
129 # that is however not guaranteed by gdb
130 # therefore we need to use 'set print address off' to
131 # make sure the counter is not there. For example:
132 # #0 in PyObject_Print ...
133 # is assumed, but sometimes this can be e.g.
134 # #0 0x00003fffb7dd1798 in PyObject_Print ...
135 'set print address off',
136
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000137 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200138
139 # GDB as of 7.4 onwards can distinguish between the
140 # value of a variable at entry vs current value:
141 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
142 # which leads to the selftests failing with errors like this:
143 # AssertionError: 'v@entry=()' != '()'
144 # Disable this:
145 if (gdb_major_version, gdb_minor_version) >= (7, 4):
146 commands += ['set print entry-values no']
147
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000148 if cmds_after_breakpoint:
149 commands += cmds_after_breakpoint
150 else:
151 commands += ['backtrace']
152
153 # print commands
154
155 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner7869a4e2014-08-16 14:38:02 +0200156 args = ["gdb", "--batch", "-nx"]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000157 args += ['--eval-command=%s' % cmd for cmd in commands]
158 args += ["--args",
159 sys.executable]
160
161 if not import_site:
162 # -S suppresses the default 'import site'
163 args += ["-S"]
164
165 if source:
166 args += ["-c", source]
167 elif script:
168 args += [script]
169
170 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100171 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000172
173 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100174 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000175
Antoine Pitrou81641d62013-05-01 00:15:44 +0200176 errlines = err.splitlines()
177 unexpected_errlines = []
178
179 # Ignore some benign messages on stderr.
180 ignore_patterns = (
181 'Function "%s" not defined.' % breakpoint,
182 "warning: no loadable sections found in added symbol-file"
183 " system-supplied DSO",
184 "warning: Unable to find libthread_db matching"
185 " inferior's thread library, thread debugging will"
186 " not be available.",
187 "warning: Cannot initialize thread debugging"
188 " library: Debugger service failed",
189 'warning: Could not load shared library symbols for '
190 'linux-vdso.so',
191 'warning: Could not load shared library symbols for '
192 'linux-gate.so',
Serhiy Storchaka6b688d82015-02-14 22:44:35 +0200193 'warning: Could not load shared library symbols for '
194 'linux-vdso64.so',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200195 'Do you need "set solib-search-path" or '
196 '"set sysroot"?',
Victor Stinner5ac1b932013-06-25 21:54:32 +0200197 'warning: Source file is more recent than executable.',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100198 # Issue #19753: missing symbols on System Z
Victor Stinnerf4a48982013-11-24 18:55:25 +0100199 'Missing separate debuginfo for ',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100200 'Try: zypper install -C ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200201 )
202 for line in errlines:
203 if not line.startswith(ignore_patterns):
204 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000205
206 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200207 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000208 return out
209
210 def get_gdb_repr(self, source,
211 cmds_after_breakpoint=None,
212 import_site=False):
213 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000214 # run "python -c'id(DATA)'" under gdb with a breakpoint on
215 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000216 # parameter, and verify that the gdb displays the same string
217 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000218 # Verify that the gdb displays the expected string
219 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000220 # For a nested structure, the first time we hit the breakpoint will
221 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100222
223 # NOTE: avoid decoding too much of the traceback as some
224 # undecodable characters may lurk there in optimized mode
225 # (issue #19743).
226 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000227 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000228 cmds_after_breakpoint=cmds_after_breakpoint,
229 import_site=import_site)
230 # gdb can insert additional '\n' and space characters in various places
231 # in its output, depending on the width of the terminal it's connected
232 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400233 m = re.match('.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000234 gdb_output, re.DOTALL)
235 if not m:
236 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
237 return m.group(1), gdb_output
238
239 def assertEndsWith(self, actual, exp_end):
240 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000241 self.assertTrue(actual.endswith(exp_end),
242 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000243
244 def assertMultilineMatches(self, actual, pattern):
245 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000246 if not m:
247 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000248
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000249 def get_sample_script(self):
250 return findfile('gdb_sample.py')
251
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000252class PrettyPrintTests(DebuggerTests):
253 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000254 gdb_output = self.get_stack_trace('id(42)')
255 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000256
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100257 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258 # Ensure that gdb's rendering of the value in a debugged process
259 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100260 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000261 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100262 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000263 self.assertEqual(gdb_repr, exp_repr,
264 ('%r did not equal expected %r; full output was:\n%s'
265 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266
267 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300268 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100269 self.assertGdbRepr(42)
270 self.assertGdbRepr(0)
271 self.assertGdbRepr(-7)
272 self.assertGdbRepr(1000000000000)
273 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274
275 def test_singletons(self):
276 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100277 self.assertGdbRepr(True)
278 self.assertGdbRepr(False)
279 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000280
281 def test_dicts(self):
282 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100283 self.assertGdbRepr({})
284 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
285 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000286
287 def test_lists(self):
288 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100289 self.assertGdbRepr([])
290 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000291
292 def test_bytes(self):
293 'Verify the pretty-printing of bytes'
294 self.assertGdbRepr(b'')
295 self.assertGdbRepr(b'And now for something hopefully the same')
296 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
297 self.assertGdbRepr(b'this is a tab:\t'
298 b' this is a slash-N:\n'
299 b' this is a slash-R:\r'
300 )
301
302 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
303
304 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000305
306 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000307 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000308 encoding = locale.getpreferredencoding()
309 def check_repr(text):
310 try:
311 text.encode(encoding)
312 printable = True
313 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000314 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000315 else:
316 self.assertGdbRepr(text)
317
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000318 self.assertGdbRepr('')
319 self.assertGdbRepr('And now for something hopefully the same')
320 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000321
322 # Test printing a single character:
323 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000324 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000325
326 # Test printing a Japanese unicode string
327 # (I believe this reads "mojibake", using 3 characters from the CJK
328 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000329 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000330
331 # Test a character outside the BMP:
332 # U+1D121 MUSICAL SYMBOL C CLEF
333 # This is:
334 # UTF-8: 0xF0 0x9D 0x84 0xA1
335 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000336 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000337
338 def test_tuples(self):
339 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100340 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000341 self.assertGdbRepr((1,), '(1,)')
342 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000343
344 def test_sets(self):
345 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200346 if (gdb_major_version, gdb_minor_version) < (7, 3):
347 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100348 self.assertGdbRepr(set(), 'set()')
349 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
350 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000351
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000352 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000353 # which happens on deletion:
354 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100355s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000356id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000357 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000358
359 def test_frozensets(self):
360 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200361 if (gdb_major_version, gdb_minor_version) < (7, 3):
362 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100363 self.assertGdbRepr(frozenset(), 'frozenset()')
364 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
365 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000366
367 def test_exceptions(self):
368 # Test a RuntimeError
369 gdb_repr, gdb_output = self.get_gdb_repr('''
370try:
371 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000372except RuntimeError as e:
373 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000374''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000375 self.assertEqual(gdb_repr,
376 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000377
378
379 # Test division by zero:
380 gdb_repr, gdb_output = self.get_gdb_repr('''
381try:
382 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000383except ZeroDivisionError as e:
384 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000385''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000386 self.assertEqual(gdb_repr,
387 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000388
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000389 def test_modern_class(self):
390 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000391 gdb_repr, gdb_output = self.get_gdb_repr('''
392class Foo:
393 pass
394foo = Foo()
395foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000396id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100397 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000398 self.assertTrue(m,
399 msg='Unexpected new-style class rendering %r' % gdb_repr)
400
401 def test_subclassing_list(self):
402 'Verify the pretty-printing of an instance of a list subclass'
403 gdb_repr, gdb_output = self.get_gdb_repr('''
404class Foo(list):
405 pass
406foo = Foo()
407foo += [1, 2, 3]
408foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000409id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100410 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 +0000411
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000412 self.assertTrue(m,
413 msg='Unexpected new-style class rendering %r' % gdb_repr)
414
415 def test_subclassing_tuple(self):
416 'Verify the pretty-printing of an instance of a tuple subclass'
417 # This should exercise the negative tp_dictoffset code in the
418 # new-style class support
419 gdb_repr, gdb_output = self.get_gdb_repr('''
420class Foo(tuple):
421 pass
422foo = Foo((1, 2, 3))
423foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000424id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100425 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 +0000426
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000427 self.assertTrue(m,
428 msg='Unexpected new-style class rendering %r' % gdb_repr)
429
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000430 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000431 '''Run Python under gdb, corrupting variables in the inferior process
432 immediately before taking a backtrace.
433
434 Verify that the variable's representation is the expected failsafe
435 representation'''
436 if corruption:
437 cmds_after_breakpoint=[corruption, 'backtrace']
438 else:
439 cmds_after_breakpoint=['backtrace']
440
441 gdb_repr, gdb_output = \
442 self.get_gdb_repr(source,
443 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000444 if exprepr:
445 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000446 # gdb managed to print the value in spite of the corruption;
447 # this is good (see http://bugs.python.org/issue8330)
448 return
449
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000450 # Match anything for the type name; 0xDEADBEEF could point to
451 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100452 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000453
454 m = re.match(pattern, gdb_repr)
455 if not m:
456 self.fail('Unexpected gdb representation: %r\n%s' % \
457 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000458
459 def test_NULL_ptr(self):
460 'Ensure that a NULL PyObject* is handled gracefully'
461 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000462 self.get_gdb_repr('id(42)',
463 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000464 'backtrace'])
465 )
466
Ezio Melottib3aedd42010-11-20 19:04:17 +0000467 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000468
469 def test_NULL_ob_type(self):
470 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000471 self.assertSane('id(42)',
472 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000473
474 def test_corrupt_ob_type(self):
475 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000476 self.assertSane('id(42)',
477 'set v->ob_type=0xDEADBEEF',
478 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000479
480 def test_corrupt_tp_flags(self):
481 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000482 self.assertSane('id(42)',
483 'set v->ob_type->tp_flags=0x0',
484 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000485
486 def test_corrupt_tp_name(self):
487 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000488 self.assertSane('id(42)',
489 'set v->ob_type->tp_name=0xDEADBEEF',
490 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000491
492 def test_builtins_help(self):
493 'Ensure that the new-style class _Helper in site.py can be handled'
494 # (this was the issue causing tracebacks in
495 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000496 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000497
Antoine Pitrou4d098732011-11-26 01:42:03 +0100498 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000499 self.assertTrue(m,
500 msg='Unexpected rendering %r' % gdb_repr)
501
502 def test_selfreferential_list(self):
503 '''Ensure that a reference loop involving a list doesn't lead proxyval
504 into an infinite loop:'''
505 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000506 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000507 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000508
509 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000510 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000511 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000512
513 def test_selfreferential_dict(self):
514 '''Ensure that a reference loop involving a dict doesn't lead proxyval
515 into an infinite loop:'''
516 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000517 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000518
Ezio Melottib3aedd42010-11-20 19:04:17 +0000519 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520
521 def test_selfreferential_old_style_instance(self):
522 gdb_repr, gdb_output = \
523 self.get_gdb_repr('''
524class Foo:
525 pass
526foo = Foo()
527foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000528id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100529 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000530 gdb_repr),
531 'Unexpected gdb representation: %r\n%s' % \
532 (gdb_repr, gdb_output))
533
534 def test_selfreferential_new_style_instance(self):
535 gdb_repr, gdb_output = \
536 self.get_gdb_repr('''
537class Foo(object):
538 pass
539foo = Foo()
540foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000541id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100542 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000543 gdb_repr),
544 'Unexpected gdb representation: %r\n%s' % \
545 (gdb_repr, gdb_output))
546
547 gdb_repr, gdb_output = \
548 self.get_gdb_repr('''
549class Foo(object):
550 pass
551a = Foo()
552b = Foo()
553a.an_attr = b
554b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000555id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100556 self.assertTrue(re.match('<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 +0000557 gdb_repr),
558 'Unexpected gdb representation: %r\n%s' % \
559 (gdb_repr, gdb_output))
560
561 def test_truncation(self):
562 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000563 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000564 self.assertEqual(gdb_repr,
565 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
566 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
567 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
568 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
569 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
570 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
571 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
572 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
573 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
574 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
575 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
576 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
577 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
578 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
579 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
580 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
581 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
582 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
583 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
584 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
585 "224, 225, 226...(truncated)")
586 self.assertEqual(len(gdb_repr),
587 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000588
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000589 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000590 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100591 self.assertTrue(re.match('<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000592 gdb_repr),
593 'Unexpected gdb representation: %r\n%s' % \
594 (gdb_repr, gdb_output))
595
596 def test_frames(self):
597 gdb_output = self.get_stack_trace('''
598def foo(a, b, c):
599 pass
600
601foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000602id(foo.__code__)''',
603 breakpoint='builtin_id',
604 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000605 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100606 self.assertTrue(re.match('.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000607 gdb_output,
608 re.DOTALL),
609 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
610
Victor Stinnerd2084162011-12-19 13:42:24 +0100611@unittest.skipIf(python_is_optimized(),
612 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000613class PyListTests(DebuggerTests):
614 def assertListing(self, expected, actual):
615 self.assertEndsWith(actual, expected)
616
617 def test_basic_command(self):
618 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000619 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000620 cmds_after_breakpoint=['py-list'])
621
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000622 self.assertListing(' 5 \n'
623 ' 6 def bar(a, b, c):\n'
624 ' 7 baz(a, b, c)\n'
625 ' 8 \n'
626 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000627 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000628 ' 11 \n'
629 ' 12 foo(1, 2, 3)\n',
630 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000631
632 def test_one_abs_arg(self):
633 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000634 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000635 cmds_after_breakpoint=['py-list 9'])
636
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000637 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000638 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000639 ' 11 \n'
640 ' 12 foo(1, 2, 3)\n',
641 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000642
643 def test_two_abs_args(self):
644 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000645 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000646 cmds_after_breakpoint=['py-list 1,3'])
647
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000648 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
649 ' 2 \n'
650 ' 3 def foo(a, b, c):\n',
651 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000652
653class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000654 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100655 @unittest.skipIf(python_is_optimized(),
656 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000657 def test_pyup_command(self):
658 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000659 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000660 cmds_after_breakpoint=['py-up'])
661 self.assertMultilineMatches(bt,
662 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100663#[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 +0000664 baz\(a, b, c\)
665$''')
666
Victor Stinner50eb60e2010-04-20 22:32:07 +0000667 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000668 def test_down_at_bottom(self):
669 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000670 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000671 cmds_after_breakpoint=['py-down'])
672 self.assertEndsWith(bt,
673 'Unable to find a newer python frame\n')
674
Victor Stinner50eb60e2010-04-20 22:32:07 +0000675 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000676 def test_up_at_top(self):
677 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000678 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000679 cmds_after_breakpoint=['py-up'] * 4)
680 self.assertEndsWith(bt,
681 'Unable to find an older python frame\n')
682
Victor Stinner50eb60e2010-04-20 22:32:07 +0000683 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100684 @unittest.skipIf(python_is_optimized(),
685 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000686 def test_up_then_down(self):
687 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000688 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689 cmds_after_breakpoint=['py-up', 'py-down'])
690 self.assertMultilineMatches(bt,
691 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100692#[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 +0000693 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100694#[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 +0000695 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696$''')
697
698class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100699 @unittest.skipIf(python_is_optimized(),
700 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200701 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000702 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000703 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000704 cmds_after_breakpoint=['py-bt'])
705 self.assertMultilineMatches(bt,
706 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200707Traceback \(most recent call first\):
708 File ".*gdb_sample.py", line 10, in baz
709 id\(42\)
710 File ".*gdb_sample.py", line 7, in bar
711 baz\(a, b, c\)
712 File ".*gdb_sample.py", line 4, in foo
713 bar\(a, b, c\)
714 File ".*gdb_sample.py", line 12, in <module>
715 foo\(1, 2, 3\)
716''')
717
Victor Stinnerd2084162011-12-19 13:42:24 +0100718 @unittest.skipIf(python_is_optimized(),
719 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200720 def test_bt_full(self):
721 'Verify that the "py-bt-full" command works'
722 bt = self.get_stack_trace(script=self.get_sample_script(),
723 cmds_after_breakpoint=['py-bt-full'])
724 self.assertMultilineMatches(bt,
725 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100726#[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 +0000727 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100728#[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 +0000729 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100730#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100731 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000732''')
733
David Malcolm8d37ffa2012-06-27 14:15:34 -0400734 @unittest.skipUnless(_thread,
735 "Python was compiled without thread support")
736 def test_threads(self):
737 'Verify that "py-bt" indicates threads that are waiting for the GIL'
738 cmd = '''
739from threading import Thread
740
741class TestThread(Thread):
742 # These threads would run forever, but we'll interrupt things with the
743 # debugger
744 def run(self):
745 i = 0
746 while 1:
747 i += 1
748
749t = {}
750for i in range(4):
751 t[i] = TestThread()
752 t[i].start()
753
754# Trigger a breakpoint on the main thread
755id(42)
756
757'''
758 # Verify with "py-bt":
759 gdb_output = self.get_stack_trace(cmd,
760 cmds_after_breakpoint=['thread apply all py-bt'])
761 self.assertIn('Waiting for the GIL', gdb_output)
762
763 # Verify with "py-bt-full":
764 gdb_output = self.get_stack_trace(cmd,
765 cmds_after_breakpoint=['thread apply all py-bt-full'])
766 self.assertIn('Waiting for the GIL', gdb_output)
767
768 @unittest.skipIf(python_is_optimized(),
769 "Python was compiled with optimizations")
770 # Some older versions of gdb will fail with
771 # "Cannot find new threads: generic error"
772 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
773 @unittest.skipUnless(_thread,
774 "Python was compiled without thread support")
775 def test_gc(self):
776 'Verify that "py-bt" indicates if a thread is garbage-collecting'
777 cmd = ('from gc import collect\n'
778 'id(42)\n'
779 'def foo():\n'
780 ' collect()\n'
781 'def bar():\n'
782 ' foo()\n'
783 'bar()\n')
784 # Verify with "py-bt":
785 gdb_output = self.get_stack_trace(cmd,
786 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
787 )
788 self.assertIn('Garbage-collecting', gdb_output)
789
790 # Verify with "py-bt-full":
791 gdb_output = self.get_stack_trace(cmd,
792 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
793 )
794 self.assertIn('Garbage-collecting', gdb_output)
795
796 @unittest.skipIf(python_is_optimized(),
797 "Python was compiled with optimizations")
798 # Some older versions of gdb will fail with
799 # "Cannot find new threads: generic error"
800 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
801 @unittest.skipUnless(_thread,
802 "Python was compiled without thread support")
803 def test_pycfunction(self):
804 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100805 # Tested function must not be defined with METH_NOARGS or METH_O,
806 # otherwise call_function() doesn't call PyCFunction_Call()
807 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400808 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100809 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400810 'def bar():\n'
811 ' foo()\n'
812 'bar()\n')
813 # Verify with "py-bt":
814 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100815 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400816 cmds_after_breakpoint=['bt', 'py-bt'],
817 )
Victor Stinner79644f92015-03-27 15:42:37 +0100818 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400819
820 # Verify with "py-bt-full":
821 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100822 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400823 cmds_after_breakpoint=['py-bt-full'],
824 )
Victor Stinner79644f92015-03-27 15:42:37 +0100825 self.assertIn('#0 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400826
827
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000828class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100829 @unittest.skipIf(python_is_optimized(),
830 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000831 def test_basic_command(self):
832 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000833 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000834 cmds_after_breakpoint=['py-print args'])
835 self.assertMultilineMatches(bt,
836 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
837
Vinay Sajip2549f872012-01-04 12:07:30 +0000838 @unittest.skipIf(python_is_optimized(),
839 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000840 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000841 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000842 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000843 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
844 self.assertMultilineMatches(bt,
845 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
846
Victor Stinnerd2084162011-12-19 13:42:24 +0100847 @unittest.skipIf(python_is_optimized(),
848 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000849 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000850 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000851 cmds_after_breakpoint=['py-print __name__'])
852 self.assertMultilineMatches(bt,
853 r".*\nglobal '__name__' = '__main__'\n.*")
854
Victor Stinnerd2084162011-12-19 13:42:24 +0100855 @unittest.skipIf(python_is_optimized(),
856 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000857 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000858 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000859 cmds_after_breakpoint=['py-print len'])
860 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100861 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000862
863class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100864 @unittest.skipIf(python_is_optimized(),
865 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000866 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000867 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000868 cmds_after_breakpoint=['py-locals'])
869 self.assertMultilineMatches(bt,
870 r".*\nargs = \(1, 2, 3\)\n.*")
871
Victor Stinner50eb60e2010-04-20 22:32:07 +0000872 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000873 @unittest.skipIf(python_is_optimized(),
874 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000875 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000876 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000877 cmds_after_breakpoint=['py-up', 'py-locals'])
878 self.assertMultilineMatches(bt,
879 r".*\na = 1\nb = 2\nc = 3\n.*")
880
881def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200882 if support.verbose:
883 print("GDB version:")
884 for line in os.fsdecode(gdb_version).splitlines():
885 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000886 run_unittest(PrettyPrintTests,
887 PyListTests,
888 StackNavigationTests,
889 PyBtTests,
890 PyPrintTests,
891 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000892 )
893
894if __name__ == "__main__":
895 test_main()