blob: 4fc8ebd4e3958002471466ae660560becd4b1a4b [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) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200524 Py_RETURN_FALSE;
Victor Stinner024e37a2011-03-31 01:31:06 +0200525 }
526 faulthandler_disable();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200527 Py_RETURN_TRUE;
Victor Stinner024e37a2011-03-31 01:31:06 +0200528}
529
530static PyObject*
531faulthandler_is_enabled(PyObject *self)
532{
533 return PyBool_FromLong(fatal_error.enabled);
534}
535
536#ifdef FAULTHANDLER_LATER
537
538static void
539faulthandler_thread(void *unused)
540{
541 PyLockStatus st;
542 const char* errmsg;
Victor Stinner024e37a2011-03-31 01:31:06 +0200543 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200544#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200545 sigset_t set;
546
547 /* we don't want to receive any signal */
548 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200549 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200550#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200551
552 do {
553 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200554 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200555 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200556 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200557 break;
558 }
559 /* Timeout => dump traceback */
560 assert(st == PY_LOCK_FAILURE);
561
Victor Stinnerc7489a52015-04-01 18:48:58 +0200562 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200563
Victor Stinner861d9ab2016-03-16 22:45:24 +0100564 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200565 ok = (errmsg == NULL);
566
567 if (thread.exit)
568 _exit(1);
569 } while (ok && thread.repeat);
570
571 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200572 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200573}
574
575static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200576cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200577{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200578 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200579 PyThread_release_lock(thread.cancel_event);
580
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200581 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200582 PyThread_acquire_lock(thread.running, 1);
583 PyThread_release_lock(thread.running);
584
585 /* The main thread should always hold the cancel_event lock */
586 PyThread_acquire_lock(thread.cancel_event, 1);
587
Victor Stinner024e37a2011-03-31 01:31:06 +0200588 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200589 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200590 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200591 thread.header = NULL;
592 }
593}
594
595static char*
596format_timeout(double timeout)
597{
598 unsigned long us, sec, min, hour;
599 double intpart, fracpart;
600 char buffer[100];
601
602 fracpart = modf(timeout, &intpart);
603 sec = (unsigned long)intpart;
604 us = (unsigned long)(fracpart * 1e6);
605 min = sec / 60;
606 sec %= 60;
607 hour = min / 60;
608 min %= 60;
609
610 if (us != 0)
611 PyOS_snprintf(buffer, sizeof(buffer),
612 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
613 hour, min, sec, us);
614 else
615 PyOS_snprintf(buffer, sizeof(buffer),
616 "Timeout (%lu:%02lu:%02lu)!\n",
617 hour, min, sec);
618
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200619 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200620}
621
622static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200623faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200624 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200625{
626 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
627 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200628 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200629 int repeat = 0;
630 PyObject *file = NULL;
631 int fd;
632 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200633 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200634 char *header;
635 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200636
637 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200638 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200639 &timeout, &repeat, &file, &exit))
640 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200641 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200642 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
643 return NULL;
644 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200645 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200646 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200647 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
648 return NULL;
649 }
650
Victor Stinnera4de6d82011-04-09 00:47:23 +0200651 tstate = get_thread_state();
652 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200653 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200654
Victor Stinner95bb7142015-03-12 15:32:03 +0100655 fd = faulthandler_get_fileno(&file);
656 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200657 return NULL;
658
Victor Stinnerc790a532011-04-08 13:39:59 +0200659 /* format the timeout */
660 header = format_timeout(timeout);
661 if (header == NULL)
662 return PyErr_NoMemory();
663 header_len = strlen(header);
664
Victor Stinner024e37a2011-03-31 01:31:06 +0200665 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200666 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200667
Victor Stinner95bb7142015-03-12 15:32:03 +0100668 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300669 Py_XSETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200670 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200671 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200672 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200673 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200674 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200675 thread.header = header;
676 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200677
678 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200679 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200680
Victor Stinner024e37a2011-03-31 01:31:06 +0200681 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200682 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200683 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200684 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200685 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200686 PyErr_SetString(PyExc_RuntimeError,
687 "unable to start watchdog thread");
688 return NULL;
689 }
690
691 Py_RETURN_NONE;
692}
693
694static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200695faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200696{
Georg Brandldeb92b52012-09-22 08:58:55 +0200697 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200698 Py_RETURN_NONE;
699}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200700#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200701
702#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200703static int
704faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
705{
706#ifdef HAVE_SIGACTION
707 struct sigaction action;
708 action.sa_handler = faulthandler_user;
709 sigemptyset(&action.sa_mask);
710 /* if the signal is received while the kernel is executing a system
711 call, try to restart the system call instead of interrupting it and
712 return EINTR. */
713 action.sa_flags = SA_RESTART;
714 if (chain) {
715 /* do not prevent the signal from being received from within its
716 own signal handler */
717 action.sa_flags = SA_NODEFER;
718 }
719#ifdef HAVE_SIGALTSTACK
720 if (stack.ss_sp != NULL) {
721 /* Call the signal handler on an alternate signal stack
722 provided by sigaltstack() */
723 action.sa_flags |= SA_ONSTACK;
724 }
725#endif
726 return sigaction(signum, &action, p_previous);
727#else
728 _Py_sighandler_t previous;
729 previous = signal(signum, faulthandler_user);
730 if (p_previous != NULL)
731 *p_previous = previous;
732 return (previous == SIG_ERR);
733#endif
734}
735
Victor Stinner024e37a2011-03-31 01:31:06 +0200736/* Handler of user signals (e.g. SIGUSR1).
737
738 Dump the traceback of the current thread, or of all threads if
739 thread.all_threads is true.
740
741 This function is signal safe and should only call signal safe functions. */
742
743static void
744faulthandler_user(int signum)
745{
746 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200747 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200748
749 user = &user_signals[signum];
750 if (!user->enabled)
751 return;
752
Victor Stinnerc7489a52015-04-01 18:48:58 +0200753 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200754
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200755#ifdef HAVE_SIGACTION
756 if (user->chain) {
757 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200758 errno = save_errno;
759
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200760 /* call the previous signal handler */
761 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200762
763 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200764 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200765 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200766 }
767#else
768 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200769 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200770 /* call the previous signal handler */
771 user->previous(signum);
772 }
773#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200774}
775
776static int
777check_signum(int signum)
778{
779 unsigned int i;
780
781 for (i=0; i < faulthandler_nsignals; i++) {
782 if (faulthandler_handlers[i].signum == signum) {
783 PyErr_Format(PyExc_RuntimeError,
784 "signal %i cannot be registered, "
785 "use enable() instead",
786 signum);
787 return 0;
788 }
789 }
790 if (signum < 1 || NSIG <= signum) {
791 PyErr_SetString(PyExc_ValueError, "signal number out of range");
792 return 0;
793 }
794 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200795}
796
797static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200798faulthandler_register_py(PyObject *self,
799 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200800{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200801 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200802 int signum;
803 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200804 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200805 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200806 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200807 user_signal_t *user;
808 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200809 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200810 int err;
811
812 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200813 "i|Oii:register", kwlist,
814 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200815 return NULL;
816
Victor Stinner44378d42011-04-01 15:37:12 +0200817 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200818 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200819
Victor Stinnera4de6d82011-04-09 00:47:23 +0200820 tstate = get_thread_state();
821 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200822 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200823
Victor Stinner95bb7142015-03-12 15:32:03 +0100824 fd = faulthandler_get_fileno(&file);
825 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200826 return NULL;
827
828 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200829 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200830 if (user_signals == NULL)
831 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200832 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200833 }
834 user = &user_signals[signum];
835
836 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200837 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200838 if (err) {
839 PyErr_SetFromErrno(PyExc_OSError);
840 return NULL;
841 }
Victor Stinner8d379542013-07-02 00:14:56 +0200842
843 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200844 }
845
Victor Stinner95bb7142015-03-12 15:32:03 +0100846 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300847 Py_XSETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200848 user->fd = fd;
849 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200850 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200851 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200852 user->enabled = 1;
853
854 Py_RETURN_NONE;
855}
856
857static int
858faulthandler_unregister(user_signal_t *user, int signum)
859{
Victor Stinnera01ca122011-04-01 12:56:17 +0200860 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200861 return 0;
862 user->enabled = 0;
863#ifdef HAVE_SIGACTION
864 (void)sigaction(signum, &user->previous, NULL);
865#else
866 (void)signal(signum, user->previous);
867#endif
868 Py_CLEAR(user->file);
869 user->fd = -1;
870 return 1;
871}
872
873static PyObject*
874faulthandler_unregister_py(PyObject *self, PyObject *args)
875{
876 int signum;
877 user_signal_t *user;
878 int change;
879
880 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
881 return NULL;
882
Victor Stinner44378d42011-04-01 15:37:12 +0200883 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200884 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200885
Victor Stinnercfa71232011-04-08 12:48:15 +0200886 if (user_signals == NULL)
887 Py_RETURN_FALSE;
888
Victor Stinner024e37a2011-03-31 01:31:06 +0200889 user = &user_signals[signum];
890 change = faulthandler_unregister(user, signum);
891 return PyBool_FromLong(change);
892}
893#endif /* FAULTHANDLER_USER */
894
895
Victor Stinner7a399122014-09-30 13:40:12 +0200896static void
897faulthandler_suppress_crash_report(void)
898{
899#ifdef MS_WINDOWS
900 UINT mode;
901
902 /* Configure Windows to not display the Windows Error Reporting dialog */
903 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
904 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
905#endif
906
907#ifdef HAVE_SYS_RESOURCE_H
908 struct rlimit rl;
909
910 /* Disable creation of core dump */
911 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
912 rl.rlim_cur = 0;
913 setrlimit(RLIMIT_CORE, &rl);
914 }
915#endif
916
917#ifdef _MSC_VER
918 /* Visual Studio: configure abort() to not display an error message nor
919 open a popup asking to report the fault. */
920 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
921#endif
922}
923
Victor Stinner024e37a2011-03-31 01:31:06 +0200924static PyObject *
925faulthandler_read_null(PyObject *self, PyObject *args)
926{
Victor Stinnera2477202012-01-30 00:07:43 +0100927 volatile int *x;
928 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100929
Victor Stinner7a399122014-09-30 13:40:12 +0200930 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100931 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200932 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200933 return PyLong_FromLong(y);
934
935}
936
Victor Stinner50838282014-09-30 13:54:14 +0200937static void
938faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200939{
Victor Stinner7a399122014-09-30 13:40:12 +0200940 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200941#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200942 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
943 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200944 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200945 SIGSEGV was raised by the kernel because of a fault, and so if the
946 program retries to execute the same instruction, the fault will be
947 raised again.
948
949 Here the fault is simulated by a fake SIGSEGV signal raised by the
950 application. We have to raise SIGSEGV at lease twice: once for
951 faulthandler_fatal_error(), and one more time for the previous signal
952 handler. */
953 while(1)
954 raise(SIGSEGV);
955#else
956 raise(SIGSEGV);
957#endif
Victor Stinner50838282014-09-30 13:54:14 +0200958}
959
960static PyObject *
961faulthandler_sigsegv(PyObject *self, PyObject *args)
962{
963 int release_gil = 0;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100964 if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
Victor Stinner50838282014-09-30 13:54:14 +0200965 return NULL;
966
967 if (release_gil) {
968 Py_BEGIN_ALLOW_THREADS
969 faulthandler_raise_sigsegv();
970 Py_END_ALLOW_THREADS
971 } else {
972 faulthandler_raise_sigsegv();
973 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200974 Py_RETURN_NONE;
975}
976
Victor Stinner861d9ab2016-03-16 22:45:24 +0100977#ifdef WITH_THREAD
978static void
979faulthandler_fatal_error_thread(void *plock)
980{
Victor Stinner9a2329f2016-12-05 17:56:36 +0100981#ifndef __clang__
Victor Stinner861d9ab2016-03-16 22:45:24 +0100982 PyThread_type_lock *lock = (PyThread_type_lock *)plock;
Victor Stinner9a2329f2016-12-05 17:56:36 +0100983#endif
Victor Stinner861d9ab2016-03-16 22:45:24 +0100984
985 Py_FatalError("in new thread");
986
Victor Stinner9a2329f2016-12-05 17:56:36 +0100987#ifndef __clang__
988 /* Issue #28152: Py_FatalError() is declared with
989 __attribute__((__noreturn__)). GCC emits a warning without
990 "PyThread_release_lock()" (compiler bug?), but Clang is smarter and
991 emits a warning on the return. */
992
Victor Stinner861d9ab2016-03-16 22:45:24 +0100993 /* notify the caller that we are done */
994 PyThread_release_lock(lock);
Victor Stinner9a2329f2016-12-05 17:56:36 +0100995#endif
Victor Stinner861d9ab2016-03-16 22:45:24 +0100996}
997
998static PyObject *
999faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
1000{
1001 long thread;
1002 PyThread_type_lock lock;
1003
1004 faulthandler_suppress_crash_report();
1005
1006 lock = PyThread_allocate_lock();
1007 if (lock == NULL)
1008 return PyErr_NoMemory();
1009
1010 PyThread_acquire_lock(lock, WAIT_LOCK);
1011
1012 thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
1013 if (thread == -1) {
1014 PyThread_free_lock(lock);
1015 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
1016 return NULL;
1017 }
1018
1019 /* wait until the thread completes: it will never occur, since Py_FatalError()
1020 exits the process immedialty. */
1021 PyThread_acquire_lock(lock, WAIT_LOCK);
1022 PyThread_release_lock(lock);
1023 PyThread_free_lock(lock);
1024
1025 Py_RETURN_NONE;
1026}
1027#endif
1028
Victor Stinner024e37a2011-03-31 01:31:06 +02001029static PyObject *
1030faulthandler_sigfpe(PyObject *self, PyObject *args)
1031{
1032 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
1033 PowerPC. Use volatile to disable compile-time optimizations. */
1034 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +02001035 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +02001036 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +02001037 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
1038 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001039 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +02001040 /* This line is never reached, but we pretend to make something with z
1041 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +02001042 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +02001043}
1044
Victor Stinnerd727e232011-04-01 12:13:55 +02001045static PyObject *
1046faulthandler_sigabrt(PyObject *self, PyObject *args)
1047{
Victor Stinner7a399122014-09-30 13:40:12 +02001048 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +02001049 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +02001050 Py_RETURN_NONE;
1051}
1052
Victor Stinner024e37a2011-03-31 01:31:06 +02001053static PyObject *
1054faulthandler_fatal_error_py(PyObject *self, PyObject *args)
1055{
1056 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +01001057 int release_gil = 0;
1058 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +02001059 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +02001060 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +01001061 if (release_gil) {
1062 Py_BEGIN_ALLOW_THREADS
1063 Py_FatalError(message);
1064 Py_END_ALLOW_THREADS
1065 }
1066 else {
1067 Py_FatalError(message);
1068 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001069 Py_RETURN_NONE;
1070}
1071
1072#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner404cdc52016-03-23 10:39:17 +01001073#define FAULTHANDLER_STACK_OVERFLOW
1074
Victor Stinner19276f12015-03-23 21:20:27 +01001075#ifdef __INTEL_COMPILER
1076 /* Issue #23654: Turn off ICC's tail call optimization for the
1077 * stack_overflow generator. ICC turns the recursive tail call into
1078 * a loop. */
1079# pragma intel optimization_level 0
1080#endif
1081static
Benjamin Petersonca470632016-09-06 13:47:26 -07001082uintptr_t
1083stack_overflow(uintptr_t min_sp, uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +02001084{
1085 /* allocate 4096 bytes on the stack at each call */
1086 unsigned char buffer[4096];
Benjamin Petersonca470632016-09-06 13:47:26 -07001087 uintptr_t sp = (uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +02001088 *depth += 1;
Victor Stinner928ad282016-03-23 15:19:12 +01001089 if (sp < min_sp || max_sp < sp)
Victor Stinnerf0480752011-03-31 11:34:08 +02001090 return sp;
Victor Stinner928ad282016-03-23 15:19:12 +01001091 buffer[0] = 1;
1092 buffer[4095] = 0;
1093 return stack_overflow(min_sp, max_sp, depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001094}
1095
1096static PyObject *
1097faulthandler_stack_overflow(PyObject *self)
1098{
1099 size_t depth, size;
Benjamin Petersonca470632016-09-06 13:47:26 -07001100 uintptr_t sp = (uintptr_t)&depth;
1101 uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +02001102
Victor Stinner7a399122014-09-30 13:40:12 +02001103 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +02001104 depth = 0;
Victor Stinner928ad282016-03-23 15:19:12 +01001105 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
1106 sp + STACK_OVERFLOW_MAX_SIZE,
1107 &depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001108 if (sp < stop)
1109 size = stop - sp;
1110 else
1111 size = sp - stop;
1112 PyErr_Format(PyExc_RuntimeError,
1113 "unable to raise a stack overflow (allocated %zu bytes "
1114 "on the stack, %zu recursive calls)",
1115 size, depth);
1116 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001117}
Victor Stinner928ad282016-03-23 15:19:12 +01001118#endif /* defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) */
Victor Stinner024e37a2011-03-31 01:31:06 +02001119
1120
1121static int
1122faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1123{
1124#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001125 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001126#endif
1127
1128#ifdef FAULTHANDLER_LATER
1129 Py_VISIT(thread.file);
1130#endif
1131#ifdef FAULTHANDLER_USER
1132 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001133 for (signum=0; signum < NSIG; signum++)
1134 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001135 }
1136#endif
1137 Py_VISIT(fatal_error.file);
1138 return 0;
1139}
1140
Victor Stinner404cdc52016-03-23 10:39:17 +01001141#ifdef MS_WINDOWS
1142static PyObject *
1143faulthandler_raise_exception(PyObject *self, PyObject *args)
1144{
1145 unsigned int code, flags = 0;
1146 if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
1147 return NULL;
1148 faulthandler_suppress_crash_report();
1149 RaiseException(code, flags, 0, NULL);
1150 Py_RETURN_NONE;
1151}
1152#endif
1153
Victor Stinner024e37a2011-03-31 01:31:06 +02001154PyDoc_STRVAR(module_doc,
1155"faulthandler module.");
1156
1157static PyMethodDef module_methods[] = {
1158 {"enable",
Victor Stinner404cdc52016-03-23 10:39:17 +01001159 (PyCFunction)faulthandler_py_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001160 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001161 "enable the fault handler")},
1162 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1163 PyDoc_STR("disable(): disable the fault handler")},
1164 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1165 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1166 {"dump_traceback",
1167 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001168 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001169 "dump the traceback of the current thread, or of all threads "
1170 "if all_threads is True, into file")},
1171#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001172 {"dump_traceback_later",
1173 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1174 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001175 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001176 "or each timeout seconds if repeat is True. If exit is True, "
1177 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001178 {"cancel_dump_traceback_later",
1179 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1180 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1181 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001182#endif
1183
1184#ifdef FAULTHANDLER_USER
1185 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001186 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1187 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001188 "register a handler for the signal 'signum': dump the "
Victor Stinner024e37a2011-03-31 01:31:06 +02001189 "traceback of the current thread, or of all threads if "
1190 "all_threads is True, into file")},
1191 {"unregister",
1192 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1193 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1194 "'signum' registered by register()")},
1195#endif
1196
Victor Stinner50838282014-09-30 13:54:14 +02001197 {"_read_null", faulthandler_read_null, METH_NOARGS,
1198 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001199 "a SIGSEGV or SIGBUS signal depending on the platform")},
1200 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001201 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner861d9ab2016-03-16 22:45:24 +01001202#ifdef WITH_THREAD
1203 {"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
1204 PyDoc_STR("fatal_error_c_thread(): "
1205 "call Py_FatalError() in a new C thread.")},
1206#endif
Victor Stinner9db521c2014-09-30 13:49:09 +02001207 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001208 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001209 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1210 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001211 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1212 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
Victor Stinner404cdc52016-03-23 10:39:17 +01001213#ifdef FAULTHANDLER_STACK_OVERFLOW
Victor Stinner024e37a2011-03-31 01:31:06 +02001214 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1215 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1216#endif
Victor Stinner404cdc52016-03-23 10:39:17 +01001217#ifdef MS_WINDOWS
1218 {"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
1219 PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
1220#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001221 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001222};
1223
1224static struct PyModuleDef module_def = {
1225 PyModuleDef_HEAD_INIT,
1226 "faulthandler",
1227 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001228 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001229 module_methods,
1230 NULL,
1231 faulthandler_traverse,
1232 NULL,
1233 NULL
1234};
1235
1236PyMODINIT_FUNC
1237PyInit_faulthandler(void)
1238{
Victor Stinner404cdc52016-03-23 10:39:17 +01001239 PyObject *m = PyModule_Create(&module_def);
1240 if (m == NULL)
1241 return NULL;
1242
1243 /* Add constants for unit tests */
1244#ifdef MS_WINDOWS
1245 /* RaiseException() codes (prefixed by an underscore) */
1246 if (PyModule_AddIntConstant(m, "_EXCEPTION_ACCESS_VIOLATION",
1247 EXCEPTION_ACCESS_VIOLATION))
1248 return NULL;
1249 if (PyModule_AddIntConstant(m, "_EXCEPTION_INT_DIVIDE_BY_ZERO",
1250 EXCEPTION_INT_DIVIDE_BY_ZERO))
1251 return NULL;
1252 if (PyModule_AddIntConstant(m, "_EXCEPTION_STACK_OVERFLOW",
1253 EXCEPTION_STACK_OVERFLOW))
1254 return NULL;
1255
1256 /* RaiseException() flags (prefixed by an underscore) */
1257 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
1258 EXCEPTION_NONCONTINUABLE))
1259 return NULL;
1260 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
1261 EXCEPTION_NONCONTINUABLE_EXCEPTION))
1262 return NULL;
1263#endif
1264
1265 return m;
Victor Stinner024e37a2011-03-31 01:31:06 +02001266}
1267
Victor Stinner410dd7d2011-05-11 20:56:08 +02001268/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1269 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001270
1271static int
1272faulthandler_env_options(void)
1273{
1274 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001275 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001276
Victor Stinner88983502013-09-08 11:36:23 +02001277 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1278 /* PYTHONFAULTHANDLER environment variable is missing
1279 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001280 int has_key;
1281
Victor Stinner024e37a2011-03-31 01:31:06 +02001282 xoptions = PySys_GetXOptions();
1283 if (xoptions == NULL)
1284 return -1;
1285
1286 key = PyUnicode_FromString("faulthandler");
1287 if (key == NULL)
1288 return -1;
1289
Victor Stinner25095b22011-05-26 13:47:08 +02001290 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001291 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001292 if (has_key <= 0)
1293 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001294 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001295
1296 module = PyImport_ImportModule("faulthandler");
1297 if (module == NULL) {
1298 return -1;
1299 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001300 res = _PyObject_CallMethodId(module, &PyId_enable, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +02001301 Py_DECREF(module);
1302 if (res == NULL)
1303 return -1;
1304 Py_DECREF(res);
1305 return 0;
1306}
1307
1308int _PyFaulthandler_Init(void)
1309{
1310#ifdef HAVE_SIGALTSTACK
1311 int err;
1312
1313 /* Try to allocate an alternate stack for faulthandler() signal handler to
1314 * be able to allocate memory on the stack, even on a stack overflow. If it
1315 * fails, ignore the error. */
1316 stack.ss_flags = 0;
1317 stack.ss_size = SIGSTKSZ;
1318 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1319 if (stack.ss_sp != NULL) {
1320 err = sigaltstack(&stack, NULL);
1321 if (err) {
1322 PyMem_Free(stack.ss_sp);
1323 stack.ss_sp = NULL;
1324 }
1325 }
1326#endif
1327#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001328 thread.file = NULL;
1329 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001330 thread.running = PyThread_allocate_lock();
1331 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001332 PyErr_SetString(PyExc_RuntimeError,
1333 "could not allocate locks for faulthandler");
1334 return -1;
1335 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001336 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001337#endif
1338
1339 return faulthandler_env_options();
1340}
1341
1342void _PyFaulthandler_Fini(void)
1343{
1344#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001345 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001346#endif
1347
1348#ifdef FAULTHANDLER_LATER
1349 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001350 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001351 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001352 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001353 PyThread_free_lock(thread.cancel_event);
1354 thread.cancel_event = NULL;
1355 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001356 if (thread.running) {
1357 PyThread_free_lock(thread.running);
1358 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001359 }
1360#endif
1361
1362#ifdef FAULTHANDLER_USER
1363 /* user */
1364 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001365 for (signum=0; signum < NSIG; signum++)
1366 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001367 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001368 user_signals = NULL;
1369 }
1370#endif
1371
1372 /* fatal */
1373 faulthandler_disable();
1374#ifdef HAVE_SIGALTSTACK
1375 if (stack.ss_sp != NULL) {
1376 PyMem_Free(stack.ss_sp);
1377 stack.ss_sp = NULL;
1378 }
1379#endif
1380}