blob: fd1275c38a73ccd523e0359e7f6bd6e44c6d66e2 [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
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100039# Verify that "gdb" can load our custom hooks
40p = subprocess.Popen(["gdb", "--batch", cmd,
41 "--args", sys.executable],
42 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
43__, gdbpy_errors = p.communicate()
44if b"auto-loading has been declined" in gdbpy_errors:
45 msg = "gdb security settings prevent use of custom hooks: %s"
46 raise unittest.SkipTest(msg % gdbpy_errors)
47
Victor Stinner50eb60e2010-04-20 22:32:07 +000048def gdb_has_frame_select():
49 # Does this build of gdb have gdb.Frame.select ?
50 cmd = "--eval-command=python print(dir(gdb.Frame))"
51 p = subprocess.Popen(["gdb", "--batch", cmd],
52 stdout=subprocess.PIPE)
53 stdout, _ = p.communicate()
54 m = re.match(br'.*\[(.*)\].*', stdout)
55 if not m:
56 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
57 gdb_frame_dir = m.group(1).split(b', ')
58 return b"'select'" in gdb_frame_dir
59
60HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000061
Martin v. Löwis5ae68102010-04-21 22:38:42 +000062BREAKPOINT_FN='builtin_id'
63
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000064class DebuggerTests(unittest.TestCase):
65
66 """Test that the debugger can debug Python."""
67
Georg Brandl09a7c722012-02-20 21:31:46 +010068 def run_gdb(self, *args, **env_vars):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000069 """Runs gdb with the command line given by *args.
70
71 Returns its stdout, stderr
72 """
Georg Brandl09a7c722012-02-20 21:31:46 +010073 if env_vars:
74 env = os.environ.copy()
75 env.update(env_vars)
76 else:
77 env = None
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000078 out, err = subprocess.Popen(
Georg Brandl09a7c722012-02-20 21:31:46 +010079 args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000080 ).communicate()
Victor Stinner534db4e2010-04-23 20:33:55 +000081 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000082
83 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000084 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000085 cmds_after_breakpoint=None,
86 import_site=False):
87 '''
88 Run 'python -c SOURCE' under gdb with a breakpoint.
89
90 Support injecting commands after the breakpoint is reached
91
92 Returns the stdout from gdb
93
94 cmds_after_breakpoint: if provided, a list of strings: gdb commands
95 '''
96 # We use "set breakpoint pending yes" to avoid blocking with a:
97 # Function "foo" not defined.
98 # Make breakpoint pending on future shared library load? (y or [n])
99 # error, which typically happens python is dynamically linked (the
100 # breakpoints of interest are to be found in the shared library)
101 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000102 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000103 # emitted to stderr each time, alas.
104
105 # Initially I had "--eval-command=continue" here, but removed it to
106 # avoid repeated print breakpoints when traversing hierarchical data
107 # structures
108
109 # Generate a list of commands in gdb's language:
110 commands = ['set breakpoint pending yes',
111 'break %s' % breakpoint,
112 'run']
113 if cmds_after_breakpoint:
114 commands += cmds_after_breakpoint
115 else:
116 commands += ['backtrace']
117
118 # print commands
119
120 # Use "commands" to generate the arguments with which to invoke "gdb":
121 args = ["gdb", "--batch"]
122 args += ['--eval-command=%s' % cmd for cmd in commands]
123 args += ["--args",
124 sys.executable]
125
126 if not import_site:
127 # -S suppresses the default 'import site'
128 args += ["-S"]
129
130 if source:
131 args += ["-c", source]
132 elif script:
133 args += [script]
134
135 # print args
136 # print ' '.join(args)
137
138 # Use "args" to invoke gdb, capturing stdout, stderr:
Georg Brandl09a7c722012-02-20 21:31:46 +0100139 out, err = self.run_gdb(*args, PYTHONHASHSEED='0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000140
141 # Ignore some noise on stderr due to the pending breakpoint:
142 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000143 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
144 err = err.replace("warning: Unable to find libthread_db matching"
145 " inferior's thread library, thread debugging will"
146 " not be available.\n",
147 '')
Jesus Ceacee36552011-03-16 01:33:16 +0100148 err = err.replace("warning: Cannot initialize thread debugging"
149 " library: Debugger service failed\n",
150 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000151
152 # Ensure no unexpected error messages:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000153 self.assertEqual(err, '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000154
155 return out
156
157 def get_gdb_repr(self, source,
158 cmds_after_breakpoint=None,
159 import_site=False):
160 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000161 # run "python -c'id(DATA)'" under gdb with a breakpoint on
162 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000163 # parameter, and verify that the gdb displays the same string
164 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000165 # Verify that the gdb displays the expected string
166 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000167 # For a nested structure, the first time we hit the breakpoint will
168 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000169 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000170 cmds_after_breakpoint=cmds_after_breakpoint,
171 import_site=import_site)
172 # gdb can insert additional '\n' and space characters in various places
173 # in its output, depending on the width of the terminal it's connected
174 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000175 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 +0000176 gdb_output, re.DOTALL)
177 if not m:
178 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
179 return m.group(1), gdb_output
180
181 def assertEndsWith(self, actual, exp_end):
182 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000183 self.assertTrue(actual.endswith(exp_end),
184 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000185
186 def assertMultilineMatches(self, actual, pattern):
187 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000188 if not m:
189 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000190
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000191 def get_sample_script(self):
192 return findfile('gdb_sample.py')
193
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194class PrettyPrintTests(DebuggerTests):
195 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000196 gdb_output = self.get_stack_trace('id(42)')
197 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000198
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000199 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000200 # Ensure that gdb's rendering of the value in a debugged process
201 # matches repr(value) in this process:
Victor Stinner150016f2010-05-19 23:04:56 +0000202 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000204 if not exp_repr:
205 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000206 self.assertEqual(gdb_repr, exp_repr,
207 ('%r did not equal expected %r; full output was:\n%s'
208 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000209
210 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000211 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000212 self.assertGdbRepr(42)
213 self.assertGdbRepr(0)
214 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000215 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000216 self.assertGdbRepr(-1000000000000000)
217
218 def test_singletons(self):
219 'Verify the pretty-printing of True, False and None'
220 self.assertGdbRepr(True)
221 self.assertGdbRepr(False)
222 self.assertGdbRepr(None)
223
224 def test_dicts(self):
225 'Verify the pretty-printing of dictionaries'
226 self.assertGdbRepr({})
227 self.assertGdbRepr({'foo': 'bar'})
Georg Brandl09a7c722012-02-20 21:31:46 +0100228 self.assertGdbRepr({'foo': 'bar', 'douglas': 42},
229 "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000230
231 def test_lists(self):
232 'Verify the pretty-printing of lists'
233 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000234 self.assertGdbRepr(list(range(5)))
235
236 def test_bytes(self):
237 'Verify the pretty-printing of bytes'
238 self.assertGdbRepr(b'')
239 self.assertGdbRepr(b'And now for something hopefully the same')
240 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
241 self.assertGdbRepr(b'this is a tab:\t'
242 b' this is a slash-N:\n'
243 b' this is a slash-R:\r'
244 )
245
246 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
247
248 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000249
250 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000251 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000252 encoding = locale.getpreferredencoding()
253 def check_repr(text):
254 try:
255 text.encode(encoding)
256 printable = True
257 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000258 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000259 else:
260 self.assertGdbRepr(text)
261
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262 self.assertGdbRepr('')
263 self.assertGdbRepr('And now for something hopefully the same')
264 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000265
266 # Test printing a single character:
267 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000268 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000269
270 # Test printing a Japanese unicode string
271 # (I believe this reads "mojibake", using 3 characters from the CJK
272 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000273 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274
275 # Test a character outside the BMP:
276 # U+1D121 MUSICAL SYMBOL C CLEF
277 # This is:
278 # UTF-8: 0xF0 0x9D 0x84 0xA1
279 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000280 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000281
282 def test_tuples(self):
283 'Verify the pretty-printing of tuples'
284 self.assertGdbRepr(tuple())
285 self.assertGdbRepr((1,), '(1,)')
286 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000287
288 def test_sets(self):
289 'Verify the pretty-printing of sets'
290 self.assertGdbRepr(set())
Georg Brandl09a7c722012-02-20 21:31:46 +0100291 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
292 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000293
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000294 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000295 # which happens on deletion:
296 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
297s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000298id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000299 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000300
301 def test_frozensets(self):
302 'Verify the pretty-printing of frozensets'
303 self.assertGdbRepr(frozenset())
Georg Brandl09a7c722012-02-20 21:31:46 +0100304 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
305 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000306
307 def test_exceptions(self):
308 # Test a RuntimeError
309 gdb_repr, gdb_output = self.get_gdb_repr('''
310try:
311 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000312except RuntimeError as e:
313 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000314''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000315 self.assertEqual(gdb_repr,
316 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000317
318
319 # Test division by zero:
320 gdb_repr, gdb_output = self.get_gdb_repr('''
321try:
322 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000323except ZeroDivisionError as e:
324 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000325''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000326 self.assertEqual(gdb_repr,
327 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000328
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000329 def test_modern_class(self):
330 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000331 gdb_repr, gdb_output = self.get_gdb_repr('''
332class Foo:
333 pass
334foo = Foo()
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)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000338 self.assertTrue(m,
339 msg='Unexpected new-style class rendering %r' % gdb_repr)
340
341 def test_subclassing_list(self):
342 'Verify the pretty-printing of an instance of a list subclass'
343 gdb_repr, gdb_output = self.get_gdb_repr('''
344class Foo(list):
345 pass
346foo = Foo()
347foo += [1, 2, 3]
348foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000349id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100350 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 +0000351
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000352 self.assertTrue(m,
353 msg='Unexpected new-style class rendering %r' % gdb_repr)
354
355 def test_subclassing_tuple(self):
356 'Verify the pretty-printing of an instance of a tuple subclass'
357 # This should exercise the negative tp_dictoffset code in the
358 # new-style class support
359 gdb_repr, gdb_output = self.get_gdb_repr('''
360class Foo(tuple):
361 pass
362foo = Foo((1, 2, 3))
363foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000364id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100365 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 +0000366
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000367 self.assertTrue(m,
368 msg='Unexpected new-style class rendering %r' % gdb_repr)
369
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000370 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000371 '''Run Python under gdb, corrupting variables in the inferior process
372 immediately before taking a backtrace.
373
374 Verify that the variable's representation is the expected failsafe
375 representation'''
376 if corruption:
377 cmds_after_breakpoint=[corruption, 'backtrace']
378 else:
379 cmds_after_breakpoint=['backtrace']
380
381 gdb_repr, gdb_output = \
382 self.get_gdb_repr(source,
383 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000384 if exprepr:
385 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000386 # gdb managed to print the value in spite of the corruption;
387 # this is good (see http://bugs.python.org/issue8330)
388 return
389
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000390 # Match anything for the type name; 0xDEADBEEF could point to
391 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100392 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000393
394 m = re.match(pattern, gdb_repr)
395 if not m:
396 self.fail('Unexpected gdb representation: %r\n%s' % \
397 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000398
399 def test_NULL_ptr(self):
400 'Ensure that a NULL PyObject* is handled gracefully'
401 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000402 self.get_gdb_repr('id(42)',
403 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404 'backtrace'])
405 )
406
Ezio Melottib3aedd42010-11-20 19:04:17 +0000407 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000408
409 def test_NULL_ob_type(self):
410 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000411 self.assertSane('id(42)',
412 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000413
414 def test_corrupt_ob_type(self):
415 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000416 self.assertSane('id(42)',
417 'set v->ob_type=0xDEADBEEF',
418 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000419
420 def test_corrupt_tp_flags(self):
421 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000422 self.assertSane('id(42)',
423 'set v->ob_type->tp_flags=0x0',
424 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000425
426 def test_corrupt_tp_name(self):
427 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000428 self.assertSane('id(42)',
429 'set v->ob_type->tp_name=0xDEADBEEF',
430 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000431
432 def test_builtins_help(self):
433 'Ensure that the new-style class _Helper in site.py can be handled'
434 # (this was the issue causing tracebacks in
435 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000436 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000437
Antoine Pitrou4d098732011-11-26 01:42:03 +0100438 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000439 self.assertTrue(m,
440 msg='Unexpected rendering %r' % gdb_repr)
441
442 def test_selfreferential_list(self):
443 '''Ensure that a reference loop involving a list doesn't lead proxyval
444 into an infinite loop:'''
445 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000446 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000447 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000448
449 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000450 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000451 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000452
453 def test_selfreferential_dict(self):
454 '''Ensure that a reference loop involving a dict doesn't lead proxyval
455 into an infinite loop:'''
456 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000457 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000458
Ezio Melottib3aedd42010-11-20 19:04:17 +0000459 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000460
461 def test_selfreferential_old_style_instance(self):
462 gdb_repr, gdb_output = \
463 self.get_gdb_repr('''
464class Foo:
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 def test_selfreferential_new_style_instance(self):
475 gdb_repr, gdb_output = \
476 self.get_gdb_repr('''
477class Foo(object):
478 pass
479foo = Foo()
480foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000481id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100482 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000483 gdb_repr),
484 'Unexpected gdb representation: %r\n%s' % \
485 (gdb_repr, gdb_output))
486
487 gdb_repr, gdb_output = \
488 self.get_gdb_repr('''
489class Foo(object):
490 pass
491a = Foo()
492b = Foo()
493a.an_attr = b
494b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000495id(a)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100496 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 +0000497 gdb_repr),
498 'Unexpected gdb representation: %r\n%s' % \
499 (gdb_repr, gdb_output))
500
501 def test_truncation(self):
502 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000503 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000504 self.assertEqual(gdb_repr,
505 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
506 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
507 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
508 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
509 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
510 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
511 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
512 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
513 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
514 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
515 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
516 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
517 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
518 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
519 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
520 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
521 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
522 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
523 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
524 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
525 "224, 225, 226...(truncated)")
526 self.assertEqual(len(gdb_repr),
527 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000528
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000529 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000530 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100531 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 +0000532 gdb_repr),
533 'Unexpected gdb representation: %r\n%s' % \
534 (gdb_repr, gdb_output))
535
536 def test_frames(self):
537 gdb_output = self.get_stack_trace('''
538def foo(a, b, c):
539 pass
540
541foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000542id(foo.__code__)''',
543 breakpoint='builtin_id',
544 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000545 )
Antoine Pitrou4d098732011-11-26 01:42:03 +0100546 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 +0000547 gdb_output,
548 re.DOTALL),
549 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
550
Victor Stinnerd2084162011-12-19 13:42:24 +0100551@unittest.skipIf(python_is_optimized(),
552 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000553class PyListTests(DebuggerTests):
554 def assertListing(self, expected, actual):
555 self.assertEndsWith(actual, expected)
556
557 def test_basic_command(self):
558 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000559 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000560 cmds_after_breakpoint=['py-list'])
561
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000562 self.assertListing(' 5 \n'
563 ' 6 def bar(a, b, c):\n'
564 ' 7 baz(a, b, c)\n'
565 ' 8 \n'
566 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000567 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000568 ' 11 \n'
569 ' 12 foo(1, 2, 3)\n',
570 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000571
572 def test_one_abs_arg(self):
573 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000574 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000575 cmds_after_breakpoint=['py-list 9'])
576
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000577 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000578 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000579 ' 11 \n'
580 ' 12 foo(1, 2, 3)\n',
581 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000582
583 def test_two_abs_args(self):
584 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000585 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000586 cmds_after_breakpoint=['py-list 1,3'])
587
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000588 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
589 ' 2 \n'
590 ' 3 def foo(a, b, c):\n',
591 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000592
593class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000594 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100595 @unittest.skipIf(python_is_optimized(),
596 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000597 def test_pyup_command(self):
598 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000599 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000600 cmds_after_breakpoint=['py-up'])
601 self.assertMultilineMatches(bt,
602 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100603#[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 +0000604 baz\(a, b, c\)
605$''')
606
Victor Stinner50eb60e2010-04-20 22:32:07 +0000607 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000608 def test_down_at_bottom(self):
609 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000610 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000611 cmds_after_breakpoint=['py-down'])
612 self.assertEndsWith(bt,
613 'Unable to find a newer python frame\n')
614
Victor Stinner50eb60e2010-04-20 22:32:07 +0000615 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000616 def test_up_at_top(self):
617 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000618 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000619 cmds_after_breakpoint=['py-up'] * 4)
620 self.assertEndsWith(bt,
621 'Unable to find an older python frame\n')
622
Victor Stinner50eb60e2010-04-20 22:32:07 +0000623 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100624 @unittest.skipIf(python_is_optimized(),
625 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000626 def test_up_then_down(self):
627 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000628 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000629 cmds_after_breakpoint=['py-up', 'py-down'])
630 self.assertMultilineMatches(bt,
631 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100632#[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 +0000633 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100634#[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 +0000635 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000636$''')
637
638class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100639 @unittest.skipIf(python_is_optimized(),
640 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200641 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000642 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000643 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000644 cmds_after_breakpoint=['py-bt'])
645 self.assertMultilineMatches(bt,
646 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200647Traceback \(most recent call first\):
648 File ".*gdb_sample.py", line 10, in baz
649 id\(42\)
650 File ".*gdb_sample.py", line 7, in bar
651 baz\(a, b, c\)
652 File ".*gdb_sample.py", line 4, in foo
653 bar\(a, b, c\)
654 File ".*gdb_sample.py", line 12, in <module>
655 foo\(1, 2, 3\)
656''')
657
Victor Stinnerd2084162011-12-19 13:42:24 +0100658 @unittest.skipIf(python_is_optimized(),
659 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200660 def test_bt_full(self):
661 'Verify that the "py-bt-full" command works'
662 bt = self.get_stack_trace(script=self.get_sample_script(),
663 cmds_after_breakpoint=['py-bt-full'])
664 self.assertMultilineMatches(bt,
665 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100666#[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 +0000667 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100668#[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 +0000669 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100670#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100671 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000672''')
673
674class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100675 @unittest.skipIf(python_is_optimized(),
676 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000677 def test_basic_command(self):
678 'Verify that the "py-print" command works'
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-print args'])
681 self.assertMultilineMatches(bt,
682 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
683
Vinay Sajip2549f872012-01-04 12:07:30 +0000684 @unittest.skipIf(python_is_optimized(),
685 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000686 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000687 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000688 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000689 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
690 self.assertMultilineMatches(bt,
691 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
692
Victor Stinnerd2084162011-12-19 13:42:24 +0100693 @unittest.skipIf(python_is_optimized(),
694 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000695 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000696 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000697 cmds_after_breakpoint=['py-print __name__'])
698 self.assertMultilineMatches(bt,
699 r".*\nglobal '__name__' = '__main__'\n.*")
700
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_printing_builtin(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-print len'])
706 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100707 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000708
709class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100710 @unittest.skipIf(python_is_optimized(),
711 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000712 def test_basic_command(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-locals'])
715 self.assertMultilineMatches(bt,
716 r".*\nargs = \(1, 2, 3\)\n.*")
717
Victor Stinner50eb60e2010-04-20 22:32:07 +0000718 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000719 @unittest.skipIf(python_is_optimized(),
720 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000721 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000722 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000723 cmds_after_breakpoint=['py-up', 'py-locals'])
724 self.assertMultilineMatches(bt,
725 r".*\na = 1\nb = 2\nc = 3\n.*")
726
727def test_main():
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000728 run_unittest(PrettyPrintTests,
729 PyListTests,
730 StackNavigationTests,
731 PyBtTests,
732 PyPrintTests,
733 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000734 )
735
736if __name__ == "__main__":
737 test_main()