blob: aaa5c69d49caaa84a312090a608c0719a52ca0ae [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',
193 'Do you need "set solib-search-path" or '
194 '"set sysroot"?',
Victor Stinner5ac1b932013-06-25 21:54:32 +0200195 'warning: Source file is more recent than executable.',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100196 # Issue #19753: missing symbols on System Z
Victor Stinnerf4a48982013-11-24 18:55:25 +0100197 'Missing separate debuginfo for ',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100198 'Try: zypper install -C ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200199 )
200 for line in errlines:
201 if not line.startswith(ignore_patterns):
202 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203
204 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200205 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000206 return out
207
208 def get_gdb_repr(self, source,
209 cmds_after_breakpoint=None,
210 import_site=False):
211 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000212 # run "python -c'id(DATA)'" under gdb with a breakpoint on
213 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000214 # parameter, and verify that the gdb displays the same string
215 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000216 # Verify that the gdb displays the expected string
217 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000218 # For a nested structure, the first time we hit the breakpoint will
219 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100220
221 # NOTE: avoid decoding too much of the traceback as some
222 # undecodable characters may lurk there in optimized mode
223 # (issue #19743).
224 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000225 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000226 cmds_after_breakpoint=cmds_after_breakpoint,
227 import_site=import_site)
228 # gdb can insert additional '\n' and space characters in various places
229 # in its output, depending on the width of the terminal it's connected
230 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400231 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 +0000232 gdb_output, re.DOTALL)
233 if not m:
234 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
235 return m.group(1), gdb_output
236
237 def assertEndsWith(self, actual, exp_end):
238 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000239 self.assertTrue(actual.endswith(exp_end),
240 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000241
242 def assertMultilineMatches(self, actual, pattern):
243 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000244 if not m:
245 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000246
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000247 def get_sample_script(self):
248 return findfile('gdb_sample.py')
249
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000250class PrettyPrintTests(DebuggerTests):
251 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000252 gdb_output = self.get_stack_trace('id(42)')
253 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000254
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100255 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000256 # Ensure that gdb's rendering of the value in a debugged process
257 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100258 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000259 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100260 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000261 self.assertEqual(gdb_repr, exp_repr,
262 ('%r did not equal expected %r; full output was:\n%s'
263 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000264
265 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300266 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100267 self.assertGdbRepr(42)
268 self.assertGdbRepr(0)
269 self.assertGdbRepr(-7)
270 self.assertGdbRepr(1000000000000)
271 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000272
273 def test_singletons(self):
274 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100275 self.assertGdbRepr(True)
276 self.assertGdbRepr(False)
277 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000278
279 def test_dicts(self):
280 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100281 self.assertGdbRepr({})
282 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
283 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000284
285 def test_lists(self):
286 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100287 self.assertGdbRepr([])
288 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000289
290 def test_bytes(self):
291 'Verify the pretty-printing of bytes'
292 self.assertGdbRepr(b'')
293 self.assertGdbRepr(b'And now for something hopefully the same')
294 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
295 self.assertGdbRepr(b'this is a tab:\t'
296 b' this is a slash-N:\n'
297 b' this is a slash-R:\r'
298 )
299
300 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
301
302 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000303
304 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000305 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000306 encoding = locale.getpreferredencoding()
307 def check_repr(text):
308 try:
309 text.encode(encoding)
310 printable = True
311 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000312 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000313 else:
314 self.assertGdbRepr(text)
315
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000316 self.assertGdbRepr('')
317 self.assertGdbRepr('And now for something hopefully the same')
318 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000319
320 # Test printing a single character:
321 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000322 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000323
324 # Test printing a Japanese unicode string
325 # (I believe this reads "mojibake", using 3 characters from the CJK
326 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000327 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000328
329 # Test a character outside the BMP:
330 # U+1D121 MUSICAL SYMBOL C CLEF
331 # This is:
332 # UTF-8: 0xF0 0x9D 0x84 0xA1
333 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000334 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000335
336 def test_tuples(self):
337 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100338 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000339 self.assertGdbRepr((1,), '(1,)')
340 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000341
342 def test_sets(self):
343 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200344 if (gdb_major_version, gdb_minor_version) < (7, 3):
345 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100346 self.assertGdbRepr(set(), 'set()')
347 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
348 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000349
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000350 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000351 # which happens on deletion:
352 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100353s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000354id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000355 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000356
357 def test_frozensets(self):
358 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200359 if (gdb_major_version, gdb_minor_version) < (7, 3):
360 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100361 self.assertGdbRepr(frozenset(), 'frozenset()')
362 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
363 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000364
365 def test_exceptions(self):
366 # Test a RuntimeError
367 gdb_repr, gdb_output = self.get_gdb_repr('''
368try:
369 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000370except RuntimeError as e:
371 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000372''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000373 self.assertEqual(gdb_repr,
374 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000375
376
377 # Test division by zero:
378 gdb_repr, gdb_output = self.get_gdb_repr('''
379try:
380 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000381except ZeroDivisionError as e:
382 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000383''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000384 self.assertEqual(gdb_repr,
385 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000386
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000387 def test_modern_class(self):
388 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000389 gdb_repr, gdb_output = self.get_gdb_repr('''
390class Foo:
391 pass
392foo = Foo()
393foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000394id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100395 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000396 self.assertTrue(m,
397 msg='Unexpected new-style class rendering %r' % gdb_repr)
398
399 def test_subclassing_list(self):
400 'Verify the pretty-printing of an instance of a list subclass'
401 gdb_repr, gdb_output = self.get_gdb_repr('''
402class Foo(list):
403 pass
404foo = Foo()
405foo += [1, 2, 3]
406foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100408 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 +0000409
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410 self.assertTrue(m,
411 msg='Unexpected new-style class rendering %r' % gdb_repr)
412
413 def test_subclassing_tuple(self):
414 'Verify the pretty-printing of an instance of a tuple subclass'
415 # This should exercise the negative tp_dictoffset code in the
416 # new-style class support
417 gdb_repr, gdb_output = self.get_gdb_repr('''
418class Foo(tuple):
419 pass
420foo = Foo((1, 2, 3))
421foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000422id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100423 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 +0000424
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000425 self.assertTrue(m,
426 msg='Unexpected new-style class rendering %r' % gdb_repr)
427
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000428 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000429 '''Run Python under gdb, corrupting variables in the inferior process
430 immediately before taking a backtrace.
431
432 Verify that the variable's representation is the expected failsafe
433 representation'''
434 if corruption:
435 cmds_after_breakpoint=[corruption, 'backtrace']
436 else:
437 cmds_after_breakpoint=['backtrace']
438
439 gdb_repr, gdb_output = \
440 self.get_gdb_repr(source,
441 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000442 if exprepr:
443 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000444 # gdb managed to print the value in spite of the corruption;
445 # this is good (see http://bugs.python.org/issue8330)
446 return
447
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000448 # Match anything for the type name; 0xDEADBEEF could point to
449 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100450 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000451
452 m = re.match(pattern, gdb_repr)
453 if not m:
454 self.fail('Unexpected gdb representation: %r\n%s' % \
455 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000456
457 def test_NULL_ptr(self):
458 'Ensure that a NULL PyObject* is handled gracefully'
459 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000460 self.get_gdb_repr('id(42)',
461 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000462 'backtrace'])
463 )
464
Ezio Melottib3aedd42010-11-20 19:04:17 +0000465 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000466
467 def test_NULL_ob_type(self):
468 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000469 self.assertSane('id(42)',
470 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000471
472 def test_corrupt_ob_type(self):
473 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000474 self.assertSane('id(42)',
475 'set v->ob_type=0xDEADBEEF',
476 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000477
478 def test_corrupt_tp_flags(self):
479 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000480 self.assertSane('id(42)',
481 'set v->ob_type->tp_flags=0x0',
482 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000483
484 def test_corrupt_tp_name(self):
485 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000486 self.assertSane('id(42)',
487 'set v->ob_type->tp_name=0xDEADBEEF',
488 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000489
490 def test_builtins_help(self):
491 'Ensure that the new-style class _Helper in site.py can be handled'
492 # (this was the issue causing tracebacks in
493 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000494 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000495
Antoine Pitrou4d098732011-11-26 01:42:03 +0100496 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000497 self.assertTrue(m,
498 msg='Unexpected rendering %r' % gdb_repr)
499
500 def test_selfreferential_list(self):
501 '''Ensure that a reference loop involving a list doesn't lead proxyval
502 into an infinite loop:'''
503 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000505 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000506
507 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000508 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000509 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000510
511 def test_selfreferential_dict(self):
512 '''Ensure that a reference loop involving a dict doesn't lead proxyval
513 into an infinite loop:'''
514 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000515 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000516
Ezio Melottib3aedd42010-11-20 19:04:17 +0000517 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000518
519 def test_selfreferential_old_style_instance(self):
520 gdb_repr, gdb_output = \
521 self.get_gdb_repr('''
522class Foo:
523 pass
524foo = Foo()
525foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000526id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100527 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000528 gdb_repr),
529 'Unexpected gdb representation: %r\n%s' % \
530 (gdb_repr, gdb_output))
531
532 def test_selfreferential_new_style_instance(self):
533 gdb_repr, gdb_output = \
534 self.get_gdb_repr('''
535class Foo(object):
536 pass
537foo = Foo()
538foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000539id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100540 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000541 gdb_repr),
542 'Unexpected gdb representation: %r\n%s' % \
543 (gdb_repr, gdb_output))
544
545 gdb_repr, gdb_output = \
546 self.get_gdb_repr('''
547class Foo(object):
548 pass
549a = Foo()
550b = Foo()
551a.an_attr = b
552b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000553id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100554 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 +0000555 gdb_repr),
556 'Unexpected gdb representation: %r\n%s' % \
557 (gdb_repr, gdb_output))
558
559 def test_truncation(self):
560 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000561 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000562 self.assertEqual(gdb_repr,
563 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
564 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
565 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
566 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
567 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
568 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
569 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
570 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
571 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
572 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
573 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
574 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
575 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
576 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
577 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
578 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
579 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
580 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
581 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
582 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
583 "224, 225, 226...(truncated)")
584 self.assertEqual(len(gdb_repr),
585 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000586
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000587 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000588 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100589 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 +0000590 gdb_repr),
591 'Unexpected gdb representation: %r\n%s' % \
592 (gdb_repr, gdb_output))
593
594 def test_frames(self):
595 gdb_output = self.get_stack_trace('''
596def foo(a, b, c):
597 pass
598
599foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000600id(foo.__code__)''',
601 breakpoint='builtin_id',
602 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000603 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100604 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 +0000605 gdb_output,
606 re.DOTALL),
607 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
608
Victor Stinnerd2084162011-12-19 13:42:24 +0100609@unittest.skipIf(python_is_optimized(),
610 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000611class PyListTests(DebuggerTests):
612 def assertListing(self, expected, actual):
613 self.assertEndsWith(actual, expected)
614
615 def test_basic_command(self):
616 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000617 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000618 cmds_after_breakpoint=['py-list'])
619
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000620 self.assertListing(' 5 \n'
621 ' 6 def bar(a, b, c):\n'
622 ' 7 baz(a, b, c)\n'
623 ' 8 \n'
624 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000625 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000626 ' 11 \n'
627 ' 12 foo(1, 2, 3)\n',
628 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000629
630 def test_one_abs_arg(self):
631 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000632 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000633 cmds_after_breakpoint=['py-list 9'])
634
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000635 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000636 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000637 ' 11 \n'
638 ' 12 foo(1, 2, 3)\n',
639 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000640
641 def test_two_abs_args(self):
642 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000643 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000644 cmds_after_breakpoint=['py-list 1,3'])
645
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000646 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
647 ' 2 \n'
648 ' 3 def foo(a, b, c):\n',
649 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000650
651class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000652 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100653 @unittest.skipIf(python_is_optimized(),
654 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000655 def test_pyup_command(self):
656 'Verify that the "py-up" command works'
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-up'])
659 self.assertMultilineMatches(bt,
660 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100661#[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 +0000662 baz\(a, b, c\)
663$''')
664
Victor Stinner50eb60e2010-04-20 22:32:07 +0000665 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000666 def test_down_at_bottom(self):
667 'Verify handling of "py-down" at the bottom of the stack'
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-down'])
670 self.assertEndsWith(bt,
671 'Unable to find a newer python frame\n')
672
Victor Stinner50eb60e2010-04-20 22:32:07 +0000673 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000674 def test_up_at_top(self):
675 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000676 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000677 cmds_after_breakpoint=['py-up'] * 4)
678 self.assertEndsWith(bt,
679 'Unable to find an older python frame\n')
680
Victor Stinner50eb60e2010-04-20 22:32:07 +0000681 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100682 @unittest.skipIf(python_is_optimized(),
683 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000684 def test_up_then_down(self):
685 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000686 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000687 cmds_after_breakpoint=['py-up', 'py-down'])
688 self.assertMultilineMatches(bt,
689 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100690#[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 +0000691 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100692#[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 +0000693 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000694$''')
695
696class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100697 @unittest.skipIf(python_is_optimized(),
698 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200699 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000700 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000701 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000702 cmds_after_breakpoint=['py-bt'])
703 self.assertMultilineMatches(bt,
704 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200705Traceback \(most recent call first\):
706 File ".*gdb_sample.py", line 10, in baz
707 id\(42\)
708 File ".*gdb_sample.py", line 7, in bar
709 baz\(a, b, c\)
710 File ".*gdb_sample.py", line 4, in foo
711 bar\(a, b, c\)
712 File ".*gdb_sample.py", line 12, in <module>
713 foo\(1, 2, 3\)
714''')
715
Victor Stinnerd2084162011-12-19 13:42:24 +0100716 @unittest.skipIf(python_is_optimized(),
717 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200718 def test_bt_full(self):
719 'Verify that the "py-bt-full" command works'
720 bt = self.get_stack_trace(script=self.get_sample_script(),
721 cmds_after_breakpoint=['py-bt-full'])
722 self.assertMultilineMatches(bt,
723 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100724#[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 +0000725 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100726#[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 +0000727 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100728#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100729 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000730''')
731
David Malcolm8d37ffa2012-06-27 14:15:34 -0400732 @unittest.skipUnless(_thread,
733 "Python was compiled without thread support")
734 def test_threads(self):
735 'Verify that "py-bt" indicates threads that are waiting for the GIL'
736 cmd = '''
737from threading import Thread
738
739class TestThread(Thread):
740 # These threads would run forever, but we'll interrupt things with the
741 # debugger
742 def run(self):
743 i = 0
744 while 1:
745 i += 1
746
747t = {}
748for i in range(4):
749 t[i] = TestThread()
750 t[i].start()
751
752# Trigger a breakpoint on the main thread
753id(42)
754
755'''
756 # Verify with "py-bt":
757 gdb_output = self.get_stack_trace(cmd,
758 cmds_after_breakpoint=['thread apply all py-bt'])
759 self.assertIn('Waiting for the GIL', gdb_output)
760
761 # Verify with "py-bt-full":
762 gdb_output = self.get_stack_trace(cmd,
763 cmds_after_breakpoint=['thread apply all py-bt-full'])
764 self.assertIn('Waiting for the GIL', gdb_output)
765
766 @unittest.skipIf(python_is_optimized(),
767 "Python was compiled with optimizations")
768 # Some older versions of gdb will fail with
769 # "Cannot find new threads: generic error"
770 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
771 @unittest.skipUnless(_thread,
772 "Python was compiled without thread support")
773 def test_gc(self):
774 'Verify that "py-bt" indicates if a thread is garbage-collecting'
775 cmd = ('from gc import collect\n'
776 'id(42)\n'
777 'def foo():\n'
778 ' collect()\n'
779 'def bar():\n'
780 ' foo()\n'
781 'bar()\n')
782 # Verify with "py-bt":
783 gdb_output = self.get_stack_trace(cmd,
784 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
785 )
786 self.assertIn('Garbage-collecting', gdb_output)
787
788 # Verify with "py-bt-full":
789 gdb_output = self.get_stack_trace(cmd,
790 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
791 )
792 self.assertIn('Garbage-collecting', gdb_output)
793
794 @unittest.skipIf(python_is_optimized(),
795 "Python was compiled with optimizations")
796 # Some older versions of gdb will fail with
797 # "Cannot find new threads: generic error"
798 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
799 @unittest.skipUnless(_thread,
800 "Python was compiled without thread support")
801 def test_pycfunction(self):
802 'Verify that "py-bt" displays invocations of PyCFunction instances'
803 cmd = ('from time import sleep\n'
804 'def foo():\n'
805 ' sleep(1)\n'
806 'def bar():\n'
807 ' foo()\n'
808 'bar()\n')
809 # Verify with "py-bt":
810 gdb_output = self.get_stack_trace(cmd,
811 breakpoint='time_sleep',
812 cmds_after_breakpoint=['bt', 'py-bt'],
813 )
814 self.assertIn('<built-in method sleep', gdb_output)
815
816 # Verify with "py-bt-full":
817 gdb_output = self.get_stack_trace(cmd,
818 breakpoint='time_sleep',
819 cmds_after_breakpoint=['py-bt-full'],
820 )
821 self.assertIn('#0 <built-in method sleep', gdb_output)
822
823
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000824class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100825 @unittest.skipIf(python_is_optimized(),
826 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000827 def test_basic_command(self):
828 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000829 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000830 cmds_after_breakpoint=['py-print args'])
831 self.assertMultilineMatches(bt,
832 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
833
Vinay Sajip2549f872012-01-04 12:07:30 +0000834 @unittest.skipIf(python_is_optimized(),
835 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000836 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000837 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000838 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000839 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
840 self.assertMultilineMatches(bt,
841 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
842
Victor Stinnerd2084162011-12-19 13:42:24 +0100843 @unittest.skipIf(python_is_optimized(),
844 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000845 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000846 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000847 cmds_after_breakpoint=['py-print __name__'])
848 self.assertMultilineMatches(bt,
849 r".*\nglobal '__name__' = '__main__'\n.*")
850
Victor Stinnerd2084162011-12-19 13:42:24 +0100851 @unittest.skipIf(python_is_optimized(),
852 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000853 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000854 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000855 cmds_after_breakpoint=['py-print len'])
856 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100857 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000858
859class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100860 @unittest.skipIf(python_is_optimized(),
861 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000862 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000863 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000864 cmds_after_breakpoint=['py-locals'])
865 self.assertMultilineMatches(bt,
866 r".*\nargs = \(1, 2, 3\)\n.*")
867
Victor Stinner50eb60e2010-04-20 22:32:07 +0000868 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000869 @unittest.skipIf(python_is_optimized(),
870 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000871 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000872 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000873 cmds_after_breakpoint=['py-up', 'py-locals'])
874 self.assertMultilineMatches(bt,
875 r".*\na = 1\nb = 2\nc = 3\n.*")
876
877def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200878 if support.verbose:
879 print("GDB version:")
880 for line in os.fsdecode(gdb_version).splitlines():
881 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000882 run_unittest(PrettyPrintTests,
883 PyListTests,
884 StackNavigationTests,
885 PyBtTests,
886 PyPrintTests,
887 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000888 )
889
890if __name__ == "__main__":
891 test_main()