blob: fb8261beff0e6b69d14e83dd19902b1ab6178f41 [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
8import subprocess
9import sys
10import unittest
Victor Stinner150016f2010-05-19 23:04:56 +000011import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000012
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000013from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000014
15try:
16 gdb_version, _ = subprocess.Popen(["gdb", "--version"],
17 stdout=subprocess.PIPE).communicate()
18except OSError:
19 # This is what "no gdb" looks like. There may, however, be other
20 # errors that manifest this way too.
21 raise unittest.SkipTest("Couldn't find gdb on the path")
22gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.", gdb_version)
23if int(gdb_version_number.group(1)) < 7:
24 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
Antoine Pitrou6a45e9d2010-04-11 22:47:34 +000025 " Saw:\n" + gdb_version.decode('ascii', 'replace'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000026
27# Verify that "gdb" was built with the embedded python support enabled:
28cmd = "--eval-command=python import sys; print sys.version_info"
29p = subprocess.Popen(["gdb", "--batch", cmd],
30 stdout=subprocess.PIPE)
31gdbpy_version, _ = p.communicate()
Benjamin Peterson9faa7ec2010-04-11 23:51:24 +000032if gdbpy_version == b'':
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000033 raise unittest.SkipTest("gdb not built with embedded python support")
34
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100035# Verify that "gdb" can load our custom hooks
36p = subprocess.Popen(["gdb", "--batch", cmd,
37 "--args", sys.executable],
38 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
39__, gdbpy_errors = p.communicate()
40if b"auto-loading has been declined" in gdbpy_errors:
41 msg = "gdb security settings prevent use of custom hooks: %s"
42 raise unittest.SkipTest(msg % gdbpy_errors)
43
Victor Stinner50eb60e2010-04-20 22:32:07 +000044def gdb_has_frame_select():
45 # Does this build of gdb have gdb.Frame.select ?
46 cmd = "--eval-command=python print(dir(gdb.Frame))"
47 p = subprocess.Popen(["gdb", "--batch", cmd],
48 stdout=subprocess.PIPE)
49 stdout, _ = p.communicate()
50 m = re.match(br'.*\[(.*)\].*', stdout)
51 if not m:
52 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
53 gdb_frame_dir = m.group(1).split(b', ')
54 return b"'select'" in gdb_frame_dir
55
56HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000057
Martin v. Löwis5ae68102010-04-21 22:38:42 +000058BREAKPOINT_FN='builtin_id'
59
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000060class DebuggerTests(unittest.TestCase):
61
62 """Test that the debugger can debug Python."""
63
Georg Brandl09a7c722012-02-20 21:31:46 +010064 def run_gdb(self, *args, **env_vars):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000065 """Runs gdb with the command line given by *args.
66
67 Returns its stdout, stderr
68 """
Georg Brandl09a7c722012-02-20 21:31:46 +010069 if env_vars:
70 env = os.environ.copy()
71 env.update(env_vars)
72 else:
73 env = None
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000074 out, err = subprocess.Popen(
Georg Brandl09a7c722012-02-20 21:31:46 +010075 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000076 ).communicate()
Victor Stinner534db4e2010-04-23 20:33:55 +000077 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000078
79 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000080 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000081 cmds_after_breakpoint=None,
82 import_site=False):
83 '''
84 Run 'python -c SOURCE' under gdb with a breakpoint.
85
86 Support injecting commands after the breakpoint is reached
87
88 Returns the stdout from gdb
89
90 cmds_after_breakpoint: if provided, a list of strings: gdb commands
91 '''
92 # We use "set breakpoint pending yes" to avoid blocking with a:
93 # Function "foo" not defined.
94 # Make breakpoint pending on future shared library load? (y or [n])
95 # error, which typically happens python is dynamically linked (the
96 # breakpoints of interest are to be found in the shared library)
97 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +000098 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000099 # emitted to stderr each time, alas.
100
101 # Initially I had "--eval-command=continue" here, but removed it to
102 # avoid repeated print breakpoints when traversing hierarchical data
103 # structures
104
105 # Generate a list of commands in gdb's language:
106 commands = ['set breakpoint pending yes',
107 'break %s' % breakpoint,
108 'run']
109 if cmds_after_breakpoint:
110 commands += cmds_after_breakpoint
111 else:
112 commands += ['backtrace']
113
114 # print commands
115
116 # Use "commands" to generate the arguments with which to invoke "gdb":
117 args = ["gdb", "--batch"]
118 args += ['--eval-command=%s' % cmd for cmd in commands]
119 args += ["--args",
120 sys.executable]
121
122 if not import_site:
123 # -S suppresses the default 'import site'
124 args += ["-S"]
125
126 if source:
127 args += ["-c", source]
128 elif script:
129 args += [script]
130
131 # print args
132 # print ' '.join(args)
133
134 # Use "args" to invoke gdb, capturing stdout, stderr:
Georg Brandl09a7c722012-02-20 21:31:46 +0100135 out, err = self.run_gdb(*args, PYTHONHASHSEED='0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000136
137 # Ignore some noise on stderr due to the pending breakpoint:
138 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000139 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
140 err = err.replace("warning: Unable to find libthread_db matching"
141 " inferior's thread library, thread debugging will"
142 " not be available.\n",
143 '')
Jesus Ceacee36552011-03-16 01:33:16 +0100144 err = err.replace("warning: Cannot initialize thread debugging"
145 " library: Debugger service failed\n",
146 '')
Benjamin Petersonf8a9a832012-09-20 23:48:23 -0400147 err = err.replace('warning: Could not load shared library symbols for '
148 'linux-vdso.so.1.\n'
149 'Do you need "set solib-search-path" or '
150 '"set sysroot"?\n',
151 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000152
153 # Ensure no unexpected error messages:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000154 self.assertEqual(err, '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000155
156 return out
157
158 def get_gdb_repr(self, source,
159 cmds_after_breakpoint=None,
160 import_site=False):
161 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000162 # run "python -c'id(DATA)'" under gdb with a breakpoint on
163 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000164 # parameter, and verify that the gdb displays the same string
165 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000166 # Verify that the gdb displays the expected string
167 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000168 # For a nested structure, the first time we hit the breakpoint will
169 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000170 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000171 cmds_after_breakpoint=cmds_after_breakpoint,
172 import_site=import_site)
173 # gdb can insert additional '\n' and space characters in various places
174 # in its output, depending on the width of the terminal it's connected
175 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000176 m = re.match('.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000177 gdb_output, re.DOTALL)
178 if not m:
179 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
180 return m.group(1), gdb_output
181
182 def assertEndsWith(self, actual, exp_end):
183 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000184 self.assertTrue(actual.endswith(exp_end),
185 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000186
187 def assertMultilineMatches(self, actual, pattern):
188 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000189 if not m:
190 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000191
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000192 def get_sample_script(self):
193 return findfile('gdb_sample.py')
194
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000195class PrettyPrintTests(DebuggerTests):
196 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000197 gdb_output = self.get_stack_trace('id(42)')
198 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000199
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000200 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000201 # Ensure that gdb's rendering of the value in a debugged process
202 # matches repr(value) in this process:
Victor Stinner150016f2010-05-19 23:04:56 +0000203 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000204 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000205 if not exp_repr:
206 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000207 self.assertEqual(gdb_repr, exp_repr,
208 ('%r did not equal expected %r; full output was:\n%s'
209 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000210
211 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000212 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000213 self.assertGdbRepr(42)
214 self.assertGdbRepr(0)
215 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000216 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000217 self.assertGdbRepr(-1000000000000000)
218
219 def test_singletons(self):
220 'Verify the pretty-printing of True, False and None'
221 self.assertGdbRepr(True)
222 self.assertGdbRepr(False)
223 self.assertGdbRepr(None)
224
225 def test_dicts(self):
226 'Verify the pretty-printing of dictionaries'
227 self.assertGdbRepr({})
228 self.assertGdbRepr({'foo': 'bar'})
Georg Brandl09a7c722012-02-20 21:31:46 +0100229 self.assertGdbRepr({'foo': 'bar', 'douglas': 42},
230 "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000231
232 def test_lists(self):
233 'Verify the pretty-printing of lists'
234 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000235 self.assertGdbRepr(list(range(5)))
236
237 def test_bytes(self):
238 'Verify the pretty-printing of bytes'
239 self.assertGdbRepr(b'')
240 self.assertGdbRepr(b'And now for something hopefully the same')
241 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
242 self.assertGdbRepr(b'this is a tab:\t'
243 b' this is a slash-N:\n'
244 b' this is a slash-R:\r'
245 )
246
247 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
248
249 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000250
251 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000252 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000253 encoding = locale.getpreferredencoding()
254 def check_repr(text):
255 try:
256 text.encode(encoding)
257 printable = True
258 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000259 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000260 else:
261 self.assertGdbRepr(text)
262
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000263 self.assertGdbRepr('')
264 self.assertGdbRepr('And now for something hopefully the same')
265 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000266
267 # Test printing a single character:
268 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000269 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000270
271 # Test printing a Japanese unicode string
272 # (I believe this reads "mojibake", using 3 characters from the CJK
273 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000274 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000275
276 # Test a character outside the BMP:
277 # U+1D121 MUSICAL SYMBOL C CLEF
278 # This is:
279 # UTF-8: 0xF0 0x9D 0x84 0xA1
280 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000281 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000282
283 def test_tuples(self):
284 'Verify the pretty-printing of tuples'
285 self.assertGdbRepr(tuple())
286 self.assertGdbRepr((1,), '(1,)')
287 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000288
289 def test_sets(self):
290 'Verify the pretty-printing of sets'
291 self.assertGdbRepr(set())
Georg Brandl09a7c722012-02-20 21:31:46 +0100292 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
293 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000294
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000295 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000296 # which happens on deletion:
297 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
298s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000299id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000300 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000301
302 def test_frozensets(self):
303 'Verify the pretty-printing of frozensets'
304 self.assertGdbRepr(frozenset())
Georg Brandl09a7c722012-02-20 21:31:46 +0100305 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
306 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000307
308 def test_exceptions(self):
309 # Test a RuntimeError
310 gdb_repr, gdb_output = self.get_gdb_repr('''
311try:
312 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000313except RuntimeError as e:
314 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000315''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000316 self.assertEqual(gdb_repr,
317 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000318
319
320 # Test division by zero:
321 gdb_repr, gdb_output = self.get_gdb_repr('''
322try:
323 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000324except ZeroDivisionError as e:
325 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000326''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000327 self.assertEqual(gdb_repr,
328 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000329
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000330 def test_modern_class(self):
331 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000332 gdb_repr, gdb_output = self.get_gdb_repr('''
333class Foo:
334 pass
335foo = Foo()
336foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000337id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000338 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
339 self.assertTrue(m,
340 msg='Unexpected new-style class rendering %r' % gdb_repr)
341
342 def test_subclassing_list(self):
343 'Verify the pretty-printing of an instance of a list subclass'
344 gdb_repr, gdb_output = self.get_gdb_repr('''
345class Foo(list):
346 pass
347foo = Foo()
348foo += [1, 2, 3]
349foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000350id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000351 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 +0000352
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000353 self.assertTrue(m,
354 msg='Unexpected new-style class rendering %r' % gdb_repr)
355
356 def test_subclassing_tuple(self):
357 'Verify the pretty-printing of an instance of a tuple subclass'
358 # This should exercise the negative tp_dictoffset code in the
359 # new-style class support
360 gdb_repr, gdb_output = self.get_gdb_repr('''
361class Foo(tuple):
362 pass
363foo = Foo((1, 2, 3))
364foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000365id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000366 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 +0000367
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000368 self.assertTrue(m,
369 msg='Unexpected new-style class rendering %r' % gdb_repr)
370
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000371 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000372 '''Run Python under gdb, corrupting variables in the inferior process
373 immediately before taking a backtrace.
374
375 Verify that the variable's representation is the expected failsafe
376 representation'''
377 if corruption:
378 cmds_after_breakpoint=[corruption, 'backtrace']
379 else:
380 cmds_after_breakpoint=['backtrace']
381
382 gdb_repr, gdb_output = \
383 self.get_gdb_repr(source,
384 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000385 if exprepr:
386 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000387 # gdb managed to print the value in spite of the corruption;
388 # this is good (see http://bugs.python.org/issue8330)
389 return
390
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000391 # Match anything for the type name; 0xDEADBEEF could point to
392 # something arbitrary (see http://bugs.python.org/issue8330)
393 pattern = '<.* at remote 0x[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000394
395 m = re.match(pattern, gdb_repr)
396 if not m:
397 self.fail('Unexpected gdb representation: %r\n%s' % \
398 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000399
400 def test_NULL_ptr(self):
401 'Ensure that a NULL PyObject* is handled gracefully'
402 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000403 self.get_gdb_repr('id(42)',
404 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000405 'backtrace'])
406 )
407
Ezio Melottib3aedd42010-11-20 19:04:17 +0000408 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000409
410 def test_NULL_ob_type(self):
411 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000412 self.assertSane('id(42)',
413 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000414
415 def test_corrupt_ob_type(self):
416 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000417 self.assertSane('id(42)',
418 'set v->ob_type=0xDEADBEEF',
419 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000420
421 def test_corrupt_tp_flags(self):
422 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000423 self.assertSane('id(42)',
424 'set v->ob_type->tp_flags=0x0',
425 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000426
427 def test_corrupt_tp_name(self):
428 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000429 self.assertSane('id(42)',
430 'set v->ob_type->tp_name=0xDEADBEEF',
431 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000432
433 def test_builtins_help(self):
434 'Ensure that the new-style class _Helper in site.py can be handled'
435 # (this was the issue causing tracebacks in
436 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000437 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000438
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000439 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
440 self.assertTrue(m,
441 msg='Unexpected rendering %r' % gdb_repr)
442
443 def test_selfreferential_list(self):
444 '''Ensure that a reference loop involving a list doesn't lead proxyval
445 into an infinite loop:'''
446 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000447 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000448 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000449
450 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000451 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000452 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000453
454 def test_selfreferential_dict(self):
455 '''Ensure that a reference loop involving a dict doesn't lead proxyval
456 into an infinite loop:'''
457 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000458 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000459
Ezio Melottib3aedd42010-11-20 19:04:17 +0000460 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000461
462 def test_selfreferential_old_style_instance(self):
463 gdb_repr, gdb_output = \
464 self.get_gdb_repr('''
465class Foo:
466 pass
467foo = Foo()
468foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000469id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000470 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
471 gdb_repr),
472 'Unexpected gdb representation: %r\n%s' % \
473 (gdb_repr, gdb_output))
474
475 def test_selfreferential_new_style_instance(self):
476 gdb_repr, gdb_output = \
477 self.get_gdb_repr('''
478class Foo(object):
479 pass
480foo = Foo()
481foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000482id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000483 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
484 gdb_repr),
485 'Unexpected gdb representation: %r\n%s' % \
486 (gdb_repr, gdb_output))
487
488 gdb_repr, gdb_output = \
489 self.get_gdb_repr('''
490class Foo(object):
491 pass
492a = Foo()
493b = Foo()
494a.an_attr = b
495b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000496id(a)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000497 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
498 gdb_repr),
499 'Unexpected gdb representation: %r\n%s' % \
500 (gdb_repr, gdb_output))
501
502 def test_truncation(self):
503 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000505 self.assertEqual(gdb_repr,
506 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
507 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
508 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
509 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
510 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
511 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
512 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
513 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
514 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
515 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
516 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
517 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
518 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
519 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
520 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
521 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
522 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
523 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
524 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
525 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
526 "224, 225, 226...(truncated)")
527 self.assertEqual(len(gdb_repr),
528 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000529
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000530 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000531 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
532 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 +0000533 gdb_repr),
534 'Unexpected gdb representation: %r\n%s' % \
535 (gdb_repr, gdb_output))
536
537 def test_frames(self):
538 gdb_output = self.get_stack_trace('''
539def foo(a, b, c):
540 pass
541
542foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000543id(foo.__code__)''',
544 breakpoint='builtin_id',
545 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000546 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000547 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 +0000548 gdb_output,
549 re.DOTALL),
550 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
551
Victor Stinnerd2084162011-12-19 13:42:24 +0100552@unittest.skipIf(python_is_optimized(),
553 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000554class PyListTests(DebuggerTests):
555 def assertListing(self, expected, actual):
556 self.assertEndsWith(actual, expected)
557
558 def test_basic_command(self):
559 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000560 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000561 cmds_after_breakpoint=['py-list'])
562
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000563 self.assertListing(' 5 \n'
564 ' 6 def bar(a, b, c):\n'
565 ' 7 baz(a, b, c)\n'
566 ' 8 \n'
567 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000568 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000569 ' 11 \n'
570 ' 12 foo(1, 2, 3)\n',
571 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000572
573 def test_one_abs_arg(self):
574 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000575 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000576 cmds_after_breakpoint=['py-list 9'])
577
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000578 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000579 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000580 ' 11 \n'
581 ' 12 foo(1, 2, 3)\n',
582 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000583
584 def test_two_abs_args(self):
585 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000586 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000587 cmds_after_breakpoint=['py-list 1,3'])
588
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000589 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
590 ' 2 \n'
591 ' 3 def foo(a, b, c):\n',
592 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000593
594class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000595 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100596 @unittest.skipIf(python_is_optimized(),
597 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000598 def test_pyup_command(self):
599 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000600 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000601 cmds_after_breakpoint=['py-up'])
602 self.assertMultilineMatches(bt,
603 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000604#[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 +0000605 baz\(a, b, c\)
606$''')
607
Victor Stinner50eb60e2010-04-20 22:32:07 +0000608 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609 def test_down_at_bottom(self):
610 'Verify handling of "py-down" at the bottom of the stack'
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-down'])
613 self.assertEndsWith(bt,
614 'Unable to find a newer python frame\n')
615
Victor Stinner50eb60e2010-04-20 22:32:07 +0000616 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000617 def test_up_at_top(self):
618 'Verify handling of "py-up" at the top of the stack'
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-up'] * 4)
621 self.assertEndsWith(bt,
622 'Unable to find an older python frame\n')
623
Victor Stinner50eb60e2010-04-20 22:32:07 +0000624 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100625 @unittest.skipIf(python_is_optimized(),
626 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000627 def test_up_then_down(self):
628 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000629 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000630 cmds_after_breakpoint=['py-up', 'py-down'])
631 self.assertMultilineMatches(bt,
632 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000633#[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 +0000634 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000635#[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 +0000636 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000637$''')
638
639class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100640 @unittest.skipIf(python_is_optimized(),
641 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200642 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000643 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000644 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000645 cmds_after_breakpoint=['py-bt'])
646 self.assertMultilineMatches(bt,
647 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200648Traceback \(most recent call first\):
649 File ".*gdb_sample.py", line 10, in baz
650 id\(42\)
651 File ".*gdb_sample.py", line 7, in bar
652 baz\(a, b, c\)
653 File ".*gdb_sample.py", line 4, in foo
654 bar\(a, b, c\)
655 File ".*gdb_sample.py", line 12, in <module>
656 foo\(1, 2, 3\)
657''')
658
Victor Stinnerd2084162011-12-19 13:42:24 +0100659 @unittest.skipIf(python_is_optimized(),
660 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200661 def test_bt_full(self):
662 'Verify that the "py-bt-full" command works'
663 bt = self.get_stack_trace(script=self.get_sample_script(),
664 cmds_after_breakpoint=['py-bt-full'])
665 self.assertMultilineMatches(bt,
666 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000667#[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 +0000668 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000669#[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 +0000670 bar\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000671#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100672 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000673''')
674
675class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100676 @unittest.skipIf(python_is_optimized(),
677 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 def test_basic_command(self):
679 'Verify that the "py-print" 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-print args'])
682 self.assertMultilineMatches(bt,
683 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
684
Vinay Sajipcdf6cd92012-01-05 11:45:31 +0000685 @unittest.skipIf(python_is_optimized(),
686 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000687 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000688 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000689 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000690 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
691 self.assertMultilineMatches(bt,
692 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
693
Victor Stinnerd2084162011-12-19 13:42:24 +0100694 @unittest.skipIf(python_is_optimized(),
695 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000697 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000698 cmds_after_breakpoint=['py-print __name__'])
699 self.assertMultilineMatches(bt,
700 r".*\nglobal '__name__' = '__main__'\n.*")
701
Victor Stinnerd2084162011-12-19 13:42:24 +0100702 @unittest.skipIf(python_is_optimized(),
703 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000704 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000705 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000706 cmds_after_breakpoint=['py-print len'])
707 self.assertMultilineMatches(bt,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000708 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000709
710class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100711 @unittest.skipIf(python_is_optimized(),
712 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000713 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000714 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000715 cmds_after_breakpoint=['py-locals'])
716 self.assertMultilineMatches(bt,
717 r".*\nargs = \(1, 2, 3\)\n.*")
718
Victor Stinner50eb60e2010-04-20 22:32:07 +0000719 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajipcdf6cd92012-01-05 11:45:31 +0000720 @unittest.skipIf(python_is_optimized(),
721 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000722 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000723 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000724 cmds_after_breakpoint=['py-up', 'py-locals'])
725 self.assertMultilineMatches(bt,
726 r".*\na = 1\nb = 2\nc = 3\n.*")
727
728def test_main():
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000729 run_unittest(PrettyPrintTests,
730 PyListTests,
731 StackNavigationTests,
732 PyBtTests,
733 PyPrintTests,
734 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000735 )
736
737if __name__ == "__main__":
738 test_main()