summaryrefslogtreecommitdiffstats
path: root/Lib/test/test_faulthandler.py
blob: 5be7c32cedd0a572d7a104a9d6bdc2bdc9f155b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
from contextlib import contextmanager
import faulthandler
import re
import signal
import subprocess
import sys
from test import support, script_helper
import tempfile
import unittest

try:
    from resource import setrlimit, RLIMIT_CORE, error as resource_error
except ImportError:
    prepare_subprocess = None
else:
    def prepare_subprocess():
        # don't create core file
        try:
            setrlimit(RLIMIT_CORE, (0, 0))
        except (ValueError, resource_error):
            pass

def expected_traceback(lineno1, lineno2, header, count=1):
    regex = header
    regex += '  File "<string>", line %s in func\n' % lineno1
    regex += '  File "<string>", line %s in <module>' % lineno2
    if count != 1:
        regex = (regex + '\n') * (count - 1) + regex
    return '^' + regex + '$'

@contextmanager
def temporary_filename():
    filename = tempfile.mktemp()
    try:
        yield filename
    finally:
        support.unlink(filename)

class FaultHandlerTests(unittest.TestCase):
    def get_output(self, code, filename=None):
        """
        Run the specified code in Python (in a new child process) and read the
        output from the standard error or from a file (if filename is set).
        Return the output lines as a list.

        Strip the reference count from the standard error for Python debug
        build, and replace "Current thread 0x00007f8d8fbd9700" by "Current
        thread XXX".
        """
        options = {}
        if prepare_subprocess:
            options['preexec_fn'] = prepare_subprocess
        process = script_helper.spawn_python('-c', code, **options)
        stdout, stderr = process.communicate()
        exitcode = process.wait()
        output = support.strip_python_stderr(stdout)
        output = output.decode('ascii', 'backslashreplace')
        if filename:
            self.assertEqual(output, '')
            with open(filename, "rb") as fp:
                output = fp.read()
            output = output.decode('ascii', 'backslashreplace')
        output = re.sub('Current thread 0x[0-9a-f]+',
                        'Current thread XXX',
                        output)
        return output.splitlines(), exitcode

    def check_fatal_error(self, code, line_number, name_regex,
                          filename=None, all_threads=False, other_regex=None):
        """
        Check that the fault handler for fatal errors is enabled and check the
        traceback from the child process output.

        Raise an error if the output doesn't match the expected format.
        """
        if all_threads:
            header = 'Current thread XXX'
        else:
            header = 'Traceback (most recent call first)'
        regex = """
^Fatal Python error: {name}

{header}:
  File "<string>", line {lineno} in <module>$
""".strip()
        regex = regex.format(
            lineno=line_number,
            name=name_regex,
            header=re.escape(header))
        if other_regex:
            regex += '|' + other_regex
        output, exitcode = self.get_output(code, filename)
        output = '\n'.join(output)
        self.assertRegex(output, regex)
        self.assertNotEqual(exitcode, 0)

    def test_read_null(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._read_null()
""".strip(),
            3,
            '(?:Segmentation fault|Bus error)')

    def test_sigsegv(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._sigsegv()
""".strip(),
            3,
            'Segmentation fault')

    def test_sigabrt(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._sigabrt()
""".strip(),
            3,
            'Aborted')

    @unittest.skipIf(sys.platform == 'win32',
                     "SIGFPE cannot be caught on Windows")
    def test_sigfpe(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._sigfpe()
""".strip(),
            3,
            'Floating point exception')

    @unittest.skipIf(not hasattr(faulthandler, '_sigbus'),
                     "need faulthandler._sigbus()")
    def test_sigbus(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._sigbus()
""".strip(),
            3,
            'Bus error')

    @unittest.skipIf(not hasattr(faulthandler, '_sigill'),
                     "need faulthandler._sigill()")
    def test_sigill(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._sigill()
""".strip(),
            3,
            'Illegal instruction')

    def test_fatal_error(self):
        self.check_fatal_error("""
import faulthandler
faulthandler._fatal_error(b'xyz')
""".strip(),
            2,
            'xyz')

    @unittest.skipIf(not hasattr(faulthandler, '_stack_overflow'),
                     'need faulthandler._stack_overflow()')
    def test_stack_overflow(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._stack_overflow()
""".strip(),
            3,
            '(?:Segmentation fault|Bus error)',
            other_regex='unable to raise a stack overflow')

    def test_gil_released(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable()
faulthandler._read_null(True)
""".strip(),
            3,
            '(?:Segmentation fault|Bus error)')

    def test_enable_file(self):
        with temporary_filename() as filename:
            self.check_fatal_error("""
import faulthandler
output = open({filename}, 'wb')
faulthandler.enable(output)
faulthandler._read_null(True)
""".strip().format(filename=repr(filename)),
                4,
                '(?:Segmentation fault|Bus error)',
                filename=filename)

    def test_enable_threads(self):
        self.check_fatal_error("""
import faulthandler
faulthandler.enable(all_threads=True)
faulthandler._read_null(True)
""".strip(),
            3,
            '(?:Segmentation fault|Bus error)',
            all_threads=True)

    def test_disable(self):
        code = """
import faulthandler
faulthandler.enable()
faulthandler.disable()
faulthandler._read_null()
""".strip()
        not_expected = 'Fatal Python error'
        stderr, exitcode = self.get_output(code)
        stder = '\n'.join(stderr)
        self.assertTrue(not_expected not in stderr,
                     "%r is present in %r" % (not_expected, stderr))
        self.assertNotEqual(exitcode, 0)

    def test_is_enabled(self):
        was_enabled = faulthandler.is_enabled()
        try:
            faulthandler.enable()
            self.assertTrue(faulthandler.is_enabled())
            faulthandler.disable()
            self.assertFalse(faulthandler.is_enabled())
        finally:
            if was_enabled:
                faulthandler.enable()
            else:
                faulthandler.disable()

    def check_dump_traceback(self, filename):
        """
        Explicitly call dump_traceback() function and check its output.
        Raise an error if the output doesn't match the expected format.
        """
        code = """
import faulthandler

def funcB():
    if {has_filename}:
        with open({filename}, "wb") as fp:
            faulthandler.dump_traceback(fp)
    else:
        faulthandler.dump_traceback()

def funcA():
    funcB()

funcA()
""".strip()
        code = code.format(
            filename=repr(filename),
            has_filename=bool(filename),
        )
        if filename:
            lineno = 6
        else:
            lineno = 8
        expected = [
            'Traceback (most recent call first):',
            '  File "<string>", line %s in funcB' % lineno,
            '  File "<string>", line 11 in funcA',
            '  File "<string>", line 13 in <module>'
        ]
        trace, exitcode = self.get_output(code, filename)
        self.assertEqual(trace, expected)
        self.assertEqual(exitcode, 0)

    def test_dump_traceback(self):
        self.check_dump_traceback(None)

    def test_dump_traceback_file(self):
        with temporary_filename() as filename:
            self.check_dump_traceback(filename)

    def check_dump_traceback_threads(self, filename):
        """
        Call explicitly dump_traceback(all_threads=True) and check the output.
        Raise an error if the output doesn't match the expected format.
        """
        code = """
import faulthandler
from threading import Thread, Event
import time

def dump():
    if {filename}:
        with open({filename}, "wb") as fp:
            faulthandler.dump_traceback(fp, all_threads=True)
    else:
        faulthandler.dump_traceback(all_threads=True)

class Waiter(Thread):
    # avoid blocking if the main thread raises an exception.
    daemon = True

    def __init__(self):
        Thread.__init__(self)
        self.running = Event()
        self.stop = Event()

    def run(self):
        self.running.set()
        self.stop.wait()

waiter = Waiter()
waiter.start()
waiter.running.wait()
dump()
waiter.stop.set()
waiter.join()
""".strip()
        code = code.format(filename=repr(filename))
        output, exitcode = self.get_output(code, filename)
        output = '\n'.join(output)
        if filename:
            lineno = 8
        else:
            lineno = 10
        regex = """
^Thread 0x[0-9a-f]+:
(?:  File ".*threading.py", line [0-9]+ in wait
)?  File ".*threading.py", line [0-9]+ in wait
  File "<string>", line 23 in run
  File ".*threading.py", line [0-9]+ in _bootstrap_inner
  File ".*threading.py", line [0-9]+ in _bootstrap

Current thread XXX:
  File "<string>", line {lineno} in dump
  File "<string>", line 28 in <module>$
""".strip()
        regex = regex.format(lineno=lineno)
        self.assertRegex(output, regex)
        self.assertEqual(exitcode, 0)

    def test_dump_traceback_threads(self):
        self.check_dump_traceback_threads(None)

    def test_dump_traceback_threads_file(self):
        with temporary_filename() as filename:
            self.check_dump_traceback_threads(filename)

    def _check_dump_tracebacks_later(self, repeat, cancel, filename):
        """
        Check how many times the traceback is written in timeout x 2.5 seconds,
        or timeout x 3.5 seconds if cancel is True: 1, 2 or 3 times depending
        on repeat and cancel options.

        Raise an error if the output doesn't match the expect format.
        """
        code = """
import faulthandler
import time

def func(repeat, cancel, timeout):
    pause = timeout * 2.5
    # on Windows XP, b-a gives 1.249931 after sleep(1.25)
    min_pause = pause * 0.9
    a = time.time()
    time.sleep(pause)
    faulthandler.cancel_dump_tracebacks_later()
    b = time.time()
    # Check that sleep() was not interrupted
    assert (b - a) >= min_pause, "{{}} < {{}}".format(b - a, min_pause)

    if cancel:
        pause = timeout * 1.5
        min_pause = pause * 0.9
        a = time.time()
        time.sleep(pause)
        b = time.time()
        # Check that sleep() was not interrupted
        assert (b - a) >= min_pause, "{{}} < {{}}".format(b - a, min_pause)

timeout = 0.5
repeat = {repeat}
cancel = {cancel}
if {has_filename}:
    file = open({filename}, "wb")
else:
    file = None
faulthandler.dump_tracebacks_later(timeout,
    repeat=repeat, file=file)
func(repeat, cancel, timeout)
if file is not None:
    file.close()
""".strip()
        code = code.format(
            filename=repr(filename),
            has_filename=bool(filename),
            repeat=repeat,
            cancel=cancel,
        )
        trace, exitcode = self.get_output(code, filename)
        trace = '\n'.join(trace)

        if repeat:
            count = 2
        else:
            count = 1
        header = 'Thread 0x[0-9a-f]+:\n'
        regex = expected_traceback(9, 33, header, count=count)
        self.assertRegex(trace, regex)
        self.assertEqual(exitcode, 0)

    @unittest.skipIf(not hasattr(faulthandler, 'dump_tracebacks_later'),
                     'need faulthandler.dump_tracebacks_later()')
    def check_dump_tracebacks_later(self, repeat=False, cancel=False,
                                  file=False):
        if file:
            with temporary_filename() as filename:
                self._check_dump_tracebacks_later(repeat, cancel, filename)
        else:
            self._check_dump_tracebacks_later(repeat, cancel, None)

    def test_dump_tracebacks_later(self):
        self.check_dump_tracebacks_later()

    def test_dump_tracebacks_later_repeat(self):
        self.check_dump_tracebacks_later(repeat=True)

    def test_dump_tracebacks_later_repeat_cancel(self):
        self.check_dump_tracebacks_later(repeat=True, cancel=True)

    def test_dump_tracebacks_later_file(self):
        self.check_dump_tracebacks_later(file=True)

    @unittest.skipIf(not hasattr(faulthandler, "register"),
                     "need faulthandler.register")
    def check_register(self, filename=False, all_threads=False,
                       unregister=False):
        """
        Register a handler displaying the traceback on a user signal. Raise the
        signal and check the written traceback.

        Raise an error if the output doesn't match the expected format.
        """
        signum = signal.SIGUSR1
        code = """
import faulthandler
import os
import signal

def func(signum):
    os.kill(os.getpid(), signum)

signum = {signum}
unregister = {unregister}
if {has_filename}:
    file = open({filename}, "wb")
else:
    file = None
faulthandler.register(signum, file=file, all_threads={all_threads})
if unregister:
    faulthandler.unregister(signum)
func(signum)
if file is not None:
    file.close()
""".strip()
        code = code.format(
            filename=repr(filename),
            has_filename=bool(filename),
            all_threads=all_threads,
            signum=signum,
            unregister=unregister,
        )
        trace, exitcode = self.get_output(code, filename)
        trace = '\n'.join(trace)
        if not unregister:
            if all_threads:
                regex = 'Current thread XXX:\n'
            else:
                regex = 'Traceback \(most recent call first\):\n'
            regex = expected_traceback(6, 17, regex)
            self.assertRegex(trace, regex)
        else:
            self.assertEqual(trace, '')
        if unregister:
            self.assertNotEqual(exitcode, 0)
        else:
            self.assertEqual(exitcode, 0)

    def test_register(self):
        self.check_register()

    def test_unregister(self):
        self.check_register(unregister=True)

    def test_register_file(self):
        with temporary_filename() as filename:
            self.check_register(filename=filename)

    def test_register_threads(self):
        self.check_register(all_threads=True)


def test_main():
    support.run_unittest(FaultHandlerTests)

if __name__ == "__main__":
    test_main()