blob: 2f8b624fd160d9db7a8bae2e45e0c17371d6fa4f [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;
Christophe Zeitouny90eafdb2017-03-24 04:20:40 -0700127static stack_t old_stack;
Victor Stinner024e37a2011-03-31 01:31:06 +0200128#endif
129
130
131/* Get the file descriptor of a file by calling its fileno() method and then
132 call its flush() method.
133
134 If file is NULL or Py_None, use sys.stderr as the new file.
Victor Stinner95bb7142015-03-12 15:32:03 +0100135 If file is an integer, it will be treated as file descriptor.
Victor Stinner024e37a2011-03-31 01:31:06 +0200136
Victor Stinner95bb7142015-03-12 15:32:03 +0100137 On success, return the file descriptor and write the new file into *file_ptr.
138 On error, return -1. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200139
Victor Stinner95bb7142015-03-12 15:32:03 +0100140static int
141faulthandler_get_fileno(PyObject **file_ptr)
Victor Stinner024e37a2011-03-31 01:31:06 +0200142{
143 PyObject *result;
144 long fd_long;
145 int fd;
Victor Stinner95bb7142015-03-12 15:32:03 +0100146 PyObject *file = *file_ptr;
Victor Stinner024e37a2011-03-31 01:31:06 +0200147
148 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100149 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200150 if (file == NULL) {
151 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
Victor Stinner95bb7142015-03-12 15:32:03 +0100152 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200153 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200154 if (file == Py_None) {
155 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
Victor Stinner95bb7142015-03-12 15:32:03 +0100156 return -1;
Victor Stinnere2d66902014-05-14 17:15:50 +0200157 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200158 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100159 else if (PyLong_Check(file)) {
160 fd = _PyLong_AsInt(file);
161 if (fd == -1 && PyErr_Occurred())
162 return -1;
Steve Dower940f33a2016-09-08 11:21:54 -0700163 if (fd < 0) {
Victor Stinner95bb7142015-03-12 15:32:03 +0100164 PyErr_SetString(PyExc_ValueError,
165 "file is not a valid file descripter");
166 return -1;
167 }
168 *file_ptr = NULL;
169 return fd;
170 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200171
Victor Stinner3466bde2016-09-05 18:16:01 -0700172 result = _PyObject_CallMethodId(file, &PyId_fileno, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200173 if (result == NULL)
Victor Stinner95bb7142015-03-12 15:32:03 +0100174 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200175
176 fd = -1;
177 if (PyLong_Check(result)) {
178 fd_long = PyLong_AsLong(result);
179 if (0 <= fd_long && fd_long < INT_MAX)
180 fd = (int)fd_long;
181 }
182 Py_DECREF(result);
183
184 if (fd == -1) {
185 PyErr_SetString(PyExc_RuntimeError,
186 "file.fileno() is not a valid file descriptor");
Victor Stinner95bb7142015-03-12 15:32:03 +0100187 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200188 }
189
Victor Stinner3466bde2016-09-05 18:16:01 -0700190 result = _PyObject_CallMethodId(file, &PyId_flush, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200191 if (result != NULL)
192 Py_DECREF(result);
193 else {
194 /* ignore flush() error */
195 PyErr_Clear();
196 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100197 *file_ptr = file;
198 return fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200199}
200
Victor Stinnera4de6d82011-04-09 00:47:23 +0200201/* Get the state of the current thread: only call this function if the current
202 thread holds the GIL. Raise an exception on error. */
203static PyThreadState*
204get_thread_state(void)
205{
Victor Stinner861d9ab2016-03-16 22:45:24 +0100206 PyThreadState *tstate = _PyThreadState_UncheckedGet();
Victor Stinnera4de6d82011-04-09 00:47:23 +0200207 if (tstate == NULL) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100208 /* just in case but very unlikely... */
Victor Stinnera4de6d82011-04-09 00:47:23 +0200209 PyErr_SetString(PyExc_RuntimeError,
210 "unable to get the current thread state");
211 return NULL;
212 }
213 return tstate;
214}
215
Victor Stinnerc7489a52015-04-01 18:48:58 +0200216static void
217faulthandler_dump_traceback(int fd, int all_threads,
218 PyInterpreterState *interp)
219{
220 static volatile int reentrant = 0;
221 PyThreadState *tstate;
222
223 if (reentrant)
224 return;
225
226 reentrant = 1;
227
228#ifdef WITH_THREAD
229 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
230 are thus delivered to the thread that caused the fault. Get the Python
231 thread state of the current thread.
232
233 PyThreadState_Get() doesn't give the state of the thread that caused the
234 fault if the thread released the GIL, and so this function cannot be
235 used. Read the thread local storage (TLS) instead: call
236 PyGILState_GetThisThreadState(). */
237 tstate = PyGILState_GetThisThreadState();
238#else
Victor Stinner861d9ab2016-03-16 22:45:24 +0100239 tstate = _PyThreadState_UncheckedGet();
Victor Stinnerc7489a52015-04-01 18:48:58 +0200240#endif
241
Victor Stinner861d9ab2016-03-16 22:45:24 +0100242 if (all_threads) {
243 (void)_Py_DumpTracebackThreads(fd, NULL, tstate);
244 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200245 else {
246 if (tstate != NULL)
247 _Py_DumpTraceback(fd, tstate);
248 }
249
250 reentrant = 0;
251}
252
Victor Stinner024e37a2011-03-31 01:31:06 +0200253static PyObject*
254faulthandler_dump_traceback_py(PyObject *self,
255 PyObject *args, PyObject *kwargs)
256{
257 static char *kwlist[] = {"file", "all_threads", NULL};
258 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200259 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200260 PyThreadState *tstate;
261 const char *errmsg;
262 int fd;
263
264 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
265 "|Oi:dump_traceback", kwlist,
266 &file, &all_threads))
267 return NULL;
268
Victor Stinner95bb7142015-03-12 15:32:03 +0100269 fd = faulthandler_get_fileno(&file);
270 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200271 return NULL;
272
Victor Stinnera4de6d82011-04-09 00:47:23 +0200273 tstate = get_thread_state();
274 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200275 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200276
277 if (all_threads) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100278 errmsg = _Py_DumpTracebackThreads(fd, NULL, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200279 if (errmsg != NULL) {
280 PyErr_SetString(PyExc_RuntimeError, errmsg);
281 return NULL;
282 }
283 }
284 else {
285 _Py_DumpTraceback(fd, tstate);
286 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200287
288 if (PyErr_CheckSignals())
289 return NULL;
290
Victor Stinner024e37a2011-03-31 01:31:06 +0200291 Py_RETURN_NONE;
292}
293
Victor Stinner404cdc52016-03-23 10:39:17 +0100294static void
295faulthandler_disable_fatal_handler(fault_handler_t *handler)
296{
297 if (!handler->enabled)
298 return;
299 handler->enabled = 0;
300#ifdef HAVE_SIGACTION
301 (void)sigaction(handler->signum, &handler->previous, NULL);
302#else
303 (void)signal(handler->signum, handler->previous);
304#endif
305}
306
Victor Stinner024e37a2011-03-31 01:31:06 +0200307
Victor Stinner410dd7d2011-05-11 20:56:08 +0200308/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200309
310 Display the current Python traceback, restore the previous handler and call
311 the previous handler.
312
Victor Stinner410dd7d2011-05-11 20:56:08 +0200313 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200314 signal handler would not be called (for an unknown reason). The execution of
315 the program continues at faulthandler_fatal_error() exit, but the same
316 instruction will raise the same fault (signal), and so the previous handler
317 will be called.
318
Victor Stinner410dd7d2011-05-11 20:56:08 +0200319 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200320
321static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200322faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200323{
324 const int fd = fatal_error.fd;
Victor Stinner404cdc52016-03-23 10:39:17 +0100325 size_t i;
Victor Stinner024e37a2011-03-31 01:31:06 +0200326 fault_handler_t *handler = NULL;
Victor Stinnerc9256172011-05-07 12:20:11 +0200327 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200328
329 if (!fatal_error.enabled)
330 return;
331
332 for (i=0; i < faulthandler_nsignals; i++) {
333 handler = &faulthandler_handlers[i];
334 if (handler->signum == signum)
335 break;
336 }
337 if (handler == NULL) {
338 /* faulthandler_nsignals == 0 (unlikely) */
339 return;
340 }
341
342 /* restore the previous handler */
Victor Stinner404cdc52016-03-23 10:39:17 +0100343 faulthandler_disable_fatal_handler(handler);
Victor Stinner024e37a2011-03-31 01:31:06 +0200344
345 PUTS(fd, "Fatal Python error: ");
346 PUTS(fd, handler->name);
347 PUTS(fd, "\n\n");
348
Victor Stinnerc7489a52015-04-01 18:48:58 +0200349 faulthandler_dump_traceback(fd, fatal_error.all_threads,
350 fatal_error.interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200351
Victor Stinnerc9256172011-05-07 12:20:11 +0200352 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200353#ifdef MS_WINDOWS
354 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200355 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200356 handler, because the Windows signal handler would not be called */
357 return;
358 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200359#endif
R David Murrayfc069992013-12-13 20:52:19 -0500360 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200361 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
362 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200363}
364
Victor Stinner404cdc52016-03-23 10:39:17 +0100365#ifdef MS_WINDOWS
366static LONG WINAPI
367faulthandler_exc_handler(struct _EXCEPTION_POINTERS *exc_info)
368{
369 const int fd = fatal_error.fd;
370 DWORD code = exc_info->ExceptionRecord->ExceptionCode;
Victor Stinner412a5e72016-03-23 14:44:14 +0100371 DWORD flags = exc_info->ExceptionRecord->ExceptionFlags;
Victor Stinner404cdc52016-03-23 10:39:17 +0100372
Victor Stinner412a5e72016-03-23 14:44:14 +0100373 /* only log fatal exceptions */
374 if (flags & EXCEPTION_NONCONTINUABLE) {
375 /* call the next exception handler */
376 return EXCEPTION_CONTINUE_SEARCH;
377 }
378
379 PUTS(fd, "Windows fatal exception: ");
Victor Stinner404cdc52016-03-23 10:39:17 +0100380 switch (code)
381 {
382 /* only format most common errors */
383 case EXCEPTION_ACCESS_VIOLATION: PUTS(fd, "access violation"); break;
384 case EXCEPTION_FLT_DIVIDE_BY_ZERO: PUTS(fd, "float divide by zero"); break;
385 case EXCEPTION_FLT_OVERFLOW: PUTS(fd, "float overflow"); break;
386 case EXCEPTION_INT_DIVIDE_BY_ZERO: PUTS(fd, "int divide by zero"); break;
387 case EXCEPTION_INT_OVERFLOW: PUTS(fd, "integer overflow"); break;
388 case EXCEPTION_IN_PAGE_ERROR: PUTS(fd, "page error"); break;
389 case EXCEPTION_STACK_OVERFLOW: PUTS(fd, "stack overflow"); break;
390 default:
Victor Stinner412a5e72016-03-23 14:44:14 +0100391 PUTS(fd, "code ");
Victor Stinner82d44f02016-03-23 18:37:54 +0100392 _Py_DumpDecimal(fd, code);
Victor Stinner404cdc52016-03-23 10:39:17 +0100393 }
394 PUTS(fd, "\n\n");
395
396 if (code == EXCEPTION_ACCESS_VIOLATION) {
397 /* disable signal handler for SIGSEGV */
398 size_t i;
399 for (i=0; i < faulthandler_nsignals; i++) {
400 fault_handler_t *handler = &faulthandler_handlers[i];
401 if (handler->signum == SIGSEGV) {
402 faulthandler_disable_fatal_handler(handler);
403 break;
404 }
405 }
406 }
407
408 faulthandler_dump_traceback(fd, fatal_error.all_threads,
409 fatal_error.interp);
410
411 /* call the next exception handler */
412 return EXCEPTION_CONTINUE_SEARCH;
413}
414#endif
415
Victor Stinnerd727e232011-04-01 12:13:55 +0200416/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200417
doko@ubuntu.combc731502016-05-18 01:06:01 +0200418static int
Victor Stinner404cdc52016-03-23 10:39:17 +0100419faulthandler_enable(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200420{
Victor Stinner404cdc52016-03-23 10:39:17 +0100421 size_t i;
Victor Stinner404cdc52016-03-23 10:39:17 +0100422
423 if (fatal_error.enabled) {
424 return 0;
425 }
Victor Stinner404cdc52016-03-23 10:39:17 +0100426 fatal_error.enabled = 1;
427
428 for (i=0; i < faulthandler_nsignals; i++) {
Victor Stinner928ad282016-03-23 15:19:12 +0100429 fault_handler_t *handler;
430#ifdef HAVE_SIGACTION
431 struct sigaction action;
432#endif
433 int err;
Victor Stinner404cdc52016-03-23 10:39:17 +0100434
Victor Stinner928ad282016-03-23 15:19:12 +0100435 handler = &faulthandler_handlers[i];
436 assert(!handler->enabled);
Victor Stinner404cdc52016-03-23 10:39:17 +0100437#ifdef HAVE_SIGACTION
438 action.sa_handler = faulthandler_fatal_error;
439 sigemptyset(&action.sa_mask);
440 /* Do not prevent the signal from being received from within
441 its own signal handler */
442 action.sa_flags = SA_NODEFER;
443#ifdef HAVE_SIGALTSTACK
444 if (stack.ss_sp != NULL) {
445 /* Call the signal handler on an alternate signal stack
446 provided by sigaltstack() */
447 action.sa_flags |= SA_ONSTACK;
448 }
449#endif
450 err = sigaction(handler->signum, &action, &handler->previous);
451#else
452 handler->previous = signal(handler->signum,
453 faulthandler_fatal_error);
454 err = (handler->previous == SIG_ERR);
455#endif
456 if (err) {
457 PyErr_SetFromErrno(PyExc_RuntimeError);
458 return -1;
459 }
460
461 handler->enabled = 1;
462 }
463
464#ifdef MS_WINDOWS
465 AddVectoredExceptionHandler(1, faulthandler_exc_handler);
466#endif
467 return 0;
468}
469
470static PyObject*
471faulthandler_py_enable(PyObject *self, PyObject *args, PyObject *kwargs)
472{
473 static char *kwlist[] = {"file", "all_threads", NULL};
474 PyObject *file = NULL;
475 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200476 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200477 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200478
479 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
480 "|Oi:enable", kwlist, &file, &all_threads))
481 return NULL;
482
Victor Stinner95bb7142015-03-12 15:32:03 +0100483 fd = faulthandler_get_fileno(&file);
484 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200485 return NULL;
486
Victor Stinnera4de6d82011-04-09 00:47:23 +0200487 tstate = get_thread_state();
488 if (tstate == NULL)
489 return NULL;
490
Victor Stinner95bb7142015-03-12 15:32:03 +0100491 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300492 Py_XSETREF(fatal_error.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200493 fatal_error.fd = fd;
494 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200495 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200496
Victor Stinner404cdc52016-03-23 10:39:17 +0100497 if (faulthandler_enable() < 0) {
498 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200499 }
Victor Stinner404cdc52016-03-23 10:39:17 +0100500
Victor Stinner024e37a2011-03-31 01:31:06 +0200501 Py_RETURN_NONE;
502}
503
504static void
505faulthandler_disable(void)
506{
507 unsigned int i;
508 fault_handler_t *handler;
509
510 if (fatal_error.enabled) {
511 fatal_error.enabled = 0;
512 for (i=0; i < faulthandler_nsignals; i++) {
513 handler = &faulthandler_handlers[i];
Victor Stinner404cdc52016-03-23 10:39:17 +0100514 faulthandler_disable_fatal_handler(handler);
Victor Stinner024e37a2011-03-31 01:31:06 +0200515 }
516 }
517
518 Py_CLEAR(fatal_error.file);
519}
520
521static PyObject*
522faulthandler_disable_py(PyObject *self)
523{
524 if (!fatal_error.enabled) {
525 Py_INCREF(Py_False);
526 return Py_False;
527 }
528 faulthandler_disable();
529 Py_INCREF(Py_True);
530 return Py_True;
531}
532
533static PyObject*
534faulthandler_is_enabled(PyObject *self)
535{
536 return PyBool_FromLong(fatal_error.enabled);
537}
538
539#ifdef FAULTHANDLER_LATER
540
541static void
542faulthandler_thread(void *unused)
543{
544 PyLockStatus st;
545 const char* errmsg;
Victor Stinner024e37a2011-03-31 01:31:06 +0200546 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200547#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200548 sigset_t set;
549
550 /* we don't want to receive any signal */
551 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200552 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200553#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200554
555 do {
556 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200557 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200558 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200559 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200560 break;
561 }
562 /* Timeout => dump traceback */
563 assert(st == PY_LOCK_FAILURE);
564
Victor Stinnerc7489a52015-04-01 18:48:58 +0200565 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200566
Victor Stinner861d9ab2016-03-16 22:45:24 +0100567 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200568 ok = (errmsg == NULL);
569
570 if (thread.exit)
571 _exit(1);
572 } while (ok && thread.repeat);
573
574 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200575 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200576}
577
578static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200579cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200580{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200581 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200582 PyThread_release_lock(thread.cancel_event);
583
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200584 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200585 PyThread_acquire_lock(thread.running, 1);
586 PyThread_release_lock(thread.running);
587
588 /* The main thread should always hold the cancel_event lock */
589 PyThread_acquire_lock(thread.cancel_event, 1);
590
Victor Stinner024e37a2011-03-31 01:31:06 +0200591 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200592 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200593 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200594 thread.header = NULL;
595 }
596}
597
598static char*
599format_timeout(double timeout)
600{
601 unsigned long us, sec, min, hour;
602 double intpart, fracpart;
603 char buffer[100];
604
605 fracpart = modf(timeout, &intpart);
606 sec = (unsigned long)intpart;
607 us = (unsigned long)(fracpart * 1e6);
608 min = sec / 60;
609 sec %= 60;
610 hour = min / 60;
611 min %= 60;
612
613 if (us != 0)
614 PyOS_snprintf(buffer, sizeof(buffer),
615 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
616 hour, min, sec, us);
617 else
618 PyOS_snprintf(buffer, sizeof(buffer),
619 "Timeout (%lu:%02lu:%02lu)!\n",
620 hour, min, sec);
621
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200622 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200623}
624
625static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200626faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200627 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200628{
629 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
630 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200631 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200632 int repeat = 0;
633 PyObject *file = NULL;
634 int fd;
635 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200636 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200637 char *header;
638 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200639
640 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200641 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200642 &timeout, &repeat, &file, &exit))
643 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200644 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200645 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
646 return NULL;
647 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200648 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200649 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200650 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
651 return NULL;
652 }
653
Victor Stinnera4de6d82011-04-09 00:47:23 +0200654 tstate = get_thread_state();
655 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200656 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200657
Victor Stinner95bb7142015-03-12 15:32:03 +0100658 fd = faulthandler_get_fileno(&file);
659 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200660 return NULL;
661
Victor Stinnerc790a532011-04-08 13:39:59 +0200662 /* format the timeout */
663 header = format_timeout(timeout);
664 if (header == NULL)
665 return PyErr_NoMemory();
666 header_len = strlen(header);
667
Victor Stinner024e37a2011-03-31 01:31:06 +0200668 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200669 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200670
Victor Stinner95bb7142015-03-12 15:32:03 +0100671 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300672 Py_XSETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200673 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200674 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200675 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200676 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200677 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200678 thread.header = header;
679 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200680
681 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200682 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200683
Victor Stinner024e37a2011-03-31 01:31:06 +0200684 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200685 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200686 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200687 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200688 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200689 PyErr_SetString(PyExc_RuntimeError,
690 "unable to start watchdog thread");
691 return NULL;
692 }
693
694 Py_RETURN_NONE;
695}
696
697static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200698faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200699{
Georg Brandldeb92b52012-09-22 08:58:55 +0200700 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200701 Py_RETURN_NONE;
702}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200703#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200704
705#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200706static int
707faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
708{
709#ifdef HAVE_SIGACTION
710 struct sigaction action;
711 action.sa_handler = faulthandler_user;
712 sigemptyset(&action.sa_mask);
713 /* if the signal is received while the kernel is executing a system
714 call, try to restart the system call instead of interrupting it and
715 return EINTR. */
716 action.sa_flags = SA_RESTART;
717 if (chain) {
718 /* do not prevent the signal from being received from within its
719 own signal handler */
720 action.sa_flags = SA_NODEFER;
721 }
722#ifdef HAVE_SIGALTSTACK
723 if (stack.ss_sp != NULL) {
724 /* Call the signal handler on an alternate signal stack
725 provided by sigaltstack() */
726 action.sa_flags |= SA_ONSTACK;
727 }
728#endif
729 return sigaction(signum, &action, p_previous);
730#else
731 _Py_sighandler_t previous;
732 previous = signal(signum, faulthandler_user);
733 if (p_previous != NULL)
734 *p_previous = previous;
735 return (previous == SIG_ERR);
736#endif
737}
738
Victor Stinner024e37a2011-03-31 01:31:06 +0200739/* Handler of user signals (e.g. SIGUSR1).
740
741 Dump the traceback of the current thread, or of all threads if
742 thread.all_threads is true.
743
744 This function is signal safe and should only call signal safe functions. */
745
746static void
747faulthandler_user(int signum)
748{
749 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200750 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200751
752 user = &user_signals[signum];
753 if (!user->enabled)
754 return;
755
Victor Stinnerc7489a52015-04-01 18:48:58 +0200756 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200757
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200758#ifdef HAVE_SIGACTION
759 if (user->chain) {
760 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200761 errno = save_errno;
762
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200763 /* call the previous signal handler */
764 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200765
766 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200767 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200768 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200769 }
770#else
771 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200772 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200773 /* call the previous signal handler */
774 user->previous(signum);
775 }
776#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200777}
778
779static int
780check_signum(int signum)
781{
782 unsigned int i;
783
784 for (i=0; i < faulthandler_nsignals; i++) {
785 if (faulthandler_handlers[i].signum == signum) {
786 PyErr_Format(PyExc_RuntimeError,
787 "signal %i cannot be registered, "
788 "use enable() instead",
789 signum);
790 return 0;
791 }
792 }
793 if (signum < 1 || NSIG <= signum) {
794 PyErr_SetString(PyExc_ValueError, "signal number out of range");
795 return 0;
796 }
797 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200798}
799
800static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200801faulthandler_register_py(PyObject *self,
802 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200803{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200804 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200805 int signum;
806 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200807 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200808 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200809 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200810 user_signal_t *user;
811 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200812 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200813 int err;
814
815 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200816 "i|Oii:register", kwlist,
817 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200818 return NULL;
819
Victor Stinner44378d42011-04-01 15:37:12 +0200820 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200821 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200822
Victor Stinnera4de6d82011-04-09 00:47:23 +0200823 tstate = get_thread_state();
824 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200825 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200826
Victor Stinner95bb7142015-03-12 15:32:03 +0100827 fd = faulthandler_get_fileno(&file);
828 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200829 return NULL;
830
831 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200832 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200833 if (user_signals == NULL)
834 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200835 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200836 }
837 user = &user_signals[signum];
838
839 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200840 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200841 if (err) {
842 PyErr_SetFromErrno(PyExc_OSError);
843 return NULL;
844 }
Victor Stinner8d379542013-07-02 00:14:56 +0200845
846 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200847 }
848
Victor Stinner95bb7142015-03-12 15:32:03 +0100849 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300850 Py_XSETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200851 user->fd = fd;
852 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200853 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200854 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200855 user->enabled = 1;
856
857 Py_RETURN_NONE;
858}
859
860static int
861faulthandler_unregister(user_signal_t *user, int signum)
862{
Victor Stinnera01ca122011-04-01 12:56:17 +0200863 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200864 return 0;
865 user->enabled = 0;
866#ifdef HAVE_SIGACTION
867 (void)sigaction(signum, &user->previous, NULL);
868#else
869 (void)signal(signum, user->previous);
870#endif
871 Py_CLEAR(user->file);
872 user->fd = -1;
873 return 1;
874}
875
876static PyObject*
877faulthandler_unregister_py(PyObject *self, PyObject *args)
878{
879 int signum;
880 user_signal_t *user;
881 int change;
882
883 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
884 return NULL;
885
Victor Stinner44378d42011-04-01 15:37:12 +0200886 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200887 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200888
Victor Stinnercfa71232011-04-08 12:48:15 +0200889 if (user_signals == NULL)
890 Py_RETURN_FALSE;
891
Victor Stinner024e37a2011-03-31 01:31:06 +0200892 user = &user_signals[signum];
893 change = faulthandler_unregister(user, signum);
894 return PyBool_FromLong(change);
895}
896#endif /* FAULTHANDLER_USER */
897
898
Victor Stinner7a399122014-09-30 13:40:12 +0200899static void
900faulthandler_suppress_crash_report(void)
901{
902#ifdef MS_WINDOWS
903 UINT mode;
904
905 /* Configure Windows to not display the Windows Error Reporting dialog */
906 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
907 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
908#endif
909
910#ifdef HAVE_SYS_RESOURCE_H
911 struct rlimit rl;
912
913 /* Disable creation of core dump */
914 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
915 rl.rlim_cur = 0;
916 setrlimit(RLIMIT_CORE, &rl);
917 }
918#endif
919
920#ifdef _MSC_VER
921 /* Visual Studio: configure abort() to not display an error message nor
922 open a popup asking to report the fault. */
923 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
924#endif
925}
926
Victor Stinner024e37a2011-03-31 01:31:06 +0200927static PyObject *
928faulthandler_read_null(PyObject *self, PyObject *args)
929{
Victor Stinnera2477202012-01-30 00:07:43 +0100930 volatile int *x;
931 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100932
Victor Stinner7a399122014-09-30 13:40:12 +0200933 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100934 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200935 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200936 return PyLong_FromLong(y);
937
938}
939
Victor Stinner50838282014-09-30 13:54:14 +0200940static void
941faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200942{
Victor Stinner7a399122014-09-30 13:40:12 +0200943 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200944#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200945 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
946 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200947 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200948 SIGSEGV was raised by the kernel because of a fault, and so if the
949 program retries to execute the same instruction, the fault will be
950 raised again.
951
952 Here the fault is simulated by a fake SIGSEGV signal raised by the
953 application. We have to raise SIGSEGV at lease twice: once for
954 faulthandler_fatal_error(), and one more time for the previous signal
955 handler. */
956 while(1)
957 raise(SIGSEGV);
958#else
959 raise(SIGSEGV);
960#endif
Victor Stinner50838282014-09-30 13:54:14 +0200961}
962
963static PyObject *
964faulthandler_sigsegv(PyObject *self, PyObject *args)
965{
966 int release_gil = 0;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100967 if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
Victor Stinner50838282014-09-30 13:54:14 +0200968 return NULL;
969
970 if (release_gil) {
971 Py_BEGIN_ALLOW_THREADS
972 faulthandler_raise_sigsegv();
973 Py_END_ALLOW_THREADS
974 } else {
975 faulthandler_raise_sigsegv();
976 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200977 Py_RETURN_NONE;
978}
979
Victor Stinner861d9ab2016-03-16 22:45:24 +0100980#ifdef WITH_THREAD
981static void
982faulthandler_fatal_error_thread(void *plock)
983{
984 PyThread_type_lock *lock = (PyThread_type_lock *)plock;
985
986 Py_FatalError("in new thread");
987
988 /* notify the caller that we are done */
989 PyThread_release_lock(lock);
990}
991
992static PyObject *
993faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
994{
995 long thread;
996 PyThread_type_lock lock;
997
998 faulthandler_suppress_crash_report();
999
1000 lock = PyThread_allocate_lock();
1001 if (lock == NULL)
1002 return PyErr_NoMemory();
1003
1004 PyThread_acquire_lock(lock, WAIT_LOCK);
1005
1006 thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
1007 if (thread == -1) {
1008 PyThread_free_lock(lock);
1009 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
1010 return NULL;
1011 }
1012
1013 /* wait until the thread completes: it will never occur, since Py_FatalError()
1014 exits the process immedialty. */
1015 PyThread_acquire_lock(lock, WAIT_LOCK);
1016 PyThread_release_lock(lock);
1017 PyThread_free_lock(lock);
1018
1019 Py_RETURN_NONE;
1020}
1021#endif
1022
Victor Stinner024e37a2011-03-31 01:31:06 +02001023static PyObject *
1024faulthandler_sigfpe(PyObject *self, PyObject *args)
1025{
1026 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
1027 PowerPC. Use volatile to disable compile-time optimizations. */
1028 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +02001029 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +02001030 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +02001031 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
1032 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001033 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +02001034 /* This line is never reached, but we pretend to make something with z
1035 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +02001036 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +02001037}
1038
Victor Stinnerd727e232011-04-01 12:13:55 +02001039static PyObject *
1040faulthandler_sigabrt(PyObject *self, PyObject *args)
1041{
Victor Stinner7a399122014-09-30 13:40:12 +02001042 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +02001043 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +02001044 Py_RETURN_NONE;
1045}
1046
Victor Stinner024e37a2011-03-31 01:31:06 +02001047static PyObject *
1048faulthandler_fatal_error_py(PyObject *self, PyObject *args)
1049{
1050 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +01001051 int release_gil = 0;
1052 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +02001053 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +02001054 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +01001055 if (release_gil) {
1056 Py_BEGIN_ALLOW_THREADS
1057 Py_FatalError(message);
1058 Py_END_ALLOW_THREADS
1059 }
1060 else {
1061 Py_FatalError(message);
1062 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001063 Py_RETURN_NONE;
1064}
1065
1066#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner404cdc52016-03-23 10:39:17 +01001067#define FAULTHANDLER_STACK_OVERFLOW
1068
Victor Stinner19276f12015-03-23 21:20:27 +01001069#ifdef __INTEL_COMPILER
1070 /* Issue #23654: Turn off ICC's tail call optimization for the
1071 * stack_overflow generator. ICC turns the recursive tail call into
1072 * a loop. */
1073# pragma intel optimization_level 0
1074#endif
1075static
Benjamin Petersonca470632016-09-06 13:47:26 -07001076uintptr_t
1077stack_overflow(uintptr_t min_sp, uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +02001078{
1079 /* allocate 4096 bytes on the stack at each call */
1080 unsigned char buffer[4096];
Benjamin Petersonca470632016-09-06 13:47:26 -07001081 uintptr_t sp = (uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +02001082 *depth += 1;
Victor Stinner928ad282016-03-23 15:19:12 +01001083 if (sp < min_sp || max_sp < sp)
Victor Stinnerf0480752011-03-31 11:34:08 +02001084 return sp;
Victor Stinner928ad282016-03-23 15:19:12 +01001085 buffer[0] = 1;
1086 buffer[4095] = 0;
1087 return stack_overflow(min_sp, max_sp, depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001088}
1089
1090static PyObject *
1091faulthandler_stack_overflow(PyObject *self)
1092{
1093 size_t depth, size;
Benjamin Petersonca470632016-09-06 13:47:26 -07001094 uintptr_t sp = (uintptr_t)&depth;
1095 uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +02001096
Victor Stinner7a399122014-09-30 13:40:12 +02001097 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +02001098 depth = 0;
Victor Stinner928ad282016-03-23 15:19:12 +01001099 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
1100 sp + STACK_OVERFLOW_MAX_SIZE,
1101 &depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001102 if (sp < stop)
1103 size = stop - sp;
1104 else
1105 size = sp - stop;
1106 PyErr_Format(PyExc_RuntimeError,
1107 "unable to raise a stack overflow (allocated %zu bytes "
1108 "on the stack, %zu recursive calls)",
1109 size, depth);
1110 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001111}
Victor Stinner928ad282016-03-23 15:19:12 +01001112#endif /* defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) */
Victor Stinner024e37a2011-03-31 01:31:06 +02001113
1114
1115static int
1116faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1117{
1118#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001119 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001120#endif
1121
1122#ifdef FAULTHANDLER_LATER
1123 Py_VISIT(thread.file);
1124#endif
1125#ifdef FAULTHANDLER_USER
1126 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001127 for (signum=0; signum < NSIG; signum++)
1128 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001129 }
1130#endif
1131 Py_VISIT(fatal_error.file);
1132 return 0;
1133}
1134
Victor Stinner404cdc52016-03-23 10:39:17 +01001135#ifdef MS_WINDOWS
1136static PyObject *
1137faulthandler_raise_exception(PyObject *self, PyObject *args)
1138{
1139 unsigned int code, flags = 0;
1140 if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
1141 return NULL;
1142 faulthandler_suppress_crash_report();
1143 RaiseException(code, flags, 0, NULL);
1144 Py_RETURN_NONE;
1145}
1146#endif
1147
Victor Stinner024e37a2011-03-31 01:31:06 +02001148PyDoc_STRVAR(module_doc,
1149"faulthandler module.");
1150
1151static PyMethodDef module_methods[] = {
1152 {"enable",
Victor Stinner404cdc52016-03-23 10:39:17 +01001153 (PyCFunction)faulthandler_py_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001154 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001155 "enable the fault handler")},
1156 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1157 PyDoc_STR("disable(): disable the fault handler")},
1158 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1159 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1160 {"dump_traceback",
1161 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001162 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001163 "dump the traceback of the current thread, or of all threads "
1164 "if all_threads is True, into file")},
1165#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001166 {"dump_traceback_later",
1167 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1168 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001169 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001170 "or each timeout seconds if repeat is True. If exit is True, "
1171 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001172 {"cancel_dump_traceback_later",
1173 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1174 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1175 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001176#endif
1177
1178#ifdef FAULTHANDLER_USER
1179 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001180 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1181 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001182 "register a handler for the signal 'signum': dump the "
Victor Stinner024e37a2011-03-31 01:31:06 +02001183 "traceback of the current thread, or of all threads if "
1184 "all_threads is True, into file")},
1185 {"unregister",
1186 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1187 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1188 "'signum' registered by register()")},
1189#endif
1190
Victor Stinner50838282014-09-30 13:54:14 +02001191 {"_read_null", faulthandler_read_null, METH_NOARGS,
1192 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001193 "a SIGSEGV or SIGBUS signal depending on the platform")},
1194 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001195 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner861d9ab2016-03-16 22:45:24 +01001196#ifdef WITH_THREAD
1197 {"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
1198 PyDoc_STR("fatal_error_c_thread(): "
1199 "call Py_FatalError() in a new C thread.")},
1200#endif
Victor Stinner9db521c2014-09-30 13:49:09 +02001201 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001202 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001203 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1204 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001205 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1206 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
Victor Stinner404cdc52016-03-23 10:39:17 +01001207#ifdef FAULTHANDLER_STACK_OVERFLOW
Victor Stinner024e37a2011-03-31 01:31:06 +02001208 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1209 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1210#endif
Victor Stinner404cdc52016-03-23 10:39:17 +01001211#ifdef MS_WINDOWS
1212 {"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
1213 PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
1214#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001215 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001216};
1217
1218static struct PyModuleDef module_def = {
1219 PyModuleDef_HEAD_INIT,
1220 "faulthandler",
1221 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001222 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001223 module_methods,
1224 NULL,
1225 faulthandler_traverse,
1226 NULL,
1227 NULL
1228};
1229
1230PyMODINIT_FUNC
1231PyInit_faulthandler(void)
1232{
Victor Stinner404cdc52016-03-23 10:39:17 +01001233 PyObject *m = PyModule_Create(&module_def);
1234 if (m == NULL)
1235 return NULL;
1236
1237 /* Add constants for unit tests */
1238#ifdef MS_WINDOWS
1239 /* RaiseException() codes (prefixed by an underscore) */
1240 if (PyModule_AddIntConstant(m, "_EXCEPTION_ACCESS_VIOLATION",
1241 EXCEPTION_ACCESS_VIOLATION))
1242 return NULL;
1243 if (PyModule_AddIntConstant(m, "_EXCEPTION_INT_DIVIDE_BY_ZERO",
1244 EXCEPTION_INT_DIVIDE_BY_ZERO))
1245 return NULL;
1246 if (PyModule_AddIntConstant(m, "_EXCEPTION_STACK_OVERFLOW",
1247 EXCEPTION_STACK_OVERFLOW))
1248 return NULL;
1249
1250 /* RaiseException() flags (prefixed by an underscore) */
1251 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
1252 EXCEPTION_NONCONTINUABLE))
1253 return NULL;
1254 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
1255 EXCEPTION_NONCONTINUABLE_EXCEPTION))
1256 return NULL;
1257#endif
1258
1259 return m;
Victor Stinner024e37a2011-03-31 01:31:06 +02001260}
1261
Victor Stinner410dd7d2011-05-11 20:56:08 +02001262/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1263 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001264
1265static int
1266faulthandler_env_options(void)
1267{
1268 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001269 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001270
Victor Stinner88983502013-09-08 11:36:23 +02001271 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1272 /* PYTHONFAULTHANDLER environment variable is missing
1273 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001274 int has_key;
1275
Victor Stinner024e37a2011-03-31 01:31:06 +02001276 xoptions = PySys_GetXOptions();
1277 if (xoptions == NULL)
1278 return -1;
1279
1280 key = PyUnicode_FromString("faulthandler");
1281 if (key == NULL)
1282 return -1;
1283
Victor Stinner25095b22011-05-26 13:47:08 +02001284 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001285 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001286 if (has_key <= 0)
1287 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001288 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001289
1290 module = PyImport_ImportModule("faulthandler");
1291 if (module == NULL) {
1292 return -1;
1293 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001294 res = _PyObject_CallMethodId(module, &PyId_enable, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +02001295 Py_DECREF(module);
1296 if (res == NULL)
1297 return -1;
1298 Py_DECREF(res);
1299 return 0;
1300}
1301
1302int _PyFaulthandler_Init(void)
1303{
1304#ifdef HAVE_SIGALTSTACK
1305 int err;
1306
1307 /* Try to allocate an alternate stack for faulthandler() signal handler to
1308 * be able to allocate memory on the stack, even on a stack overflow. If it
1309 * fails, ignore the error. */
1310 stack.ss_flags = 0;
1311 stack.ss_size = SIGSTKSZ;
1312 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1313 if (stack.ss_sp != NULL) {
Christophe Zeitouny90eafdb2017-03-24 04:20:40 -07001314 err = sigaltstack(&stack, &old_stack);
Victor Stinner024e37a2011-03-31 01:31:06 +02001315 if (err) {
1316 PyMem_Free(stack.ss_sp);
1317 stack.ss_sp = NULL;
1318 }
1319 }
1320#endif
1321#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001322 thread.file = NULL;
1323 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001324 thread.running = PyThread_allocate_lock();
1325 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001326 PyErr_SetString(PyExc_RuntimeError,
1327 "could not allocate locks for faulthandler");
1328 return -1;
1329 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001330 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001331#endif
1332
1333 return faulthandler_env_options();
1334}
1335
1336void _PyFaulthandler_Fini(void)
1337{
1338#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001339 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001340#endif
1341
1342#ifdef FAULTHANDLER_LATER
1343 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001344 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001345 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001346 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001347 PyThread_free_lock(thread.cancel_event);
1348 thread.cancel_event = NULL;
1349 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001350 if (thread.running) {
1351 PyThread_free_lock(thread.running);
1352 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001353 }
1354#endif
1355
1356#ifdef FAULTHANDLER_USER
1357 /* user */
1358 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001359 for (signum=0; signum < NSIG; signum++)
1360 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001361 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001362 user_signals = NULL;
1363 }
1364#endif
1365
1366 /* fatal */
1367 faulthandler_disable();
1368#ifdef HAVE_SIGALTSTACK
1369 if (stack.ss_sp != NULL) {
Christophe Zeitouny90eafdb2017-03-24 04:20:40 -07001370 /* Fetch the current alt stack */
1371 stack_t current_stack;
1372 if (sigaltstack(NULL, &current_stack) == 0) {
1373 if (current_stack.ss_sp == stack.ss_sp) {
1374 /* The current alt stack is the one that we installed.
1375 It is safe to restore the old stack that we found when
1376 we installed ours */
1377 sigaltstack(&old_stack, NULL);
1378 } else {
1379 /* Someone switched to a different alt stack and didn't
1380 restore ours when they were done (if they're done).
1381 There's not much we can do in this unlikely case */
1382 }
1383 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001384 PyMem_Free(stack.ss_sp);
1385 stack.ss_sp = NULL;
1386 }
1387#endif
1388}