test_gdb.py revision 73bcde20bca31d6a1bba10b763cfaa192f277d23
1# 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 11import sysconfig 12 13from test.test_support import run_unittest, findfile 14 15try: 16 gdb_version, _ = subprocess.Popen(["gdb", "-nx", "--version"], 17 stdout=subprocess.PIPE).communicate() 18except OSError: 19 # This is what "no gdb" looks like. There may, however, be other 20 # errors that manifest this way too. 21 raise unittest.SkipTest("Couldn't find gdb on the path") 22gdb_version_number = re.search("^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: 26 raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding" 27 " Saw:\n" + gdb_version) 28if sys.platform.startswith("sunos"): 29 raise unittest.SkipTest("test doesn't work very well on Solaris") 30 31 32# Location of custom hooks file in a repository checkout. 33checkout_hook_path = os.path.join(os.path.dirname(sys.executable), 34 'python-gdb.py') 35 36def run_gdb(*args, **env_vars): 37 """Runs gdb in batch mode with the additional arguments given by *args. 38 39 Returns its (stdout, stderr) 40 """ 41 if env_vars: 42 env = os.environ.copy() 43 env.update(env_vars) 44 else: 45 env = None 46 # -nx: Do not execute commands from any .gdbinit initialization files 47 # (issue #22188) 48 base_cmd = ('gdb', '--batch', '-nx') 49 if (gdb_major_version, gdb_minor_version) >= (7, 4): 50 base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path) 51 out, err = subprocess.Popen(base_cmd + args, 52 stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, 53 ).communicate() 54 return out, err 55 56# Verify that "gdb" was built with the embedded python support enabled: 57gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)") 58if not gdbpy_version: 59 raise unittest.SkipTest("gdb not built with embedded python support") 60 61# Verify that "gdb" can load our custom hooks, as OS security settings may 62# disallow this without a customised .gdbinit. 63cmd = ['--args', sys.executable] 64_, gdbpy_errors = run_gdb('--args', sys.executable) 65if "auto-loading has been declined" in gdbpy_errors: 66 msg = "gdb security settings prevent use of custom hooks: " 67 raise unittest.SkipTest(msg + gdbpy_errors.rstrip()) 68 69def python_is_optimized(): 70 cflags = sysconfig.get_config_vars()['PY_CFLAGS'] 71 final_opt = "" 72 for opt in cflags.split(): 73 if opt.startswith('-O'): 74 final_opt = opt 75 return (final_opt and final_opt != '-O0') 76 77def gdb_has_frame_select(): 78 # Does this build of gdb have gdb.Frame.select ? 79 stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))") 80 m = re.match(r'.*\[(.*)\].*', stdout) 81 if not m: 82 raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test") 83 gdb_frame_dir = m.group(1).split(', ') 84 return "'select'" in gdb_frame_dir 85 86HAS_PYUP_PYDOWN = gdb_has_frame_select() 87 88class DebuggerTests(unittest.TestCase): 89 90 """Test that the debugger can debug Python.""" 91 92 def get_stack_trace(self, source=None, script=None, 93 breakpoint='PyObject_Print', 94 cmds_after_breakpoint=None, 95 import_site=False): 96 ''' 97 Run 'python -c SOURCE' under gdb with a breakpoint. 98 99 Support injecting commands after the breakpoint is reached 100 101 Returns the stdout from gdb 102 103 cmds_after_breakpoint: if provided, a list of strings: gdb commands 104 ''' 105 # We use "set breakpoint pending yes" to avoid blocking with a: 106 # Function "foo" not defined. 107 # Make breakpoint pending on future shared library load? (y or [n]) 108 # error, which typically happens python is dynamically linked (the 109 # breakpoints of interest are to be found in the shared library) 110 # When this happens, we still get: 111 # Function "PyObject_Print" not defined. 112 # emitted to stderr each time, alas. 113 114 # Initially I had "--eval-command=continue" here, but removed it to 115 # avoid repeated print breakpoints when traversing hierarchical data 116 # structures 117 118 # Generate a list of commands in gdb's language: 119 commands = ['set breakpoint pending yes', 120 'break %s' % breakpoint, 121 122 # GDB as of 7.4 (?) onwards can distinguish between the 123 # value of a variable at entry vs current value: 124 # http://sourceware.org/gdb/onlinedocs/gdb/Variables.html 125 # which leads to the selftests failing with errors like this: 126 # AssertionError: 'v@entry=()' != '()' 127 # Disable this: 128 'set print entry-values no', 129 130 # The tests assume that the first frame of printed 131 # backtrace will not contain program counter, 132 # that is however not guaranteed by gdb 133 # therefore we need to use 'set print address off' to 134 # make sure the counter is not there. For example: 135 # #0 in PyObject_Print ... 136 # is assumed, but sometimes this can be e.g. 137 # #0 0x00003fffb7dd1798 in PyObject_Print ... 138 'set print address off', 139 140 'run'] 141 if cmds_after_breakpoint: 142 commands += cmds_after_breakpoint 143 else: 144 commands += ['backtrace'] 145 146 # print commands 147 148 # Use "commands" to generate the arguments with which to invoke "gdb": 149 args = ["gdb", "--batch", "-nx"] 150 args += ['--eval-command=%s' % cmd for cmd in commands] 151 args += ["--args", 152 sys.executable] 153 154 if not import_site: 155 # -S suppresses the default 'import site' 156 args += ["-S"] 157 158 if source: 159 args += ["-c", source] 160 elif script: 161 args += [script] 162 163 # print args 164 # print ' '.join(args) 165 166 # Use "args" to invoke gdb, capturing stdout, stderr: 167 out, err = run_gdb(*args, PYTHONHASHSEED='0') 168 169 errlines = err.splitlines() 170 unexpected_errlines = [] 171 172 # Ignore some benign messages on stderr. 173 ignore_patterns = ( 174 'Function "%s" not defined.' % breakpoint, 175 "warning: no loadable sections found in added symbol-file" 176 " system-supplied DSO", 177 "warning: Unable to find libthread_db matching" 178 " inferior's thread library, thread debugging will" 179 " not be available.", 180 "warning: Cannot initialize thread debugging" 181 " library: Debugger service failed", 182 'warning: Could not load shared library symbols for ' 183 'linux-vdso.so', 184 'warning: Could not load shared library symbols for ' 185 'linux-gate.so', 186 'Do you need "set solib-search-path" or ' 187 '"set sysroot"?', 188 'warning: Source file is more recent than executable.', 189 # Issue #19753: missing symbols on System Z 190 'Missing separate debuginfo for ', 191 'Try: zypper install -C ', 192 ) 193 for line in errlines: 194 if not line.startswith(ignore_patterns): 195 unexpected_errlines.append(line) 196 197 # Ensure no unexpected error messages: 198 self.assertEqual(unexpected_errlines, []) 199 return out 200 201 def get_gdb_repr(self, source, 202 cmds_after_breakpoint=None, 203 import_site=False): 204 # Given an input python source representation of data, 205 # run "python -c'print DATA'" under gdb with a breakpoint on 206 # PyObject_Print and scrape out gdb's representation of the "op" 207 # parameter, and verify that the gdb displays the same string 208 # 209 # For a nested structure, the first time we hit the breakpoint will 210 # give us the top-level structure 211 gdb_output = self.get_stack_trace(source, breakpoint='PyObject_Print', 212 cmds_after_breakpoint=cmds_after_breakpoint, 213 import_site=import_site) 214 # gdb can insert additional '\n' and space characters in various places 215 # in its output, depending on the width of the terminal it's connected 216 # to (using its "wrap_here" function) 217 m = re.match('.*#0\s+PyObject_Print\s+\(\s*op\=\s*(.*?),\s+fp=.*\).*', 218 gdb_output, re.DOTALL) 219 if not m: 220 self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output)) 221 return m.group(1), gdb_output 222 223 def assertEndsWith(self, actual, exp_end): 224 '''Ensure that the given "actual" string ends with "exp_end"''' 225 self.assertTrue(actual.endswith(exp_end), 226 msg='%r did not end with %r' % (actual, exp_end)) 227 228 def assertMultilineMatches(self, actual, pattern): 229 m = re.match(pattern, actual, re.DOTALL) 230 self.assertTrue(m, msg='%r did not match %r' % (actual, pattern)) 231 232 def get_sample_script(self): 233 return findfile('gdb_sample.py') 234 235class PrettyPrintTests(DebuggerTests): 236 def test_getting_backtrace(self): 237 gdb_output = self.get_stack_trace('print 42') 238 self.assertTrue('PyObject_Print' in gdb_output) 239 240 def assertGdbRepr(self, val, cmds_after_breakpoint=None): 241 # Ensure that gdb's rendering of the value in a debugged process 242 # matches repr(value) in this process: 243 gdb_repr, gdb_output = self.get_gdb_repr('print ' + repr(val), 244 cmds_after_breakpoint) 245 self.assertEqual(gdb_repr, repr(val)) 246 247 def test_int(self): 248 'Verify the pretty-printing of various "int" values' 249 self.assertGdbRepr(42) 250 self.assertGdbRepr(0) 251 self.assertGdbRepr(-7) 252 self.assertGdbRepr(sys.maxint) 253 self.assertGdbRepr(-sys.maxint) 254 255 def test_long(self): 256 'Verify the pretty-printing of various "long" values' 257 self.assertGdbRepr(0L) 258 self.assertGdbRepr(1000000000000L) 259 self.assertGdbRepr(-1L) 260 self.assertGdbRepr(-1000000000000000L) 261 262 def test_singletons(self): 263 'Verify the pretty-printing of True, False and None' 264 self.assertGdbRepr(True) 265 self.assertGdbRepr(False) 266 self.assertGdbRepr(None) 267 268 def test_dicts(self): 269 'Verify the pretty-printing of dictionaries' 270 self.assertGdbRepr({}) 271 self.assertGdbRepr({'foo': 'bar'}) 272 self.assertGdbRepr("{'foo': 'bar', 'douglas':42}") 273 274 def test_lists(self): 275 'Verify the pretty-printing of lists' 276 self.assertGdbRepr([]) 277 self.assertGdbRepr(range(5)) 278 279 def test_strings(self): 280 'Verify the pretty-printing of strings' 281 self.assertGdbRepr('') 282 self.assertGdbRepr('And now for something hopefully the same') 283 self.assertGdbRepr('string with embedded NUL here \0 and then some more text') 284 self.assertGdbRepr('this is byte 255:\xff and byte 128:\x80') 285 286 def test_tuples(self): 287 'Verify the pretty-printing of tuples' 288 self.assertGdbRepr(tuple()) 289 self.assertGdbRepr((1,)) 290 self.assertGdbRepr(('foo', 'bar', 'baz')) 291 292 def test_unicode(self): 293 'Verify the pretty-printing of unicode values' 294 # Test the empty unicode string: 295 self.assertGdbRepr(u'') 296 297 self.assertGdbRepr(u'hello world') 298 299 # Test printing a single character: 300 # U+2620 SKULL AND CROSSBONES 301 self.assertGdbRepr(u'\u2620') 302 303 # Test printing a Japanese unicode string 304 # (I believe this reads "mojibake", using 3 characters from the CJK 305 # Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE) 306 self.assertGdbRepr(u'\u6587\u5b57\u5316\u3051') 307 308 # Test a character outside the BMP: 309 # U+1D121 MUSICAL SYMBOL C CLEF 310 # This is: 311 # UTF-8: 0xF0 0x9D 0x84 0xA1 312 # UTF-16: 0xD834 0xDD21 313 # This will only work on wide-unicode builds: 314 self.assertGdbRepr(u"\U0001D121") 315 316 def test_sets(self): 317 'Verify the pretty-printing of sets' 318 self.assertGdbRepr(set()) 319 rep = self.get_gdb_repr("print set(['a', 'b'])")[0] 320 self.assertTrue(rep.startswith("set([")) 321 self.assertTrue(rep.endswith("])")) 322 self.assertEqual(eval(rep), {'a', 'b'}) 323 rep = self.get_gdb_repr("print set([4, 5])")[0] 324 self.assertTrue(rep.startswith("set([")) 325 self.assertTrue(rep.endswith("])")) 326 self.assertEqual(eval(rep), {4, 5}) 327 328 # Ensure that we handled sets containing the "dummy" key value, 329 # which happens on deletion: 330 gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b']) 331s.pop() 332print s''') 333 self.assertEqual(gdb_repr, "set(['b'])") 334 335 def test_frozensets(self): 336 'Verify the pretty-printing of frozensets' 337 self.assertGdbRepr(frozenset()) 338 rep = self.get_gdb_repr("print frozenset(['a', 'b'])")[0] 339 self.assertTrue(rep.startswith("frozenset([")) 340 self.assertTrue(rep.endswith("])")) 341 self.assertEqual(eval(rep), {'a', 'b'}) 342 rep = self.get_gdb_repr("print frozenset([4, 5])")[0] 343 self.assertTrue(rep.startswith("frozenset([")) 344 self.assertTrue(rep.endswith("])")) 345 self.assertEqual(eval(rep), {4, 5}) 346 347 def test_exceptions(self): 348 # Test a RuntimeError 349 gdb_repr, gdb_output = self.get_gdb_repr(''' 350try: 351 raise RuntimeError("I am an error") 352except RuntimeError, e: 353 print e 354''') 355 self.assertEqual(gdb_repr, 356 "exceptions.RuntimeError('I am an error',)") 357 358 359 # Test division by zero: 360 gdb_repr, gdb_output = self.get_gdb_repr(''' 361try: 362 a = 1 / 0 363except ZeroDivisionError, e: 364 print e 365''') 366 self.assertEqual(gdb_repr, 367 "exceptions.ZeroDivisionError('integer division or modulo by zero',)") 368 369 def test_classic_class(self): 370 'Verify the pretty-printing of classic class instances' 371 gdb_repr, gdb_output = self.get_gdb_repr(''' 372class Foo: 373 pass 374foo = Foo() 375foo.an_int = 42 376print foo''') 377 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 378 self.assertTrue(m, 379 msg='Unexpected classic-class rendering %r' % gdb_repr) 380 381 def test_modern_class(self): 382 'Verify the pretty-printing of new-style class instances' 383 gdb_repr, gdb_output = self.get_gdb_repr(''' 384class Foo(object): 385 pass 386foo = Foo() 387foo.an_int = 42 388print foo''') 389 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 390 self.assertTrue(m, 391 msg='Unexpected new-style class rendering %r' % gdb_repr) 392 393 def test_subclassing_list(self): 394 'Verify the pretty-printing of an instance of a list subclass' 395 gdb_repr, gdb_output = self.get_gdb_repr(''' 396class Foo(list): 397 pass 398foo = Foo() 399foo += [1, 2, 3] 400foo.an_int = 42 401print foo''') 402 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 403 self.assertTrue(m, 404 msg='Unexpected new-style class rendering %r' % gdb_repr) 405 406 def test_subclassing_tuple(self): 407 'Verify the pretty-printing of an instance of a tuple subclass' 408 # This should exercise the negative tp_dictoffset code in the 409 # new-style class support 410 gdb_repr, gdb_output = self.get_gdb_repr(''' 411class Foo(tuple): 412 pass 413foo = Foo((1, 2, 3)) 414foo.an_int = 42 415print foo''') 416 m = re.match(r'<Foo\(an_int=42\) at remote 0x[0-9a-f]+>', gdb_repr) 417 self.assertTrue(m, 418 msg='Unexpected new-style class rendering %r' % gdb_repr) 419 420 def assertSane(self, source, corruption, expvalue=None, exptype=None): 421 '''Run Python under gdb, corrupting variables in the inferior process 422 immediately before taking a backtrace. 423 424 Verify that the variable's representation is the expected failsafe 425 representation''' 426 if corruption: 427 cmds_after_breakpoint=[corruption, 'backtrace'] 428 else: 429 cmds_after_breakpoint=['backtrace'] 430 431 gdb_repr, gdb_output = \ 432 self.get_gdb_repr(source, 433 cmds_after_breakpoint=cmds_after_breakpoint) 434 435 if expvalue: 436 if gdb_repr == repr(expvalue): 437 # gdb managed to print the value in spite of the corruption; 438 # this is good (see http://bugs.python.org/issue8330) 439 return 440 441 if exptype: 442 pattern = '<' + exptype + ' at remote 0x[0-9a-f]+>' 443 else: 444 # Match anything for the type name; 0xDEADBEEF could point to 445 # something arbitrary (see http://bugs.python.org/issue8330) 446 pattern = '<.* at remote 0x[0-9a-f]+>' 447 448 m = re.match(pattern, gdb_repr) 449 if not m: 450 self.fail('Unexpected gdb representation: %r\n%s' % \ 451 (gdb_repr, gdb_output)) 452 453 def test_NULL_ptr(self): 454 'Ensure that a NULL PyObject* is handled gracefully' 455 gdb_repr, gdb_output = ( 456 self.get_gdb_repr('print 42', 457 cmds_after_breakpoint=['set variable op=0', 458 'backtrace']) 459 ) 460 461 self.assertEqual(gdb_repr, '0x0') 462 463 def test_NULL_ob_type(self): 464 'Ensure that a PyObject* with NULL ob_type is handled gracefully' 465 self.assertSane('print 42', 466 'set op->ob_type=0') 467 468 def test_corrupt_ob_type(self): 469 'Ensure that a PyObject* with a corrupt ob_type is handled gracefully' 470 self.assertSane('print 42', 471 'set op->ob_type=0xDEADBEEF', 472 expvalue=42) 473 474 def test_corrupt_tp_flags(self): 475 'Ensure that a PyObject* with a type with corrupt tp_flags is handled' 476 self.assertSane('print 42', 477 'set op->ob_type->tp_flags=0x0', 478 expvalue=42) 479 480 def test_corrupt_tp_name(self): 481 'Ensure that a PyObject* with a type with corrupt tp_name is handled' 482 self.assertSane('print 42', 483 'set op->ob_type->tp_name=0xDEADBEEF', 484 expvalue=42) 485 486 def test_NULL_instance_dict(self): 487 'Ensure that a PyInstanceObject with with a NULL in_dict is handled' 488 self.assertSane(''' 489class Foo: 490 pass 491foo = Foo() 492foo.an_int = 42 493print foo''', 494 'set ((PyInstanceObject*)op)->in_dict = 0', 495 exptype='Foo') 496 497 def test_builtins_help(self): 498 'Ensure that the new-style class _Helper in site.py can be handled' 499 # (this was the issue causing tracebacks in 500 # http://bugs.python.org/issue8032#msg100537 ) 501 502 gdb_repr, gdb_output = self.get_gdb_repr('print __builtins__.help', import_site=True) 503 m = re.match(r'<_Helper at remote 0x[0-9a-f]+>', gdb_repr) 504 self.assertTrue(m, 505 msg='Unexpected rendering %r' % gdb_repr) 506 507 def test_selfreferential_list(self): 508 '''Ensure that a reference loop involving a list doesn't lead proxyval 509 into an infinite loop:''' 510 gdb_repr, gdb_output = \ 511 self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; print a") 512 513 self.assertEqual(gdb_repr, '[3, 4, 5, [...]]') 514 515 gdb_repr, gdb_output = \ 516 self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; print a") 517 518 self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]') 519 520 def test_selfreferential_dict(self): 521 '''Ensure that a reference loop involving a dict doesn't lead proxyval 522 into an infinite loop:''' 523 gdb_repr, gdb_output = \ 524 self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; print a") 525 526 self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}") 527 528 def test_selfreferential_old_style_instance(self): 529 gdb_repr, gdb_output = \ 530 self.get_gdb_repr(''' 531class Foo: 532 pass 533foo = Foo() 534foo.an_attr = foo 535print foo''') 536 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>', 537 gdb_repr), 538 'Unexpected gdb representation: %r\n%s' % \ 539 (gdb_repr, gdb_output)) 540 541 def test_selfreferential_new_style_instance(self): 542 gdb_repr, gdb_output = \ 543 self.get_gdb_repr(''' 544class Foo(object): 545 pass 546foo = Foo() 547foo.an_attr = foo 548print foo''') 549 self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>', 550 gdb_repr), 551 'Unexpected gdb representation: %r\n%s' % \ 552 (gdb_repr, gdb_output)) 553 554 gdb_repr, gdb_output = \ 555 self.get_gdb_repr(''' 556class Foo(object): 557 pass 558a = Foo() 559b = Foo() 560a.an_attr = b 561b.an_attr = a 562print a''') 563 self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x[0-9a-f]+>\) at remote 0x[0-9a-f]+>', 564 gdb_repr), 565 'Unexpected gdb representation: %r\n%s' % \ 566 (gdb_repr, gdb_output)) 567 568 def test_truncation(self): 569 'Verify that very long output is truncated' 570 gdb_repr, gdb_output = self.get_gdb_repr('print range(1000)') 571 self.assertEqual(gdb_repr, 572 "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, " 573 "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, " 574 "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, " 575 "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, " 576 "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, " 577 "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, " 578 "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, " 579 "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, " 580 "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, " 581 "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, " 582 "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, " 583 "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, " 584 "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, " 585 "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, " 586 "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, " 587 "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, " 588 "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, " 589 "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, " 590 "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, " 591 "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, " 592 "224, 225, 226...(truncated)") 593 self.assertEqual(len(gdb_repr), 594 1024 + len('...(truncated)')) 595 596 def test_builtin_function(self): 597 gdb_repr, gdb_output = self.get_gdb_repr('print len') 598 self.assertEqual(gdb_repr, '<built-in function len>') 599 600 def test_builtin_method(self): 601 gdb_repr, gdb_output = self.get_gdb_repr('import sys; print sys.stdout.readlines') 602 self.assertTrue(re.match('<built-in method readlines of file object at remote 0x[0-9a-f]+>', 603 gdb_repr), 604 'Unexpected gdb representation: %r\n%s' % \ 605 (gdb_repr, gdb_output)) 606 607 def test_frames(self): 608 gdb_output = self.get_stack_trace(''' 609def foo(a, b, c): 610 pass 611 612foo(3, 4, 5) 613print foo.__code__''', 614 breakpoint='PyObject_Print', 615 cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)op)->co_zombieframe)'] 616 ) 617 self.assertTrue(re.match(r'.*\s+\$1 =\s+Frame 0x[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*', 618 gdb_output, 619 re.DOTALL), 620 'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output)) 621 622@unittest.skipIf(python_is_optimized(), 623 "Python was compiled with optimizations") 624class PyListTests(DebuggerTests): 625 def assertListing(self, expected, actual): 626 self.assertEndsWith(actual, expected) 627 628 def test_basic_command(self): 629 'Verify that the "py-list" command works' 630 bt = self.get_stack_trace(script=self.get_sample_script(), 631 cmds_after_breakpoint=['py-list']) 632 633 self.assertListing(' 5 \n' 634 ' 6 def bar(a, b, c):\n' 635 ' 7 baz(a, b, c)\n' 636 ' 8 \n' 637 ' 9 def baz(*args):\n' 638 ' >10 print(42)\n' 639 ' 11 \n' 640 ' 12 foo(1, 2, 3)\n', 641 bt) 642 643 def test_one_abs_arg(self): 644 'Verify the "py-list" command with one absolute argument' 645 bt = self.get_stack_trace(script=self.get_sample_script(), 646 cmds_after_breakpoint=['py-list 9']) 647 648 self.assertListing(' 9 def baz(*args):\n' 649 ' >10 print(42)\n' 650 ' 11 \n' 651 ' 12 foo(1, 2, 3)\n', 652 bt) 653 654 def test_two_abs_args(self): 655 'Verify the "py-list" command with two absolute arguments' 656 bt = self.get_stack_trace(script=self.get_sample_script(), 657 cmds_after_breakpoint=['py-list 1,3']) 658 659 self.assertListing(' 1 # Sample script for use by test_gdb.py\n' 660 ' 2 \n' 661 ' 3 def foo(a, b, c):\n', 662 bt) 663 664class StackNavigationTests(DebuggerTests): 665 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 666 @unittest.skipIf(python_is_optimized(), 667 "Python was compiled with optimizations") 668 def test_pyup_command(self): 669 'Verify that the "py-up" command works' 670 bt = self.get_stack_trace(script=self.get_sample_script(), 671 cmds_after_breakpoint=['py-up']) 672 self.assertMultilineMatches(bt, 673 r'''^.* 674#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\) 675 baz\(a, b, c\) 676$''') 677 678 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 679 def test_down_at_bottom(self): 680 'Verify handling of "py-down" at the bottom of the stack' 681 bt = self.get_stack_trace(script=self.get_sample_script(), 682 cmds_after_breakpoint=['py-down']) 683 self.assertEndsWith(bt, 684 'Unable to find a newer python frame\n') 685 686 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 687 def test_up_at_top(self): 688 'Verify handling of "py-up" at the top of the stack' 689 bt = self.get_stack_trace(script=self.get_sample_script(), 690 cmds_after_breakpoint=['py-up'] * 4) 691 self.assertEndsWith(bt, 692 'Unable to find an older python frame\n') 693 694 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 695 @unittest.skipIf(python_is_optimized(), 696 "Python was compiled with optimizations") 697 def test_up_then_down(self): 698 'Verify "py-up" followed by "py-down"' 699 bt = self.get_stack_trace(script=self.get_sample_script(), 700 cmds_after_breakpoint=['py-up', 'py-down']) 701 self.assertMultilineMatches(bt, 702 r'''^.* 703#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\) 704 baz\(a, b, c\) 705#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\) 706 print\(42\) 707$''') 708 709class PyBtTests(DebuggerTests): 710 @unittest.skipIf(python_is_optimized(), 711 "Python was compiled with optimizations") 712 def test_basic_command(self): 713 'Verify that the "py-bt" command works' 714 bt = self.get_stack_trace(script=self.get_sample_script(), 715 cmds_after_breakpoint=['py-bt']) 716 self.assertMultilineMatches(bt, 717 r'''^.* 718#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\) 719 baz\(a, b, c\) 720#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\) 721 bar\(a, b, c\) 722#[0-9]+ Frame 0x[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\) 723 foo\(1, 2, 3\) 724''') 725 726class PyPrintTests(DebuggerTests): 727 @unittest.skipIf(python_is_optimized(), 728 "Python was compiled with optimizations") 729 def test_basic_command(self): 730 'Verify that the "py-print" command works' 731 bt = self.get_stack_trace(script=self.get_sample_script(), 732 cmds_after_breakpoint=['py-print args']) 733 self.assertMultilineMatches(bt, 734 r".*\nlocal 'args' = \(1, 2, 3\)\n.*") 735 736 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 737 @unittest.skipIf(python_is_optimized(), 738 "Python was compiled with optimizations") 739 def test_print_after_up(self): 740 bt = self.get_stack_trace(script=self.get_sample_script(), 741 cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a']) 742 self.assertMultilineMatches(bt, 743 r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*") 744 745 @unittest.skipIf(python_is_optimized(), 746 "Python was compiled with optimizations") 747 def test_printing_global(self): 748 bt = self.get_stack_trace(script=self.get_sample_script(), 749 cmds_after_breakpoint=['py-print __name__']) 750 self.assertMultilineMatches(bt, 751 r".*\nglobal '__name__' = '__main__'\n.*") 752 753 @unittest.skipIf(python_is_optimized(), 754 "Python was compiled with optimizations") 755 def test_printing_builtin(self): 756 bt = self.get_stack_trace(script=self.get_sample_script(), 757 cmds_after_breakpoint=['py-print len']) 758 self.assertMultilineMatches(bt, 759 r".*\nbuiltin 'len' = <built-in function len>\n.*") 760 761class PyLocalsTests(DebuggerTests): 762 @unittest.skipIf(python_is_optimized(), 763 "Python was compiled with optimizations") 764 def test_basic_command(self): 765 bt = self.get_stack_trace(script=self.get_sample_script(), 766 cmds_after_breakpoint=['py-locals']) 767 self.assertMultilineMatches(bt, 768 r".*\nargs = \(1, 2, 3\)\n.*") 769 770 @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands") 771 @unittest.skipIf(python_is_optimized(), 772 "Python was compiled with optimizations") 773 def test_locals_after_up(self): 774 bt = self.get_stack_trace(script=self.get_sample_script(), 775 cmds_after_breakpoint=['py-up', 'py-locals']) 776 self.assertMultilineMatches(bt, 777 r".*\na = 1\nb = 2\nc = 3\n.*") 778 779def test_main(): 780 run_unittest(PrettyPrintTests, 781 PyListTests, 782 StackNavigationTests, 783 PyBtTests, 784 PyPrintTests, 785 PyLocalsTests 786 ) 787 788if __name__ == "__main__": 789 test_main() 790