blob: ac6ab7ed0fa0dc0d0f79dfa5449ea73c501e4e80 [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 Stinner024e37a2011-03-31 01:31:06 +020058} fatal_error = {0, NULL, -1, 0};
59
60#ifdef FAULTHANDLER_LATER
61static struct {
62 PyObject *file;
63 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020064 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020065 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020066 PyInterpreterState *interp;
67 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020068 char *header;
69 size_t header_len;
Victor Stinner410dd7d2011-05-11 20:56:08 +020070 /* The main thread always holds this lock. It is only released when
71 faulthandler_thread() is interrupted before this thread exits, or at
Victor Stinnerde10f402011-04-08 12:57:06 +020072 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020073 PyThread_type_lock cancel_event;
74 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020075 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020076} thread;
77#endif
78
79#ifdef FAULTHANDLER_USER
80typedef struct {
81 int enabled;
82 PyObject *file;
83 int fd;
84 int all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +020085 int chain;
Victor Stinner024e37a2011-03-31 01:31:06 +020086 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020087 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020088} user_signal_t;
89
90static user_signal_t *user_signals;
91
92/* the following macros come from Python: Modules/signalmodule.c */
Victor Stinner024e37a2011-03-31 01:31:06 +020093#ifndef NSIG
94# if defined(_NSIG)
95# define NSIG _NSIG /* For BSD/SysV */
96# elif defined(_SIGMAX)
97# define NSIG (_SIGMAX + 1) /* For QNX */
98# elif defined(SIGMAX)
99# define NSIG (SIGMAX + 1) /* For djgpp */
100# else
101# define NSIG 64 /* Use a reasonable default value */
102# endif
103#endif
104
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200105static void faulthandler_user(int signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200106#endif /* FAULTHANDLER_USER */
107
108
109static fault_handler_t faulthandler_handlers[] = {
110#ifdef SIGBUS
111 {SIGBUS, 0, "Bus error", },
112#endif
113#ifdef SIGILL
114 {SIGILL, 0, "Illegal instruction", },
115#endif
116 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200117 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200118 /* define SIGSEGV at the end to make it the default choice if searching the
119 handler fails in faulthandler_fatal_error() */
120 {SIGSEGV, 0, "Segmentation fault", }
121};
Victor Stinner404cdc52016-03-23 10:39:17 +0100122static const size_t faulthandler_nsignals = \
Victor Stinner63941882011-09-29 00:42:28 +0200123 Py_ARRAY_LENGTH(faulthandler_handlers);
Victor Stinner024e37a2011-03-31 01:31:06 +0200124
125#ifdef HAVE_SIGALTSTACK
126static stack_t stack;
127#endif
128
129
130/* Get the file descriptor of a file by calling its fileno() method and then
131 call its flush() method.
132
133 If file is NULL or Py_None, use sys.stderr as the new file.
Victor Stinner95bb7142015-03-12 15:32:03 +0100134 If file is an integer, it will be treated as file descriptor.
Victor Stinner024e37a2011-03-31 01:31:06 +0200135
Victor Stinner95bb7142015-03-12 15:32:03 +0100136 On success, return the file descriptor and write the new file into *file_ptr.
137 On error, return -1. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200138
Victor Stinner95bb7142015-03-12 15:32:03 +0100139static int
140faulthandler_get_fileno(PyObject **file_ptr)
Victor Stinner024e37a2011-03-31 01:31:06 +0200141{
142 PyObject *result;
143 long fd_long;
144 int fd;
Victor Stinner95bb7142015-03-12 15:32:03 +0100145 PyObject *file = *file_ptr;
Victor Stinner024e37a2011-03-31 01:31:06 +0200146
147 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100148 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200149 if (file == NULL) {
150 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
Victor Stinner95bb7142015-03-12 15:32:03 +0100151 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200152 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200153 if (file == Py_None) {
154 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
Victor Stinner95bb7142015-03-12 15:32:03 +0100155 return -1;
Victor Stinnere2d66902014-05-14 17:15:50 +0200156 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200157 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100158 else if (PyLong_Check(file)) {
159 fd = _PyLong_AsInt(file);
160 if (fd == -1 && PyErr_Occurred())
161 return -1;
Steve Dower940f33a2016-09-08 11:21:54 -0700162 if (fd < 0) {
Victor Stinner95bb7142015-03-12 15:32:03 +0100163 PyErr_SetString(PyExc_ValueError,
164 "file is not a valid file descripter");
165 return -1;
166 }
167 *file_ptr = NULL;
168 return fd;
169 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200170
Victor Stinner3466bde2016-09-05 18:16:01 -0700171 result = _PyObject_CallMethodId(file, &PyId_fileno, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200172 if (result == NULL)
Victor Stinner95bb7142015-03-12 15:32:03 +0100173 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200174
175 fd = -1;
176 if (PyLong_Check(result)) {
177 fd_long = PyLong_AsLong(result);
178 if (0 <= fd_long && fd_long < INT_MAX)
179 fd = (int)fd_long;
180 }
181 Py_DECREF(result);
182
183 if (fd == -1) {
184 PyErr_SetString(PyExc_RuntimeError,
185 "file.fileno() is not a valid file descriptor");
Victor Stinner95bb7142015-03-12 15:32:03 +0100186 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200187 }
188
Victor Stinner3466bde2016-09-05 18:16:01 -0700189 result = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200190 if (result != NULL)
191 Py_DECREF(result);
192 else {
193 /* ignore flush() error */
194 PyErr_Clear();
195 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100196 *file_ptr = file;
197 return fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200198}
199
Victor Stinnera4de6d82011-04-09 00:47:23 +0200200/* Get the state of the current thread: only call this function if the current
201 thread holds the GIL. Raise an exception on error. */
202static PyThreadState*
203get_thread_state(void)
204{
Victor Stinner861d9ab2016-03-16 22:45:24 +0100205 PyThreadState *tstate = _PyThreadState_UncheckedGet();
Victor Stinnera4de6d82011-04-09 00:47:23 +0200206 if (tstate == NULL) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100207 /* just in case but very unlikely... */
Victor Stinnera4de6d82011-04-09 00:47:23 +0200208 PyErr_SetString(PyExc_RuntimeError,
209 "unable to get the current thread state");
210 return NULL;
211 }
212 return tstate;
213}
214
Victor Stinnerc7489a52015-04-01 18:48:58 +0200215static void
216faulthandler_dump_traceback(int fd, int all_threads,
217 PyInterpreterState *interp)
218{
219 static volatile int reentrant = 0;
220 PyThreadState *tstate;
221
222 if (reentrant)
223 return;
224
225 reentrant = 1;
226
227#ifdef WITH_THREAD
228 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
229 are thus delivered to the thread that caused the fault. Get the Python
230 thread state of the current thread.
231
232 PyThreadState_Get() doesn't give the state of the thread that caused the
233 fault if the thread released the GIL, and so this function cannot be
234 used. Read the thread local storage (TLS) instead: call
235 PyGILState_GetThisThreadState(). */
236 tstate = PyGILState_GetThisThreadState();
237#else
Victor Stinner861d9ab2016-03-16 22:45:24 +0100238 tstate = _PyThreadState_UncheckedGet();
Victor Stinnerc7489a52015-04-01 18:48:58 +0200239#endif
240
Victor Stinner861d9ab2016-03-16 22:45:24 +0100241 if (all_threads) {
242 (void)_Py_DumpTracebackThreads(fd, NULL, tstate);
243 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200244 else {
245 if (tstate != NULL)
246 _Py_DumpTraceback(fd, tstate);
247 }
248
249 reentrant = 0;
250}
251
Victor Stinner024e37a2011-03-31 01:31:06 +0200252static PyObject*
253faulthandler_dump_traceback_py(PyObject *self,
254 PyObject *args, PyObject *kwargs)
255{
256 static char *kwlist[] = {"file", "all_threads", NULL};
257 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200258 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200259 PyThreadState *tstate;
260 const char *errmsg;
261 int fd;
262
263 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
264 "|Oi:dump_traceback", kwlist,
265 &file, &all_threads))
266 return NULL;
267
Victor Stinner95bb7142015-03-12 15:32:03 +0100268 fd = faulthandler_get_fileno(&file);
269 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200270 return NULL;
271
Victor Stinnera4de6d82011-04-09 00:47:23 +0200272 tstate = get_thread_state();
273 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200274 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200275
276 if (all_threads) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100277 errmsg = _Py_DumpTracebackThreads(fd, NULL, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200278 if (errmsg != NULL) {
279 PyErr_SetString(PyExc_RuntimeError, errmsg);
280 return NULL;
281 }
282 }
283 else {
284 _Py_DumpTraceback(fd, tstate);
285 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200286
287 if (PyErr_CheckSignals())
288 return NULL;
289
Victor Stinner024e37a2011-03-31 01:31:06 +0200290 Py_RETURN_NONE;
291}
292
Victor Stinner404cdc52016-03-23 10:39:17 +0100293static void
294faulthandler_disable_fatal_handler(fault_handler_t *handler)
295{
296 if (!handler->enabled)
297 return;
298 handler->enabled = 0;
299#ifdef HAVE_SIGACTION
300 (void)sigaction(handler->signum, &handler->previous, NULL);
301#else
302 (void)signal(handler->signum, handler->previous);
303#endif
304}
305
Victor Stinner024e37a2011-03-31 01:31:06 +0200306
Victor Stinner410dd7d2011-05-11 20:56:08 +0200307/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200308
309 Display the current Python traceback, restore the previous handler and call
310 the previous handler.
311
Victor Stinner410dd7d2011-05-11 20:56:08 +0200312 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200313 signal handler would not be called (for an unknown reason). The execution of
314 the program continues at faulthandler_fatal_error() exit, but the same
315 instruction will raise the same fault (signal), and so the previous handler
316 will be called.
317
Victor Stinner410dd7d2011-05-11 20:56:08 +0200318 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200319
320static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200321faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200322{
323 const int fd = fatal_error.fd;
Victor Stinner404cdc52016-03-23 10:39:17 +0100324 size_t i;
Victor Stinner024e37a2011-03-31 01:31:06 +0200325 fault_handler_t *handler = NULL;
Victor Stinnerc9256172011-05-07 12:20:11 +0200326 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200327
328 if (!fatal_error.enabled)
329 return;
330
331 for (i=0; i < faulthandler_nsignals; i++) {
332 handler = &faulthandler_handlers[i];
333 if (handler->signum == signum)
334 break;
335 }
336 if (handler == NULL) {
337 /* faulthandler_nsignals == 0 (unlikely) */
338 return;
339 }
340
341 /* restore the previous handler */
Victor Stinner404cdc52016-03-23 10:39:17 +0100342 faulthandler_disable_fatal_handler(handler);
Victor Stinner024e37a2011-03-31 01:31:06 +0200343
344 PUTS(fd, "Fatal Python error: ");
345 PUTS(fd, handler->name);
346 PUTS(fd, "\n\n");
347
Victor Stinnerc7489a52015-04-01 18:48:58 +0200348 faulthandler_dump_traceback(fd, fatal_error.all_threads,
349 fatal_error.interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200350
Victor Stinnerc9256172011-05-07 12:20:11 +0200351 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200352#ifdef MS_WINDOWS
353 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200354 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200355 handler, because the Windows signal handler would not be called */
356 return;
357 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200358#endif
R David Murrayfc069992013-12-13 20:52:19 -0500359 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200360 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
361 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200362}
363
Victor Stinner404cdc52016-03-23 10:39:17 +0100364#ifdef MS_WINDOWS
365static LONG WINAPI
366faulthandler_exc_handler(struct _EXCEPTION_POINTERS *exc_info)
367{
368 const int fd = fatal_error.fd;
369 DWORD code = exc_info->ExceptionRecord->ExceptionCode;
Victor Stinner412a5e72016-03-23 14:44:14 +0100370 DWORD flags = exc_info->ExceptionRecord->ExceptionFlags;
Victor Stinner404cdc52016-03-23 10:39:17 +0100371
Victor Stinner412a5e72016-03-23 14:44:14 +0100372 /* only log fatal exceptions */
373 if (flags & EXCEPTION_NONCONTINUABLE) {
374 /* call the next exception handler */
375 return EXCEPTION_CONTINUE_SEARCH;
376 }
377
378 PUTS(fd, "Windows fatal exception: ");
Victor Stinner404cdc52016-03-23 10:39:17 +0100379 switch (code)
380 {
381 /* only format most common errors */
382 case EXCEPTION_ACCESS_VIOLATION: PUTS(fd, "access violation"); break;
383 case EXCEPTION_FLT_DIVIDE_BY_ZERO: PUTS(fd, "float divide by zero"); break;
384 case EXCEPTION_FLT_OVERFLOW: PUTS(fd, "float overflow"); break;
385 case EXCEPTION_INT_DIVIDE_BY_ZERO: PUTS(fd, "int divide by zero"); break;
386 case EXCEPTION_INT_OVERFLOW: PUTS(fd, "integer overflow"); break;
387 case EXCEPTION_IN_PAGE_ERROR: PUTS(fd, "page error"); break;
388 case EXCEPTION_STACK_OVERFLOW: PUTS(fd, "stack overflow"); break;
389 default:
Victor Stinner412a5e72016-03-23 14:44:14 +0100390 PUTS(fd, "code ");
Victor Stinner82d44f02016-03-23 18:37:54 +0100391 _Py_DumpDecimal(fd, code);
Victor Stinner404cdc52016-03-23 10:39:17 +0100392 }
393 PUTS(fd, "\n\n");
394
395 if (code == EXCEPTION_ACCESS_VIOLATION) {
396 /* disable signal handler for SIGSEGV */
397 size_t i;
398 for (i=0; i < faulthandler_nsignals; i++) {
399 fault_handler_t *handler = &faulthandler_handlers[i];
400 if (handler->signum == SIGSEGV) {
401 faulthandler_disable_fatal_handler(handler);
402 break;
403 }
404 }
405 }
406
407 faulthandler_dump_traceback(fd, fatal_error.all_threads,
408 fatal_error.interp);
409
410 /* call the next exception handler */
411 return EXCEPTION_CONTINUE_SEARCH;
412}
413#endif
414
Victor Stinnerd727e232011-04-01 12:13:55 +0200415/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200416
doko@ubuntu.combc731502016-05-18 01:06:01 +0200417static int
Victor Stinner404cdc52016-03-23 10:39:17 +0100418faulthandler_enable(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200419{
Victor Stinner404cdc52016-03-23 10:39:17 +0100420 size_t i;
Victor Stinner404cdc52016-03-23 10:39:17 +0100421
422 if (fatal_error.enabled) {
423 return 0;
424 }
Victor Stinner404cdc52016-03-23 10:39:17 +0100425 fatal_error.enabled = 1;
426
427 for (i=0; i < faulthandler_nsignals; i++) {
Victor Stinner928ad282016-03-23 15:19:12 +0100428 fault_handler_t *handler;
429#ifdef HAVE_SIGACTION
430 struct sigaction action;
431#endif
432 int err;
Victor Stinner404cdc52016-03-23 10:39:17 +0100433
Victor Stinner928ad282016-03-23 15:19:12 +0100434 handler = &faulthandler_handlers[i];
435 assert(!handler->enabled);
Victor Stinner404cdc52016-03-23 10:39:17 +0100436#ifdef HAVE_SIGACTION
437 action.sa_handler = faulthandler_fatal_error;
438 sigemptyset(&action.sa_mask);
439 /* Do not prevent the signal from being received from within
440 its own signal handler */
441 action.sa_flags = SA_NODEFER;
442#ifdef HAVE_SIGALTSTACK
443 if (stack.ss_sp != NULL) {
444 /* Call the signal handler on an alternate signal stack
445 provided by sigaltstack() */
446 action.sa_flags |= SA_ONSTACK;
447 }
448#endif
449 err = sigaction(handler->signum, &action, &handler->previous);
450#else
451 handler->previous = signal(handler->signum,
452 faulthandler_fatal_error);
453 err = (handler->previous == SIG_ERR);
454#endif
455 if (err) {
456 PyErr_SetFromErrno(PyExc_RuntimeError);
457 return -1;
458 }
459
460 handler->enabled = 1;
461 }
462
463#ifdef MS_WINDOWS
464 AddVectoredExceptionHandler(1, faulthandler_exc_handler);
465#endif
466 return 0;
467}
468
469static PyObject*
470faulthandler_py_enable(PyObject *self, PyObject *args, PyObject *kwargs)
471{
472 static char *kwlist[] = {"file", "all_threads", NULL};
473 PyObject *file = NULL;
474 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200475 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200476 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200477
478 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
479 "|Oi:enable", kwlist, &file, &all_threads))
480 return NULL;
481
Victor Stinner95bb7142015-03-12 15:32:03 +0100482 fd = faulthandler_get_fileno(&file);
483 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200484 return NULL;
485
Victor Stinnera4de6d82011-04-09 00:47:23 +0200486 tstate = get_thread_state();
487 if (tstate == NULL)
488 return NULL;
489
Victor Stinner95bb7142015-03-12 15:32:03 +0100490 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300491 Py_XSETREF(fatal_error.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200492 fatal_error.fd = fd;
493 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200494 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200495
Victor Stinner404cdc52016-03-23 10:39:17 +0100496 if (faulthandler_enable() < 0) {
497 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200498 }
Victor Stinner404cdc52016-03-23 10:39:17 +0100499
Victor Stinner024e37a2011-03-31 01:31:06 +0200500 Py_RETURN_NONE;
501}
502
503static void
504faulthandler_disable(void)
505{
506 unsigned int i;
507 fault_handler_t *handler;
508
509 if (fatal_error.enabled) {
510 fatal_error.enabled = 0;
511 for (i=0; i < faulthandler_nsignals; i++) {
512 handler = &faulthandler_handlers[i];
Victor Stinner404cdc52016-03-23 10:39:17 +0100513 faulthandler_disable_fatal_handler(handler);
Victor Stinner024e37a2011-03-31 01:31:06 +0200514 }
515 }
516
517 Py_CLEAR(fatal_error.file);
518}
519
520static PyObject*
521faulthandler_disable_py(PyObject *self)
522{
523 if (!fatal_error.enabled) {
524 Py_INCREF(Py_False);
525 return Py_False;
526 }
527 faulthandler_disable();
528 Py_INCREF(Py_True);
529 return Py_True;
530}
531
532static PyObject*
533faulthandler_is_enabled(PyObject *self)
534{
535 return PyBool_FromLong(fatal_error.enabled);
536}
537
538#ifdef FAULTHANDLER_LATER
539
540static void
541faulthandler_thread(void *unused)
542{
543 PyLockStatus st;
544 const char* errmsg;
Victor Stinner024e37a2011-03-31 01:31:06 +0200545 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200546#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200547 sigset_t set;
548
549 /* we don't want to receive any signal */
550 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200551 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200552#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200553
554 do {
555 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200556 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200557 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200558 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200559 break;
560 }
561 /* Timeout => dump traceback */
562 assert(st == PY_LOCK_FAILURE);
563
Victor Stinnerc7489a52015-04-01 18:48:58 +0200564 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200565
Victor Stinner861d9ab2016-03-16 22:45:24 +0100566 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200567 ok = (errmsg == NULL);
568
569 if (thread.exit)
570 _exit(1);
571 } while (ok && thread.repeat);
572
573 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200574 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200575}
576
577static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200578cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200579{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200580 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200581 PyThread_release_lock(thread.cancel_event);
582
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200583 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200584 PyThread_acquire_lock(thread.running, 1);
585 PyThread_release_lock(thread.running);
586
587 /* The main thread should always hold the cancel_event lock */
588 PyThread_acquire_lock(thread.cancel_event, 1);
589
Victor Stinner024e37a2011-03-31 01:31:06 +0200590 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200591 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200592 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200593 thread.header = NULL;
594 }
595}
596
597static char*
598format_timeout(double timeout)
599{
600 unsigned long us, sec, min, hour;
601 double intpart, fracpart;
602 char buffer[100];
603
604 fracpart = modf(timeout, &intpart);
605 sec = (unsigned long)intpart;
606 us = (unsigned long)(fracpart * 1e6);
607 min = sec / 60;
608 sec %= 60;
609 hour = min / 60;
610 min %= 60;
611
612 if (us != 0)
613 PyOS_snprintf(buffer, sizeof(buffer),
614 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
615 hour, min, sec, us);
616 else
617 PyOS_snprintf(buffer, sizeof(buffer),
618 "Timeout (%lu:%02lu:%02lu)!\n",
619 hour, min, sec);
620
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200621 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200622}
623
624static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200625faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200626 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200627{
628 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
629 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200630 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200631 int repeat = 0;
632 PyObject *file = NULL;
633 int fd;
634 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200635 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200636 char *header;
637 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200638
639 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200640 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200641 &timeout, &repeat, &file, &exit))
642 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200643 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200644 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
645 return NULL;
646 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200647 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200648 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200649 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
650 return NULL;
651 }
652
Victor Stinnera4de6d82011-04-09 00:47:23 +0200653 tstate = get_thread_state();
654 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200655 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200656
Victor Stinner95bb7142015-03-12 15:32:03 +0100657 fd = faulthandler_get_fileno(&file);
658 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200659 return NULL;
660
Victor Stinnerc790a532011-04-08 13:39:59 +0200661 /* format the timeout */
662 header = format_timeout(timeout);
663 if (header == NULL)
664 return PyErr_NoMemory();
665 header_len = strlen(header);
666
Victor Stinner024e37a2011-03-31 01:31:06 +0200667 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200668 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200669
Victor Stinner95bb7142015-03-12 15:32:03 +0100670 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300671 Py_XSETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200672 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200673 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200674 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200675 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200676 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200677 thread.header = header;
678 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200679
680 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200681 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200682
Victor Stinner024e37a2011-03-31 01:31:06 +0200683 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200684 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200685 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200686 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200687 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200688 PyErr_SetString(PyExc_RuntimeError,
689 "unable to start watchdog thread");
690 return NULL;
691 }
692
693 Py_RETURN_NONE;
694}
695
696static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200697faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200698{
Georg Brandldeb92b52012-09-22 08:58:55 +0200699 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200700 Py_RETURN_NONE;
701}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200702#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200703
704#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200705static int
706faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
707{
708#ifdef HAVE_SIGACTION
709 struct sigaction action;
710 action.sa_handler = faulthandler_user;
711 sigemptyset(&action.sa_mask);
712 /* if the signal is received while the kernel is executing a system
713 call, try to restart the system call instead of interrupting it and
714 return EINTR. */
715 action.sa_flags = SA_RESTART;
716 if (chain) {
717 /* do not prevent the signal from being received from within its
718 own signal handler */
719 action.sa_flags = SA_NODEFER;
720 }
721#ifdef HAVE_SIGALTSTACK
722 if (stack.ss_sp != NULL) {
723 /* Call the signal handler on an alternate signal stack
724 provided by sigaltstack() */
725 action.sa_flags |= SA_ONSTACK;
726 }
727#endif
728 return sigaction(signum, &action, p_previous);
729#else
730 _Py_sighandler_t previous;
731 previous = signal(signum, faulthandler_user);
732 if (p_previous != NULL)
733 *p_previous = previous;
734 return (previous == SIG_ERR);
735#endif
736}
737
Victor Stinner024e37a2011-03-31 01:31:06 +0200738/* Handler of user signals (e.g. SIGUSR1).
739
740 Dump the traceback of the current thread, or of all threads if
741 thread.all_threads is true.
742
743 This function is signal safe and should only call signal safe functions. */
744
745static void
746faulthandler_user(int signum)
747{
748 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200749 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200750
751 user = &user_signals[signum];
752 if (!user->enabled)
753 return;
754
Victor Stinnerc7489a52015-04-01 18:48:58 +0200755 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200756
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200757#ifdef HAVE_SIGACTION
758 if (user->chain) {
759 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200760 errno = save_errno;
761
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200762 /* call the previous signal handler */
763 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200764
765 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200766 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200767 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200768 }
769#else
770 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200771 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200772 /* call the previous signal handler */
773 user->previous(signum);
774 }
775#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200776}
777
778static int
779check_signum(int signum)
780{
781 unsigned int i;
782
783 for (i=0; i < faulthandler_nsignals; i++) {
784 if (faulthandler_handlers[i].signum == signum) {
785 PyErr_Format(PyExc_RuntimeError,
786 "signal %i cannot be registered, "
787 "use enable() instead",
788 signum);
789 return 0;
790 }
791 }
792 if (signum < 1 || NSIG <= signum) {
793 PyErr_SetString(PyExc_ValueError, "signal number out of range");
794 return 0;
795 }
796 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200797}
798
799static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200800faulthandler_register_py(PyObject *self,
801 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200802{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200803 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200804 int signum;
805 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200806 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200807 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200808 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200809 user_signal_t *user;
810 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200811 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200812 int err;
813
814 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200815 "i|Oii:register", kwlist,
816 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200817 return NULL;
818
Victor Stinner44378d42011-04-01 15:37:12 +0200819 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200820 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200821
Victor Stinnera4de6d82011-04-09 00:47:23 +0200822 tstate = get_thread_state();
823 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200824 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200825
Victor Stinner95bb7142015-03-12 15:32:03 +0100826 fd = faulthandler_get_fileno(&file);
827 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200828 return NULL;
829
830 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200831 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200832 if (user_signals == NULL)
833 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200834 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200835 }
836 user = &user_signals[signum];
837
838 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200839 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200840 if (err) {
841 PyErr_SetFromErrno(PyExc_OSError);
842 return NULL;
843 }
Victor Stinner8d379542013-07-02 00:14:56 +0200844
845 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200846 }
847
Victor Stinner95bb7142015-03-12 15:32:03 +0100848 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300849 Py_XSETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200850 user->fd = fd;
851 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200852 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200853 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200854 user->enabled = 1;
855
856 Py_RETURN_NONE;
857}
858
859static int
860faulthandler_unregister(user_signal_t *user, int signum)
861{
Victor Stinnera01ca122011-04-01 12:56:17 +0200862 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200863 return 0;
864 user->enabled = 0;
865#ifdef HAVE_SIGACTION
866 (void)sigaction(signum, &user->previous, NULL);
867#else
868 (void)signal(signum, user->previous);
869#endif
870 Py_CLEAR(user->file);
871 user->fd = -1;
872 return 1;
873}
874
875static PyObject*
876faulthandler_unregister_py(PyObject *self, PyObject *args)
877{
878 int signum;
879 user_signal_t *user;
880 int change;
881
882 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
883 return NULL;
884
Victor Stinner44378d42011-04-01 15:37:12 +0200885 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200886 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200887
Victor Stinnercfa71232011-04-08 12:48:15 +0200888 if (user_signals == NULL)
889 Py_RETURN_FALSE;
890
Victor Stinner024e37a2011-03-31 01:31:06 +0200891 user = &user_signals[signum];
892 change = faulthandler_unregister(user, signum);
893 return PyBool_FromLong(change);
894}
895#endif /* FAULTHANDLER_USER */
896
897
Victor Stinner7a399122014-09-30 13:40:12 +0200898static void
899faulthandler_suppress_crash_report(void)
900{
901#ifdef MS_WINDOWS
902 UINT mode;
903
904 /* Configure Windows to not display the Windows Error Reporting dialog */
905 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
906 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
907#endif
908
909#ifdef HAVE_SYS_RESOURCE_H
910 struct rlimit rl;
911
912 /* Disable creation of core dump */
913 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
914 rl.rlim_cur = 0;
915 setrlimit(RLIMIT_CORE, &rl);
916 }
917#endif
918
919#ifdef _MSC_VER
920 /* Visual Studio: configure abort() to not display an error message nor
921 open a popup asking to report the fault. */
922 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
923#endif
924}
925
Victor Stinner024e37a2011-03-31 01:31:06 +0200926static PyObject *
927faulthandler_read_null(PyObject *self, PyObject *args)
928{
Victor Stinnera2477202012-01-30 00:07:43 +0100929 volatile int *x;
930 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100931
Victor Stinner7a399122014-09-30 13:40:12 +0200932 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100933 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200934 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200935 return PyLong_FromLong(y);
936
937}
938
Victor Stinner50838282014-09-30 13:54:14 +0200939static void
940faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200941{
Victor Stinner7a399122014-09-30 13:40:12 +0200942 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200943#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200944 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
945 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200946 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200947 SIGSEGV was raised by the kernel because of a fault, and so if the
948 program retries to execute the same instruction, the fault will be
949 raised again.
950
951 Here the fault is simulated by a fake SIGSEGV signal raised by the
952 application. We have to raise SIGSEGV at lease twice: once for
953 faulthandler_fatal_error(), and one more time for the previous signal
954 handler. */
955 while(1)
956 raise(SIGSEGV);
957#else
958 raise(SIGSEGV);
959#endif
Victor Stinner50838282014-09-30 13:54:14 +0200960}
961
962static PyObject *
963faulthandler_sigsegv(PyObject *self, PyObject *args)
964{
965 int release_gil = 0;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100966 if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
Victor Stinner50838282014-09-30 13:54:14 +0200967 return NULL;
968
969 if (release_gil) {
970 Py_BEGIN_ALLOW_THREADS
971 faulthandler_raise_sigsegv();
972 Py_END_ALLOW_THREADS
973 } else {
974 faulthandler_raise_sigsegv();
975 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200976 Py_RETURN_NONE;
977}
978
Victor Stinner861d9ab2016-03-16 22:45:24 +0100979#ifdef WITH_THREAD
980static void
981faulthandler_fatal_error_thread(void *plock)
982{
Victor Stinner9a2329f2016-12-05 17:56:36 +0100983#ifndef __clang__
Victor Stinner861d9ab2016-03-16 22:45:24 +0100984 PyThread_type_lock *lock = (PyThread_type_lock *)plock;
Victor Stinner9a2329f2016-12-05 17:56:36 +0100985#endif
Victor Stinner861d9ab2016-03-16 22:45:24 +0100986
987 Py_FatalError("in new thread");
988
Victor Stinner9a2329f2016-12-05 17:56:36 +0100989#ifndef __clang__
990 /* Issue #28152: Py_FatalError() is declared with
991 __attribute__((__noreturn__)). GCC emits a warning without
992 "PyThread_release_lock()" (compiler bug?), but Clang is smarter and
993 emits a warning on the return. */
994
Victor Stinner861d9ab2016-03-16 22:45:24 +0100995 /* notify the caller that we are done */
996 PyThread_release_lock(lock);
Victor Stinner9a2329f2016-12-05 17:56:36 +0100997#endif
Victor Stinner861d9ab2016-03-16 22:45:24 +0100998}
999
1000static PyObject *
1001faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
1002{
1003 long thread;
1004 PyThread_type_lock lock;
1005
1006 faulthandler_suppress_crash_report();
1007
1008 lock = PyThread_allocate_lock();
1009 if (lock == NULL)
1010 return PyErr_NoMemory();
1011
1012 PyThread_acquire_lock(lock, WAIT_LOCK);
1013
1014 thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
1015 if (thread == -1) {
1016 PyThread_free_lock(lock);
1017 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
1018 return NULL;
1019 }
1020
1021 /* wait until the thread completes: it will never occur, since Py_FatalError()
1022 exits the process immedialty. */
1023 PyThread_acquire_lock(lock, WAIT_LOCK);
1024 PyThread_release_lock(lock);
1025 PyThread_free_lock(lock);
1026
1027 Py_RETURN_NONE;
1028}
1029#endif
1030
Victor Stinner024e37a2011-03-31 01:31:06 +02001031static PyObject *
1032faulthandler_sigfpe(PyObject *self, PyObject *args)
1033{
1034 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
1035 PowerPC. Use volatile to disable compile-time optimizations. */
1036 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +02001037 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +02001038 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +02001039 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
1040 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001041 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +02001042 /* This line is never reached, but we pretend to make something with z
1043 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +02001044 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +02001045}
1046
Victor Stinnerd727e232011-04-01 12:13:55 +02001047static PyObject *
1048faulthandler_sigabrt(PyObject *self, PyObject *args)
1049{
Victor Stinner7a399122014-09-30 13:40:12 +02001050 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +02001051 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +02001052 Py_RETURN_NONE;
1053}
1054
Victor Stinner024e37a2011-03-31 01:31:06 +02001055static PyObject *
1056faulthandler_fatal_error_py(PyObject *self, PyObject *args)
1057{
1058 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +01001059 int release_gil = 0;
1060 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +02001061 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +02001062 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +01001063 if (release_gil) {
1064 Py_BEGIN_ALLOW_THREADS
1065 Py_FatalError(message);
1066 Py_END_ALLOW_THREADS
1067 }
1068 else {
1069 Py_FatalError(message);
1070 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001071 Py_RETURN_NONE;
1072}
1073
1074#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner404cdc52016-03-23 10:39:17 +01001075#define FAULTHANDLER_STACK_OVERFLOW
1076
Victor Stinner19276f12015-03-23 21:20:27 +01001077#ifdef __INTEL_COMPILER
1078 /* Issue #23654: Turn off ICC's tail call optimization for the
1079 * stack_overflow generator. ICC turns the recursive tail call into
1080 * a loop. */
1081# pragma intel optimization_level 0
1082#endif
1083static
Benjamin Petersonca470632016-09-06 13:47:26 -07001084uintptr_t
1085stack_overflow(uintptr_t min_sp, uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +02001086{
1087 /* allocate 4096 bytes on the stack at each call */
1088 unsigned char buffer[4096];
Benjamin Petersonca470632016-09-06 13:47:26 -07001089 uintptr_t sp = (uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +02001090 *depth += 1;
Victor Stinner928ad282016-03-23 15:19:12 +01001091 if (sp < min_sp || max_sp < sp)
Victor Stinnerf0480752011-03-31 11:34:08 +02001092 return sp;
Victor Stinner928ad282016-03-23 15:19:12 +01001093 buffer[0] = 1;
1094 buffer[4095] = 0;
1095 return stack_overflow(min_sp, max_sp, depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001096}
1097
1098static PyObject *
1099faulthandler_stack_overflow(PyObject *self)
1100{
1101 size_t depth, size;
Benjamin Petersonca470632016-09-06 13:47:26 -07001102 uintptr_t sp = (uintptr_t)&depth;
1103 uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +02001104
Victor Stinner7a399122014-09-30 13:40:12 +02001105 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +02001106 depth = 0;
Victor Stinner928ad282016-03-23 15:19:12 +01001107 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
1108 sp + STACK_OVERFLOW_MAX_SIZE,
1109 &depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001110 if (sp < stop)
1111 size = stop - sp;
1112 else
1113 size = sp - stop;
1114 PyErr_Format(PyExc_RuntimeError,
1115 "unable to raise a stack overflow (allocated %zu bytes "
1116 "on the stack, %zu recursive calls)",
1117 size, depth);
1118 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001119}
Victor Stinner928ad282016-03-23 15:19:12 +01001120#endif /* defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) */
Victor Stinner024e37a2011-03-31 01:31:06 +02001121
1122
1123static int
1124faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1125{
1126#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001127 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001128#endif
1129
1130#ifdef FAULTHANDLER_LATER
1131 Py_VISIT(thread.file);
1132#endif
1133#ifdef FAULTHANDLER_USER
1134 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001135 for (signum=0; signum < NSIG; signum++)
1136 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001137 }
1138#endif
1139 Py_VISIT(fatal_error.file);
1140 return 0;
1141}
1142
Victor Stinner404cdc52016-03-23 10:39:17 +01001143#ifdef MS_WINDOWS
1144static PyObject *
1145faulthandler_raise_exception(PyObject *self, PyObject *args)
1146{
1147 unsigned int code, flags = 0;
1148 if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
1149 return NULL;
1150 faulthandler_suppress_crash_report();
1151 RaiseException(code, flags, 0, NULL);
1152 Py_RETURN_NONE;
1153}
1154#endif
1155
Victor Stinner024e37a2011-03-31 01:31:06 +02001156PyDoc_STRVAR(module_doc,
1157"faulthandler module.");
1158
1159static PyMethodDef module_methods[] = {
1160 {"enable",
Victor Stinner404cdc52016-03-23 10:39:17 +01001161 (PyCFunction)faulthandler_py_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001162 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001163 "enable the fault handler")},
1164 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1165 PyDoc_STR("disable(): disable the fault handler")},
1166 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1167 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1168 {"dump_traceback",
1169 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001170 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001171 "dump the traceback of the current thread, or of all threads "
1172 "if all_threads is True, into file")},
1173#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001174 {"dump_traceback_later",
1175 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1176 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001177 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001178 "or each timeout seconds if repeat is True. If exit is True, "
1179 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001180 {"cancel_dump_traceback_later",
1181 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1182 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1183 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001184#endif
1185
1186#ifdef FAULTHANDLER_USER
1187 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001188 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1189 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001190 "register a handler for the signal 'signum': dump the "
Victor Stinner024e37a2011-03-31 01:31:06 +02001191 "traceback of the current thread, or of all threads if "
1192 "all_threads is True, into file")},
1193 {"unregister",
1194 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1195 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1196 "'signum' registered by register()")},
1197#endif
1198
Victor Stinner50838282014-09-30 13:54:14 +02001199 {"_read_null", faulthandler_read_null, METH_NOARGS,
1200 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001201 "a SIGSEGV or SIGBUS signal depending on the platform")},
1202 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001203 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner861d9ab2016-03-16 22:45:24 +01001204#ifdef WITH_THREAD
1205 {"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
1206 PyDoc_STR("fatal_error_c_thread(): "
1207 "call Py_FatalError() in a new C thread.")},
1208#endif
Victor Stinner9db521c2014-09-30 13:49:09 +02001209 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001210 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001211 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1212 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001213 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1214 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
Victor Stinner404cdc52016-03-23 10:39:17 +01001215#ifdef FAULTHANDLER_STACK_OVERFLOW
Victor Stinner024e37a2011-03-31 01:31:06 +02001216 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1217 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1218#endif
Victor Stinner404cdc52016-03-23 10:39:17 +01001219#ifdef MS_WINDOWS
1220 {"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
1221 PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
1222#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001223 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001224};
1225
1226static struct PyModuleDef module_def = {
1227 PyModuleDef_HEAD_INIT,
1228 "faulthandler",
1229 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001230 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001231 module_methods,
1232 NULL,
1233 faulthandler_traverse,
1234 NULL,
1235 NULL
1236};
1237
1238PyMODINIT_FUNC
1239PyInit_faulthandler(void)
1240{
Victor Stinner404cdc52016-03-23 10:39:17 +01001241 PyObject *m = PyModule_Create(&module_def);
1242 if (m == NULL)
1243 return NULL;
1244
1245 /* Add constants for unit tests */
1246#ifdef MS_WINDOWS
1247 /* RaiseException() codes (prefixed by an underscore) */
1248 if (PyModule_AddIntConstant(m, "_EXCEPTION_ACCESS_VIOLATION",
1249 EXCEPTION_ACCESS_VIOLATION))
1250 return NULL;
1251 if (PyModule_AddIntConstant(m, "_EXCEPTION_INT_DIVIDE_BY_ZERO",
1252 EXCEPTION_INT_DIVIDE_BY_ZERO))
1253 return NULL;
1254 if (PyModule_AddIntConstant(m, "_EXCEPTION_STACK_OVERFLOW",
1255 EXCEPTION_STACK_OVERFLOW))
1256 return NULL;
1257
1258 /* RaiseException() flags (prefixed by an underscore) */
1259 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
1260 EXCEPTION_NONCONTINUABLE))
1261 return NULL;
1262 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
1263 EXCEPTION_NONCONTINUABLE_EXCEPTION))
1264 return NULL;
1265#endif
1266
1267 return m;
Victor Stinner024e37a2011-03-31 01:31:06 +02001268}
1269
Victor Stinner410dd7d2011-05-11 20:56:08 +02001270/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1271 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001272
1273static int
1274faulthandler_env_options(void)
1275{
1276 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001277 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001278
Victor Stinner88983502013-09-08 11:36:23 +02001279 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1280 /* PYTHONFAULTHANDLER environment variable is missing
1281 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001282 int has_key;
1283
Victor Stinner024e37a2011-03-31 01:31:06 +02001284 xoptions = PySys_GetXOptions();
1285 if (xoptions == NULL)
1286 return -1;
1287
1288 key = PyUnicode_FromString("faulthandler");
1289 if (key == NULL)
1290 return -1;
1291
Victor Stinner25095b22011-05-26 13:47:08 +02001292 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001293 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001294 if (has_key <= 0)
1295 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001296 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001297
1298 module = PyImport_ImportModule("faulthandler");
1299 if (module == NULL) {
1300 return -1;
1301 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001302 res = _PyObject_CallMethodId(module, &PyId_enable, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +02001303 Py_DECREF(module);
1304 if (res == NULL)
1305 return -1;
1306 Py_DECREF(res);
1307 return 0;
1308}
1309
1310int _PyFaulthandler_Init(void)
1311{
1312#ifdef HAVE_SIGALTSTACK
1313 int err;
1314
1315 /* Try to allocate an alternate stack for faulthandler() signal handler to
1316 * be able to allocate memory on the stack, even on a stack overflow. If it
1317 * fails, ignore the error. */
1318 stack.ss_flags = 0;
1319 stack.ss_size = SIGSTKSZ;
1320 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1321 if (stack.ss_sp != NULL) {
1322 err = sigaltstack(&stack, NULL);
1323 if (err) {
1324 PyMem_Free(stack.ss_sp);
1325 stack.ss_sp = NULL;
1326 }
1327 }
1328#endif
1329#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001330 thread.file = NULL;
1331 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001332 thread.running = PyThread_allocate_lock();
1333 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001334 PyErr_SetString(PyExc_RuntimeError,
1335 "could not allocate locks for faulthandler");
1336 return -1;
1337 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001338 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001339#endif
1340
1341 return faulthandler_env_options();
1342}
1343
1344void _PyFaulthandler_Fini(void)
1345{
1346#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001347 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001348#endif
1349
1350#ifdef FAULTHANDLER_LATER
1351 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001352 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001353 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001354 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001355 PyThread_free_lock(thread.cancel_event);
1356 thread.cancel_event = NULL;
1357 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001358 if (thread.running) {
1359 PyThread_free_lock(thread.running);
1360 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001361 }
1362#endif
1363
1364#ifdef FAULTHANDLER_USER
1365 /* user */
1366 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001367 for (signum=0; signum < NSIG; signum++)
1368 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001369 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001370 user_signals = NULL;
1371 }
1372#endif
1373
1374 /* fatal */
1375 faulthandler_disable();
1376#ifdef HAVE_SIGALTSTACK
1377 if (stack.ss_sp != NULL) {
1378 PyMem_Free(stack.ss_sp);
1379 stack.ss_sp = NULL;
1380 }
1381#endif
1382}