blob: 4fba3c33b94accf01a9390bf1db43c80fabe2841 [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,
126 'run']
127 if cmds_after_breakpoint:
128 commands += cmds_after_breakpoint
129 else:
130 commands += ['backtrace']
131
132 # print commands
133
134 # Use "commands" to generate the arguments with which to invoke "gdb":
Victor Stinner7869a4e2014-08-16 14:38:02 +0200135 args = ["gdb", "--batch", "-nx"]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000136 args += ['--eval-command=%s' % cmd for cmd in commands]
137 args += ["--args",
138 sys.executable]
139
140 if not import_site:
141 # -S suppresses the default 'import site'
142 args += ["-S"]
143
144 if source:
145 args += ["-c", source]
146 elif script:
147 args += [script]
148
149 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100150 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000151
152 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100153 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000154
Antoine Pitrou81641d62013-05-01 00:15:44 +0200155 errlines = err.splitlines()
156 unexpected_errlines = []
157
158 # Ignore some benign messages on stderr.
159 ignore_patterns = (
160 'Function "%s" not defined.' % breakpoint,
161 "warning: no loadable sections found in added symbol-file"
162 " system-supplied DSO",
163 "warning: Unable to find libthread_db matching"
164 " inferior's thread library, thread debugging will"
165 " not be available.",
166 "warning: Cannot initialize thread debugging"
167 " library: Debugger service failed",
168 'warning: Could not load shared library symbols for '
169 'linux-vdso.so',
170 'warning: Could not load shared library symbols for '
171 'linux-gate.so',
172 'Do you need "set solib-search-path" or '
173 '"set sysroot"?',
Victor Stinner5ac1b932013-06-25 21:54:32 +0200174 'warning: Source file is more recent than executable.',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100175 # Issue #19753: missing symbols on System Z
Victor Stinnerf4a48982013-11-24 18:55:25 +0100176 'Missing separate debuginfo for ',
Victor Stinner23ed7e32013-11-25 10:43:59 +0100177 'Try: zypper install -C ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200178 )
179 for line in errlines:
180 if not line.startswith(ignore_patterns):
181 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000182
183 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200184 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000185 return out
186
187 def get_gdb_repr(self, source,
188 cmds_after_breakpoint=None,
189 import_site=False):
190 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000191 # run "python -c'id(DATA)'" under gdb with a breakpoint on
192 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000193 # parameter, and verify that the gdb displays the same string
194 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000195 # Verify that the gdb displays the expected string
196 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000197 # For a nested structure, the first time we hit the breakpoint will
198 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100199
200 # NOTE: avoid decoding too much of the traceback as some
201 # undecodable characters may lurk there in optimized mode
202 # (issue #19743).
203 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000204 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000205 cmds_after_breakpoint=cmds_after_breakpoint,
206 import_site=import_site)
207 # gdb can insert additional '\n' and space characters in various places
208 # in its output, depending on the width of the terminal it's connected
209 # to (using its "wrap_here" function)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400210 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 +0000211 gdb_output, re.DOTALL)
212 if not m:
213 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
214 return m.group(1), gdb_output
215
216 def assertEndsWith(self, actual, exp_end):
217 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000218 self.assertTrue(actual.endswith(exp_end),
219 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000220
221 def assertMultilineMatches(self, actual, pattern):
222 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000223 if not m:
224 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000225
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000226 def get_sample_script(self):
227 return findfile('gdb_sample.py')
228
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000229class PrettyPrintTests(DebuggerTests):
230 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000231 gdb_output = self.get_stack_trace('id(42)')
232 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000233
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100234 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000235 # Ensure that gdb's rendering of the value in a debugged process
236 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100237 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000238 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100239 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000240 self.assertEqual(gdb_repr, exp_repr,
241 ('%r did not equal expected %r; full output was:\n%s'
242 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000243
244 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300245 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100246 self.assertGdbRepr(42)
247 self.assertGdbRepr(0)
248 self.assertGdbRepr(-7)
249 self.assertGdbRepr(1000000000000)
250 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000251
252 def test_singletons(self):
253 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100254 self.assertGdbRepr(True)
255 self.assertGdbRepr(False)
256 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000257
258 def test_dicts(self):
259 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100260 self.assertGdbRepr({})
261 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
262 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000263
264 def test_lists(self):
265 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100266 self.assertGdbRepr([])
267 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000268
269 def test_bytes(self):
270 'Verify the pretty-printing of bytes'
271 self.assertGdbRepr(b'')
272 self.assertGdbRepr(b'And now for something hopefully the same')
273 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
274 self.assertGdbRepr(b'this is a tab:\t'
275 b' this is a slash-N:\n'
276 b' this is a slash-R:\r'
277 )
278
279 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
280
281 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000282
283 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000284 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000285 encoding = locale.getpreferredencoding()
286 def check_repr(text):
287 try:
288 text.encode(encoding)
289 printable = True
290 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000291 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000292 else:
293 self.assertGdbRepr(text)
294
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000295 self.assertGdbRepr('')
296 self.assertGdbRepr('And now for something hopefully the same')
297 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000298
299 # Test printing a single character:
300 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000301 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000302
303 # Test printing a Japanese unicode string
304 # (I believe this reads "mojibake", using 3 characters from the CJK
305 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000306 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000307
308 # Test a character outside the BMP:
309 # U+1D121 MUSICAL SYMBOL C CLEF
310 # This is:
311 # UTF-8: 0xF0 0x9D 0x84 0xA1
312 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000313 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000314
315 def test_tuples(self):
316 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100317 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000318 self.assertGdbRepr((1,), '(1,)')
319 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000320
321 def test_sets(self):
322 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200323 if (gdb_major_version, gdb_minor_version) < (7, 3):
324 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100325 self.assertGdbRepr(set(), 'set()')
326 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
327 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000328
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000329 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000330 # which happens on deletion:
331 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100332s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000333id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000334 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000335
336 def test_frozensets(self):
337 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200338 if (gdb_major_version, gdb_minor_version) < (7, 3):
339 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinnera2828252013-11-21 10:25:09 +0100340 self.assertGdbRepr(frozenset(), 'frozenset()')
341 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
342 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000343
344 def test_exceptions(self):
345 # Test a RuntimeError
346 gdb_repr, gdb_output = self.get_gdb_repr('''
347try:
348 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000349except RuntimeError as e:
350 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000351''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000352 self.assertEqual(gdb_repr,
353 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000354
355
356 # Test division by zero:
357 gdb_repr, gdb_output = self.get_gdb_repr('''
358try:
359 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000360except ZeroDivisionError as e:
361 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000362''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000363 self.assertEqual(gdb_repr,
364 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000365
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000366 def test_modern_class(self):
367 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000368 gdb_repr, gdb_output = self.get_gdb_repr('''
369class Foo:
370 pass
371foo = Foo()
372foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000373id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100374 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000375 self.assertTrue(m,
376 msg='Unexpected new-style class rendering %r' % gdb_repr)
377
378 def test_subclassing_list(self):
379 'Verify the pretty-printing of an instance of a list subclass'
380 gdb_repr, gdb_output = self.get_gdb_repr('''
381class Foo(list):
382 pass
383foo = Foo()
384foo += [1, 2, 3]
385foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000386id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100387 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 +0000388
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000389 self.assertTrue(m,
390 msg='Unexpected new-style class rendering %r' % gdb_repr)
391
392 def test_subclassing_tuple(self):
393 'Verify the pretty-printing of an instance of a tuple subclass'
394 # This should exercise the negative tp_dictoffset code in the
395 # new-style class support
396 gdb_repr, gdb_output = self.get_gdb_repr('''
397class Foo(tuple):
398 pass
399foo = Foo((1, 2, 3))
400foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000401id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100402 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 +0000403
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404 self.assertTrue(m,
405 msg='Unexpected new-style class rendering %r' % gdb_repr)
406
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000408 '''Run Python under gdb, corrupting variables in the inferior process
409 immediately before taking a backtrace.
410
411 Verify that the variable's representation is the expected failsafe
412 representation'''
413 if corruption:
414 cmds_after_breakpoint=[corruption, 'backtrace']
415 else:
416 cmds_after_breakpoint=['backtrace']
417
418 gdb_repr, gdb_output = \
419 self.get_gdb_repr(source,
420 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000421 if exprepr:
422 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000423 # gdb managed to print the value in spite of the corruption;
424 # this is good (see http://bugs.python.org/issue8330)
425 return
426
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000427 # Match anything for the type name; 0xDEADBEEF could point to
428 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100429 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000430
431 m = re.match(pattern, gdb_repr)
432 if not m:
433 self.fail('Unexpected gdb representation: %r\n%s' % \
434 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000435
436 def test_NULL_ptr(self):
437 'Ensure that a NULL PyObject* is handled gracefully'
438 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000439 self.get_gdb_repr('id(42)',
440 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000441 'backtrace'])
442 )
443
Ezio Melottib3aedd42010-11-20 19:04:17 +0000444 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000445
446 def test_NULL_ob_type(self):
447 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000448 self.assertSane('id(42)',
449 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000450
451 def test_corrupt_ob_type(self):
452 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000453 self.assertSane('id(42)',
454 'set v->ob_type=0xDEADBEEF',
455 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000456
457 def test_corrupt_tp_flags(self):
458 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000459 self.assertSane('id(42)',
460 'set v->ob_type->tp_flags=0x0',
461 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000462
463 def test_corrupt_tp_name(self):
464 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000465 self.assertSane('id(42)',
466 'set v->ob_type->tp_name=0xDEADBEEF',
467 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000468
469 def test_builtins_help(self):
470 'Ensure that the new-style class _Helper in site.py can be handled'
471 # (this was the issue causing tracebacks in
472 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000473 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000474
Antoine Pitrou4d098732011-11-26 01:42:03 +0100475 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000476 self.assertTrue(m,
477 msg='Unexpected rendering %r' % gdb_repr)
478
479 def test_selfreferential_list(self):
480 '''Ensure that a reference loop involving a list doesn't lead proxyval
481 into an infinite loop:'''
482 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000483 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000484 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000485
486 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000487 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000488 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000489
490 def test_selfreferential_dict(self):
491 '''Ensure that a reference loop involving a dict doesn't lead proxyval
492 into an infinite loop:'''
493 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000494 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000495
Ezio Melottib3aedd42010-11-20 19:04:17 +0000496 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000497
498 def test_selfreferential_old_style_instance(self):
499 gdb_repr, gdb_output = \
500 self.get_gdb_repr('''
501class Foo:
502 pass
503foo = Foo()
504foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000505id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100506 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000507 gdb_repr),
508 'Unexpected gdb representation: %r\n%s' % \
509 (gdb_repr, gdb_output))
510
511 def test_selfreferential_new_style_instance(self):
512 gdb_repr, gdb_output = \
513 self.get_gdb_repr('''
514class Foo(object):
515 pass
516foo = Foo()
517foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000518id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100519 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520 gdb_repr),
521 'Unexpected gdb representation: %r\n%s' % \
522 (gdb_repr, gdb_output))
523
524 gdb_repr, gdb_output = \
525 self.get_gdb_repr('''
526class Foo(object):
527 pass
528a = Foo()
529b = Foo()
530a.an_attr = b
531b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000532id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100533 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 +0000534 gdb_repr),
535 'Unexpected gdb representation: %r\n%s' % \
536 (gdb_repr, gdb_output))
537
538 def test_truncation(self):
539 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000540 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000541 self.assertEqual(gdb_repr,
542 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
543 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
544 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
545 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
546 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
547 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
548 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
549 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
550 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
551 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
552 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
553 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
554 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
555 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
556 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
557 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
558 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
559 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
560 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
561 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
562 "224, 225, 226...(truncated)")
563 self.assertEqual(len(gdb_repr),
564 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000565
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000566 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000567 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100568 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 +0000569 gdb_repr),
570 'Unexpected gdb representation: %r\n%s' % \
571 (gdb_repr, gdb_output))
572
573 def test_frames(self):
574 gdb_output = self.get_stack_trace('''
575def foo(a, b, c):
576 pass
577
578foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000579id(foo.__code__)''',
580 breakpoint='builtin_id',
581 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000582 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100583 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 +0000584 gdb_output,
585 re.DOTALL),
586 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
587
Victor Stinnerd2084162011-12-19 13:42:24 +0100588@unittest.skipIf(python_is_optimized(),
589 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000590class PyListTests(DebuggerTests):
591 def assertListing(self, expected, actual):
592 self.assertEndsWith(actual, expected)
593
594 def test_basic_command(self):
595 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000596 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000597 cmds_after_breakpoint=['py-list'])
598
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000599 self.assertListing(' 5 \n'
600 ' 6 def bar(a, b, c):\n'
601 ' 7 baz(a, b, c)\n'
602 ' 8 \n'
603 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000604 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000605 ' 11 \n'
606 ' 12 foo(1, 2, 3)\n',
607 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000608
609 def test_one_abs_arg(self):
610 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000611 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000612 cmds_after_breakpoint=['py-list 9'])
613
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000614 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000615 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000616 ' 11 \n'
617 ' 12 foo(1, 2, 3)\n',
618 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000619
620 def test_two_abs_args(self):
621 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000622 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000623 cmds_after_breakpoint=['py-list 1,3'])
624
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000625 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
626 ' 2 \n'
627 ' 3 def foo(a, b, c):\n',
628 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000629
630class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000631 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100632 @unittest.skipIf(python_is_optimized(),
633 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000634 def test_pyup_command(self):
635 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000636 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000637 cmds_after_breakpoint=['py-up'])
638 self.assertMultilineMatches(bt,
639 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100640#[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 +0000641 baz\(a, b, c\)
642$''')
643
Victor Stinner50eb60e2010-04-20 22:32:07 +0000644 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000645 def test_down_at_bottom(self):
646 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000647 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000648 cmds_after_breakpoint=['py-down'])
649 self.assertEndsWith(bt,
650 'Unable to find a newer python frame\n')
651
Victor Stinner50eb60e2010-04-20 22:32:07 +0000652 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000653 def test_up_at_top(self):
654 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000655 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000656 cmds_after_breakpoint=['py-up'] * 4)
657 self.assertEndsWith(bt,
658 'Unable to find an older python frame\n')
659
Victor Stinner50eb60e2010-04-20 22:32:07 +0000660 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100661 @unittest.skipIf(python_is_optimized(),
662 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000663 def test_up_then_down(self):
664 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000665 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000666 cmds_after_breakpoint=['py-up', 'py-down'])
667 self.assertMultilineMatches(bt,
668 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100669#[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 +0000670 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100671#[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 +0000672 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000673$''')
674
675class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100676 @unittest.skipIf(python_is_optimized(),
677 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200678 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000679 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000680 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000681 cmds_after_breakpoint=['py-bt'])
682 self.assertMultilineMatches(bt,
683 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200684Traceback \(most recent call first\):
685 File ".*gdb_sample.py", line 10, in baz
686 id\(42\)
687 File ".*gdb_sample.py", line 7, in bar
688 baz\(a, b, c\)
689 File ".*gdb_sample.py", line 4, in foo
690 bar\(a, b, c\)
691 File ".*gdb_sample.py", line 12, in <module>
692 foo\(1, 2, 3\)
693''')
694
Victor Stinnerd2084162011-12-19 13:42:24 +0100695 @unittest.skipIf(python_is_optimized(),
696 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200697 def test_bt_full(self):
698 'Verify that the "py-bt-full" command works'
699 bt = self.get_stack_trace(script=self.get_sample_script(),
700 cmds_after_breakpoint=['py-bt-full'])
701 self.assertMultilineMatches(bt,
702 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100703#[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 +0000704 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100705#[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 +0000706 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100707#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100708 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000709''')
710
David Malcolm8d37ffa2012-06-27 14:15:34 -0400711 @unittest.skipUnless(_thread,
712 "Python was compiled without thread support")
713 def test_threads(self):
714 'Verify that "py-bt" indicates threads that are waiting for the GIL'
715 cmd = '''
716from threading import Thread
717
718class TestThread(Thread):
719 # These threads would run forever, but we'll interrupt things with the
720 # debugger
721 def run(self):
722 i = 0
723 while 1:
724 i += 1
725
726t = {}
727for i in range(4):
728 t[i] = TestThread()
729 t[i].start()
730
731# Trigger a breakpoint on the main thread
732id(42)
733
734'''
735 # Verify with "py-bt":
736 gdb_output = self.get_stack_trace(cmd,
737 cmds_after_breakpoint=['thread apply all py-bt'])
738 self.assertIn('Waiting for the GIL', gdb_output)
739
740 # Verify with "py-bt-full":
741 gdb_output = self.get_stack_trace(cmd,
742 cmds_after_breakpoint=['thread apply all py-bt-full'])
743 self.assertIn('Waiting for the GIL', gdb_output)
744
745 @unittest.skipIf(python_is_optimized(),
746 "Python was compiled with optimizations")
747 # Some older versions of gdb will fail with
748 # "Cannot find new threads: generic error"
749 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
750 @unittest.skipUnless(_thread,
751 "Python was compiled without thread support")
752 def test_gc(self):
753 'Verify that "py-bt" indicates if a thread is garbage-collecting'
754 cmd = ('from gc import collect\n'
755 'id(42)\n'
756 'def foo():\n'
757 ' collect()\n'
758 'def bar():\n'
759 ' foo()\n'
760 'bar()\n')
761 # Verify with "py-bt":
762 gdb_output = self.get_stack_trace(cmd,
763 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
764 )
765 self.assertIn('Garbage-collecting', gdb_output)
766
767 # Verify with "py-bt-full":
768 gdb_output = self.get_stack_trace(cmd,
769 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
770 )
771 self.assertIn('Garbage-collecting', gdb_output)
772
773 @unittest.skipIf(python_is_optimized(),
774 "Python was compiled with optimizations")
775 # Some older versions of gdb will fail with
776 # "Cannot find new threads: generic error"
777 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
778 @unittest.skipUnless(_thread,
779 "Python was compiled without thread support")
780 def test_pycfunction(self):
781 'Verify that "py-bt" displays invocations of PyCFunction instances'
782 cmd = ('from time import sleep\n'
783 'def foo():\n'
784 ' sleep(1)\n'
785 'def bar():\n'
786 ' foo()\n'
787 'bar()\n')
788 # Verify with "py-bt":
789 gdb_output = self.get_stack_trace(cmd,
790 breakpoint='time_sleep',
791 cmds_after_breakpoint=['bt', 'py-bt'],
792 )
793 self.assertIn('<built-in method sleep', gdb_output)
794
795 # Verify with "py-bt-full":
796 gdb_output = self.get_stack_trace(cmd,
797 breakpoint='time_sleep',
798 cmds_after_breakpoint=['py-bt-full'],
799 )
800 self.assertIn('#0 <built-in method sleep', gdb_output)
801
802
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000803class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100804 @unittest.skipIf(python_is_optimized(),
805 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000806 def test_basic_command(self):
807 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000808 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000809 cmds_after_breakpoint=['py-print args'])
810 self.assertMultilineMatches(bt,
811 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
812
Vinay Sajip2549f872012-01-04 12:07:30 +0000813 @unittest.skipIf(python_is_optimized(),
814 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000815 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000816 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000817 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000818 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
819 self.assertMultilineMatches(bt,
820 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
821
Victor Stinnerd2084162011-12-19 13:42:24 +0100822 @unittest.skipIf(python_is_optimized(),
823 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000824 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000825 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000826 cmds_after_breakpoint=['py-print __name__'])
827 self.assertMultilineMatches(bt,
828 r".*\nglobal '__name__' = '__main__'\n.*")
829
Victor Stinnerd2084162011-12-19 13:42:24 +0100830 @unittest.skipIf(python_is_optimized(),
831 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000832 def test_printing_builtin(self):
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 len'])
835 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100836 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000837
838class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100839 @unittest.skipIf(python_is_optimized(),
840 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000841 def test_basic_command(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-locals'])
844 self.assertMultilineMatches(bt,
845 r".*\nargs = \(1, 2, 3\)\n.*")
846
Victor Stinner50eb60e2010-04-20 22:32:07 +0000847 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000848 @unittest.skipIf(python_is_optimized(),
849 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000850 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000851 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000852 cmds_after_breakpoint=['py-up', 'py-locals'])
853 self.assertMultilineMatches(bt,
854 r".*\na = 1\nb = 2\nc = 3\n.*")
855
856def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200857 if support.verbose:
858 print("GDB version:")
859 for line in os.fsdecode(gdb_version).splitlines():
860 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000861 run_unittest(PrettyPrintTests,
862 PyListTests,
863 StackNavigationTests,
864 PyBtTests,
865 PyPrintTests,
866 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000867 )
868
869if __name__ == "__main__":
870 test_main()