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