blob: 9e0eaea8c8f69219285318c9dd00c2855ebf0238 [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
Victor Stinner61108332017-02-01 16:29:54 +01006import locale
Benjamin Peterson6a6666a2010-04-11 21:49:28 +00007import os
8import re
9import subprocess
10import sys
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010011import sysconfig
Victor Stinner61108332017-02-01 16:29:54 +010012import textwrap
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000013import unittest
14
Antoine Pitroud0f3e072013-09-21 23:56:17 +020015from test import support
Benjamin Peterson65c66ab2010-10-29 21:31:35 +000016from test.support import run_unittest, findfile, python_is_optimized
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000017
Victor Stinner5b6b4a82015-09-02 23:19:55 +020018def get_gdb_version():
19 try:
20 proc = subprocess.Popen(["gdb", "-nx", "--version"],
21 stdout=subprocess.PIPE,
Benjamin Petersoncbef66d2016-09-06 10:06:31 -070022 stderr=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020023 universal_newlines=True)
24 with proc:
25 version = proc.communicate()[0]
26 except OSError:
27 # This is what "no gdb" looks like. There may, however, be other
28 # errors that manifest this way too.
29 raise unittest.SkipTest("Couldn't find gdb on the path")
30
31 # Regex to parse:
32 # 'GNU gdb (GDB; SUSE Linux Enterprise 12) 7.7\n' -> 7.7
33 # 'GNU gdb (GDB) Fedora 7.9.1-17.fc22\n' -> 7.9
Victor Stinner479fea62015-09-03 15:42:26 +020034 # 'GNU gdb 6.1.1 [FreeBSD]\n' -> 6.1
35 # 'GNU gdb (GDB) Fedora (7.5.1-37.fc18)\n' -> 7.5
Victor Stinnera578eb32015-09-15 00:22:55 +020036 match = re.search(r"^GNU gdb.*?\b(\d+)\.(\d+)", version)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020037 if match is None:
38 raise Exception("unable to parse GDB version: %r" % version)
39 return (version, int(match.group(1)), int(match.group(2)))
40
41gdb_version, gdb_major_version, gdb_minor_version = get_gdb_version()
R David Murrayf9333022012-10-27 13:22:41 -040042if gdb_major_version < 7:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +020043 raise unittest.SkipTest("gdb versions before 7.0 didn't support python "
44 "embedding. Saw %s.%s:\n%s"
45 % (gdb_major_version, gdb_minor_version,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020046 gdb_version))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000047
Vinay Sajipf1b34ee2012-05-06 12:03:05 +010048if not sysconfig.is_python_build():
49 raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
50
R David Murrayf9333022012-10-27 13:22:41 -040051# Location of custom hooks file in a repository checkout.
52checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
53 'python-gdb.py')
54
Victor Stinner51324932013-11-20 12:27:48 +010055PYTHONHASHSEED = '123'
56
R David Murrayf9333022012-10-27 13:22:41 -040057def run_gdb(*args, **env_vars):
58 """Runs gdb in --batch mode with the additional arguments given by *args.
59
60 Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
61 """
62 if env_vars:
63 env = os.environ.copy()
64 env.update(env_vars)
65 else:
66 env = None
Victor Stinner7869a4e2014-08-16 14:38:02 +020067 # -nx: Do not execute commands from any .gdbinit initialization files
68 # (issue #22188)
69 base_cmd = ('gdb', '--batch', '-nx')
R David Murrayf9333022012-10-27 13:22:41 -040070 if (gdb_major_version, gdb_minor_version) >= (7, 4):
71 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
Victor Stinner5b6b4a82015-09-02 23:19:55 +020072 proc = subprocess.Popen(base_cmd + args,
Martin Panter7a5fe6d2016-01-16 05:18:47 +000073 # Redirect stdin to prevent GDB from messing with
74 # the terminal settings
75 stdin=subprocess.PIPE,
Victor Stinner5b6b4a82015-09-02 23:19:55 +020076 stdout=subprocess.PIPE,
77 stderr=subprocess.PIPE,
78 env=env)
79 with proc:
80 out, err = proc.communicate()
R David Murrayf9333022012-10-27 13:22:41 -040081 return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
82
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000083# Verify that "gdb" was built with the embedded python support enabled:
Antoine Pitroue50240c2013-11-23 17:40:36 +010084gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
R David Murrayf9333022012-10-27 13:22:41 -040085if not gdbpy_version:
Benjamin Peterson6a6666a2010-04-11 21:49:28 +000086 raise unittest.SkipTest("gdb not built with embedded python support")
87
Nick Coghlance346872013-09-22 19:38:16 +100088# Verify that "gdb" can load our custom hooks, as OS security settings may
Raymond Hettinger7ea386e2016-08-25 21:11:50 -070089# disallow this without a customized .gdbinit.
R David Murrayf9333022012-10-27 13:22:41 -040090_, gdbpy_errors = run_gdb('--args', sys.executable)
91if "auto-loading has been declined" in gdbpy_errors:
92 msg = "gdb security settings prevent use of custom hooks: "
93 raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
Nick Coghlanbe4e4b52012-06-17 18:57:20 +100094
Victor Stinner50eb60e2010-04-20 22:32:07 +000095def gdb_has_frame_select():
96 # Does this build of gdb have gdb.Frame.select ?
R David Murrayf9333022012-10-27 13:22:41 -040097 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
98 m = re.match(r'.*\[(.*)\].*', stdout)
Victor Stinner50eb60e2010-04-20 22:32:07 +000099 if not m:
100 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
R David Murrayf9333022012-10-27 13:22:41 -0400101 gdb_frame_dir = m.group(1).split(', ')
102 return "'select'" in gdb_frame_dir
Victor Stinner50eb60e2010-04-20 22:32:07 +0000103
104HAS_PYUP_PYDOWN = gdb_has_frame_select()
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000105
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000106BREAKPOINT_FN='builtin_id'
107
Benjamin Peterson437df902016-09-06 20:22:41 -0700108@unittest.skipIf(support.PGO, "not useful for PGO")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000109class DebuggerTests(unittest.TestCase):
110
111 """Test that the debugger can debug Python."""
112
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000113 def get_stack_trace(self, source=None, script=None,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000114 breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000115 cmds_after_breakpoint=None,
116 import_site=False):
117 '''
118 Run 'python -c SOURCE' under gdb with a breakpoint.
119
120 Support injecting commands after the breakpoint is reached
121
122 Returns the stdout from gdb
123
124 cmds_after_breakpoint: if provided, a list of strings: gdb commands
125 '''
126 # We use "set breakpoint pending yes" to avoid blocking with a:
127 # Function "foo" not defined.
128 # Make breakpoint pending on future shared library load? (y or [n])
129 # error, which typically happens python is dynamically linked (the
130 # breakpoints of interest are to be found in the shared library)
131 # When this happens, we still get:
Victor Stinner67df3a42010-04-21 13:53:05 +0000132 # Function "textiowrapper_write" not defined.
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000133 # emitted to stderr each time, alas.
134
135 # Initially I had "--eval-command=continue" here, but removed it to
136 # avoid repeated print breakpoints when traversing hierarchical data
137 # structures
138
139 # Generate a list of commands in gdb's language:
140 commands = ['set breakpoint pending yes',
141 'break %s' % breakpoint,
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200142
Serhiy Storchakafdc99532015-01-31 11:48:52 +0200143 # The tests assume that the first frame of printed
144 # backtrace will not contain program counter,
145 # that is however not guaranteed by gdb
146 # therefore we need to use 'set print address off' to
147 # make sure the counter is not there. For example:
148 # #0 in PyObject_Print ...
149 # is assumed, but sometimes this can be e.g.
150 # #0 0x00003fffb7dd1798 in PyObject_Print ...
151 'set print address off',
152
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000153 'run']
Serhiy Storchaka17d337b2015-02-06 08:35:20 +0200154
155 # GDB as of 7.4 onwards can distinguish between the
156 # value of a variable at entry vs current value:
157 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
158 # which leads to the selftests failing with errors like this:
159 # AssertionError: 'v@entry=()' != '()'
160 # Disable this:
161 if (gdb_major_version, gdb_minor_version) >= (7, 4):
162 commands += ['set print entry-values no']
163
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000164 if cmds_after_breakpoint:
165 commands += cmds_after_breakpoint
166 else:
167 commands += ['backtrace']
168
169 # print commands
170
171 # Use "commands" to generate the arguments with which to invoke "gdb":
Martin Panter40e102c2015-12-08 21:54:42 +0000172 args = ['--eval-command=%s' % cmd for cmd in commands]
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000173 args += ["--args",
174 sys.executable]
Victor Stinner22756f12016-01-22 14:16:47 +0100175 args.extend(subprocess._args_from_interpreter_flags())
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000176
177 if not import_site:
178 # -S suppresses the default 'import site'
179 args += ["-S"]
180
181 if source:
182 args += ["-c", source]
183 elif script:
184 args += [script]
185
186 # print args
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100187 # print (' '.join(args))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000188
189 # Use "args" to invoke gdb, capturing stdout, stderr:
Victor Stinner51324932013-11-20 12:27:48 +0100190 out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000191
Antoine Pitrou81641d62013-05-01 00:15:44 +0200192 errlines = err.splitlines()
193 unexpected_errlines = []
194
195 # Ignore some benign messages on stderr.
196 ignore_patterns = (
197 'Function "%s" not defined.' % breakpoint,
Antoine Pitrou81641d62013-05-01 00:15:44 +0200198 'Do you need "set solib-search-path" or '
199 '"set sysroot"?',
Victor Stinner904f5de2016-03-23 18:32:54 +0100200 # BFD: /usr/lib/debug/(...): unable to initialize decompress
201 # status for section .debug_aranges
202 'BFD: ',
203 # ignore all warnings
204 'warning: ',
Antoine Pitrou81641d62013-05-01 00:15:44 +0200205 )
206 for line in errlines:
Victor Stinnerc53195b2016-03-23 21:08:25 +0100207 if not line:
208 continue
Antoine Pitrou81641d62013-05-01 00:15:44 +0200209 if not line.startswith(ignore_patterns):
210 unexpected_errlines.append(line)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000211
212 # Ensure no unexpected error messages:
Antoine Pitrou81641d62013-05-01 00:15:44 +0200213 self.assertEqual(unexpected_errlines, [])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000214 return out
215
216 def get_gdb_repr(self, source,
217 cmds_after_breakpoint=None,
218 import_site=False):
219 # Given an input python source representation of data,
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000220 # run "python -c'id(DATA)'" under gdb with a breakpoint on
221 # builtin_id and scrape out gdb's representation of the "op"
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000222 # parameter, and verify that the gdb displays the same string
223 #
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000224 # Verify that the gdb displays the expected string
225 #
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000226 # For a nested structure, the first time we hit the breakpoint will
227 # give us the top-level structure
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100228
229 # NOTE: avoid decoding too much of the traceback as some
230 # undecodable characters may lurk there in optimized mode
231 # (issue #19743).
232 cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000233 gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000234 cmds_after_breakpoint=cmds_after_breakpoint,
235 import_site=import_site)
236 # gdb can insert additional '\n' and space characters in various places
237 # in its output, depending on the width of the terminal it's connected
238 # to (using its "wrap_here" function)
R David Murray44b548d2016-09-08 13:59:53 -0400239 m = re.match(r'.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000240 gdb_output, re.DOTALL)
241 if not m:
242 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
243 return m.group(1), gdb_output
244
245 def assertEndsWith(self, actual, exp_end):
246 '''Ensure that the given "actual" string ends with "exp_end"'''
Ezio Melottib3aedd42010-11-20 19:04:17 +0000247 self.assertTrue(actual.endswith(exp_end),
248 msg='%r did not end with %r' % (actual, exp_end))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000249
250 def assertMultilineMatches(self, actual, pattern):
251 m = re.match(pattern, actual, re.DOTALL)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000252 if not m:
253 self.fail(msg='%r did not match %r' % (actual, pattern))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000254
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000255 def get_sample_script(self):
256 return findfile('gdb_sample.py')
257
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000258class PrettyPrintTests(DebuggerTests):
259 def test_getting_backtrace(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000260 gdb_output = self.get_stack_trace('id(42)')
261 self.assertTrue(BREAKPOINT_FN in gdb_output)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000262
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100263 def assertGdbRepr(self, val, exp_repr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000264 # Ensure that gdb's rendering of the value in a debugged process
265 # matches repr(value) in this process:
Antoine Pitrouf6eb31f2013-11-24 14:58:17 +0100266 gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000267 if not exp_repr:
Victor Stinnera2828252013-11-21 10:25:09 +0100268 exp_repr = repr(val)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000269 self.assertEqual(gdb_repr, exp_repr,
270 ('%r did not equal expected %r; full output was:\n%s'
271 % (gdb_repr, exp_repr, gdb_output)))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000272
273 def test_int(self):
Serhiy Storchaka95949422013-08-27 19:40:23 +0300274 'Verify the pretty-printing of various int values'
Victor Stinnera2828252013-11-21 10:25:09 +0100275 self.assertGdbRepr(42)
276 self.assertGdbRepr(0)
277 self.assertGdbRepr(-7)
278 self.assertGdbRepr(1000000000000)
279 self.assertGdbRepr(-1000000000000000)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000280
281 def test_singletons(self):
282 'Verify the pretty-printing of True, False and None'
Victor Stinnera2828252013-11-21 10:25:09 +0100283 self.assertGdbRepr(True)
284 self.assertGdbRepr(False)
285 self.assertGdbRepr(None)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000286
287 def test_dicts(self):
288 'Verify the pretty-printing of dictionaries'
Victor Stinnera2828252013-11-21 10:25:09 +0100289 self.assertGdbRepr({})
290 self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
INADA Naokid7d2bc82016-11-22 19:40:58 +0900291 # Python preserves insertion order since 3.6
292 self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'foo': 'bar', 'douglas': 42}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000293
294 def test_lists(self):
295 'Verify the pretty-printing of lists'
Victor Stinnera2828252013-11-21 10:25:09 +0100296 self.assertGdbRepr([])
297 self.assertGdbRepr(list(range(5)))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000298
299 def test_bytes(self):
300 'Verify the pretty-printing of bytes'
301 self.assertGdbRepr(b'')
302 self.assertGdbRepr(b'And now for something hopefully the same')
303 self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
304 self.assertGdbRepr(b'this is a tab:\t'
305 b' this is a slash-N:\n'
306 b' this is a slash-R:\r'
307 )
308
309 self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
310
311 self.assertGdbRepr(bytes([b for b in range(255)]))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000312
313 def test_strings(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000314 'Verify the pretty-printing of unicode strings'
Victor Stinner150016f2010-05-19 23:04:56 +0000315 encoding = locale.getpreferredencoding()
316 def check_repr(text):
317 try:
318 text.encode(encoding)
319 printable = True
320 except UnicodeEncodeError:
Antoine Pitrou4c7c4212010-09-09 20:40:28 +0000321 self.assertGdbRepr(text, ascii(text))
Victor Stinner150016f2010-05-19 23:04:56 +0000322 else:
323 self.assertGdbRepr(text)
324
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000325 self.assertGdbRepr('')
326 self.assertGdbRepr('And now for something hopefully the same')
327 self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000328
329 # Test printing a single character:
330 # U+2620 SKULL AND CROSSBONES
Victor Stinner150016f2010-05-19 23:04:56 +0000331 check_repr('\u2620')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000332
333 # Test printing a Japanese unicode string
334 # (I believe this reads "mojibake", using 3 characters from the CJK
335 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
Victor Stinner150016f2010-05-19 23:04:56 +0000336 check_repr('\u6587\u5b57\u5316\u3051')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000337
338 # Test a character outside the BMP:
339 # U+1D121 MUSICAL SYMBOL C CLEF
340 # This is:
341 # UTF-8: 0xF0 0x9D 0x84 0xA1
342 # UTF-16: 0xD834 0xDD21
Victor Stinner150016f2010-05-19 23:04:56 +0000343 check_repr(chr(0x1D121))
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000344
345 def test_tuples(self):
346 'Verify the pretty-printing of tuples'
Victor Stinner51324932013-11-20 12:27:48 +0100347 self.assertGdbRepr(tuple(), '()')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000348 self.assertGdbRepr((1,), '(1,)')
349 self.assertGdbRepr(('foo', 'bar', 'baz'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000350
351 def test_sets(self):
352 'Verify the pretty-printing of sets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200353 if (gdb_major_version, gdb_minor_version) < (7, 3):
354 self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
Victor Stinner5a701f02016-01-22 15:04:27 +0100355 self.assertGdbRepr(set(), "set()")
356 self.assertGdbRepr(set(['a']), "{'a'}")
357 # PYTHONHASHSEED is need to get the exact frozenset item order
358 if not sys.flags.ignore_environment:
359 self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
360 self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000361
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000362 # Ensure that we handle sets containing the "dummy" key value,
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000363 # which happens on deletion:
364 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
Victor Stinner51324932013-11-20 12:27:48 +0100365s.remove('a')
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000366id(s)''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000367 self.assertEqual(gdb_repr, "{'b'}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000368
369 def test_frozensets(self):
370 'Verify the pretty-printing of frozensets'
Antoine Pitroua78cccb2013-09-22 00:14:27 +0200371 if (gdb_major_version, gdb_minor_version) < (7, 3):
372 self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
Victor Stinner22756f12016-01-22 14:16:47 +0100373 self.assertGdbRepr(frozenset(), "frozenset()")
374 self.assertGdbRepr(frozenset(['a']), "frozenset({'a'})")
375 # PYTHONHASHSEED is need to get the exact frozenset item order
376 if not sys.flags.ignore_environment:
377 self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
378 self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000379
380 def test_exceptions(self):
381 # Test a RuntimeError
382 gdb_repr, gdb_output = self.get_gdb_repr('''
383try:
384 raise RuntimeError("I am an error")
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000385except RuntimeError as e:
386 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000387''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000388 self.assertEqual(gdb_repr,
389 "RuntimeError('I am an error',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000390
391
392 # Test division by zero:
393 gdb_repr, gdb_output = self.get_gdb_repr('''
394try:
395 a = 1 / 0
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000396except ZeroDivisionError as e:
397 id(e)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000398''')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000399 self.assertEqual(gdb_repr,
400 "ZeroDivisionError('division by zero',)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000401
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000402 def test_modern_class(self):
403 'Verify the pretty-printing of new-style class instances'
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000404 gdb_repr, gdb_output = self.get_gdb_repr('''
405class Foo:
406 pass
407foo = Foo()
408foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000409id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100410 m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000411 self.assertTrue(m,
412 msg='Unexpected new-style class rendering %r' % gdb_repr)
413
414 def test_subclassing_list(self):
415 'Verify the pretty-printing of an instance of a list subclass'
416 gdb_repr, gdb_output = self.get_gdb_repr('''
417class Foo(list):
418 pass
419foo = Foo()
420foo += [1, 2, 3]
421foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000422id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100423 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 +0000424
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000425 self.assertTrue(m,
426 msg='Unexpected new-style class rendering %r' % gdb_repr)
427
428 def test_subclassing_tuple(self):
429 'Verify the pretty-printing of an instance of a tuple subclass'
430 # This should exercise the negative tp_dictoffset code in the
431 # new-style class support
432 gdb_repr, gdb_output = self.get_gdb_repr('''
433class Foo(tuple):
434 pass
435foo = Foo((1, 2, 3))
436foo.an_int = 42
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000437id(foo)''')
Antoine Pitrou4d098732011-11-26 01:42:03 +0100438 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 +0000439
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000440 self.assertTrue(m,
441 msg='Unexpected new-style class rendering %r' % gdb_repr)
442
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000443 def assertSane(self, source, corruption, exprepr=None):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000444 '''Run Python under gdb, corrupting variables in the inferior process
445 immediately before taking a backtrace.
446
447 Verify that the variable's representation is the expected failsafe
448 representation'''
449 if corruption:
450 cmds_after_breakpoint=[corruption, 'backtrace']
451 else:
452 cmds_after_breakpoint=['backtrace']
453
454 gdb_repr, gdb_output = \
455 self.get_gdb_repr(source,
456 cmds_after_breakpoint=cmds_after_breakpoint)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000457 if exprepr:
458 if gdb_repr == exprepr:
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000459 # gdb managed to print the value in spite of the corruption;
460 # this is good (see http://bugs.python.org/issue8330)
461 return
462
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000463 # Match anything for the type name; 0xDEADBEEF could point to
464 # something arbitrary (see http://bugs.python.org/issue8330)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100465 pattern = '<.* at remote 0x-?[0-9a-f]+>'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000466
467 m = re.match(pattern, gdb_repr)
468 if not m:
469 self.fail('Unexpected gdb representation: %r\n%s' % \
470 (gdb_repr, gdb_output))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000471
472 def test_NULL_ptr(self):
473 'Ensure that a NULL PyObject* is handled gracefully'
474 gdb_repr, gdb_output = (
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000475 self.get_gdb_repr('id(42)',
476 cmds_after_breakpoint=['set variable v=0',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000477 'backtrace'])
478 )
479
Ezio Melottib3aedd42010-11-20 19:04:17 +0000480 self.assertEqual(gdb_repr, '0x0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000481
482 def test_NULL_ob_type(self):
483 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000484 self.assertSane('id(42)',
485 'set v->ob_type=0')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000486
487 def test_corrupt_ob_type(self):
488 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000489 self.assertSane('id(42)',
490 'set v->ob_type=0xDEADBEEF',
491 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000492
493 def test_corrupt_tp_flags(self):
494 'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000495 self.assertSane('id(42)',
496 'set v->ob_type->tp_flags=0x0',
497 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000498
499 def test_corrupt_tp_name(self):
500 'Ensure that a PyObject* with a type with corrupt tp_name is handled'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000501 self.assertSane('id(42)',
502 'set v->ob_type->tp_name=0xDEADBEEF',
503 exprepr='42')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000504
505 def test_builtins_help(self):
506 'Ensure that the new-style class _Helper in site.py can be handled'
Victor Stinner22756f12016-01-22 14:16:47 +0100507
508 if sys.flags.no_site:
509 self.skipTest("need site module, but -S option was used")
510
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000511 # (this was the issue causing tracebacks in
512 # http://bugs.python.org/issue8032#msg100537 )
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000513 gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000514
Antoine Pitrou4d098732011-11-26 01:42:03 +0100515 m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000516 self.assertTrue(m,
517 msg='Unexpected rendering %r' % gdb_repr)
518
519 def test_selfreferential_list(self):
520 '''Ensure that a reference loop involving a list doesn't lead proxyval
521 into an infinite loop:'''
522 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000523 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000524 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000525
526 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000527 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000528 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000529
530 def test_selfreferential_dict(self):
531 '''Ensure that a reference loop involving a dict doesn't lead proxyval
532 into an infinite loop:'''
533 gdb_repr, gdb_output = \
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000534 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000535
Ezio Melottib3aedd42010-11-20 19:04:17 +0000536 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000537
538 def test_selfreferential_old_style_instance(self):
539 gdb_repr, gdb_output = \
540 self.get_gdb_repr('''
541class Foo:
542 pass
543foo = Foo()
544foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000545id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400546 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000547 gdb_repr),
548 'Unexpected gdb representation: %r\n%s' % \
549 (gdb_repr, gdb_output))
550
551 def test_selfreferential_new_style_instance(self):
552 gdb_repr, gdb_output = \
553 self.get_gdb_repr('''
554class Foo(object):
555 pass
556foo = Foo()
557foo.an_attr = foo
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000558id(foo)''')
R David Murray44b548d2016-09-08 13:59:53 -0400559 self.assertTrue(re.match(r'<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000560 gdb_repr),
561 'Unexpected gdb representation: %r\n%s' % \
562 (gdb_repr, gdb_output))
563
564 gdb_repr, gdb_output = \
565 self.get_gdb_repr('''
566class Foo(object):
567 pass
568a = Foo()
569b = Foo()
570a.an_attr = b
571b.an_attr = a
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000572id(a)''')
R David Murray44b548d2016-09-08 13:59:53 -0400573 self.assertTrue(re.match(r'<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 +0000574 gdb_repr),
575 'Unexpected gdb representation: %r\n%s' % \
576 (gdb_repr, gdb_output))
577
578 def test_truncation(self):
579 'Verify that very long output is truncated'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000580 gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000581 self.assertEqual(gdb_repr,
582 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
583 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
584 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
585 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
586 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
587 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
588 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
589 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
590 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
591 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
592 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
593 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
594 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
595 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
596 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
597 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
598 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
599 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
600 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
601 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
602 "224, 225, 226...(truncated)")
603 self.assertEqual(len(gdb_repr),
604 1024 + len('...(truncated)'))
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000605
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000606 def test_builtin_method(self):
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000607 gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
R David Murray44b548d2016-09-08 13:59:53 -0400608 self.assertTrue(re.match(r'<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000609 gdb_repr),
610 'Unexpected gdb representation: %r\n%s' % \
611 (gdb_repr, gdb_output))
612
613 def test_frames(self):
614 gdb_output = self.get_stack_trace('''
615def foo(a, b, c):
616 pass
617
618foo(3, 4, 5)
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000619id(foo.__code__)''',
620 breakpoint='builtin_id',
621 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000622 )
R David Murray44b548d2016-09-08 13:59:53 -0400623 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000624 gdb_output,
625 re.DOTALL),
626 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
627
Victor Stinnerd2084162011-12-19 13:42:24 +0100628@unittest.skipIf(python_is_optimized(),
629 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000630class PyListTests(DebuggerTests):
631 def assertListing(self, expected, actual):
632 self.assertEndsWith(actual, expected)
633
634 def test_basic_command(self):
635 'Verify that the "py-list" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000636 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000637 cmds_after_breakpoint=['py-list'])
638
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000639 self.assertListing(' 5 \n'
640 ' 6 def bar(a, b, c):\n'
641 ' 7 baz(a, b, c)\n'
642 ' 8 \n'
643 ' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000644 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000645 ' 11 \n'
646 ' 12 foo(1, 2, 3)\n',
647 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000648
649 def test_one_abs_arg(self):
650 'Verify the "py-list" command with one absolute argument'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000651 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000652 cmds_after_breakpoint=['py-list 9'])
653
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000654 self.assertListing(' 9 def baz(*args):\n'
Martin v. Löwis5ae68102010-04-21 22:38:42 +0000655 ' >10 id(42)\n'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000656 ' 11 \n'
657 ' 12 foo(1, 2, 3)\n',
658 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000659
660 def test_two_abs_args(self):
661 'Verify the "py-list" command with two absolute arguments'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000662 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000663 cmds_after_breakpoint=['py-list 1,3'])
664
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000665 self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
666 ' 2 \n'
667 ' 3 def foo(a, b, c):\n',
668 bt)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000669
670class StackNavigationTests(DebuggerTests):
Victor Stinner50eb60e2010-04-20 22:32:07 +0000671 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Victor Stinnerd2084162011-12-19 13:42:24 +0100672 @unittest.skipIf(python_is_optimized(),
673 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000674 def test_pyup_command(self):
675 'Verify that the "py-up" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000676 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100677 cmds_after_breakpoint=['py-up', 'py-up'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000678 self.assertMultilineMatches(bt,
679 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100680#[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 +0000681 baz\(a, b, c\)
682$''')
683
Victor Stinner50eb60e2010-04-20 22:32:07 +0000684 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000685 def test_down_at_bottom(self):
686 'Verify handling of "py-down" at the bottom of the stack'
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-down'])
689 self.assertEndsWith(bt,
690 'Unable to find a newer python frame\n')
691
Victor Stinner50eb60e2010-04-20 22:32:07 +0000692 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000693 def test_up_at_top(self):
694 'Verify handling of "py-up" at the top of the stack'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000695 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100696 cmds_after_breakpoint=['py-up'] * 5)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000697 self.assertEndsWith(bt,
698 'Unable to find an older python frame\n')
699
Victor Stinner50eb60e2010-04-20 22:32:07 +0000700 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
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_up_then_down(self):
704 'Verify "py-up" followed by "py-down"'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000705 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100706 cmds_after_breakpoint=['py-up', 'py-up', 'py-down'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000707 self.assertMultilineMatches(bt,
708 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100709#[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 +0000710 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100711#[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 +0000712 id\(42\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000713$''')
714
715class PyBtTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100716 @unittest.skipIf(python_is_optimized(),
717 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200718 def test_bt(self):
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000719 'Verify that the "py-bt" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000720 bt = self.get_stack_trace(script=self.get_sample_script(),
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000721 cmds_after_breakpoint=['py-bt'])
722 self.assertMultilineMatches(bt,
723 r'''^.*
Victor Stinnere670c882011-05-13 17:40:15 +0200724Traceback \(most recent call first\):
Victor Stinnere3d75c62016-11-22 22:53:18 +0100725 <built-in method id of module object .*>
Victor Stinnere670c882011-05-13 17:40:15 +0200726 File ".*gdb_sample.py", line 10, in baz
727 id\(42\)
728 File ".*gdb_sample.py", line 7, in bar
729 baz\(a, b, c\)
730 File ".*gdb_sample.py", line 4, in foo
731 bar\(a, b, c\)
732 File ".*gdb_sample.py", line 12, in <module>
733 foo\(1, 2, 3\)
734''')
735
Victor Stinnerd2084162011-12-19 13:42:24 +0100736 @unittest.skipIf(python_is_optimized(),
737 "Python was compiled with optimizations")
Victor Stinnere670c882011-05-13 17:40:15 +0200738 def test_bt_full(self):
739 'Verify that the "py-bt-full" command works'
740 bt = self.get_stack_trace(script=self.get_sample_script(),
741 cmds_after_breakpoint=['py-bt-full'])
742 self.assertMultilineMatches(bt,
743 r'''^.*
Antoine Pitrou4d098732011-11-26 01:42:03 +0100744#[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 +0000745 baz\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100746#[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 +0000747 bar\(a, b, c\)
Antoine Pitrou4d098732011-11-26 01:42:03 +0100748#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
Victor Stinnerd2084162011-12-19 13:42:24 +0100749 foo\(1, 2, 3\)
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000750''')
751
David Malcolm8d37ffa2012-06-27 14:15:34 -0400752 def test_threads(self):
753 'Verify that "py-bt" indicates threads that are waiting for the GIL'
754 cmd = '''
755from threading import Thread
756
757class TestThread(Thread):
758 # These threads would run forever, but we'll interrupt things with the
759 # debugger
760 def run(self):
761 i = 0
762 while 1:
763 i += 1
764
765t = {}
766for i in range(4):
767 t[i] = TestThread()
768 t[i].start()
769
770# Trigger a breakpoint on the main thread
771id(42)
772
773'''
774 # Verify with "py-bt":
775 gdb_output = self.get_stack_trace(cmd,
776 cmds_after_breakpoint=['thread apply all py-bt'])
777 self.assertIn('Waiting for the GIL', gdb_output)
778
779 # Verify with "py-bt-full":
780 gdb_output = self.get_stack_trace(cmd,
781 cmds_after_breakpoint=['thread apply all py-bt-full'])
782 self.assertIn('Waiting for the GIL', gdb_output)
783
784 @unittest.skipIf(python_is_optimized(),
785 "Python was compiled with optimizations")
786 # Some older versions of gdb will fail with
787 # "Cannot find new threads: generic error"
788 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400789 def test_gc(self):
790 'Verify that "py-bt" indicates if a thread is garbage-collecting'
791 cmd = ('from gc import collect\n'
792 'id(42)\n'
793 'def foo():\n'
794 ' collect()\n'
795 'def bar():\n'
796 ' foo()\n'
797 'bar()\n')
798 # Verify with "py-bt":
799 gdb_output = self.get_stack_trace(cmd,
800 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
801 )
802 self.assertIn('Garbage-collecting', gdb_output)
803
804 # Verify with "py-bt-full":
805 gdb_output = self.get_stack_trace(cmd,
806 cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
807 )
808 self.assertIn('Garbage-collecting', gdb_output)
809
810 @unittest.skipIf(python_is_optimized(),
811 "Python was compiled with optimizations")
812 # Some older versions of gdb will fail with
813 # "Cannot find new threads: generic error"
814 # unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
David Malcolm8d37ffa2012-06-27 14:15:34 -0400815 def test_pycfunction(self):
816 'Verify that "py-bt" displays invocations of PyCFunction instances'
Victor Stinner79644f92015-03-27 15:42:37 +0100817 # Tested function must not be defined with METH_NOARGS or METH_O,
818 # otherwise call_function() doesn't call PyCFunction_Call()
819 cmd = ('from time import gmtime\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400820 'def foo():\n'
Victor Stinner79644f92015-03-27 15:42:37 +0100821 ' gmtime(1)\n'
David Malcolm8d37ffa2012-06-27 14:15:34 -0400822 'def bar():\n'
823 ' foo()\n'
824 'bar()\n')
825 # Verify with "py-bt":
826 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100827 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400828 cmds_after_breakpoint=['bt', 'py-bt'],
829 )
Victor Stinner79644f92015-03-27 15:42:37 +0100830 self.assertIn('<built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400831
832 # Verify with "py-bt-full":
833 gdb_output = self.get_stack_trace(cmd,
Victor Stinner79644f92015-03-27 15:42:37 +0100834 breakpoint='time_gmtime',
David Malcolm8d37ffa2012-06-27 14:15:34 -0400835 cmds_after_breakpoint=['py-bt-full'],
836 )
INADA Naoki5566bbb2017-02-03 07:43:03 +0900837 self.assertIn('#2 <built-in method gmtime', gdb_output)
David Malcolm8d37ffa2012-06-27 14:15:34 -0400838
Victor Stinner61108332017-02-01 16:29:54 +0100839 @unittest.skipIf(python_is_optimized(),
840 "Python was compiled with optimizations")
841 def test_wrapper_call(self):
842 cmd = textwrap.dedent('''
843 class MyList(list):
844 def __init__(self):
845 super().__init__() # wrapper_call()
846
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100847 id("first break point")
Victor Stinner61108332017-02-01 16:29:54 +0100848 l = MyList()
849 ''')
850 # Verify with "py-bt":
851 gdb_output = self.get_stack_trace(cmd,
Victor Stinnerf94b68a2017-02-01 17:00:32 +0100852 cmds_after_breakpoint=['break wrapper_call', 'continue', 'py-bt'])
Victor Stinner72268ae2017-02-01 18:26:14 +0100853 self.assertRegex(gdb_output,
854 r"<method-wrapper u?'__init__' of MyList object at ")
Victor Stinner61108332017-02-01 16:29:54 +0100855
David Malcolm8d37ffa2012-06-27 14:15:34 -0400856
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000857class PyPrintTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100858 @unittest.skipIf(python_is_optimized(),
859 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000860 def test_basic_command(self):
861 'Verify that the "py-print" command works'
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000862 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100863 cmds_after_breakpoint=['py-up', 'py-print args'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000864 self.assertMultilineMatches(bt,
865 r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
866
Vinay Sajip2549f872012-01-04 12:07:30 +0000867 @unittest.skipIf(python_is_optimized(),
868 "Python was compiled with optimizations")
Victor Stinner50eb60e2010-04-20 22:32:07 +0000869 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000870 def test_print_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000871 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100872 cmds_after_breakpoint=['py-up', 'py-up', 'py-print c', 'py-print b', 'py-print a'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000873 self.assertMultilineMatches(bt,
874 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
875
Victor Stinnerd2084162011-12-19 13:42:24 +0100876 @unittest.skipIf(python_is_optimized(),
877 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000878 def test_printing_global(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000879 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100880 cmds_after_breakpoint=['py-up', 'py-print __name__'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000881 self.assertMultilineMatches(bt,
882 r".*\nglobal '__name__' = '__main__'\n.*")
883
Victor Stinnerd2084162011-12-19 13:42:24 +0100884 @unittest.skipIf(python_is_optimized(),
885 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000886 def test_printing_builtin(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000887 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100888 cmds_after_breakpoint=['py-up', 'py-print len'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000889 self.assertMultilineMatches(bt,
Antoine Pitrou4d098732011-11-26 01:42:03 +0100890 r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000891
892class PyLocalsTests(DebuggerTests):
Victor Stinnerd2084162011-12-19 13:42:24 +0100893 @unittest.skipIf(python_is_optimized(),
894 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000895 def test_basic_command(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000896 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100897 cmds_after_breakpoint=['py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000898 self.assertMultilineMatches(bt,
899 r".*\nargs = \(1, 2, 3\)\n.*")
900
Victor Stinner50eb60e2010-04-20 22:32:07 +0000901 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
Vinay Sajip2549f872012-01-04 12:07:30 +0000902 @unittest.skipIf(python_is_optimized(),
903 "Python was compiled with optimizations")
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000904 def test_locals_after_up(self):
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000905 bt = self.get_stack_trace(script=self.get_sample_script(),
Victor Stinnere3d75c62016-11-22 22:53:18 +0100906 cmds_after_breakpoint=['py-up', 'py-up', 'py-locals'])
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000907 self.assertMultilineMatches(bt,
908 r".*\na = 1\nb = 2\nc = 3\n.*")
909
910def test_main():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200911 if support.verbose:
Victor Stinner2f3ac1e2015-09-02 23:12:14 +0200912 print("GDB version %s.%s:" % (gdb_major_version, gdb_minor_version))
Victor Stinner5b6b4a82015-09-02 23:19:55 +0200913 for line in gdb_version.splitlines():
Antoine Pitroud0f3e072013-09-21 23:56:17 +0200914 print(" " * 4 + line)
Martin v. Löwis5226fd62010-04-21 06:05:58 +0000915 run_unittest(PrettyPrintTests,
916 PyListTests,
917 StackNavigationTests,
918 PyBtTests,
919 PyPrintTests,
920 PyLocalsTests
Benjamin Peterson6a6666a2010-04-11 21:49:28 +0000921 )
922
923if __name__ == "__main__":
924 test_main()