blob: c4c4803000eb0b05fea0972656b8dff0f1afd7af [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
Victor Stinner50eb60e2010-04-20 22:32:07 +000035def gdb_has_frame_select():
36 # Does this build of gdb have gdb.Frame.select ?
37 cmd = "--eval-command=python print(dir(gdb.Frame))"
38 p = subprocess.Popen(["gdb", "--batch", cmd],
39 stdout=subprocess.PIPE)
40 stdout, _ = p.communicate()
41 m = re.match(br'.*\[(.*)\].*', stdout)
42 if not m:
43 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
44 gdb_frame_dir = m.group(1).split(b', ')
45 return b"'select'" in gdb_frame_dir
46
47HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000048
Martin v. Löwis5ae68102010-04-21 22:38:42 +000049BREAKPOINT_FN='builtin_id'
50
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000051class DebuggerTests(unittest.TestCase):
52
53 """Test that the debugger can debug Python."""
54
Georg Brandl09a7c722012-02-20 21:31:46 +010055 def run_gdb(self, *args, **env_vars):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000056 """Runs gdb with the command line given by *args.
57
58 Returns its stdout, stderr
59 """
Georg Brandl09a7c722012-02-20 21:31:46 +010060 if env_vars:
61 env = os.environ.copy()
62 env.update(env_vars)
63 else:
64 env = None
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000065 out, err = subprocess.Popen(
Georg Brandl09a7c722012-02-20 21:31:46 +010066 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000067 ).communicate()
Victor Stinner534db4e2010-04-23 20:33:55 +000068 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000069
70 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000071 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000072 cmds_after_breakpoint=None,
73 import_site=False):
74 '''
75 Run 'python -c SOURCE' under gdb with a breakpoint.
76
77 Support injecting commands after the breakpoint is reached
78
79 Returns the stdout from gdb
80
81 cmds_after_breakpoint: if provided, a list of strings: gdb commands
82 '''
83 # We use "set breakpoint pending yes" to avoid blocking with a:
84 # Function "foo" not defined.
85 # Make breakpoint pending on future shared library load? (y or [n])
86 # error, which typically happens python is dynamically linked (the
87 # breakpoints of interest are to be found in the shared library)
88 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +000089 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000090 # emitted to stderr each time, alas.
91
92 # Initially I had "--eval-command=continue" here, but removed it to
93 # avoid repeated print breakpoints when traversing hierarchical data
94 # structures
95
96 # Generate a list of commands in gdb's language:
97 commands = ['set breakpoint pending yes',
98 'break %s' % breakpoint,
99 'run']
100 if cmds_after_breakpoint:
101 commands += cmds_after_breakpoint
102 else:
103 commands += ['backtrace']
104
105 # print commands
106
107 # Use "commands" to generate the arguments with which to invoke "gdb":
108 args = ["gdb", "--batch"]
109 args += ['--eval-command=%s' % cmd for cmd in commands]
110 args += ["--args",
111 sys.executable]
112
113 if not import_site:
114 # -S suppresses the default 'import site'
115 args += ["-S"]
116
117 if source:
118 args += ["-c", source]
119 elif script:
120 args += [script]
121
122 # print args
123 # print ' '.join(args)
124
125 # Use "args" to invoke gdb, capturing stdout, stderr:
Georg Brandl09a7c722012-02-20 21:31:46 +0100126 out, err = self.run_gdb(*args, PYTHONHASHSEED='0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000127
128 # Ignore some noise on stderr due to the pending breakpoint:
129 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000130 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
131 err = err.replace("warning: Unable to find libthread_db matching"
132 " inferior's thread library, thread debugging will"
133 " not be available.\n",
134 '')
Jesus Ceacee36552011-03-16 01:33:16 +0100135 err = err.replace("warning: Cannot initialize thread debugging"
136 " library: Debugger service failed\n",
137 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000138
139 # Ensure no unexpected error messages:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000140 self.assertEqual(err, '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000141
142 return out
143
144 def get_gdb_repr(self, source,
145 cmds_after_breakpoint=None,
146 import_site=False):
147 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000148 # run "python -c'id(DATA)'" under gdb with a breakpoint on
149 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000150 # parameter, and verify that the gdb displays the same string
151 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000152 # Verify that the gdb displays the expected string
153 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000154 # For a nested structure, the first time we hit the breakpoint will
155 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000156 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000157 cmds_after_breakpoint=cmds_after_breakpoint,
158 import_site=import_site)
159 # gdb can insert additional '\n' and space characters in various places
160 # in its output, depending on the width of the terminal it's connected
161 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000162 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 +0000163 gdb_output, re.DOTALL)
164 if not m:
165 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
166 return m.group(1), gdb_output
167
168 def assertEndsWith(self, actual, exp_end):
169 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000170 self.assertTrue(actual.endswith(exp_end),
171 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000172
173 def assertMultilineMatches(self, actual, pattern):
174 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000175 if not m:
176 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000177
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000178 def get_sample_script(self):
179 return findfile('gdb_sample.py')
180
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000181class PrettyPrintTests(DebuggerTests):
182 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000183 gdb_output = self.get_stack_trace('id(42)')
184 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000185
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000186 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000187 # Ensure that gdb's rendering of the value in a debugged process
188 # matches repr(value) in this process:
Victor Stinner150016f2010-05-19 23:04:56 +0000189 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000190 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000191 if not exp_repr:
192 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000193 self.assertEqual(gdb_repr, exp_repr,
194 ('%r did not equal expected %r; full output was:\n%s'
195 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000196
197 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000198 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000199 self.assertGdbRepr(42)
200 self.assertGdbRepr(0)
201 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000202 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203 self.assertGdbRepr(-1000000000000000)
204
205 def test_singletons(self):
206 'Verify the pretty-printing of True, False and None'
207 self.assertGdbRepr(True)
208 self.assertGdbRepr(False)
209 self.assertGdbRepr(None)
210
211 def test_dicts(self):
212 'Verify the pretty-printing of dictionaries'
213 self.assertGdbRepr({})
214 self.assertGdbRepr({'foo': 'bar'})
Georg Brandl09a7c722012-02-20 21:31:46 +0100215 self.assertGdbRepr({'foo': 'bar', 'douglas': 42},
216 "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000217
218 def test_lists(self):
219 'Verify the pretty-printing of lists'
220 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000221 self.assertGdbRepr(list(range(5)))
222
223 def test_bytes(self):
224 'Verify the pretty-printing of bytes'
225 self.assertGdbRepr(b'')
226 self.assertGdbRepr(b'And now for something hopefully the same')
227 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
228 self.assertGdbRepr(b'this is a tab:\t'
229 b' this is a slash-N:\n'
230 b' this is a slash-R:\r'
231 )
232
233 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
234
235 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000236
237 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000238 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000239 encoding = locale.getpreferredencoding()
240 def check_repr(text):
241 try:
242 text.encode(encoding)
243 printable = True
244 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000245 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000246 else:
247 self.assertGdbRepr(text)
248
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000249 self.assertGdbRepr('')
250 self.assertGdbRepr('And now for something hopefully the same')
251 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000252
253 # Test printing a single character:
254 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000255 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000256
257 # Test printing a Japanese unicode string
258 # (I believe this reads "mojibake", using 3 characters from the CJK
259 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000260 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000261
262 # Test a character outside the BMP:
263 # U+1D121 MUSICAL SYMBOL C CLEF
264 # This is:
265 # UTF-8: 0xF0 0x9D 0x84 0xA1
266 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000267 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000268
269 def test_tuples(self):
270 'Verify the pretty-printing of tuples'
271 self.assertGdbRepr(tuple())
272 self.assertGdbRepr((1,), '(1,)')
273 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274
275 def test_sets(self):
276 'Verify the pretty-printing of sets'
277 self.assertGdbRepr(set())
Georg Brandl09a7c722012-02-20 21:31:46 +0100278 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
279 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000280
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000281 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000282 # which happens on deletion:
283 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
284s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000285id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000286 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000287
288 def test_frozensets(self):
289 'Verify the pretty-printing of frozensets'
290 self.assertGdbRepr(frozenset())
Georg Brandl09a7c722012-02-20 21:31:46 +0100291 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
292 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000293
294 def test_exceptions(self):
295 # Test a RuntimeError
296 gdb_repr, gdb_output = self.get_gdb_repr('''
297try:
298 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000299except RuntimeError as e:
300 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000301''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000302 self.assertEqual(gdb_repr,
303 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000304
305
306 # Test division by zero:
307 gdb_repr, gdb_output = self.get_gdb_repr('''
308try:
309 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000310except ZeroDivisionError as e:
311 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000312''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000313 self.assertEqual(gdb_repr,
314 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000315
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000316 def test_modern_class(self):
317 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000318 gdb_repr, gdb_output = self.get_gdb_repr('''
319class Foo:
320 pass
321foo = Foo()
322foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000323id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100324 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000325 self.assertTrue(m,
326 msg='Unexpected new-style class rendering %r' % gdb_repr)
327
328 def test_subclassing_list(self):
329 'Verify the pretty-printing of an instance of a list subclass'
330 gdb_repr, gdb_output = self.get_gdb_repr('''
331class Foo(list):
332 pass
333foo = Foo()
334foo += [1, 2, 3]
335foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000336id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100337 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 +0000338
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000339 self.assertTrue(m,
340 msg='Unexpected new-style class rendering %r' % gdb_repr)
341
342 def test_subclassing_tuple(self):
343 'Verify the pretty-printing of an instance of a tuple subclass'
344 # This should exercise the negative tp_dictoffset code in the
345 # new-style class support
346 gdb_repr, gdb_output = self.get_gdb_repr('''
347class Foo(tuple):
348 pass
349foo = Foo((1, 2, 3))
350foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000351id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100352 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 +0000353
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000354 self.assertTrue(m,
355 msg='Unexpected new-style class rendering %r' % gdb_repr)
356
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000357 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000358 '''Run Python under gdb, corrupting variables in the inferior process
359 immediately before taking a backtrace.
360
361 Verify that the variable's representation is the expected failsafe
362 representation'''
363 if corruption:
364 cmds_after_breakpoint=[corruption, 'backtrace']
365 else:
366 cmds_after_breakpoint=['backtrace']
367
368 gdb_repr, gdb_output = \
369 self.get_gdb_repr(source,
370 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000371 if exprepr:
372 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000373 # gdb managed to print the value in spite of the corruption;
374 # this is good (see http://bugs.python.org/issue8330)
375 return
376
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000377 # Match anything for the type name; 0xDEADBEEF could point to
378 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100379 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000380
381 m = re.match(pattern, gdb_repr)
382 if not m:
383 self.fail('Unexpected gdb representation: %r\n%s' % \
384 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000385
386 def test_NULL_ptr(self):
387 'Ensure that a NULL PyObject* is handled gracefully'
388 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000389 self.get_gdb_repr('id(42)',
390 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000391 'backtrace'])
392 )
393
Ezio Melottib3aedd42010-11-20 19:04:17 +0000394 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000395
396 def test_NULL_ob_type(self):
397 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000398 self.assertSane('id(42)',
399 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000400
401 def test_corrupt_ob_type(self):
402 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000403 self.assertSane('id(42)',
404 'set v->ob_type=0xDEADBEEF',
405 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000406
407 def test_corrupt_tp_flags(self):
408 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000409 self.assertSane('id(42)',
410 'set v->ob_type->tp_flags=0x0',
411 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000412
413 def test_corrupt_tp_name(self):
414 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000415 self.assertSane('id(42)',
416 'set v->ob_type->tp_name=0xDEADBEEF',
417 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000418
419 def test_builtins_help(self):
420 'Ensure that the new-style class _Helper in site.py can be handled'
421 # (this was the issue causing tracebacks in
422 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000423 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000424
Antoine Pitrou4d098732011-11-26 01:42:03 +0100425 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000426 self.assertTrue(m,
427 msg='Unexpected rendering %r' % gdb_repr)
428
429 def test_selfreferential_list(self):
430 '''Ensure that a reference loop involving a list doesn't lead proxyval
431 into an infinite loop:'''
432 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000433 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000434 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000435
436 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000437 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000438 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000439
440 def test_selfreferential_dict(self):
441 '''Ensure that a reference loop involving a dict doesn't lead proxyval
442 into an infinite loop:'''
443 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000444 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000445
Ezio Melottib3aedd42010-11-20 19:04:17 +0000446 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000447
448 def test_selfreferential_old_style_instance(self):
449 gdb_repr, gdb_output = \
450 self.get_gdb_repr('''
451class Foo:
452 pass
453foo = Foo()
454foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000455id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100456 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000457 gdb_repr),
458 'Unexpected gdb representation: %r\n%s' % \
459 (gdb_repr, gdb_output))
460
461 def test_selfreferential_new_style_instance(self):
462 gdb_repr, gdb_output = \
463 self.get_gdb_repr('''
464class Foo(object):
465 pass
466foo = Foo()
467foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000468id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100469 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000470 gdb_repr),
471 'Unexpected gdb representation: %r\n%s' % \
472 (gdb_repr, gdb_output))
473
474 gdb_repr, gdb_output = \
475 self.get_gdb_repr('''
476class Foo(object):
477 pass
478a = Foo()
479b = Foo()
480a.an_attr = b
481b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000482id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100483 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 +0000484 gdb_repr),
485 'Unexpected gdb representation: %r\n%s' % \
486 (gdb_repr, gdb_output))
487
488 def test_truncation(self):
489 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000490 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000491 self.assertEqual(gdb_repr,
492 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
493 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
494 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
495 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
496 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
497 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
498 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
499 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
500 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
501 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
502 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
503 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
504 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
505 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
506 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
507 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
508 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
509 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
510 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
511 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
512 "224, 225, 226...(truncated)")
513 self.assertEqual(len(gdb_repr),
514 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000515
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000516 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000517 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100518 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 +0000519 gdb_repr),
520 'Unexpected gdb representation: %r\n%s' % \
521 (gdb_repr, gdb_output))
522
523 def test_frames(self):
524 gdb_output = self.get_stack_trace('''
525def foo(a, b, c):
526 pass
527
528foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000529id(foo.__code__)''',
530 breakpoint='builtin_id',
531 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000532 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100533 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 +0000534 gdb_output,
535 re.DOTALL),
536 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
537
Victor Stinnerd2084162011-12-19 13:42:24 +0100538@unittest.skipIf(python_is_optimized(),
539 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000540class PyListTests(DebuggerTests):
541 def assertListing(self, expected, actual):
542 self.assertEndsWith(actual, expected)
543
544 def test_basic_command(self):
545 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000546 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000547 cmds_after_breakpoint=['py-list'])
548
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000549 self.assertListing(' 5 \n'
550 ' 6 def bar(a, b, c):\n'
551 ' 7 baz(a, b, c)\n'
552 ' 8 \n'
553 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000554 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000555 ' 11 \n'
556 ' 12 foo(1, 2, 3)\n',
557 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000558
559 def test_one_abs_arg(self):
560 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000561 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000562 cmds_after_breakpoint=['py-list 9'])
563
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000564 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000565 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000566 ' 11 \n'
567 ' 12 foo(1, 2, 3)\n',
568 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000569
570 def test_two_abs_args(self):
571 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000572 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000573 cmds_after_breakpoint=['py-list 1,3'])
574
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000575 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
576 ' 2 \n'
577 ' 3 def foo(a, b, c):\n',
578 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000579
580class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000581 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100582 @unittest.skipIf(python_is_optimized(),
583 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000584 def test_pyup_command(self):
585 'Verify that the "py-up" command works'
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-up'])
588 self.assertMultilineMatches(bt,
589 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100590#[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 +0000591 baz\(a, b, c\)
592$''')
593
Victor Stinner50eb60e2010-04-20 22:32:07 +0000594 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000595 def test_down_at_bottom(self):
596 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000597 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000598 cmds_after_breakpoint=['py-down'])
599 self.assertEndsWith(bt,
600 'Unable to find a newer python frame\n')
601
Victor Stinner50eb60e2010-04-20 22:32:07 +0000602 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000603 def test_up_at_top(self):
604 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000605 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000606 cmds_after_breakpoint=['py-up'] * 4)
607 self.assertEndsWith(bt,
608 'Unable to find an older python frame\n')
609
Victor Stinner50eb60e2010-04-20 22:32:07 +0000610 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100611 @unittest.skipIf(python_is_optimized(),
612 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000613 def test_up_then_down(self):
614 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000615 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000616 cmds_after_breakpoint=['py-up', 'py-down'])
617 self.assertMultilineMatches(bt,
618 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100619#[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 +0000620 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100621#[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 +0000622 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000623$''')
624
625class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100626 @unittest.skipIf(python_is_optimized(),
627 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200628 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000629 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000630 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000631 cmds_after_breakpoint=['py-bt'])
632 self.assertMultilineMatches(bt,
633 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200634Traceback \(most recent call first\):
635 File ".*gdb_sample.py", line 10, in baz
636 id\(42\)
637 File ".*gdb_sample.py", line 7, in bar
638 baz\(a, b, c\)
639 File ".*gdb_sample.py", line 4, in foo
640 bar\(a, b, c\)
641 File ".*gdb_sample.py", line 12, in <module>
642 foo\(1, 2, 3\)
643''')
644
Victor Stinnerd2084162011-12-19 13:42:24 +0100645 @unittest.skipIf(python_is_optimized(),
646 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200647 def test_bt_full(self):
648 'Verify that the "py-bt-full" command works'
649 bt = self.get_stack_trace(script=self.get_sample_script(),
650 cmds_after_breakpoint=['py-bt-full'])
651 self.assertMultilineMatches(bt,
652 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100653#[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 +0000654 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100655#[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 +0000656 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100657#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100658 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000659''')
660
661class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100662 @unittest.skipIf(python_is_optimized(),
663 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000664 def test_basic_command(self):
665 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000666 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000667 cmds_after_breakpoint=['py-print args'])
668 self.assertMultilineMatches(bt,
669 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
670
Vinay Sajip2549f872012-01-04 12:07:30 +0000671 @unittest.skipIf(python_is_optimized(),
672 "Python was compiled with optimizations")
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_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000675 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000676 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
677 self.assertMultilineMatches(bt,
678 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
679
Victor Stinnerd2084162011-12-19 13:42:24 +0100680 @unittest.skipIf(python_is_optimized(),
681 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000682 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000683 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000684 cmds_after_breakpoint=['py-print __name__'])
685 self.assertMultilineMatches(bt,
686 r".*\nglobal '__name__' = '__main__'\n.*")
687
Victor Stinnerd2084162011-12-19 13:42:24 +0100688 @unittest.skipIf(python_is_optimized(),
689 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000690 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000691 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000692 cmds_after_breakpoint=['py-print len'])
693 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100694 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000695
696class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100697 @unittest.skipIf(python_is_optimized(),
698 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000699 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000700 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000701 cmds_after_breakpoint=['py-locals'])
702 self.assertMultilineMatches(bt,
703 r".*\nargs = \(1, 2, 3\)\n.*")
704
Victor Stinner50eb60e2010-04-20 22:32:07 +0000705 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000706 @unittest.skipIf(python_is_optimized(),
707 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000708 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000709 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000710 cmds_after_breakpoint=['py-up', 'py-locals'])
711 self.assertMultilineMatches(bt,
712 r".*\na = 1\nb = 2\nc = 3\n.*")
713
714def test_main():
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000715 run_unittest(PrettyPrintTests,
716 PyListTests,
717 StackNavigationTests,
718 PyBtTests,
719 PyPrintTests,
720 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000721 )
722
723if __name__ == "__main__":
724 test_main()