blob: 6d96550a9bc892ebae77df77b4e320b0d8683592 [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")
R David Murrayf9333022012-10-27 13:22:41 -040022gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
23gdb_major_version = int(gdb_version_number.group(1))
24gdb_minor_version = int(gdb_version_number.group(2))
25if gdb_major_version < 7:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000026 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
Antoine Pitrou6a45e9d2010-04-11 22:47:34 +000027 " Saw:\n" + gdb_version.decode('ascii', 'replace'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000028
R David Murrayf9333022012-10-27 13:22:41 -040029# Location of custom hooks file in a repository checkout.
30checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
31 'python-gdb.py')
32
33def run_gdb(*args, **env_vars):
34 """Runs gdb in --batch mode with the additional arguments given by *args.
35
36 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
37 """
38 if env_vars:
39 env = os.environ.copy()
40 env.update(env_vars)
41 else:
42 env = None
43 base_cmd = ('gdb', '--batch')
44 if (gdb_major_version, gdb_minor_version) >= (7, 4):
45 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
46 out, err = subprocess.Popen(base_cmd + args,
47 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
48 ).communicate()
49 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
50
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000051# Verify that "gdb" was built with the embedded python support enabled:
R David Murrayf9333022012-10-27 13:22:41 -040052gdbpy_version, _ = run_gdb("--eval-command=python import sys; print sys.version_info")
53if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000054 raise unittest.SkipTest("gdb not built with embedded python support")
55
R David Murrayf9333022012-10-27 13:22:41 -040056# Verify that "gdb" can load our custom hooks. In theory this should never
57# fail, but we don't handle the case of the hooks file not existing if the
58# tests are run from an installed Python (we'll produce failures in that case).
59cmd = ['--args', sys.executable]
60_, gdbpy_errors = run_gdb('--args', sys.executable)
61if "auto-loading has been declined" in gdbpy_errors:
62 msg = "gdb security settings prevent use of custom hooks: "
63 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100064
Victor Stinner50eb60e2010-04-20 22:32:07 +000065def gdb_has_frame_select():
66 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -040067 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
68 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +000069 if not m:
70 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -040071 gdb_frame_dir = m.group(1).split(', ')
72 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +000073
74HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000075
Martin v. Löwis5ae68102010-04-21 22:38:42 +000076BREAKPOINT_FN='builtin_id'
77
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000078class DebuggerTests(unittest.TestCase):
79
80 """Test that the debugger can debug Python."""
81
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000082 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +000083 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000084 cmds_after_breakpoint=None,
85 import_site=False):
86 '''
87 Run 'python -c SOURCE' under gdb with a breakpoint.
88
89 Support injecting commands after the breakpoint is reached
90
91 Returns the stdout from gdb
92
93 cmds_after_breakpoint: if provided, a list of strings: gdb commands
94 '''
95 # We use "set breakpoint pending yes" to avoid blocking with a:
96 # Function "foo" not defined.
97 # Make breakpoint pending on future shared library load? (y or [n])
98 # error, which typically happens python is dynamically linked (the
99 # breakpoints of interest are to be found in the shared library)
100 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000101 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000102 # emitted to stderr each time, alas.
103
104 # Initially I had "--eval-command=continue" here, but removed it to
105 # avoid repeated print breakpoints when traversing hierarchical data
106 # structures
107
108 # Generate a list of commands in gdb's language:
109 commands = ['set breakpoint pending yes',
110 'break %s' % breakpoint,
111 'run']
112 if cmds_after_breakpoint:
113 commands += cmds_after_breakpoint
114 else:
115 commands += ['backtrace']
116
117 # print commands
118
119 # Use "commands" to generate the arguments with which to invoke "gdb":
120 args = ["gdb", "--batch"]
121 args += ['--eval-command=%s' % cmd for cmd in commands]
122 args += ["--args",
123 sys.executable]
124
125 if not import_site:
126 # -S suppresses the default 'import site'
127 args += ["-S"]
128
129 if source:
130 args += ["-c", source]
131 elif script:
132 args += [script]
133
134 # print args
135 # print ' '.join(args)
136
137 # Use "args" to invoke gdb, capturing stdout, stderr:
R David Murrayf9333022012-10-27 13:22:41 -0400138 out, err = run_gdb(*args, PYTHONHASHSEED='0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000139
140 # Ignore some noise on stderr due to the pending breakpoint:
141 err = err.replace('Function "%s" not defined.\n' % breakpoint, '')
Antoine Pitroua045f192010-05-05 18:30:22 +0000142 # Ignore some other noise on stderr (http://bugs.python.org/issue8600)
143 err = err.replace("warning: Unable to find libthread_db matching"
144 " inferior's thread library, thread debugging will"
145 " not be available.\n",
146 '')
Jesus Ceacee36552011-03-16 01:33:16 +0100147 err = err.replace("warning: Cannot initialize thread debugging"
148 " library: Debugger service failed\n",
149 '')
Benjamin Petersonf8a9a832012-09-20 23:48:23 -0400150 err = err.replace('warning: Could not load shared library symbols for '
151 'linux-vdso.so.1.\n'
152 'Do you need "set solib-search-path" or '
153 '"set sysroot"?\n',
154 '')
R David Murrayf9333022012-10-27 13:22:41 -0400155 err = err.replace('warning: Could not load shared library symbols for '
156 'linux-gate.so.1.\n'
157 'Do you need "set solib-search-path" or '
158 '"set sysroot"?\n',
159 '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000160
161 # Ensure no unexpected error messages:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000162 self.assertEqual(err, '')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000163
164 return out
165
166 def get_gdb_repr(self, source,
167 cmds_after_breakpoint=None,
168 import_site=False):
169 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000170 # run "python -c'id(DATA)'" under gdb with a breakpoint on
171 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000172 # parameter, and verify that the gdb displays the same string
173 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000174 # Verify that the gdb displays the expected string
175 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000176 # For a nested structure, the first time we hit the breakpoint will
177 # give us the top-level structure
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000178 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000179 cmds_after_breakpoint=cmds_after_breakpoint,
180 import_site=import_site)
181 # gdb can insert additional '\n' and space characters in various places
182 # in its output, depending on the width of the terminal it's connected
183 # to (using its "wrap_here" function)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000184 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 +0000185 gdb_output, re.DOTALL)
186 if not m:
187 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
188 return m.group(1), gdb_output
189
190 def assertEndsWith(self, actual, exp_end):
191 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000192 self.assertTrue(actual.endswith(exp_end),
193 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000194
195 def assertMultilineMatches(self, actual, pattern):
196 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000197 if not m:
198 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000199
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000200 def get_sample_script(self):
201 return findfile('gdb_sample.py')
202
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000203class PrettyPrintTests(DebuggerTests):
204 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000205 gdb_output = self.get_stack_trace('id(42)')
206 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000207
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000208 def assertGdbRepr(self, val, exp_repr=None, cmds_after_breakpoint=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000209 # Ensure that gdb's rendering of the value in a debugged process
210 # matches repr(value) in this process:
Victor Stinner150016f2010-05-19 23:04:56 +0000211 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000212 cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000213 if not exp_repr:
214 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000215 self.assertEqual(gdb_repr, exp_repr,
216 ('%r did not equal expected %r; full output was:\n%s'
217 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000218
219 def test_int(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000220 'Verify the pretty-printing of various "int"/long values'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000221 self.assertGdbRepr(42)
222 self.assertGdbRepr(0)
223 self.assertGdbRepr(-7)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000224 self.assertGdbRepr(1000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000225 self.assertGdbRepr(-1000000000000000)
226
227 def test_singletons(self):
228 'Verify the pretty-printing of True, False and None'
229 self.assertGdbRepr(True)
230 self.assertGdbRepr(False)
231 self.assertGdbRepr(None)
232
233 def test_dicts(self):
234 'Verify the pretty-printing of dictionaries'
235 self.assertGdbRepr({})
236 self.assertGdbRepr({'foo': 'bar'})
Georg Brandl09a7c722012-02-20 21:31:46 +0100237 self.assertGdbRepr({'foo': 'bar', 'douglas': 42},
238 "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000239
240 def test_lists(self):
241 'Verify the pretty-printing of lists'
242 self.assertGdbRepr([])
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000243 self.assertGdbRepr(list(range(5)))
244
245 def test_bytes(self):
246 'Verify the pretty-printing of bytes'
247 self.assertGdbRepr(b'')
248 self.assertGdbRepr(b'And now for something hopefully the same')
249 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
250 self.assertGdbRepr(b'this is a tab:\t'
251 b' this is a slash-N:\n'
252 b' this is a slash-R:\r'
253 )
254
255 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
256
257 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258
259 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000260 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000261 encoding = locale.getpreferredencoding()
262 def check_repr(text):
263 try:
264 text.encode(encoding)
265 printable = True
266 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000267 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000268 else:
269 self.assertGdbRepr(text)
270
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000271 self.assertGdbRepr('')
272 self.assertGdbRepr('And now for something hopefully the same')
273 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000274
275 # Test printing a single character:
276 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000277 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000278
279 # Test printing a Japanese unicode string
280 # (I believe this reads "mojibake", using 3 characters from the CJK
281 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000282 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000283
284 # Test a character outside the BMP:
285 # U+1D121 MUSICAL SYMBOL C CLEF
286 # This is:
287 # UTF-8: 0xF0 0x9D 0x84 0xA1
288 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000289 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000290
291 def test_tuples(self):
292 'Verify the pretty-printing of tuples'
293 self.assertGdbRepr(tuple())
294 self.assertGdbRepr((1,), '(1,)')
295 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000296
297 def test_sets(self):
298 'Verify the pretty-printing of sets'
299 self.assertGdbRepr(set())
Georg Brandl09a7c722012-02-20 21:31:46 +0100300 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
301 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000302
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000303 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000304 # which happens on deletion:
305 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
306s.pop()
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000307id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000308 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000309
310 def test_frozensets(self):
311 'Verify the pretty-printing of frozensets'
312 self.assertGdbRepr(frozenset())
Georg Brandl09a7c722012-02-20 21:31:46 +0100313 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
314 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000315
316 def test_exceptions(self):
317 # Test a RuntimeError
318 gdb_repr, gdb_output = self.get_gdb_repr('''
319try:
320 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000321except RuntimeError as e:
322 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000323''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000324 self.assertEqual(gdb_repr,
325 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000326
327
328 # Test division by zero:
329 gdb_repr, gdb_output = self.get_gdb_repr('''
330try:
331 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000332except ZeroDivisionError as e:
333 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000334''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000335 self.assertEqual(gdb_repr,
336 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000337
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000338 def test_modern_class(self):
339 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000340 gdb_repr, gdb_output = self.get_gdb_repr('''
341class Foo:
342 pass
343foo = Foo()
344foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000345id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000346 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr)
347 self.assertTrue(m,
348 msg='Unexpected new-style class rendering %r' % gdb_repr)
349
350 def test_subclassing_list(self):
351 'Verify the pretty-printing of an instance of a list subclass'
352 gdb_repr, gdb_output = self.get_gdb_repr('''
353class Foo(list):
354 pass
355foo = Foo()
356foo += [1, 2, 3]
357foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000358id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000359 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 +0000360
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000361 self.assertTrue(m,
362 msg='Unexpected new-style class rendering %r' % gdb_repr)
363
364 def test_subclassing_tuple(self):
365 'Verify the pretty-printing of an instance of a tuple subclass'
366 # This should exercise the negative tp_dictoffset code in the
367 # new-style class support
368 gdb_repr, gdb_output = self.get_gdb_repr('''
369class Foo(tuple):
370 pass
371foo = Foo((1, 2, 3))
372foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000373id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000374 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 +0000375
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000376 self.assertTrue(m,
377 msg='Unexpected new-style class rendering %r' % gdb_repr)
378
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000379 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000380 '''Run Python under gdb, corrupting variables in the inferior process
381 immediately before taking a backtrace.
382
383 Verify that the variable's representation is the expected failsafe
384 representation'''
385 if corruption:
386 cmds_after_breakpoint=[corruption, 'backtrace']
387 else:
388 cmds_after_breakpoint=['backtrace']
389
390 gdb_repr, gdb_output = \
391 self.get_gdb_repr(source,
392 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000393 if exprepr:
394 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000395 # gdb managed to print the value in spite of the corruption;
396 # this is good (see http://bugs.python.org/issue8330)
397 return
398
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000399 # Match anything for the type name; 0xDEADBEEF could point to
400 # something arbitrary (see http://bugs.python.org/issue8330)
401 pattern = '<.* at remote 0x[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000402
403 m = re.match(pattern, gdb_repr)
404 if not m:
405 self.fail('Unexpected gdb representation: %r\n%s' % \
406 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000407
408 def test_NULL_ptr(self):
409 'Ensure that a NULL PyObject* is handled gracefully'
410 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000411 self.get_gdb_repr('id(42)',
412 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000413 'backtrace'])
414 )
415
Ezio Melottib3aedd42010-11-20 19:04:17 +0000416 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000417
418 def test_NULL_ob_type(self):
419 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000420 self.assertSane('id(42)',
421 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000422
423 def test_corrupt_ob_type(self):
424 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000425 self.assertSane('id(42)',
426 'set v->ob_type=0xDEADBEEF',
427 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000428
429 def test_corrupt_tp_flags(self):
430 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000431 self.assertSane('id(42)',
432 'set v->ob_type->tp_flags=0x0',
433 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000434
435 def test_corrupt_tp_name(self):
436 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000437 self.assertSane('id(42)',
438 'set v->ob_type->tp_name=0xDEADBEEF',
439 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000440
441 def test_builtins_help(self):
442 'Ensure that the new-style class _Helper in site.py can be handled'
443 # (this was the issue causing tracebacks in
444 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000445 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000446
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000447 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr)
448 self.assertTrue(m,
449 msg='Unexpected rendering %r' % gdb_repr)
450
451 def test_selfreferential_list(self):
452 '''Ensure that a reference loop involving a list doesn't lead proxyval
453 into an infinite loop:'''
454 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000455 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000456 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000457
458 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000459 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000460 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000461
462 def test_selfreferential_dict(self):
463 '''Ensure that a reference loop involving a dict doesn't lead proxyval
464 into an infinite loop:'''
465 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000466 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000467
Ezio Melottib3aedd42010-11-20 19:04:17 +0000468 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000469
470 def test_selfreferential_old_style_instance(self):
471 gdb_repr, gdb_output = \
472 self.get_gdb_repr('''
473class Foo:
474 pass
475foo = Foo()
476foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000477id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000478 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
479 gdb_repr),
480 'Unexpected gdb representation: %r\n%s' % \
481 (gdb_repr, gdb_output))
482
483 def test_selfreferential_new_style_instance(self):
484 gdb_repr, gdb_output = \
485 self.get_gdb_repr('''
486class Foo(object):
487 pass
488foo = Foo()
489foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000490id(foo)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000491 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>',
492 gdb_repr),
493 'Unexpected gdb representation: %r\n%s' % \
494 (gdb_repr, gdb_output))
495
496 gdb_repr, gdb_output = \
497 self.get_gdb_repr('''
498class Foo(object):
499 pass
500a = Foo()
501b = Foo()
502a.an_attr = b
503b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000504id(a)''')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000505 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>',
506 gdb_repr),
507 'Unexpected gdb representation: %r\n%s' % \
508 (gdb_repr, gdb_output))
509
510 def test_truncation(self):
511 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000512 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000513 self.assertEqual(gdb_repr,
514 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
515 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
516 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
517 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
518 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
519 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
520 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
521 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
522 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
523 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
524 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
525 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
526 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
527 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
528 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
529 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
530 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
531 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
532 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
533 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
534 "224, 225, 226...(truncated)")
535 self.assertEqual(len(gdb_repr),
536 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000537
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000538 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000539 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
540 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 +0000541 gdb_repr),
542 'Unexpected gdb representation: %r\n%s' % \
543 (gdb_repr, gdb_output))
544
545 def test_frames(self):
546 gdb_output = self.get_stack_trace('''
547def foo(a, b, c):
548 pass
549
550foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000551id(foo.__code__)''',
552 breakpoint='builtin_id',
553 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000554 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000555 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 +0000556 gdb_output,
557 re.DOTALL),
558 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
559
Victor Stinnerd2084162011-12-19 13:42:24 +0100560@unittest.skipIf(python_is_optimized(),
561 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000562class PyListTests(DebuggerTests):
563 def assertListing(self, expected, actual):
564 self.assertEndsWith(actual, expected)
565
566 def test_basic_command(self):
567 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000568 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000569 cmds_after_breakpoint=['py-list'])
570
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000571 self.assertListing(' 5 \n'
572 ' 6 def bar(a, b, c):\n'
573 ' 7 baz(a, b, c)\n'
574 ' 8 \n'
575 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000576 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000577 ' 11 \n'
578 ' 12 foo(1, 2, 3)\n',
579 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000580
581 def test_one_abs_arg(self):
582 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000583 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000584 cmds_after_breakpoint=['py-list 9'])
585
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000586 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000587 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000588 ' 11 \n'
589 ' 12 foo(1, 2, 3)\n',
590 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000591
592 def test_two_abs_args(self):
593 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000594 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000595 cmds_after_breakpoint=['py-list 1,3'])
596
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000597 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
598 ' 2 \n'
599 ' 3 def foo(a, b, c):\n',
600 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000601
602class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000603 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100604 @unittest.skipIf(python_is_optimized(),
605 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000606 def test_pyup_command(self):
607 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000608 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609 cmds_after_breakpoint=['py-up'])
610 self.assertMultilineMatches(bt,
611 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000612#[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 +0000613 baz\(a, b, c\)
614$''')
615
Victor Stinner50eb60e2010-04-20 22:32:07 +0000616 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000617 def test_down_at_bottom(self):
618 'Verify handling of "py-down" at the bottom of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000619 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000620 cmds_after_breakpoint=['py-down'])
621 self.assertEndsWith(bt,
622 'Unable to find a newer python frame\n')
623
Victor Stinner50eb60e2010-04-20 22:32:07 +0000624 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000625 def test_up_at_top(self):
626 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000627 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000628 cmds_after_breakpoint=['py-up'] * 4)
629 self.assertEndsWith(bt,
630 'Unable to find an older python frame\n')
631
Victor Stinner50eb60e2010-04-20 22:32:07 +0000632 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100633 @unittest.skipIf(python_is_optimized(),
634 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000635 def test_up_then_down(self):
636 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000637 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000638 cmds_after_breakpoint=['py-up', 'py-down'])
639 self.assertMultilineMatches(bt,
640 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000641#[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 +0000642 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000643#[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 +0000644 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000645$''')
646
647class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100648 @unittest.skipIf(python_is_optimized(),
649 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200650 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000651 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000652 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000653 cmds_after_breakpoint=['py-bt'])
654 self.assertMultilineMatches(bt,
655 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200656Traceback \(most recent call first\):
657 File ".*gdb_sample.py", line 10, in baz
658 id\(42\)
659 File ".*gdb_sample.py", line 7, in bar
660 baz\(a, b, c\)
661 File ".*gdb_sample.py", line 4, in foo
662 bar\(a, b, c\)
663 File ".*gdb_sample.py", line 12, in <module>
664 foo\(1, 2, 3\)
665''')
666
Victor Stinnerd2084162011-12-19 13:42:24 +0100667 @unittest.skipIf(python_is_optimized(),
668 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200669 def test_bt_full(self):
670 'Verify that the "py-bt-full" command works'
671 bt = self.get_stack_trace(script=self.get_sample_script(),
672 cmds_after_breakpoint=['py-bt-full'])
673 self.assertMultilineMatches(bt,
674 r'''^.*
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000675#[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 +0000676 baz\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000677#[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 +0000678 bar\(a, b, c\)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000679#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100680 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000681''')
682
683class PyPrintTests(DebuggerTests):
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_basic_command(self):
687 'Verify that the "py-print" command works'
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-print args'])
690 self.assertMultilineMatches(bt,
691 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
692
Vinay Sajipcdf6cd92012-01-05 11:45:31 +0000693 @unittest.skipIf(python_is_optimized(),
694 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000695 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000696 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000697 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000698 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
699 self.assertMultilineMatches(bt,
700 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
701
Victor Stinnerd2084162011-12-19 13:42:24 +0100702 @unittest.skipIf(python_is_optimized(),
703 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000704 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000705 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000706 cmds_after_breakpoint=['py-print __name__'])
707 self.assertMultilineMatches(bt,
708 r".*\nglobal '__name__' = '__main__'\n.*")
709
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_printing_builtin(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-print len'])
715 self.assertMultilineMatches(bt,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000716 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000717
718class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100719 @unittest.skipIf(python_is_optimized(),
720 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000721 def test_basic_command(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-locals'])
724 self.assertMultilineMatches(bt,
725 r".*\nargs = \(1, 2, 3\)\n.*")
726
Victor Stinner50eb60e2010-04-20 22:32:07 +0000727 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajipcdf6cd92012-01-05 11:45:31 +0000728 @unittest.skipIf(python_is_optimized(),
729 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000730 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000731 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000732 cmds_after_breakpoint=['py-up', 'py-locals'])
733 self.assertMultilineMatches(bt,
734 r".*\na = 1\nb = 2\nc = 3\n.*")
735
736def test_main():
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000737 run_unittest(PrettyPrintTests,
738 PyListTests,
739 StackNavigationTests,
740 PyBtTests,
741 PyPrintTests,
742 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000743 )
744
745if __name__ == "__main__":
746 test_main()