blob: 2efa998ff89aac1a06946c0d1ddb9266356d9bd6 [file] [log] [blame]
Victor Stinner024e37a2011-03-31 01:31:06 +02001#include "Python.h"
2#include "pythread.h"
3#include <signal.h>
4#include <object.h>
5#include <frameobject.h>
6#include <signal.h>
Victor Stinner0aafa4f2011-06-29 23:28:02 +02007#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinner7a399122014-09-30 13:40:12 +02008# include <pthread.h>
9#endif
10#ifdef MS_WINDOWS
11# include <windows.h>
12#endif
13#ifdef HAVE_SYS_RESOURCE_H
14# include <sys/resource.h>
Victor Stinner0aafa4f2011-06-29 23:28:02 +020015#endif
16
Victor Stinner96994402011-04-07 11:37:19 +020017/* Allocate at maximum 100 MB of the stack to raise the stack overflow */
18#define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)
19
Victor Stinner024e37a2011-03-31 01:31:06 +020020#ifdef WITH_THREAD
21# define FAULTHANDLER_LATER
22#endif
23
24#ifndef MS_WINDOWS
Victor Stinnerd727e232011-04-01 12:13:55 +020025 /* register() is useless on Windows, because only SIGSEGV, SIGABRT and
26 SIGILL can be handled by the process, and these signals can only be used
27 with enable(), not using register() */
Victor Stinner024e37a2011-03-31 01:31:06 +020028# define FAULTHANDLER_USER
29#endif
30
Victor Stinnerc7489a52015-04-01 18:48:58 +020031#define PUTS(fd, str) _Py_write_noraise(fd, str, strlen(str))
Victor Stinner024e37a2011-03-31 01:31:06 +020032
Victor Stinnerbd303c12013-11-07 23:07:29 +010033_Py_IDENTIFIER(enable);
34_Py_IDENTIFIER(fileno);
35_Py_IDENTIFIER(flush);
36_Py_IDENTIFIER(stderr);
37
Victor Stinner024e37a2011-03-31 01:31:06 +020038#ifdef HAVE_SIGACTION
39typedef struct sigaction _Py_sighandler_t;
40#else
41typedef PyOS_sighandler_t _Py_sighandler_t;
42#endif
43
44typedef struct {
45 int signum;
46 int enabled;
47 const char* name;
48 _Py_sighandler_t previous;
49 int all_threads;
50} fault_handler_t;
51
52static struct {
53 int enabled;
54 PyObject *file;
55 int fd;
56 int all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +020057 PyInterpreterState *interp;
Victor Stinner3a8f8ea2017-04-21 23:17:33 +020058#ifdef MS_WINDOWS
59 void *exc_handler;
60#endif
Victor Stinner024e37a2011-03-31 01:31:06 +020061} fatal_error = {0, NULL, -1, 0};
62
63#ifdef FAULTHANDLER_LATER
64static struct {
65 PyObject *file;
66 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020067 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020068 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020069 PyInterpreterState *interp;
70 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020071 char *header;
72 size_t header_len;
Victor Stinner410dd7d2011-05-11 20:56:08 +020073 /* The main thread always holds this lock. It is only released when
74 faulthandler_thread() is interrupted before this thread exits, or at
Victor Stinnerde10f402011-04-08 12:57:06 +020075 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020076 PyThread_type_lock cancel_event;
77 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020078 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020079} thread;
80#endif
81
82#ifdef FAULTHANDLER_USER
83typedef struct {
84 int enabled;
85 PyObject *file;
86 int fd;
87 int all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +020088 int chain;
Victor Stinner024e37a2011-03-31 01:31:06 +020089 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020090 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020091} user_signal_t;
92
93static user_signal_t *user_signals;
94
95/* the following macros come from Python: Modules/signalmodule.c */
Victor Stinner024e37a2011-03-31 01:31:06 +020096#ifndef NSIG
97# if defined(_NSIG)
98# define NSIG _NSIG /* For BSD/SysV */
99# elif defined(_SIGMAX)
100# define NSIG (_SIGMAX + 1) /* For QNX */
101# elif defined(SIGMAX)
102# define NSIG (SIGMAX + 1) /* For djgpp */
103# else
104# define NSIG 64 /* Use a reasonable default value */
105# endif
106#endif
107
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200108static void faulthandler_user(int signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200109#endif /* FAULTHANDLER_USER */
110
111
112static fault_handler_t faulthandler_handlers[] = {
113#ifdef SIGBUS
114 {SIGBUS, 0, "Bus error", },
115#endif
116#ifdef SIGILL
117 {SIGILL, 0, "Illegal instruction", },
118#endif
119 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200120 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200121 /* define SIGSEGV at the end to make it the default choice if searching the
122 handler fails in faulthandler_fatal_error() */
123 {SIGSEGV, 0, "Segmentation fault", }
124};
Victor Stinner404cdc52016-03-23 10:39:17 +0100125static const size_t faulthandler_nsignals = \
Victor Stinner63941882011-09-29 00:42:28 +0200126 Py_ARRAY_LENGTH(faulthandler_handlers);
Victor Stinner024e37a2011-03-31 01:31:06 +0200127
128#ifdef HAVE_SIGALTSTACK
129static stack_t stack;
Christophe Zeitouny90eafdb2017-03-24 04:20:40 -0700130static stack_t old_stack;
Victor Stinner024e37a2011-03-31 01:31:06 +0200131#endif
132
133
134/* Get the file descriptor of a file by calling its fileno() method and then
135 call its flush() method.
136
137 If file is NULL or Py_None, use sys.stderr as the new file.
Victor Stinner95bb7142015-03-12 15:32:03 +0100138 If file is an integer, it will be treated as file descriptor.
Victor Stinner024e37a2011-03-31 01:31:06 +0200139
Victor Stinner95bb7142015-03-12 15:32:03 +0100140 On success, return the file descriptor and write the new file into *file_ptr.
141 On error, return -1. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200142
Victor Stinner95bb7142015-03-12 15:32:03 +0100143static int
144faulthandler_get_fileno(PyObject **file_ptr)
Victor Stinner024e37a2011-03-31 01:31:06 +0200145{
146 PyObject *result;
147 long fd_long;
148 int fd;
Victor Stinner95bb7142015-03-12 15:32:03 +0100149 PyObject *file = *file_ptr;
Victor Stinner024e37a2011-03-31 01:31:06 +0200150
151 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100152 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200153 if (file == NULL) {
154 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
Victor Stinner95bb7142015-03-12 15:32:03 +0100155 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200156 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200157 if (file == Py_None) {
158 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
Victor Stinner95bb7142015-03-12 15:32:03 +0100159 return -1;
Victor Stinnere2d66902014-05-14 17:15:50 +0200160 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200161 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100162 else if (PyLong_Check(file)) {
163 fd = _PyLong_AsInt(file);
164 if (fd == -1 && PyErr_Occurred())
165 return -1;
Steve Dower940f33a2016-09-08 11:21:54 -0700166 if (fd < 0) {
Victor Stinner95bb7142015-03-12 15:32:03 +0100167 PyErr_SetString(PyExc_ValueError,
168 "file is not a valid file descripter");
169 return -1;
170 }
171 *file_ptr = NULL;
172 return fd;
173 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200174
Victor Stinner3466bde2016-09-05 18:16:01 -0700175 result = _PyObject_CallMethodId(file, &PyId_fileno, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200176 if (result == NULL)
Victor Stinner95bb7142015-03-12 15:32:03 +0100177 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200178
179 fd = -1;
180 if (PyLong_Check(result)) {
181 fd_long = PyLong_AsLong(result);
182 if (0 <= fd_long && fd_long < INT_MAX)
183 fd = (int)fd_long;
184 }
185 Py_DECREF(result);
186
187 if (fd == -1) {
188 PyErr_SetString(PyExc_RuntimeError,
189 "file.fileno() is not a valid file descriptor");
Victor Stinner95bb7142015-03-12 15:32:03 +0100190 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200191 }
192
Victor Stinner3466bde2016-09-05 18:16:01 -0700193 result = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200194 if (result != NULL)
195 Py_DECREF(result);
196 else {
197 /* ignore flush() error */
198 PyErr_Clear();
199 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100200 *file_ptr = file;
201 return fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200202}
203
Victor Stinnera4de6d82011-04-09 00:47:23 +0200204/* Get the state of the current thread: only call this function if the current
205 thread holds the GIL. Raise an exception on error. */
206static PyThreadState*
207get_thread_state(void)
208{
Victor Stinner861d9ab2016-03-16 22:45:24 +0100209 PyThreadState *tstate = _PyThreadState_UncheckedGet();
Victor Stinnera4de6d82011-04-09 00:47:23 +0200210 if (tstate == NULL) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100211 /* just in case but very unlikely... */
Victor Stinnera4de6d82011-04-09 00:47:23 +0200212 PyErr_SetString(PyExc_RuntimeError,
213 "unable to get the current thread state");
214 return NULL;
215 }
216 return tstate;
217}
218
Victor Stinnerc7489a52015-04-01 18:48:58 +0200219static void
220faulthandler_dump_traceback(int fd, int all_threads,
221 PyInterpreterState *interp)
222{
223 static volatile int reentrant = 0;
224 PyThreadState *tstate;
225
226 if (reentrant)
227 return;
228
229 reentrant = 1;
230
231#ifdef WITH_THREAD
232 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
233 are thus delivered to the thread that caused the fault. Get the Python
234 thread state of the current thread.
235
236 PyThreadState_Get() doesn't give the state of the thread that caused the
237 fault if the thread released the GIL, and so this function cannot be
238 used. Read the thread local storage (TLS) instead: call
239 PyGILState_GetThisThreadState(). */
240 tstate = PyGILState_GetThisThreadState();
241#else
Victor Stinner861d9ab2016-03-16 22:45:24 +0100242 tstate = _PyThreadState_UncheckedGet();
Victor Stinnerc7489a52015-04-01 18:48:58 +0200243#endif
244
Victor Stinner861d9ab2016-03-16 22:45:24 +0100245 if (all_threads) {
246 (void)_Py_DumpTracebackThreads(fd, NULL, tstate);
247 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200248 else {
249 if (tstate != NULL)
250 _Py_DumpTraceback(fd, tstate);
251 }
252
253 reentrant = 0;
254}
255
Victor Stinner024e37a2011-03-31 01:31:06 +0200256static PyObject*
257faulthandler_dump_traceback_py(PyObject *self,
258 PyObject *args, PyObject *kwargs)
259{
260 static char *kwlist[] = {"file", "all_threads", NULL};
261 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200262 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200263 PyThreadState *tstate;
264 const char *errmsg;
265 int fd;
266
267 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
268 "|Oi:dump_traceback", kwlist,
269 &file, &all_threads))
270 return NULL;
271
Victor Stinner95bb7142015-03-12 15:32:03 +0100272 fd = faulthandler_get_fileno(&file);
273 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200274 return NULL;
275
Victor Stinnera4de6d82011-04-09 00:47:23 +0200276 tstate = get_thread_state();
277 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200278 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200279
280 if (all_threads) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100281 errmsg = _Py_DumpTracebackThreads(fd, NULL, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200282 if (errmsg != NULL) {
283 PyErr_SetString(PyExc_RuntimeError, errmsg);
284 return NULL;
285 }
286 }
287 else {
288 _Py_DumpTraceback(fd, tstate);
289 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200290
291 if (PyErr_CheckSignals())
292 return NULL;
293
Victor Stinner024e37a2011-03-31 01:31:06 +0200294 Py_RETURN_NONE;
295}
296
Victor Stinner404cdc52016-03-23 10:39:17 +0100297static void
298faulthandler_disable_fatal_handler(fault_handler_t *handler)
299{
300 if (!handler->enabled)
301 return;
302 handler->enabled = 0;
303#ifdef HAVE_SIGACTION
304 (void)sigaction(handler->signum, &handler->previous, NULL);
305#else
306 (void)signal(handler->signum, handler->previous);
307#endif
308}
309
Victor Stinner024e37a2011-03-31 01:31:06 +0200310
Victor Stinner410dd7d2011-05-11 20:56:08 +0200311/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200312
313 Display the current Python traceback, restore the previous handler and call
314 the previous handler.
315
Victor Stinner410dd7d2011-05-11 20:56:08 +0200316 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200317 signal handler would not be called (for an unknown reason). The execution of
318 the program continues at faulthandler_fatal_error() exit, but the same
319 instruction will raise the same fault (signal), and so the previous handler
320 will be called.
321
Victor Stinner410dd7d2011-05-11 20:56:08 +0200322 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200323
324static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200325faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200326{
327 const int fd = fatal_error.fd;
Victor Stinner404cdc52016-03-23 10:39:17 +0100328 size_t i;
Victor Stinner024e37a2011-03-31 01:31:06 +0200329 fault_handler_t *handler = NULL;
Victor Stinnerc9256172011-05-07 12:20:11 +0200330 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200331
332 if (!fatal_error.enabled)
333 return;
334
335 for (i=0; i < faulthandler_nsignals; i++) {
336 handler = &faulthandler_handlers[i];
337 if (handler->signum == signum)
338 break;
339 }
340 if (handler == NULL) {
341 /* faulthandler_nsignals == 0 (unlikely) */
342 return;
343 }
344
345 /* restore the previous handler */
Victor Stinner404cdc52016-03-23 10:39:17 +0100346 faulthandler_disable_fatal_handler(handler);
Victor Stinner024e37a2011-03-31 01:31:06 +0200347
348 PUTS(fd, "Fatal Python error: ");
349 PUTS(fd, handler->name);
350 PUTS(fd, "\n\n");
351
Victor Stinnerc7489a52015-04-01 18:48:58 +0200352 faulthandler_dump_traceback(fd, fatal_error.all_threads,
353 fatal_error.interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200354
Victor Stinnerc9256172011-05-07 12:20:11 +0200355 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200356#ifdef MS_WINDOWS
357 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200358 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200359 handler, because the Windows signal handler would not be called */
360 return;
361 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200362#endif
R David Murrayfc069992013-12-13 20:52:19 -0500363 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200364 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
365 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200366}
367
Victor Stinner404cdc52016-03-23 10:39:17 +0100368#ifdef MS_WINDOWS
369static LONG WINAPI
370faulthandler_exc_handler(struct _EXCEPTION_POINTERS *exc_info)
371{
372 const int fd = fatal_error.fd;
373 DWORD code = exc_info->ExceptionRecord->ExceptionCode;
Victor Stinner412a5e72016-03-23 14:44:14 +0100374 DWORD flags = exc_info->ExceptionRecord->ExceptionFlags;
Victor Stinner404cdc52016-03-23 10:39:17 +0100375
Steve Dower2bafc0d2017-06-06 13:47:14 -0700376 /* bpo-30557: only log fatal exceptions */
377 if (!(code & 0x80000000)) {
Victor Stinner412a5e72016-03-23 14:44:14 +0100378 /* call the next exception handler */
379 return EXCEPTION_CONTINUE_SEARCH;
380 }
381
382 PUTS(fd, "Windows fatal exception: ");
Victor Stinner404cdc52016-03-23 10:39:17 +0100383 switch (code)
384 {
385 /* only format most common errors */
386 case EXCEPTION_ACCESS_VIOLATION: PUTS(fd, "access violation"); break;
387 case EXCEPTION_FLT_DIVIDE_BY_ZERO: PUTS(fd, "float divide by zero"); break;
388 case EXCEPTION_FLT_OVERFLOW: PUTS(fd, "float overflow"); break;
389 case EXCEPTION_INT_DIVIDE_BY_ZERO: PUTS(fd, "int divide by zero"); break;
390 case EXCEPTION_INT_OVERFLOW: PUTS(fd, "integer overflow"); break;
391 case EXCEPTION_IN_PAGE_ERROR: PUTS(fd, "page error"); break;
392 case EXCEPTION_STACK_OVERFLOW: PUTS(fd, "stack overflow"); break;
393 default:
Steve Dower2bafc0d2017-06-06 13:47:14 -0700394 PUTS(fd, "code 0x");
395 _Py_DumpHexadecimal(fd, code, 8);
Victor Stinner404cdc52016-03-23 10:39:17 +0100396 }
397 PUTS(fd, "\n\n");
398
399 if (code == EXCEPTION_ACCESS_VIOLATION) {
400 /* disable signal handler for SIGSEGV */
401 size_t i;
402 for (i=0; i < faulthandler_nsignals; i++) {
403 fault_handler_t *handler = &faulthandler_handlers[i];
404 if (handler->signum == SIGSEGV) {
405 faulthandler_disable_fatal_handler(handler);
406 break;
407 }
408 }
409 }
410
411 faulthandler_dump_traceback(fd, fatal_error.all_threads,
412 fatal_error.interp);
413
414 /* call the next exception handler */
415 return EXCEPTION_CONTINUE_SEARCH;
416}
417#endif
418
Victor Stinnerd727e232011-04-01 12:13:55 +0200419/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200420
doko@ubuntu.combc731502016-05-18 01:06:01 +0200421static int
Victor Stinner404cdc52016-03-23 10:39:17 +0100422faulthandler_enable(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200423{
Victor Stinner404cdc52016-03-23 10:39:17 +0100424 size_t i;
Victor Stinner404cdc52016-03-23 10:39:17 +0100425
426 if (fatal_error.enabled) {
427 return 0;
428 }
Victor Stinner404cdc52016-03-23 10:39:17 +0100429 fatal_error.enabled = 1;
430
431 for (i=0; i < faulthandler_nsignals; i++) {
Victor Stinner928ad282016-03-23 15:19:12 +0100432 fault_handler_t *handler;
433#ifdef HAVE_SIGACTION
434 struct sigaction action;
435#endif
436 int err;
Victor Stinner404cdc52016-03-23 10:39:17 +0100437
Victor Stinner928ad282016-03-23 15:19:12 +0100438 handler = &faulthandler_handlers[i];
439 assert(!handler->enabled);
Victor Stinner404cdc52016-03-23 10:39:17 +0100440#ifdef HAVE_SIGACTION
441 action.sa_handler = faulthandler_fatal_error;
442 sigemptyset(&action.sa_mask);
443 /* Do not prevent the signal from being received from within
444 its own signal handler */
445 action.sa_flags = SA_NODEFER;
446#ifdef HAVE_SIGALTSTACK
447 if (stack.ss_sp != NULL) {
448 /* Call the signal handler on an alternate signal stack
449 provided by sigaltstack() */
450 action.sa_flags |= SA_ONSTACK;
451 }
452#endif
453 err = sigaction(handler->signum, &action, &handler->previous);
454#else
455 handler->previous = signal(handler->signum,
456 faulthandler_fatal_error);
457 err = (handler->previous == SIG_ERR);
458#endif
459 if (err) {
460 PyErr_SetFromErrno(PyExc_RuntimeError);
461 return -1;
462 }
463
464 handler->enabled = 1;
465 }
466
467#ifdef MS_WINDOWS
Victor Stinner3a8f8ea2017-04-21 23:17:33 +0200468 assert(fatal_error.exc_handler == NULL);
469 fatal_error.exc_handler = AddVectoredExceptionHandler(1, faulthandler_exc_handler);
Victor Stinner404cdc52016-03-23 10:39:17 +0100470#endif
471 return 0;
472}
473
474static PyObject*
475faulthandler_py_enable(PyObject *self, PyObject *args, PyObject *kwargs)
476{
477 static char *kwlist[] = {"file", "all_threads", NULL};
478 PyObject *file = NULL;
479 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200480 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200481 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200482
483 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
484 "|Oi:enable", kwlist, &file, &all_threads))
485 return NULL;
486
Victor Stinner95bb7142015-03-12 15:32:03 +0100487 fd = faulthandler_get_fileno(&file);
488 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200489 return NULL;
490
Victor Stinnera4de6d82011-04-09 00:47:23 +0200491 tstate = get_thread_state();
492 if (tstate == NULL)
493 return NULL;
494
Victor Stinner95bb7142015-03-12 15:32:03 +0100495 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300496 Py_XSETREF(fatal_error.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200497 fatal_error.fd = fd;
498 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200499 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200500
Victor Stinner404cdc52016-03-23 10:39:17 +0100501 if (faulthandler_enable() < 0) {
502 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200503 }
Victor Stinner404cdc52016-03-23 10:39:17 +0100504
Victor Stinner024e37a2011-03-31 01:31:06 +0200505 Py_RETURN_NONE;
506}
507
508static void
509faulthandler_disable(void)
510{
511 unsigned int i;
512 fault_handler_t *handler;
513
514 if (fatal_error.enabled) {
515 fatal_error.enabled = 0;
516 for (i=0; i < faulthandler_nsignals; i++) {
517 handler = &faulthandler_handlers[i];
Victor Stinner404cdc52016-03-23 10:39:17 +0100518 faulthandler_disable_fatal_handler(handler);
Victor Stinner024e37a2011-03-31 01:31:06 +0200519 }
520 }
Victor Stinner3a8f8ea2017-04-21 23:17:33 +0200521#ifdef MS_WINDOWS
522 if (fatal_error.exc_handler != NULL) {
523 RemoveVectoredExceptionHandler(fatal_error.exc_handler);
524 fatal_error.exc_handler = NULL;
525 }
526#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200527 Py_CLEAR(fatal_error.file);
528}
529
530static PyObject*
531faulthandler_disable_py(PyObject *self)
532{
533 if (!fatal_error.enabled) {
534 Py_INCREF(Py_False);
535 return Py_False;
536 }
537 faulthandler_disable();
538 Py_INCREF(Py_True);
539 return Py_True;
540}
541
542static PyObject*
543faulthandler_is_enabled(PyObject *self)
544{
545 return PyBool_FromLong(fatal_error.enabled);
546}
547
548#ifdef FAULTHANDLER_LATER
549
550static void
551faulthandler_thread(void *unused)
552{
553 PyLockStatus st;
554 const char* errmsg;
Victor Stinner024e37a2011-03-31 01:31:06 +0200555 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200556#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200557 sigset_t set;
558
559 /* we don't want to receive any signal */
560 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200561 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200562#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200563
564 do {
565 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200566 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200567 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200568 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200569 break;
570 }
571 /* Timeout => dump traceback */
572 assert(st == PY_LOCK_FAILURE);
573
Victor Stinnerc7489a52015-04-01 18:48:58 +0200574 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200575
Victor Stinner861d9ab2016-03-16 22:45:24 +0100576 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200577 ok = (errmsg == NULL);
578
579 if (thread.exit)
580 _exit(1);
581 } while (ok && thread.repeat);
582
583 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200584 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200585}
586
587static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200588cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200589{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200590 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200591 PyThread_release_lock(thread.cancel_event);
592
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200593 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200594 PyThread_acquire_lock(thread.running, 1);
595 PyThread_release_lock(thread.running);
596
597 /* The main thread should always hold the cancel_event lock */
598 PyThread_acquire_lock(thread.cancel_event, 1);
599
Victor Stinner024e37a2011-03-31 01:31:06 +0200600 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200601 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200602 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200603 thread.header = NULL;
604 }
605}
606
607static char*
608format_timeout(double timeout)
609{
610 unsigned long us, sec, min, hour;
611 double intpart, fracpart;
612 char buffer[100];
613
614 fracpart = modf(timeout, &intpart);
615 sec = (unsigned long)intpart;
616 us = (unsigned long)(fracpart * 1e6);
617 min = sec / 60;
618 sec %= 60;
619 hour = min / 60;
620 min %= 60;
621
622 if (us != 0)
623 PyOS_snprintf(buffer, sizeof(buffer),
624 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
625 hour, min, sec, us);
626 else
627 PyOS_snprintf(buffer, sizeof(buffer),
628 "Timeout (%lu:%02lu:%02lu)!\n",
629 hour, min, sec);
630
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200631 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200632}
633
634static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200635faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200636 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200637{
638 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
639 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200640 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200641 int repeat = 0;
642 PyObject *file = NULL;
643 int fd;
644 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200645 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200646 char *header;
647 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200648
649 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200650 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200651 &timeout, &repeat, &file, &exit))
652 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200653 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200654 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
655 return NULL;
656 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200657 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200658 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200659 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
660 return NULL;
661 }
662
Victor Stinnera4de6d82011-04-09 00:47:23 +0200663 tstate = get_thread_state();
664 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200665 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200666
Victor Stinner95bb7142015-03-12 15:32:03 +0100667 fd = faulthandler_get_fileno(&file);
668 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200669 return NULL;
670
Victor Stinnerc790a532011-04-08 13:39:59 +0200671 /* format the timeout */
672 header = format_timeout(timeout);
673 if (header == NULL)
674 return PyErr_NoMemory();
675 header_len = strlen(header);
676
Victor Stinner024e37a2011-03-31 01:31:06 +0200677 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200678 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200679
Victor Stinner95bb7142015-03-12 15:32:03 +0100680 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300681 Py_XSETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200682 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200683 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200684 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200685 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200686 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200687 thread.header = header;
688 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200689
690 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200691 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200692
Victor Stinner024e37a2011-03-31 01:31:06 +0200693 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200694 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200695 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200696 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200697 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200698 PyErr_SetString(PyExc_RuntimeError,
699 "unable to start watchdog thread");
700 return NULL;
701 }
702
703 Py_RETURN_NONE;
704}
705
706static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200707faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200708{
Georg Brandldeb92b52012-09-22 08:58:55 +0200709 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200710 Py_RETURN_NONE;
711}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200712#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200713
714#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200715static int
716faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
717{
718#ifdef HAVE_SIGACTION
719 struct sigaction action;
720 action.sa_handler = faulthandler_user;
721 sigemptyset(&action.sa_mask);
722 /* if the signal is received while the kernel is executing a system
723 call, try to restart the system call instead of interrupting it and
724 return EINTR. */
725 action.sa_flags = SA_RESTART;
726 if (chain) {
727 /* do not prevent the signal from being received from within its
728 own signal handler */
729 action.sa_flags = SA_NODEFER;
730 }
731#ifdef HAVE_SIGALTSTACK
732 if (stack.ss_sp != NULL) {
733 /* Call the signal handler on an alternate signal stack
734 provided by sigaltstack() */
735 action.sa_flags |= SA_ONSTACK;
736 }
737#endif
738 return sigaction(signum, &action, p_previous);
739#else
740 _Py_sighandler_t previous;
741 previous = signal(signum, faulthandler_user);
742 if (p_previous != NULL)
743 *p_previous = previous;
744 return (previous == SIG_ERR);
745#endif
746}
747
Victor Stinner024e37a2011-03-31 01:31:06 +0200748/* Handler of user signals (e.g. SIGUSR1).
749
750 Dump the traceback of the current thread, or of all threads if
751 thread.all_threads is true.
752
753 This function is signal safe and should only call signal safe functions. */
754
755static void
756faulthandler_user(int signum)
757{
758 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200759 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200760
761 user = &user_signals[signum];
762 if (!user->enabled)
763 return;
764
Victor Stinnerc7489a52015-04-01 18:48:58 +0200765 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200766
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200767#ifdef HAVE_SIGACTION
768 if (user->chain) {
769 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200770 errno = save_errno;
771
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200772 /* call the previous signal handler */
773 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200774
775 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200776 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200777 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200778 }
779#else
780 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200781 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200782 /* call the previous signal handler */
783 user->previous(signum);
784 }
785#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200786}
787
788static int
789check_signum(int signum)
790{
791 unsigned int i;
792
793 for (i=0; i < faulthandler_nsignals; i++) {
794 if (faulthandler_handlers[i].signum == signum) {
795 PyErr_Format(PyExc_RuntimeError,
796 "signal %i cannot be registered, "
797 "use enable() instead",
798 signum);
799 return 0;
800 }
801 }
802 if (signum < 1 || NSIG <= signum) {
803 PyErr_SetString(PyExc_ValueError, "signal number out of range");
804 return 0;
805 }
806 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200807}
808
809static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200810faulthandler_register_py(PyObject *self,
811 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200812{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200813 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200814 int signum;
815 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200816 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200817 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200818 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200819 user_signal_t *user;
820 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200821 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200822 int err;
823
824 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200825 "i|Oii:register", kwlist,
826 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200827 return NULL;
828
Victor Stinner44378d42011-04-01 15:37:12 +0200829 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200830 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200831
Victor Stinnera4de6d82011-04-09 00:47:23 +0200832 tstate = get_thread_state();
833 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200834 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200835
Victor Stinner95bb7142015-03-12 15:32:03 +0100836 fd = faulthandler_get_fileno(&file);
837 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200838 return NULL;
839
840 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200841 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200842 if (user_signals == NULL)
843 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200844 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200845 }
846 user = &user_signals[signum];
847
848 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200849 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200850 if (err) {
851 PyErr_SetFromErrno(PyExc_OSError);
852 return NULL;
853 }
Victor Stinner8d379542013-07-02 00:14:56 +0200854
855 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200856 }
857
Victor Stinner95bb7142015-03-12 15:32:03 +0100858 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300859 Py_XSETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200860 user->fd = fd;
861 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200862 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200863 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200864 user->enabled = 1;
865
866 Py_RETURN_NONE;
867}
868
869static int
870faulthandler_unregister(user_signal_t *user, int signum)
871{
Victor Stinnera01ca122011-04-01 12:56:17 +0200872 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200873 return 0;
874 user->enabled = 0;
875#ifdef HAVE_SIGACTION
876 (void)sigaction(signum, &user->previous, NULL);
877#else
878 (void)signal(signum, user->previous);
879#endif
880 Py_CLEAR(user->file);
881 user->fd = -1;
882 return 1;
883}
884
885static PyObject*
886faulthandler_unregister_py(PyObject *self, PyObject *args)
887{
888 int signum;
889 user_signal_t *user;
890 int change;
891
892 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
893 return NULL;
894
Victor Stinner44378d42011-04-01 15:37:12 +0200895 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200896 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200897
Victor Stinnercfa71232011-04-08 12:48:15 +0200898 if (user_signals == NULL)
899 Py_RETURN_FALSE;
900
Victor Stinner024e37a2011-03-31 01:31:06 +0200901 user = &user_signals[signum];
902 change = faulthandler_unregister(user, signum);
903 return PyBool_FromLong(change);
904}
905#endif /* FAULTHANDLER_USER */
906
907
Victor Stinner7a399122014-09-30 13:40:12 +0200908static void
909faulthandler_suppress_crash_report(void)
910{
911#ifdef MS_WINDOWS
912 UINT mode;
913
914 /* Configure Windows to not display the Windows Error Reporting dialog */
915 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
916 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
917#endif
918
919#ifdef HAVE_SYS_RESOURCE_H
920 struct rlimit rl;
921
922 /* Disable creation of core dump */
923 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
924 rl.rlim_cur = 0;
925 setrlimit(RLIMIT_CORE, &rl);
926 }
927#endif
928
929#ifdef _MSC_VER
930 /* Visual Studio: configure abort() to not display an error message nor
931 open a popup asking to report the fault. */
932 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
933#endif
934}
935
Victor Stinner024e37a2011-03-31 01:31:06 +0200936static PyObject *
937faulthandler_read_null(PyObject *self, PyObject *args)
938{
Victor Stinnera2477202012-01-30 00:07:43 +0100939 volatile int *x;
940 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100941
Victor Stinner7a399122014-09-30 13:40:12 +0200942 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100943 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200944 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200945 return PyLong_FromLong(y);
946
947}
948
Victor Stinner50838282014-09-30 13:54:14 +0200949static void
950faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200951{
Victor Stinner7a399122014-09-30 13:40:12 +0200952 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200953#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200954 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
955 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200956 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200957 SIGSEGV was raised by the kernel because of a fault, and so if the
958 program retries to execute the same instruction, the fault will be
959 raised again.
960
961 Here the fault is simulated by a fake SIGSEGV signal raised by the
962 application. We have to raise SIGSEGV at lease twice: once for
963 faulthandler_fatal_error(), and one more time for the previous signal
964 handler. */
965 while(1)
966 raise(SIGSEGV);
967#else
968 raise(SIGSEGV);
969#endif
Victor Stinner50838282014-09-30 13:54:14 +0200970}
971
972static PyObject *
973faulthandler_sigsegv(PyObject *self, PyObject *args)
974{
975 int release_gil = 0;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100976 if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
Victor Stinner50838282014-09-30 13:54:14 +0200977 return NULL;
978
979 if (release_gil) {
980 Py_BEGIN_ALLOW_THREADS
981 faulthandler_raise_sigsegv();
982 Py_END_ALLOW_THREADS
983 } else {
984 faulthandler_raise_sigsegv();
985 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200986 Py_RETURN_NONE;
987}
988
Victor Stinner861d9ab2016-03-16 22:45:24 +0100989#ifdef WITH_THREAD
990static void
991faulthandler_fatal_error_thread(void *plock)
992{
993 PyThread_type_lock *lock = (PyThread_type_lock *)plock;
994
995 Py_FatalError("in new thread");
996
997 /* notify the caller that we are done */
998 PyThread_release_lock(lock);
999}
1000
1001static PyObject *
1002faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
1003{
1004 long thread;
1005 PyThread_type_lock lock;
1006
1007 faulthandler_suppress_crash_report();
1008
1009 lock = PyThread_allocate_lock();
1010 if (lock == NULL)
1011 return PyErr_NoMemory();
1012
1013 PyThread_acquire_lock(lock, WAIT_LOCK);
1014
1015 thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
1016 if (thread == -1) {
1017 PyThread_free_lock(lock);
1018 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
1019 return NULL;
1020 }
1021
1022 /* wait until the thread completes: it will never occur, since Py_FatalError()
1023 exits the process immedialty. */
1024 PyThread_acquire_lock(lock, WAIT_LOCK);
1025 PyThread_release_lock(lock);
1026 PyThread_free_lock(lock);
1027
1028 Py_RETURN_NONE;
1029}
1030#endif
1031
Victor Stinner024e37a2011-03-31 01:31:06 +02001032static PyObject *
1033faulthandler_sigfpe(PyObject *self, PyObject *args)
1034{
1035 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
1036 PowerPC. Use volatile to disable compile-time optimizations. */
1037 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +02001038 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +02001039 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +02001040 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
1041 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001042 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +02001043 /* This line is never reached, but we pretend to make something with z
1044 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +02001045 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +02001046}
1047
Victor Stinnerd727e232011-04-01 12:13:55 +02001048static PyObject *
1049faulthandler_sigabrt(PyObject *self, PyObject *args)
1050{
Victor Stinner7a399122014-09-30 13:40:12 +02001051 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +02001052 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +02001053 Py_RETURN_NONE;
1054}
1055
Victor Stinner024e37a2011-03-31 01:31:06 +02001056static PyObject *
1057faulthandler_fatal_error_py(PyObject *self, PyObject *args)
1058{
1059 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +01001060 int release_gil = 0;
1061 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +02001062 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +02001063 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +01001064 if (release_gil) {
1065 Py_BEGIN_ALLOW_THREADS
1066 Py_FatalError(message);
1067 Py_END_ALLOW_THREADS
1068 }
1069 else {
1070 Py_FatalError(message);
1071 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001072 Py_RETURN_NONE;
1073}
1074
1075#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner404cdc52016-03-23 10:39:17 +01001076#define FAULTHANDLER_STACK_OVERFLOW
1077
Victor Stinner19276f12015-03-23 21:20:27 +01001078#ifdef __INTEL_COMPILER
1079 /* Issue #23654: Turn off ICC's tail call optimization for the
1080 * stack_overflow generator. ICC turns the recursive tail call into
1081 * a loop. */
1082# pragma intel optimization_level 0
1083#endif
1084static
Benjamin Petersonca470632016-09-06 13:47:26 -07001085uintptr_t
1086stack_overflow(uintptr_t min_sp, uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +02001087{
1088 /* allocate 4096 bytes on the stack at each call */
1089 unsigned char buffer[4096];
Benjamin Petersonca470632016-09-06 13:47:26 -07001090 uintptr_t sp = (uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +02001091 *depth += 1;
Victor Stinner928ad282016-03-23 15:19:12 +01001092 if (sp < min_sp || max_sp < sp)
Victor Stinnerf0480752011-03-31 11:34:08 +02001093 return sp;
Victor Stinner928ad282016-03-23 15:19:12 +01001094 buffer[0] = 1;
1095 buffer[4095] = 0;
1096 return stack_overflow(min_sp, max_sp, depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001097}
1098
1099static PyObject *
1100faulthandler_stack_overflow(PyObject *self)
1101{
1102 size_t depth, size;
Benjamin Petersonca470632016-09-06 13:47:26 -07001103 uintptr_t sp = (uintptr_t)&depth;
1104 uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +02001105
Victor Stinner7a399122014-09-30 13:40:12 +02001106 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +02001107 depth = 0;
Victor Stinner928ad282016-03-23 15:19:12 +01001108 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
1109 sp + STACK_OVERFLOW_MAX_SIZE,
1110 &depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001111 if (sp < stop)
1112 size = stop - sp;
1113 else
1114 size = sp - stop;
1115 PyErr_Format(PyExc_RuntimeError,
1116 "unable to raise a stack overflow (allocated %zu bytes "
1117 "on the stack, %zu recursive calls)",
1118 size, depth);
1119 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001120}
Victor Stinner928ad282016-03-23 15:19:12 +01001121#endif /* defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) */
Victor Stinner024e37a2011-03-31 01:31:06 +02001122
1123
1124static int
1125faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1126{
1127#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001128 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001129#endif
1130
1131#ifdef FAULTHANDLER_LATER
1132 Py_VISIT(thread.file);
1133#endif
1134#ifdef FAULTHANDLER_USER
1135 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001136 for (signum=0; signum < NSIG; signum++)
1137 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001138 }
1139#endif
1140 Py_VISIT(fatal_error.file);
1141 return 0;
1142}
1143
Victor Stinner404cdc52016-03-23 10:39:17 +01001144#ifdef MS_WINDOWS
1145static PyObject *
1146faulthandler_raise_exception(PyObject *self, PyObject *args)
1147{
1148 unsigned int code, flags = 0;
1149 if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
1150 return NULL;
1151 faulthandler_suppress_crash_report();
1152 RaiseException(code, flags, 0, NULL);
1153 Py_RETURN_NONE;
1154}
1155#endif
1156
Victor Stinner024e37a2011-03-31 01:31:06 +02001157PyDoc_STRVAR(module_doc,
1158"faulthandler module.");
1159
1160static PyMethodDef module_methods[] = {
1161 {"enable",
Victor Stinner404cdc52016-03-23 10:39:17 +01001162 (PyCFunction)faulthandler_py_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001163 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001164 "enable the fault handler")},
1165 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1166 PyDoc_STR("disable(): disable the fault handler")},
1167 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1168 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1169 {"dump_traceback",
1170 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001171 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001172 "dump the traceback of the current thread, or of all threads "
1173 "if all_threads is True, into file")},
1174#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001175 {"dump_traceback_later",
1176 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1177 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001178 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001179 "or each timeout seconds if repeat is True. If exit is True, "
1180 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001181 {"cancel_dump_traceback_later",
1182 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1183 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1184 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001185#endif
1186
1187#ifdef FAULTHANDLER_USER
1188 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001189 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1190 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001191 "register a handler for the signal 'signum': dump the "
Victor Stinner024e37a2011-03-31 01:31:06 +02001192 "traceback of the current thread, or of all threads if "
1193 "all_threads is True, into file")},
1194 {"unregister",
1195 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1196 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1197 "'signum' registered by register()")},
1198#endif
1199
Victor Stinner50838282014-09-30 13:54:14 +02001200 {"_read_null", faulthandler_read_null, METH_NOARGS,
1201 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001202 "a SIGSEGV or SIGBUS signal depending on the platform")},
1203 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001204 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner861d9ab2016-03-16 22:45:24 +01001205#ifdef WITH_THREAD
1206 {"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
1207 PyDoc_STR("fatal_error_c_thread(): "
1208 "call Py_FatalError() in a new C thread.")},
1209#endif
Victor Stinner9db521c2014-09-30 13:49:09 +02001210 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001211 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001212 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1213 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001214 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1215 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
Victor Stinner404cdc52016-03-23 10:39:17 +01001216#ifdef FAULTHANDLER_STACK_OVERFLOW
Victor Stinner024e37a2011-03-31 01:31:06 +02001217 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1218 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1219#endif
Victor Stinner404cdc52016-03-23 10:39:17 +01001220#ifdef MS_WINDOWS
1221 {"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
1222 PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
1223#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001224 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001225};
1226
1227static struct PyModuleDef module_def = {
1228 PyModuleDef_HEAD_INIT,
1229 "faulthandler",
1230 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001231 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001232 module_methods,
1233 NULL,
1234 faulthandler_traverse,
1235 NULL,
1236 NULL
1237};
1238
1239PyMODINIT_FUNC
1240PyInit_faulthandler(void)
1241{
Victor Stinner404cdc52016-03-23 10:39:17 +01001242 PyObject *m = PyModule_Create(&module_def);
1243 if (m == NULL)
1244 return NULL;
1245
1246 /* Add constants for unit tests */
1247#ifdef MS_WINDOWS
1248 /* RaiseException() codes (prefixed by an underscore) */
1249 if (PyModule_AddIntConstant(m, "_EXCEPTION_ACCESS_VIOLATION",
1250 EXCEPTION_ACCESS_VIOLATION))
1251 return NULL;
1252 if (PyModule_AddIntConstant(m, "_EXCEPTION_INT_DIVIDE_BY_ZERO",
1253 EXCEPTION_INT_DIVIDE_BY_ZERO))
1254 return NULL;
1255 if (PyModule_AddIntConstant(m, "_EXCEPTION_STACK_OVERFLOW",
1256 EXCEPTION_STACK_OVERFLOW))
1257 return NULL;
1258
1259 /* RaiseException() flags (prefixed by an underscore) */
1260 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
1261 EXCEPTION_NONCONTINUABLE))
1262 return NULL;
1263 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
1264 EXCEPTION_NONCONTINUABLE_EXCEPTION))
1265 return NULL;
1266#endif
1267
1268 return m;
Victor Stinner024e37a2011-03-31 01:31:06 +02001269}
1270
Victor Stinner410dd7d2011-05-11 20:56:08 +02001271/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1272 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001273
1274static int
1275faulthandler_env_options(void)
1276{
1277 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001278 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001279
Victor Stinner88983502013-09-08 11:36:23 +02001280 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1281 /* PYTHONFAULTHANDLER environment variable is missing
1282 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001283 int has_key;
1284
Victor Stinner024e37a2011-03-31 01:31:06 +02001285 xoptions = PySys_GetXOptions();
1286 if (xoptions == NULL)
1287 return -1;
1288
1289 key = PyUnicode_FromString("faulthandler");
1290 if (key == NULL)
1291 return -1;
1292
Victor Stinner25095b22011-05-26 13:47:08 +02001293 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001294 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001295 if (has_key <= 0)
1296 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001297 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001298
1299 module = PyImport_ImportModule("faulthandler");
1300 if (module == NULL) {
1301 return -1;
1302 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001303 res = _PyObject_CallMethodId(module, &PyId_enable, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +02001304 Py_DECREF(module);
1305 if (res == NULL)
1306 return -1;
1307 Py_DECREF(res);
1308 return 0;
1309}
1310
1311int _PyFaulthandler_Init(void)
1312{
1313#ifdef HAVE_SIGALTSTACK
1314 int err;
1315
1316 /* Try to allocate an alternate stack for faulthandler() signal handler to
1317 * be able to allocate memory on the stack, even on a stack overflow. If it
1318 * fails, ignore the error. */
1319 stack.ss_flags = 0;
1320 stack.ss_size = SIGSTKSZ;
1321 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1322 if (stack.ss_sp != NULL) {
Christophe Zeitouny90eafdb2017-03-24 04:20:40 -07001323 err = sigaltstack(&stack, &old_stack);
Victor Stinner024e37a2011-03-31 01:31:06 +02001324 if (err) {
1325 PyMem_Free(stack.ss_sp);
1326 stack.ss_sp = NULL;
1327 }
1328 }
1329#endif
1330#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001331 thread.file = NULL;
1332 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001333 thread.running = PyThread_allocate_lock();
1334 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001335 PyErr_SetString(PyExc_RuntimeError,
1336 "could not allocate locks for faulthandler");
1337 return -1;
1338 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001339 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001340#endif
1341
1342 return faulthandler_env_options();
1343}
1344
1345void _PyFaulthandler_Fini(void)
1346{
1347#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001348 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001349#endif
1350
1351#ifdef FAULTHANDLER_LATER
1352 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001353 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001354 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001355 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001356 PyThread_free_lock(thread.cancel_event);
1357 thread.cancel_event = NULL;
1358 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001359 if (thread.running) {
1360 PyThread_free_lock(thread.running);
1361 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001362 }
1363#endif
1364
1365#ifdef FAULTHANDLER_USER
1366 /* user */
1367 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001368 for (signum=0; signum < NSIG; signum++)
1369 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001370 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001371 user_signals = NULL;
1372 }
1373#endif
1374
1375 /* fatal */
1376 faulthandler_disable();
1377#ifdef HAVE_SIGALTSTACK
1378 if (stack.ss_sp != NULL) {
Christophe Zeitouny90eafdb2017-03-24 04:20:40 -07001379 /* Fetch the current alt stack */
1380 stack_t current_stack;
1381 if (sigaltstack(NULL, &current_stack) == 0) {
1382 if (current_stack.ss_sp == stack.ss_sp) {
1383 /* The current alt stack is the one that we installed.
1384 It is safe to restore the old stack that we found when
1385 we installed ours */
1386 sigaltstack(&old_stack, NULL);
1387 } else {
1388 /* Someone switched to a different alt stack and didn't
1389 restore ours when they were done (if they're done).
1390 There's not much we can do in this unlikely case */
1391 }
1392 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001393 PyMem_Free(stack.ss_sp);
1394 stack.ss_sp = NULL;
1395 }
1396#endif
1397}