blob: 91543c6888f4b735217eb1bde80b29cdbef5dd21 [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
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010010import sysconfig
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000011import unittest
Victor Stinner150016f2010-05-19 23:04:56 +000012import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000013
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000014from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000015
16try:
17 gdb_version, _ = subprocess.Popen(["gdb", "--version"],
18 stdout=subprocess.PIPE).communicate()
19except OSError:
20 # This is what "no gdb" looks like. There may, however, be other
21 # errors that manifest this way too.
22 raise unittest.SkipTest("Couldn't find gdb on the path")
23gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.", gdb_version)
24if int(gdb_version_number.group(1)) < 7:
25 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
Antoine Pitrou6a45e9d2010-04-11 22:47:34 +000026 " Saw:\n" + gdb_version.decode('ascii', 'replace'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000027
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010028if not sysconfig.is_python_build():
29 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
30
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000031# Verify that "gdb" was built with the embedded python support enabled:
32cmd = "--eval-command=python import sys; print sys.version_info"
33p = subprocess.Popen(["gdb", "--batch", cmd],
34 stdout=subprocess.PIPE)
35gdbpy_version, _ = p.communicate()
Benjamin Peterson9faa7ec2010-04-11 23:51:24 +000036if gdbpy_version == b'':
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000037 raise unittest.SkipTest("gdb not built with embedded python support")
38
Victor Stinner50eb60e2010-04-20 22:32:07 +000039def gdb_has_frame_select():
40 # Does this build of gdb have gdb.Frame.select ?
41 cmd = "--eval-command=python print(dir(gdb.Frame))"
42 p = subprocess.Popen(["gdb", "--batch", cmd],
43 stdout=subprocess.PIPE)
44 stdout, _ = p.communicate()
45 m = re.match(br'.*\[(.*)\].*', stdout)
46 if not m:
47 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
48 gdb_frame_dir = m.group(1).split(b', ')
49 return b"'select'" in gdb_frame_dir
50
51HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000052
Martin v. Löwis5ae68102010-04-21 22:38:42 +000053BREAKPOINT_FN='builtin_id'
54
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000055class DebuggerTests(unittest.TestCase):
56
57 """Test that the debugger can debug Python."""
58
Georg Brandl09a7c722012-02-20 21:31:46 +010059 def run_gdb(self, *args, **env_vars):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000060 """Runs gdb with the command line given by *args.
61
62 Returns its stdout, stderr
63 """
Georg Brandl09a7c722012-02-20 21:31:46 +010064 if env_vars:
65 env = os.environ.copy()
66 env.update(env_vars)
67 else:
68 env = None
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000069 out, err = subprocess.Popen(
Georg Brandl09a7c722012-02-20 21:31:46 +010070 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000071 ).communicate()
Victor Stinner534db4e2010-04-23 20:33:55 +000072 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000073
74 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000075 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000076 cmds_after_breakpoint=None,
77 import_site=False):
78 '''
79 Run 'python -c SOURCE' under gdb with a breakpoint.
80
81 Support injecting commands after the breakpoint is reached
82
83 Returns the stdout from gdb
84
85 cmds_after_breakpoint: if provided, a list of strings: gdb commands
86 '''
87 # We use "set breakpoint pending yes" to avoid blocking with a:
88 # Function "foo" not defined.
89 # Make breakpoint pending on future shared library load? (y or [n])
90 # error, which typically happens python is dynamically linked (the
91 # breakpoints of interest are to be found in the shared library)
92 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +000093 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000094 # emitted to stderr each time, alas.
95
96 # Initially I had "--eval-command=continue" here, but removed it to
97 # avoid repeated print breakpoints when traversing hierarchical data
98 # structures
99
100 # Generate a list of commands in gdb's language:
101 commands = ['set breakpoint pending yes',
102 'break %s' % breakpoint,
103 'run']
104 if cmds_after_breakpoint:
105 commands += cmds_after_breakpoint
106 else:
107 commands += ['backtrace']
108
109 # print commands
110
111 # Use "commands" to generate the arguments with which to invoke "gdb":
112 args = ["gdb", "--batch"]
113 args += ['--eval-command=%s' % cmd for cmd in commands]
114 args += ["--args",
115 sys.executable]
116
117 if not import_site:
118 # -S suppresses the default 'import site'
119 args += ["-S"]
120
121 if source:
122 args += ["-c", source]
123 elif script:
124 args += [script]
125
126 # print args
127 # print ' '.join(args)
128
129 # Use "args" to invoke gdb, capturing stdout, stderr:
Georg Brandl09a7c722012-02-20 21:31:46 +0100130 out, err = self.run_gdb(*args, PYTHONHASHSEED='0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000131
132 # Ignore some noise on stderr due to the pending breakpoint:
133 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000134 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
135 err = err.replace("warning: Unable to find libthread_db matching"
136 " inferior's thread library, thread debugging will"
137 " not be available.\n",
138 '')
Jesus Ceacee36552011-03-16 01:33:16 +0100139 err = err.replace("warning: Cannot initialize thread debugging"
140 " library: Debugger service failed\n",
141 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000142
143 # Ensure no unexpected error messages:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000144 self.assertEqual(err, '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000145
146 return out
147
148 def get_gdb_repr(self, source,
149 cmds_after_breakpoint=None,
150 import_site=False):
151 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000152 # run "python -c'id(DATA)'" under gdb with a breakpoint on
153 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000154 # parameter, and verify that the gdb displays the same string
155 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000156 # Verify that the gdb displays the expected string
157 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000158 # For a nested structure, the first time we hit the breakpoint will
159 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000160 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000161 cmds_after_breakpoint=cmds_after_breakpoint,
162 import_site=import_site)
163 # gdb can insert additional '\n' and space characters in various places
164 # in its output, depending on the width of the terminal it's connected
165 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000166 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 +0000167 gdb_output, re.DOTALL)
168 if not m:
169 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
170 return m.group(1), gdb_output
171
172 def assertEndsWith(self, actual, exp_end):
173 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000174 self.assertTrue(actual.endswith(exp_end),
175 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000176
177 def assertMultilineMatches(self, actual, pattern):
178 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000179 if not m:
180 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000181
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000182 def get_sample_script(self):
183 return findfile('gdb_sample.py')
184
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000185class PrettyPrintTests(DebuggerTests):
186 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000187 gdb_output = self.get_stack_trace('id(42)')
188 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000189
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000190 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000191 # Ensure that gdb's rendering of the value in a debugged process
192 # matches repr(value) in this process:
Victor Stinner150016f2010-05-19 23:04:56 +0000193 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000195 if not exp_repr:
196 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000197 self.assertEqual(gdb_repr, exp_repr,
198 ('%r did not equal expected %r; full output was:\n%s'
199 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000200
201 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000202 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203 self.assertGdbRepr(42)
204 self.assertGdbRepr(0)
205 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000206 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000207 self.assertGdbRepr(-1000000000000000)
208
209 def test_singletons(self):
210 'Verify the pretty-printing of True, False and None'
211 self.assertGdbRepr(True)
212 self.assertGdbRepr(False)
213 self.assertGdbRepr(None)
214
215 def test_dicts(self):
216 'Verify the pretty-printing of dictionaries'
217 self.assertGdbRepr({})
218 self.assertGdbRepr({'foo': 'bar'})
Georg Brandl09a7c722012-02-20 21:31:46 +0100219 self.assertGdbRepr({'foo': 'bar', 'douglas': 42},
220 "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000221
222 def test_lists(self):
223 'Verify the pretty-printing of lists'
224 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000225 self.assertGdbRepr(list(range(5)))
226
227 def test_bytes(self):
228 'Verify the pretty-printing of bytes'
229 self.assertGdbRepr(b'')
230 self.assertGdbRepr(b'And now for something hopefully the same')
231 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
232 self.assertGdbRepr(b'this is a tab:\t'
233 b' this is a slash-N:\n'
234 b' this is a slash-R:\r'
235 )
236
237 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
238
239 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000240
241 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000242 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000243 encoding = locale.getpreferredencoding()
244 def check_repr(text):
245 try:
246 text.encode(encoding)
247 printable = True
248 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000249 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000250 else:
251 self.assertGdbRepr(text)
252
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000253 self.assertGdbRepr('')
254 self.assertGdbRepr('And now for something hopefully the same')
255 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000256
257 # Test printing a single character:
258 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000259 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000260
261 # Test printing a Japanese unicode string
262 # (I believe this reads "mojibake", using 3 characters from the CJK
263 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000264 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000265
266 # Test a character outside the BMP:
267 # U+1D121 MUSICAL SYMBOL C CLEF
268 # This is:
269 # UTF-8: 0xF0 0x9D 0x84 0xA1
270 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000271 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000272
273 def test_tuples(self):
274 'Verify the pretty-printing of tuples'
275 self.assertGdbRepr(tuple())
276 self.assertGdbRepr((1,), '(1,)')
277 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000278
279 def test_sets(self):
280 'Verify the pretty-printing of sets'
281 self.assertGdbRepr(set())
Georg Brandl09a7c722012-02-20 21:31:46 +0100282 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
283 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000284
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000285 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000286 # which happens on deletion:
287 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
288s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000289id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000290 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000291
292 def test_frozensets(self):
293 'Verify the pretty-printing of frozensets'
294 self.assertGdbRepr(frozenset())
Georg Brandl09a7c722012-02-20 21:31:46 +0100295 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
296 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000297
298 def test_exceptions(self):
299 # Test a RuntimeError
300 gdb_repr, gdb_output = self.get_gdb_repr('''
301try:
302 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000303except RuntimeError as e:
304 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000305''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000306 self.assertEqual(gdb_repr,
307 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000308
309
310 # Test division by zero:
311 gdb_repr, gdb_output = self.get_gdb_repr('''
312try:
313 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000314except ZeroDivisionError as e:
315 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000316''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000317 self.assertEqual(gdb_repr,
318 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000319
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000320 def test_modern_class(self):
321 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000322 gdb_repr, gdb_output = self.get_gdb_repr('''
323class Foo:
324 pass
325foo = Foo()
326foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000327id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100328 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000329 self.assertTrue(m,
330 msg='Unexpected new-style class rendering %r' % gdb_repr)
331
332 def test_subclassing_list(self):
333 'Verify the pretty-printing of an instance of a list subclass'
334 gdb_repr, gdb_output = self.get_gdb_repr('''
335class Foo(list):
336 pass
337foo = Foo()
338foo += [1, 2, 3]
339foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000340id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100341 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 +0000342
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000343 self.assertTrue(m,
344 msg='Unexpected new-style class rendering %r' % gdb_repr)
345
346 def test_subclassing_tuple(self):
347 'Verify the pretty-printing of an instance of a tuple subclass'
348 # This should exercise the negative tp_dictoffset code in the
349 # new-style class support
350 gdb_repr, gdb_output = self.get_gdb_repr('''
351class Foo(tuple):
352 pass
353foo = Foo((1, 2, 3))
354foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000355id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100356 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 +0000357
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000358 self.assertTrue(m,
359 msg='Unexpected new-style class rendering %r' % gdb_repr)
360
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000361 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000362 '''Run Python under gdb, corrupting variables in the inferior process
363 immediately before taking a backtrace.
364
365 Verify that the variable's representation is the expected failsafe
366 representation'''
367 if corruption:
368 cmds_after_breakpoint=[corruption, 'backtrace']
369 else:
370 cmds_after_breakpoint=['backtrace']
371
372 gdb_repr, gdb_output = \
373 self.get_gdb_repr(source,
374 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000375 if exprepr:
376 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000377 # gdb managed to print the value in spite of the corruption;
378 # this is good (see http://bugs.python.org/issue8330)
379 return
380
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000381 # Match anything for the type name; 0xDEADBEEF could point to
382 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100383 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000384
385 m = re.match(pattern, gdb_repr)
386 if not m:
387 self.fail('Unexpected gdb representation: %r\n%s' % \
388 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000389
390 def test_NULL_ptr(self):
391 'Ensure that a NULL PyObject* is handled gracefully'
392 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000393 self.get_gdb_repr('id(42)',
394 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000395 'backtrace'])
396 )
397
Ezio Melottib3aedd42010-11-20 19:04:17 +0000398 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000399
400 def test_NULL_ob_type(self):
401 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000402 self.assertSane('id(42)',
403 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404
405 def test_corrupt_ob_type(self):
406 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000407 self.assertSane('id(42)',
408 'set v->ob_type=0xDEADBEEF',
409 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000410
411 def test_corrupt_tp_flags(self):
412 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000413 self.assertSane('id(42)',
414 'set v->ob_type->tp_flags=0x0',
415 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000416
417 def test_corrupt_tp_name(self):
418 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000419 self.assertSane('id(42)',
420 'set v->ob_type->tp_name=0xDEADBEEF',
421 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000422
423 def test_builtins_help(self):
424 'Ensure that the new-style class _Helper in site.py can be handled'
425 # (this was the issue causing tracebacks in
426 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000427 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000428
Antoine Pitrou4d098732011-11-26 01:42:03 +0100429 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000430 self.assertTrue(m,
431 msg='Unexpected rendering %r' % gdb_repr)
432
433 def test_selfreferential_list(self):
434 '''Ensure that a reference loop involving a list doesn't lead proxyval
435 into an infinite loop:'''
436 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000437 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; 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 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000441 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000442 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000443
444 def test_selfreferential_dict(self):
445 '''Ensure that a reference loop involving a dict doesn't lead proxyval
446 into an infinite loop:'''
447 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000448 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000449
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000451
452 def test_selfreferential_old_style_instance(self):
453 gdb_repr, gdb_output = \
454 self.get_gdb_repr('''
455class Foo:
456 pass
457foo = Foo()
458foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000459id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100460 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000461 gdb_repr),
462 'Unexpected gdb representation: %r\n%s' % \
463 (gdb_repr, gdb_output))
464
465 def test_selfreferential_new_style_instance(self):
466 gdb_repr, gdb_output = \
467 self.get_gdb_repr('''
468class Foo(object):
469 pass
470foo = Foo()
471foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000472id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100473 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000474 gdb_repr),
475 'Unexpected gdb representation: %r\n%s' % \
476 (gdb_repr, gdb_output))
477
478 gdb_repr, gdb_output = \
479 self.get_gdb_repr('''
480class Foo(object):
481 pass
482a = Foo()
483b = Foo()
484a.an_attr = b
485b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000486id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100487 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 +0000488 gdb_repr),
489 'Unexpected gdb representation: %r\n%s' % \
490 (gdb_repr, gdb_output))
491
492 def test_truncation(self):
493 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000494 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000495 self.assertEqual(gdb_repr,
496 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
497 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
498 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
499 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
500 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
501 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
502 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
503 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
504 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
505 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
506 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
507 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
508 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
509 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
510 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
511 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
512 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
513 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
514 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
515 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
516 "224, 225, 226...(truncated)")
517 self.assertEqual(len(gdb_repr),
518 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000519
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000520 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000521 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100522 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 +0000523 gdb_repr),
524 'Unexpected gdb representation: %r\n%s' % \
525 (gdb_repr, gdb_output))
526
527 def test_frames(self):
528 gdb_output = self.get_stack_trace('''
529def foo(a, b, c):
530 pass
531
532foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000533id(foo.__code__)''',
534 breakpoint='builtin_id',
535 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000536 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100537 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 +0000538 gdb_output,
539 re.DOTALL),
540 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
541
Victor Stinnerd2084162011-12-19 13:42:24 +0100542@unittest.skipIf(python_is_optimized(),
543 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000544class PyListTests(DebuggerTests):
545 def assertListing(self, expected, actual):
546 self.assertEndsWith(actual, expected)
547
548 def test_basic_command(self):
549 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000550 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000551 cmds_after_breakpoint=['py-list'])
552
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000553 self.assertListing(' 5 \n'
554 ' 6 def bar(a, b, c):\n'
555 ' 7 baz(a, b, c)\n'
556 ' 8 \n'
557 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000558 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000559 ' 11 \n'
560 ' 12 foo(1, 2, 3)\n',
561 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000562
563 def test_one_abs_arg(self):
564 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000565 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000566 cmds_after_breakpoint=['py-list 9'])
567
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000568 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000569 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000570 ' 11 \n'
571 ' 12 foo(1, 2, 3)\n',
572 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000573
574 def test_two_abs_args(self):
575 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000576 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000577 cmds_after_breakpoint=['py-list 1,3'])
578
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000579 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
580 ' 2 \n'
581 ' 3 def foo(a, b, c):\n',
582 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000583
584class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000585 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100586 @unittest.skipIf(python_is_optimized(),
587 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000588 def test_pyup_command(self):
589 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000590 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000591 cmds_after_breakpoint=['py-up'])
592 self.assertMultilineMatches(bt,
593 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100594#[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 +0000595 baz\(a, b, c\)
596$''')
597
Victor Stinner50eb60e2010-04-20 22:32:07 +0000598 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000599 def test_down_at_bottom(self):
600 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000601 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000602 cmds_after_breakpoint=['py-down'])
603 self.assertEndsWith(bt,
604 'Unable to find a newer python frame\n')
605
Victor Stinner50eb60e2010-04-20 22:32:07 +0000606 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000607 def test_up_at_top(self):
608 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000609 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000610 cmds_after_breakpoint=['py-up'] * 4)
611 self.assertEndsWith(bt,
612 'Unable to find an older python frame\n')
613
Victor Stinner50eb60e2010-04-20 22:32:07 +0000614 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100615 @unittest.skipIf(python_is_optimized(),
616 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000617 def test_up_then_down(self):
618 'Verify "py-up" followed by "py-down"'
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', 'py-down'])
621 self.assertMultilineMatches(bt,
622 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100623#[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 +0000624 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100625#[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 +0000626 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000627$''')
628
629class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100630 @unittest.skipIf(python_is_optimized(),
631 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200632 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000633 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000634 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000635 cmds_after_breakpoint=['py-bt'])
636 self.assertMultilineMatches(bt,
637 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200638Traceback \(most recent call first\):
639 File ".*gdb_sample.py", line 10, in baz
640 id\(42\)
641 File ".*gdb_sample.py", line 7, in bar
642 baz\(a, b, c\)
643 File ".*gdb_sample.py", line 4, in foo
644 bar\(a, b, c\)
645 File ".*gdb_sample.py", line 12, in <module>
646 foo\(1, 2, 3\)
647''')
648
Victor Stinnerd2084162011-12-19 13:42:24 +0100649 @unittest.skipIf(python_is_optimized(),
650 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200651 def test_bt_full(self):
652 'Verify that the "py-bt-full" command works'
653 bt = self.get_stack_trace(script=self.get_sample_script(),
654 cmds_after_breakpoint=['py-bt-full'])
655 self.assertMultilineMatches(bt,
656 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100657#[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 +0000658 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100659#[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 +0000660 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100661#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100662 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000663''')
664
665class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100666 @unittest.skipIf(python_is_optimized(),
667 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000668 def test_basic_command(self):
669 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000670 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000671 cmds_after_breakpoint=['py-print args'])
672 self.assertMultilineMatches(bt,
673 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
674
Vinay Sajip2549f872012-01-04 12:07:30 +0000675 @unittest.skipIf(python_is_optimized(),
676 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000677 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000679 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000680 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
681 self.assertMultilineMatches(bt,
682 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
683
Victor Stinnerd2084162011-12-19 13:42:24 +0100684 @unittest.skipIf(python_is_optimized(),
685 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000686 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000687 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000688 cmds_after_breakpoint=['py-print __name__'])
689 self.assertMultilineMatches(bt,
690 r".*\nglobal '__name__' = '__main__'\n.*")
691
Victor Stinnerd2084162011-12-19 13:42:24 +0100692 @unittest.skipIf(python_is_optimized(),
693 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000694 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000695 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 cmds_after_breakpoint=['py-print len'])
697 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100698 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000699
700class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100701 @unittest.skipIf(python_is_optimized(),
702 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000703 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000704 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000705 cmds_after_breakpoint=['py-locals'])
706 self.assertMultilineMatches(bt,
707 r".*\nargs = \(1, 2, 3\)\n.*")
708
Victor Stinner50eb60e2010-04-20 22:32:07 +0000709 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000710 @unittest.skipIf(python_is_optimized(),
711 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000712 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000713 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000714 cmds_after_breakpoint=['py-up', 'py-locals'])
715 self.assertMultilineMatches(bt,
716 r".*\na = 1\nb = 2\nc = 3\n.*")
717
718def test_main():
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000719 run_unittest(PrettyPrintTests,
720 PyListTests,
721 StackNavigationTests,
722 PyBtTests,
723 PyPrintTests,
724 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000725 )
726
727if __name__ == "__main__":
728 test_main()