Debian Codegraph @

lib-python/3/test/test_faulthandler.py

raw symbols SCIP
1 from contextlib import contextmanager
2 import datetime
3 import faulthandler
4 import os
5 import re
6 import signal
7 import subprocess
8 import sys
9 from test import support
10 from test.support import os_helper, script_helper, is_android, MS_WINDOWS
11 import tempfile
12 import unittest
13 from textwrap import dedent
14
15 try:
16 import _testcapi
17 except ImportError:
18 _testcapi = None
19
20 if not support.has_subprocess_support:
21 raise unittest.SkipTest("test module requires subprocess")
22
23 TIMEOUT = 0.5
24
25
26 def expected_traceback(lineno1, lineno2, header, min_count=1):
27 regex = header
28 regex += ' File "<string>", line %s in func\n' % lineno1
29 regex += ' File "<string>", line %s in <module>' % lineno2
30 if 1 < min_count:
31 return '^' + (regex + '\n') * (min_count - 1) + regex
32 else:
33 return '^' + regex + '$'
34
35 def skip_segfault_on_android(test):
36 # gh-76319: Raising SIGSEGV on Android may not cause a crash.
37 return unittest.skipIf(is_android,
38 'raising SIGSEGV on Android is unreliable')(test)
39
40 @contextmanager
41 def temporary_filename():
42 filename = tempfile.mktemp()
43 try:
44 yield filename
45 finally:
46 os_helper.unlink(filename)
47
48 # NOTE: all the tests give a sensible result on PyPy too (tested
49 # manually in py3.5, revision e0ba73be669b, by setting maxDiff=None in
50 # the class). The details of the outputs differ too much to make it
51 # easy to generalize the tests to accept both CPython's and PyPy's
52 # style. For now let's skip the tests on PyPy.
53 @support.cpython_only
54 class FaultHandlerTests(unittest.TestCase):
55
56 def get_output(self, code, filename=None, fd=None):
57 """
58 Run the specified code in Python (in a new child process) and read the
59 output from the standard error or from a file (if filename is set).
60 Return the output lines as a list.
61
62 Strip the reference count from the standard error for Python debug
63 build, and replace "Current thread 0x00007f8d8fbd9700" by "Current
64 thread XXX".
65 """
66 code = dedent(code).strip()
67 pass_fds = []
68 if fd is not None:
69 pass_fds.append(fd)
70 env = dict(os.environ)
71
72 # Sanitizers must not handle SIGSEGV (ex: for test_enable_fd())
73 option = 'handle_segv=0'
74 support.set_sanitizer_env_var(env, option)
75
76 with support.SuppressCrashReport():
77 process = script_helper.spawn_python('-c', code,
78 pass_fds=pass_fds,
79 env=env)
80 with process:
81 output, stderr = process.communicate()
82 exitcode = process.wait()
83 output = output.decode('ascii', 'backslashreplace')
84 if filename:
85 self.assertEqual(output, '')
86 with open(filename, "rb") as fp:
87 output = fp.read()
88 output = output.decode('ascii', 'backslashreplace')
89 elif fd is not None:
90 self.assertEqual(output, '')
91 os.lseek(fd, os.SEEK_SET, 0)
92 with open(fd, "rb", closefd=False) as fp:
93 output = fp.read()
94 output = output.decode('ascii', 'backslashreplace')
95 return output.splitlines(), exitcode
96
97 def check_error(self, code, lineno, fatal_error, *,
98 filename=None, all_threads=True, other_regex=None,
99 fd=None, know_current_thread=True,
100 py_fatal_error=False,
101 garbage_collecting=False,
102 function='<module>'):
103 """
104 Check that the fault handler for fatal errors is enabled and check the
105 traceback from the child process output.
106
107 Raise an error if the output doesn't match the expected format.
108 """
109 if all_threads:
110 if know_current_thread:
111 header = 'Current thread 0x[0-9a-f]+'
112 else:
113 header = 'Thread 0x[0-9a-f]+'
114 else:
115 header = 'Stack'
116 regex = [f'^{fatal_error}']
117 if py_fatal_error:
118 regex.append("Python runtime state: initialized")
119 regex.append('')
120 regex.append(fr'{header} \(most recent call first\):')
121 if garbage_collecting:
122 regex.append(' Garbage-collecting')
123 regex.append(fr' File "<string>", line {lineno} in {function}')
124 regex = '\n'.join(regex)
125
126 if other_regex:
127 regex = f'(?:{regex}|{other_regex})'
128
129 # Enable MULTILINE flag
130 regex = f'(?m){regex}'
131 output, exitcode = self.get_output(code, filename=filename, fd=fd)
132 output = '\n'.join(output)
133 self.assertRegex(output, regex)
134 self.assertNotEqual(exitcode, 0)
135
136 def check_fatal_error(self, code, line_number, name_regex, func=None, **kw):
137 if func:
138 name_regex = '%s: %s' % (func, name_regex)
139 fatal_error = 'Fatal Python error: %s' % name_regex
140 self.check_error(code, line_number, fatal_error, **kw)
141
142 def check_windows_exception(self, code, line_number, name_regex, **kw):
143 fatal_error = 'Windows fatal exception: %s' % name_regex
144 self.check_error(code, line_number, fatal_error, **kw)
145
146 @unittest.skipIf(sys.platform.startswith('aix'),
147 "the first page of memory is a mapped read-only on AIX")
148 def test_read_null(self):
149 if not MS_WINDOWS:
150 self.check_fatal_error("""
151 import faulthandler
152 faulthandler.enable()
153 faulthandler._read_null()
154 """,
155 3,
156 # Issue #12700: Read NULL raises SIGILL on Mac OS X Lion
157 '(?:Segmentation fault'
158 '|Bus error'
159 '|Illegal instruction)')
160 else:
161 self.check_windows_exception("""
162 import faulthandler
163 faulthandler.enable()
164 faulthandler._read_null()
165 """,
166 3,
167 'access violation')
168
169 @skip_segfault_on_android
170 def test_sigsegv(self):
171 self.check_fatal_error("""
172 import faulthandler
173 faulthandler.enable()
174 faulthandler._sigsegv()
175 """,
176 3,
177 'Segmentation fault')
178
179 @skip_segfault_on_android
180 def test_gc(self):
181 # bpo-44466: Detect if the GC is running
182 self.check_fatal_error("""
183 import faulthandler
184 import gc
185 import sys
186
187 faulthandler.enable()
188
189 class RefCycle:
190 def __del__(self):
191 faulthandler._sigsegv()
192
193 # create a reference cycle which triggers a fatal
194 # error in a destructor
195 a = RefCycle()
196 b = RefCycle()
197 a.b = b
198 b.a = a
199
200 # Delete the objects, not the cycle
201 a = None
202 b = None
203
204 # Break the reference cycle: call __del__()
205 gc.collect()
206
207 # Should not reach this line
208 print("exit", file=sys.stderr)
209 """,
210 9,
211 'Segmentation fault',
212 function='__del__',
213 garbage_collecting=True)
214
215 def test_fatal_error_c_thread(self):
216 self.check_fatal_error("""
217 import faulthandler
218 faulthandler.enable()
219 faulthandler._fatal_error_c_thread()
220 """,
221 3,
222 'in new thread',
223 know_current_thread=False,
224 func='faulthandler_fatal_error_thread',
225 py_fatal_error=True)
226
227 def test_sigabrt(self):
228 self.check_fatal_error("""
229 import faulthandler
230 faulthandler.enable()
231 faulthandler._sigabrt()
232 """,
233 3,
234 'Aborted')
235
236 @unittest.skipIf(sys.platform == 'win32',
237 "SIGFPE cannot be caught on Windows")
238 def test_sigfpe(self):
239 self.check_fatal_error("""
240 import faulthandler
241 faulthandler.enable()
242 faulthandler._sigfpe()
243 """,
244 3,
245 'Floating point exception')
246
247 @unittest.skipIf(_testcapi is None, 'need _testcapi')
248 @unittest.skipUnless(hasattr(signal, 'SIGBUS'), 'need signal.SIGBUS')
249 @skip_segfault_on_android
250 def test_sigbus(self):
251 self.check_fatal_error("""
252 import faulthandler
253 import signal
254
255 faulthandler.enable()
256 signal.raise_signal(signal.SIGBUS)
257 """,
258 5,
259 'Bus error')
260
261 @unittest.skipIf(_testcapi is None, 'need _testcapi')
262 @unittest.skipUnless(hasattr(signal, 'SIGILL'), 'need signal.SIGILL')
263 @skip_segfault_on_android
264 def test_sigill(self):
265 self.check_fatal_error("""
266 import faulthandler
267 import signal
268
269 faulthandler.enable()
270 signal.raise_signal(signal.SIGILL)
271 """,
272 5,
273 'Illegal instruction')
274
275 def check_fatal_error_func(self, release_gil):
276 # Test that Py_FatalError() dumps a traceback
277 with support.SuppressCrashReport():
278 self.check_fatal_error(f"""
279 import _testcapi
280 _testcapi.fatal_error(b'xyz', {release_gil})
281 """,
282 2,
283 'xyz',
284 func='test_fatal_error',
285 py_fatal_error=True)
286
287 def test_fatal_error(self):
288 self.check_fatal_error_func(False)
289
290 def test_fatal_error_without_gil(self):
291 self.check_fatal_error_func(True)
292
293 @unittest.skipIf(sys.platform.startswith('openbsd'),
294 "Issue #12868: sigaltstack() doesn't work on "
295 "OpenBSD if Python is compiled with pthread")
296 @unittest.skipIf(not hasattr(faulthandler, '_stack_overflow'),
297 'need faulthandler._stack_overflow()')
298 def test_stack_overflow(self):
299 self.check_fatal_error("""
300 import faulthandler
301 faulthandler.enable()
302 faulthandler._stack_overflow()
303 """,
304 3,
305 '(?:Segmentation fault|Bus error)',
306 other_regex='unable to raise a stack overflow')
307
308 @skip_segfault_on_android
309 def test_gil_released(self):
310 self.check_fatal_error("""
311 import faulthandler
312 faulthandler.enable()
313 faulthandler._sigsegv(True)
314 """,
315 3,
316 'Segmentation fault')
317
318 @skip_segfault_on_android
319 def test_enable_file(self):
320 with temporary_filename() as filename:
321 self.check_fatal_error("""
322 import faulthandler
323 output = open({filename}, 'wb')
324 faulthandler.enable(output)
325 faulthandler._sigsegv()
326 """.format(filename=repr(filename)),
327 4,
328 'Segmentation fault',
329 filename=filename)
330
331 @unittest.skipIf(sys.platform == "win32",
332 "subprocess doesn't support pass_fds on Windows")
333 @skip_segfault_on_android
334 def test_enable_fd(self):
335 with tempfile.TemporaryFile('wb+') as fp:
336 fd = fp.fileno()
337 self.check_fatal_error("""
338 import faulthandler
339 import sys
340 faulthandler.enable(%s)
341 faulthandler._sigsegv()
342 """ % fd,
343 4,
344 'Segmentation fault',
345 fd=fd)
346
347 @skip_segfault_on_android
348 def test_enable_single_thread(self):
349 self.check_fatal_error("""
350 import faulthandler
351 faulthandler.enable(all_threads=False)
352 faulthandler._sigsegv()
353 """,
354 3,
355 'Segmentation fault',
356 all_threads=False)
357
358 @skip_segfault_on_android
359 def test_disable(self):
360 code = """
361 import faulthandler
362 faulthandler.enable()
363 faulthandler.disable()
364 faulthandler._sigsegv()
365 """
366 not_expected = 'Fatal Python error'
367 stderr, exitcode = self.get_output(code)
368 stderr = '\n'.join(stderr)
369 self.assertTrue(not_expected not in stderr,
370 "%r is present in %r" % (not_expected, stderr))
371 self.assertNotEqual(exitcode, 0)
372
373 @skip_segfault_on_android
374 def test_dump_ext_modules(self):
375 code = """
376 import faulthandler
377 import sys
378 # Don't filter stdlib module names
379 sys.stdlib_module_names = frozenset()
380 faulthandler.enable()
381 faulthandler._sigsegv()
382 """
383 stderr, exitcode = self.get_output(code)
384 stderr = '\n'.join(stderr)
385 match = re.search(r'^Extension modules:(.*) \(total: [0-9]+\)$',
386 stderr, re.MULTILINE)
387 if not match:
388 self.fail(f"Cannot find 'Extension modules:' in {stderr!r}")
389 modules = set(match.group(1).strip().split(', '))
390 for name in ('sys', 'faulthandler'):
391 self.assertIn(name, modules)
392
393 def test_is_enabled(self):
394 orig_stderr = sys.stderr
395 try:
396 # regrtest may replace sys.stderr by io.StringIO object, but
397 # faulthandler.enable() requires that sys.stderr has a fileno()
398 # method
399 sys.stderr = sys.__stderr__
400
401 was_enabled = faulthandler.is_enabled()
402 try:
403 faulthandler.enable()
404 self.assertTrue(faulthandler.is_enabled())
405 faulthandler.disable()
406 self.assertFalse(faulthandler.is_enabled())
407 finally:
408 if was_enabled:
409 faulthandler.enable()
410 else:
411 faulthandler.disable()
412 finally:
413 sys.stderr = orig_stderr
414
415 @support.requires_subprocess()
416 def test_disabled_by_default(self):
417 # By default, the module should be disabled
418 code = "import faulthandler; print(faulthandler.is_enabled())"
419 args = (sys.executable, "-E", "-c", code)
420 # don't use assert_python_ok() because it always enables faulthandler
421 output = subprocess.check_output(args)
422 self.assertEqual(output.rstrip(), b"False")
423
424 @support.requires_subprocess()
425 def test_sys_xoptions(self):
426 # Test python -X faulthandler
427 code = "import faulthandler; print(faulthandler.is_enabled())"
428 args = filter(None, (sys.executable,
429 "-E" if sys.flags.ignore_environment else "",
430 "-X", "faulthandler", "-c", code))
431 env = os.environ.copy()
432 env.pop("PYTHONFAULTHANDLER", None)
433 # don't use assert_python_ok() because it always enables faulthandler
434 output = subprocess.check_output(args, env=env)
435 self.assertEqual(output.rstrip(), b"True")
436
437 @support.requires_subprocess()
438 def test_env_var(self):
439 # empty env var
440 code = "import faulthandler; print(faulthandler.is_enabled())"
441 args = (sys.executable, "-c", code)
442 env = dict(os.environ)
443 env['PYTHONFAULTHANDLER'] = ''
444 env['PYTHONDEVMODE'] = ''
445 # don't use assert_python_ok() because it always enables faulthandler
446 output = subprocess.check_output(args, env=env)
447 self.assertEqual(output.rstrip(), b"False")
448
449 # non-empty env var
450 env = dict(os.environ)
451 env['PYTHONFAULTHANDLER'] = '1'
452 env['PYTHONDEVMODE'] = ''
453 output = subprocess.check_output(args, env=env)
454 self.assertEqual(output.rstrip(), b"True")
455
456 def check_dump_traceback(self, *, filename=None, fd=None):
457 """
458 Explicitly call dump_traceback() function and check its output.
459 Raise an error if the output doesn't match the expected format.
460 """
461 code = """
462 import faulthandler
463
464 filename = {filename!r}
465 fd = {fd}
466
467 def funcB():
468 if filename:
469 with open(filename, "wb") as fp:
470 faulthandler.dump_traceback(fp, all_threads=False)
471 elif fd is not None:
472 faulthandler.dump_traceback(fd,
473 all_threads=False)
474 else:
475 faulthandler.dump_traceback(all_threads=False)
476
477 def funcA():
478 funcB()
479
480 funcA()
481 """
482 code = code.format(
483 filename=filename,
484 fd=fd,
485 )
486 if filename:
487 lineno = 9
488 elif fd is not None:
489 lineno = 11
490 else:
491 lineno = 14
492 expected = [
493 'Stack (most recent call first):',
494 ' File "<string>", line %s in funcB' % lineno,
495 ' File "<string>", line 17 in funcA',
496 ' File "<string>", line 19 in <module>'
497 ]
498 trace, exitcode = self.get_output(code, filename, fd)
499 self.assertEqual(trace, expected)
500 self.assertEqual(exitcode, 0)
501
502 def test_dump_traceback(self):
503 self.check_dump_traceback()
504
505 def test_dump_traceback_file(self):
506 with temporary_filename() as filename:
507 self.check_dump_traceback(filename=filename)
508
509 @unittest.skipIf(sys.platform == "win32",
510 "subprocess doesn't support pass_fds on Windows")
511 def test_dump_traceback_fd(self):
512 with tempfile.TemporaryFile('wb+') as fp:
513 self.check_dump_traceback(fd=fp.fileno())
514
515 def test_truncate(self):
516 maxlen = 500
517 func_name = 'x' * (maxlen + 50)
518 truncated = 'x' * maxlen + '...'
519 code = """
520 import faulthandler
521
522 def {func_name}():
523 faulthandler.dump_traceback(all_threads=False)
524
525 {func_name}()
526 """
527 code = code.format(
528 func_name=func_name,
529 )
530 expected = [
531 'Stack (most recent call first):',
532 ' File "<string>", line 4 in %s' % truncated,
533 ' File "<string>", line 6 in <module>'
534 ]
535 trace, exitcode = self.get_output(code)
536 self.assertEqual(trace, expected)
537 self.assertEqual(exitcode, 0)
538
539 def check_dump_traceback_threads(self, filename):
540 """
541 Call explicitly dump_traceback(all_threads=True) and check the output.
542 Raise an error if the output doesn't match the expected format.
543 """
544 code = """
545 import faulthandler
546 from threading import Thread, Event
547 import time
548
549 def dump():
550 if {filename}:
551 with open({filename}, "wb") as fp:
552 faulthandler.dump_traceback(fp, all_threads=True)
553 else:
554 faulthandler.dump_traceback(all_threads=True)
555
556 class Waiter(Thread):
557 # avoid blocking if the main thread raises an exception.
558 daemon = True
559
560 def __init__(self):
561 Thread.__init__(self)
562 self.running = Event()
563 self.stop = Event()
564
565 def run(self):
566 self.running.set()
567 self.stop.wait()
568
569 waiter = Waiter()
570 waiter.start()
571 waiter.running.wait()
572 dump()
573 waiter.stop.set()
574 waiter.join()
575 """
576 code = code.format(filename=repr(filename))
577 output, exitcode = self.get_output(code, filename)
578 output = '\n'.join(output)
579 if filename:
580 lineno = 8
581 else:
582 lineno = 10
583 regex = r"""
584 ^Thread 0x[0-9a-f]+ \(most recent call first\):
585 (?: File ".*threading.py", line [0-9]+ in [_a-z]+
586 ){{1,3}} File "<string>", line 23 in run
587 File ".*threading.py", line [0-9]+ in _bootstrap_inner
588 File ".*threading.py", line [0-9]+ in _bootstrap
589
590 Current thread 0x[0-9a-f]+ \(most recent call first\):
591 File "<string>", line {lineno} in dump
592 File "<string>", line 28 in <module>$
593 """
594 regex = dedent(regex.format(lineno=lineno)).strip()
595 self.assertRegex(output, regex)
596 self.assertEqual(exitcode, 0)
597
598 def test_dump_traceback_threads(self):
599 self.check_dump_traceback_threads(None)
600
601 def test_dump_traceback_threads_file(self):
602 with temporary_filename() as filename:
603 self.check_dump_traceback_threads(filename)
604
605 def check_dump_traceback_later(self, repeat=False, cancel=False, loops=1,
606 *, filename=None, fd=None):
607 """
608 Check how many times the traceback is written in timeout x 2.5 seconds,
609 or timeout x 3.5 seconds if cancel is True: 1, 2 or 3 times depending
610 on repeat and cancel options.
611
612 Raise an error if the output doesn't match the expect format.
613 """
614 timeout_str = str(datetime.timedelta(seconds=TIMEOUT))
615 code = """
616 import faulthandler
617 import time
618 import sys
619
620 timeout = {timeout}
621 repeat = {repeat}
622 cancel = {cancel}
623 loops = {loops}
624 filename = {filename!r}
625 fd = {fd}
626
627 def func(timeout, repeat, cancel, file, loops):
628 for loop in range(loops):
629 faulthandler.dump_traceback_later(timeout, repeat=repeat, file=file)
630 if cancel:
631 faulthandler.cancel_dump_traceback_later()
632 time.sleep(timeout * 5)
633 faulthandler.cancel_dump_traceback_later()
634
635 if filename:
636 file = open(filename, "wb")
637 elif fd is not None:
638 file = sys.stderr.fileno()
639 else:
640 file = None
641 func(timeout, repeat, cancel, file, loops)
642 if filename:
643 file.close()
644 """
645 code = code.format(
646 timeout=TIMEOUT,
647 repeat=repeat,
648 cancel=cancel,
649 loops=loops,
650 filename=filename,
651 fd=fd,
652 )
653 trace, exitcode = self.get_output(code, filename)
654 trace = '\n'.join(trace)
655
656 if not cancel:
657 count = loops
658 if repeat:
659 count *= 2
660 header = r'Timeout \(%s\)!\nThread 0x[0-9a-f]+ \(most recent call first\):\n' % timeout_str
661 regex = expected_traceback(17, 26, header, min_count=count)
662 self.assertRegex(trace, regex)
663 else:
664 self.assertEqual(trace, '')
665 self.assertEqual(exitcode, 0)
666
667 def test_dump_traceback_later(self):
668 self.check_dump_traceback_later()
669
670 def test_dump_traceback_later_repeat(self):
671 self.check_dump_traceback_later(repeat=True)
672
673 def test_dump_traceback_later_cancel(self):
674 self.check_dump_traceback_later(cancel=True)
675
676 def test_dump_traceback_later_file(self):
677 with temporary_filename() as filename:
678 self.check_dump_traceback_later(filename=filename)
679
680 @unittest.skipIf(sys.platform == "win32",
681 "subprocess doesn't support pass_fds on Windows")
682 def test_dump_traceback_later_fd(self):
683 with tempfile.TemporaryFile('wb+') as fp:
684 self.check_dump_traceback_later(fd=fp.fileno())
685
686 @support.requires_resource('walltime')
687 def test_dump_traceback_later_twice(self):
688 self.check_dump_traceback_later(loops=2)
689
690 @unittest.skipIf(not hasattr(faulthandler, "register"),
691 "need faulthandler.register")
692 def check_register(self, filename=False, all_threads=False,
693 unregister=False, chain=False, fd=None):
694 """
695 Register a handler displaying the traceback on a user signal. Raise the
696 signal and check the written traceback.
697
698 If chain is True, check that the previous signal handler is called.
699
700 Raise an error if the output doesn't match the expected format.
701 """
702 signum = signal.SIGUSR1
703 code = """
704 import faulthandler
705 import os
706 import signal
707 import sys
708
709 all_threads = {all_threads}
710 signum = {signum:d}
711 unregister = {unregister}
712 chain = {chain}
713 filename = {filename!r}
714 fd = {fd}
715
716 def func(signum):
717 os.kill(os.getpid(), signum)
718
719 def handler(signum, frame):
720 handler.called = True
721 handler.called = False
722
723 if filename:
724 file = open(filename, "wb")
725 elif fd is not None:
726 file = sys.stderr.fileno()
727 else:
728 file = None
729 if chain:
730 signal.signal(signum, handler)
731 faulthandler.register(signum, file=file,
732 all_threads=all_threads, chain={chain})
733 if unregister:
734 faulthandler.unregister(signum)
735 func(signum)
736 if chain and not handler.called:
737 if file is not None:
738 output = file
739 else:
740 output = sys.stderr
741 print("Error: signal handler not called!", file=output)
742 exitcode = 1
743 else:
744 exitcode = 0
745 if filename:
746 file.close()
747 sys.exit(exitcode)
748 """
749 code = code.format(
750 all_threads=all_threads,
751 signum=signum,
752 unregister=unregister,
753 chain=chain,
754 filename=filename,
755 fd=fd,
756 )
757 trace, exitcode = self.get_output(code, filename)
758 trace = '\n'.join(trace)
759 if not unregister:
760 if all_threads:
761 regex = r'Current thread 0x[0-9a-f]+ \(most recent call first\):\n'
762 else:
763 regex = r'Stack \(most recent call first\):\n'
764 regex = expected_traceback(14, 32, regex)
765 self.assertRegex(trace, regex)
766 else:
767 self.assertEqual(trace, '')
768 if unregister:
769 self.assertNotEqual(exitcode, 0)
770 else:
771 self.assertEqual(exitcode, 0)
772
773 def test_register(self):
774 self.check_register()
775
776 def test_unregister(self):
777 self.check_register(unregister=True)
778
779 def test_register_file(self):
780 with temporary_filename() as filename:
781 self.check_register(filename=filename)
782
783 @unittest.skipIf(sys.platform == "win32",
784 "subprocess doesn't support pass_fds on Windows")
785 def test_register_fd(self):
786 with tempfile.TemporaryFile('wb+') as fp:
787 self.check_register(fd=fp.fileno())
788
789 def test_register_threads(self):
790 self.check_register(all_threads=True)
791
792 def test_register_chain(self):
793 self.check_register(chain=True)
794
795 @contextmanager
796 def check_stderr_none(self):
797 stderr = sys.stderr
798 try:
799 sys.stderr = None
800 with self.assertRaises(RuntimeError) as cm:
801 yield
802 self.assertEqual(str(cm.exception), "sys.stderr is None")
803 finally:
804 sys.stderr = stderr
805
806 def test_stderr_None(self):
807 # Issue #21497: provide a helpful error if sys.stderr is None,
808 # instead of just an attribute error: "None has no attribute fileno".
809 with self.check_stderr_none():
810 faulthandler.enable()
811 with self.check_stderr_none():
812 faulthandler.dump_traceback()
813 with self.check_stderr_none():
814 faulthandler.dump_traceback_later(1e-3)
815 if hasattr(faulthandler, "register"):
816 with self.check_stderr_none():
817 faulthandler.register(signal.SIGUSR1)
818
819 @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
820 def test_raise_exception(self):
821 for exc, name in (
822 ('EXCEPTION_ACCESS_VIOLATION', 'access violation'),
823 ('EXCEPTION_INT_DIVIDE_BY_ZERO', 'int divide by zero'),
824 ('EXCEPTION_STACK_OVERFLOW', 'stack overflow'),
825 ):
826 self.check_windows_exception(f"""
827 import faulthandler
828 faulthandler.enable()
829 faulthandler._raise_exception(faulthandler._{exc})
830 """,
831 3,
832 name)
833
834 @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
835 def test_ignore_exception(self):
836 for exc_code in (
837 0xE06D7363, # MSC exception ("Emsc")
838 0xE0434352, # COM Callable Runtime exception ("ECCR")
839 ):
840 code = f"""
841 import faulthandler
842 faulthandler.enable()
843 faulthandler._raise_exception({exc_code})
844 """
845 code = dedent(code)
846 output, exitcode = self.get_output(code)
847 self.assertEqual(output, [])
848 self.assertEqual(exitcode, exc_code)
849
850 @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
851 def test_raise_nonfatal_exception(self):
852 # These exceptions are not strictly errors. Letting
853 # faulthandler display the traceback when they are
854 # raised is likely to result in noise. However, they
855 # may still terminate the process if there is no
856 # handler installed for them (which there typically
857 # is, e.g. for debug messages).
858 for exc in (
859 0x00000000,
860 0x34567890,
861 0x40000000,
862 0x40001000,
863 0x70000000,
864 0x7FFFFFFF,
865 ):
866 output, exitcode = self.get_output(f"""
867 import faulthandler
868 faulthandler.enable()
869 faulthandler._raise_exception(0x{exc:x})
870 """
871 )
872 self.assertEqual(output, [])
873 # On Windows older than 7 SP1, the actual exception code has
874 # bit 29 cleared.
875 self.assertIn(exitcode,
876 (exc, exc & ~0x10000000))
877
878 @unittest.skipUnless(MS_WINDOWS, 'specific to Windows')
879 def test_disable_windows_exc_handler(self):
880 code = dedent("""
881 import faulthandler
882 faulthandler.enable()
883 faulthandler.disable()
884 code = faulthandler._EXCEPTION_ACCESS_VIOLATION
885 faulthandler._raise_exception(code)
886 """)
887 output, exitcode = self.get_output(code)
888 self.assertEqual(output, [])
889 self.assertEqual(exitcode, 0xC0000005)
890
891 def test_cancel_later_without_dump_traceback_later(self):
892 # bpo-37933: Calling cancel_dump_traceback_later()
893 # without dump_traceback_later() must not segfault.
894 code = dedent("""
895 import faulthandler
896 faulthandler.cancel_dump_traceback_later()
897 """)
898 output, exitcode = self.get_output(code)
899 self.assertEqual(output, [])
900 self.assertEqual(exitcode, 0)
901
902
903 if __name__ == "__main__":
904 unittest.main()