blob: fc9490d0d44889c3131b354ed479c88248a97a90 [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 Zeitouny20fbf8a2017-03-23 10:14:29 -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) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200525 Py_RETURN_FALSE;
Victor Stinner024e37a2011-03-31 01:31:06 +0200526 }
527 faulthandler_disable();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200528 Py_RETURN_TRUE;
Victor Stinner024e37a2011-03-31 01:31:06 +0200529}
530
531static PyObject*
532faulthandler_is_enabled(PyObject *self)
533{
534 return PyBool_FromLong(fatal_error.enabled);
535}
536
537#ifdef FAULTHANDLER_LATER
538
539static void
540faulthandler_thread(void *unused)
541{
542 PyLockStatus st;
543 const char* errmsg;
Victor Stinner024e37a2011-03-31 01:31:06 +0200544 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200545#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200546 sigset_t set;
547
548 /* we don't want to receive any signal */
549 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200550 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200551#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200552
553 do {
554 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200555 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200556 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200557 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200558 break;
559 }
560 /* Timeout => dump traceback */
561 assert(st == PY_LOCK_FAILURE);
562
Victor Stinnerc7489a52015-04-01 18:48:58 +0200563 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200564
Victor Stinner861d9ab2016-03-16 22:45:24 +0100565 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200566 ok = (errmsg == NULL);
567
568 if (thread.exit)
569 _exit(1);
570 } while (ok && thread.repeat);
571
572 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200573 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200574}
575
576static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200577cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200578{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200579 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200580 PyThread_release_lock(thread.cancel_event);
581
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200582 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200583 PyThread_acquire_lock(thread.running, 1);
584 PyThread_release_lock(thread.running);
585
586 /* The main thread should always hold the cancel_event lock */
587 PyThread_acquire_lock(thread.cancel_event, 1);
588
Victor Stinner024e37a2011-03-31 01:31:06 +0200589 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200590 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200591 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200592 thread.header = NULL;
593 }
594}
595
596static char*
597format_timeout(double timeout)
598{
599 unsigned long us, sec, min, hour;
600 double intpart, fracpart;
601 char buffer[100];
602
603 fracpart = modf(timeout, &intpart);
604 sec = (unsigned long)intpart;
605 us = (unsigned long)(fracpart * 1e6);
606 min = sec / 60;
607 sec %= 60;
608 hour = min / 60;
609 min %= 60;
610
611 if (us != 0)
612 PyOS_snprintf(buffer, sizeof(buffer),
613 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
614 hour, min, sec, us);
615 else
616 PyOS_snprintf(buffer, sizeof(buffer),
617 "Timeout (%lu:%02lu:%02lu)!\n",
618 hour, min, sec);
619
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200620 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200621}
622
623static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200624faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200625 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200626{
627 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
628 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200629 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200630 int repeat = 0;
631 PyObject *file = NULL;
632 int fd;
633 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200634 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200635 char *header;
636 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200637
638 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200639 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200640 &timeout, &repeat, &file, &exit))
641 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200642 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200643 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
644 return NULL;
645 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200646 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200647 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200648 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
649 return NULL;
650 }
651
Victor Stinnera4de6d82011-04-09 00:47:23 +0200652 tstate = get_thread_state();
653 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200654 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200655
Victor Stinner95bb7142015-03-12 15:32:03 +0100656 fd = faulthandler_get_fileno(&file);
657 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200658 return NULL;
659
Victor Stinnerc790a532011-04-08 13:39:59 +0200660 /* format the timeout */
661 header = format_timeout(timeout);
662 if (header == NULL)
663 return PyErr_NoMemory();
664 header_len = strlen(header);
665
Victor Stinner024e37a2011-03-31 01:31:06 +0200666 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200667 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200668
Victor Stinner95bb7142015-03-12 15:32:03 +0100669 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300670 Py_XSETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200671 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200672 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200673 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200674 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200675 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200676 thread.header = header;
677 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200678
679 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200680 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200681
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200682 if (PyThread_start_new_thread(faulthandler_thread, NULL) == PYTHREAD_INVALID_THREAD_ID) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200683 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200684 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200685 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200686 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200687 PyErr_SetString(PyExc_RuntimeError,
688 "unable to start watchdog thread");
689 return NULL;
690 }
691
692 Py_RETURN_NONE;
693}
694
695static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200696faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200697{
Georg Brandldeb92b52012-09-22 08:58:55 +0200698 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200699 Py_RETURN_NONE;
700}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200701#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200702
703#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200704static int
705faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
706{
707#ifdef HAVE_SIGACTION
708 struct sigaction action;
709 action.sa_handler = faulthandler_user;
710 sigemptyset(&action.sa_mask);
711 /* if the signal is received while the kernel is executing a system
712 call, try to restart the system call instead of interrupting it and
713 return EINTR. */
714 action.sa_flags = SA_RESTART;
715 if (chain) {
716 /* do not prevent the signal from being received from within its
717 own signal handler */
718 action.sa_flags = SA_NODEFER;
719 }
720#ifdef HAVE_SIGALTSTACK
721 if (stack.ss_sp != NULL) {
722 /* Call the signal handler on an alternate signal stack
723 provided by sigaltstack() */
724 action.sa_flags |= SA_ONSTACK;
725 }
726#endif
727 return sigaction(signum, &action, p_previous);
728#else
729 _Py_sighandler_t previous;
730 previous = signal(signum, faulthandler_user);
731 if (p_previous != NULL)
732 *p_previous = previous;
733 return (previous == SIG_ERR);
734#endif
735}
736
Victor Stinner024e37a2011-03-31 01:31:06 +0200737/* Handler of user signals (e.g. SIGUSR1).
738
739 Dump the traceback of the current thread, or of all threads if
740 thread.all_threads is true.
741
742 This function is signal safe and should only call signal safe functions. */
743
744static void
745faulthandler_user(int signum)
746{
747 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200748 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200749
750 user = &user_signals[signum];
751 if (!user->enabled)
752 return;
753
Victor Stinnerc7489a52015-04-01 18:48:58 +0200754 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200755
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200756#ifdef HAVE_SIGACTION
757 if (user->chain) {
758 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200759 errno = save_errno;
760
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200761 /* call the previous signal handler */
762 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200763
764 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200765 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200766 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200767 }
768#else
769 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200770 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200771 /* call the previous signal handler */
772 user->previous(signum);
773 }
774#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200775}
776
777static int
778check_signum(int signum)
779{
780 unsigned int i;
781
782 for (i=0; i < faulthandler_nsignals; i++) {
783 if (faulthandler_handlers[i].signum == signum) {
784 PyErr_Format(PyExc_RuntimeError,
785 "signal %i cannot be registered, "
786 "use enable() instead",
787 signum);
788 return 0;
789 }
790 }
791 if (signum < 1 || NSIG <= signum) {
792 PyErr_SetString(PyExc_ValueError, "signal number out of range");
793 return 0;
794 }
795 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200796}
797
798static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200799faulthandler_register_py(PyObject *self,
800 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200801{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200802 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200803 int signum;
804 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200805 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200806 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200807 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200808 user_signal_t *user;
809 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200810 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200811 int err;
812
813 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200814 "i|Oii:register", kwlist,
815 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200816 return NULL;
817
Victor Stinner44378d42011-04-01 15:37:12 +0200818 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200819 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200820
Victor Stinnera4de6d82011-04-09 00:47:23 +0200821 tstate = get_thread_state();
822 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200823 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200824
Victor Stinner95bb7142015-03-12 15:32:03 +0100825 fd = faulthandler_get_fileno(&file);
826 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200827 return NULL;
828
829 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200830 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200831 if (user_signals == NULL)
832 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200833 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200834 }
835 user = &user_signals[signum];
836
837 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200838 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200839 if (err) {
840 PyErr_SetFromErrno(PyExc_OSError);
841 return NULL;
842 }
Victor Stinner8d379542013-07-02 00:14:56 +0200843
844 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200845 }
846
Victor Stinner95bb7142015-03-12 15:32:03 +0100847 Py_XINCREF(file);
Serhiy Storchaka48842712016-04-06 09:45:48 +0300848 Py_XSETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200849 user->fd = fd;
850 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200851 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200852 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200853 user->enabled = 1;
854
855 Py_RETURN_NONE;
856}
857
858static int
859faulthandler_unregister(user_signal_t *user, int signum)
860{
Victor Stinnera01ca122011-04-01 12:56:17 +0200861 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200862 return 0;
863 user->enabled = 0;
864#ifdef HAVE_SIGACTION
865 (void)sigaction(signum, &user->previous, NULL);
866#else
867 (void)signal(signum, user->previous);
868#endif
869 Py_CLEAR(user->file);
870 user->fd = -1;
871 return 1;
872}
873
874static PyObject*
875faulthandler_unregister_py(PyObject *self, PyObject *args)
876{
877 int signum;
878 user_signal_t *user;
879 int change;
880
881 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
882 return NULL;
883
Victor Stinner44378d42011-04-01 15:37:12 +0200884 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200885 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200886
Victor Stinnercfa71232011-04-08 12:48:15 +0200887 if (user_signals == NULL)
888 Py_RETURN_FALSE;
889
Victor Stinner024e37a2011-03-31 01:31:06 +0200890 user = &user_signals[signum];
891 change = faulthandler_unregister(user, signum);
892 return PyBool_FromLong(change);
893}
894#endif /* FAULTHANDLER_USER */
895
896
Victor Stinner7a399122014-09-30 13:40:12 +0200897static void
898faulthandler_suppress_crash_report(void)
899{
900#ifdef MS_WINDOWS
901 UINT mode;
902
903 /* Configure Windows to not display the Windows Error Reporting dialog */
904 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
905 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
906#endif
907
908#ifdef HAVE_SYS_RESOURCE_H
909 struct rlimit rl;
910
911 /* Disable creation of core dump */
912 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
913 rl.rlim_cur = 0;
914 setrlimit(RLIMIT_CORE, &rl);
915 }
916#endif
917
918#ifdef _MSC_VER
919 /* Visual Studio: configure abort() to not display an error message nor
920 open a popup asking to report the fault. */
921 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
922#endif
923}
924
Victor Stinner024e37a2011-03-31 01:31:06 +0200925static PyObject *
926faulthandler_read_null(PyObject *self, PyObject *args)
927{
Victor Stinnera2477202012-01-30 00:07:43 +0100928 volatile int *x;
929 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100930
Victor Stinner7a399122014-09-30 13:40:12 +0200931 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100932 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200933 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200934 return PyLong_FromLong(y);
935
936}
937
Victor Stinner50838282014-09-30 13:54:14 +0200938static void
939faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200940{
Victor Stinner7a399122014-09-30 13:40:12 +0200941 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200942#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200943 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
944 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200945 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200946 SIGSEGV was raised by the kernel because of a fault, and so if the
947 program retries to execute the same instruction, the fault will be
948 raised again.
949
950 Here the fault is simulated by a fake SIGSEGV signal raised by the
951 application. We have to raise SIGSEGV at lease twice: once for
952 faulthandler_fatal_error(), and one more time for the previous signal
953 handler. */
954 while(1)
955 raise(SIGSEGV);
956#else
957 raise(SIGSEGV);
958#endif
Victor Stinner50838282014-09-30 13:54:14 +0200959}
960
961static PyObject *
962faulthandler_sigsegv(PyObject *self, PyObject *args)
963{
964 int release_gil = 0;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100965 if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
Victor Stinner50838282014-09-30 13:54:14 +0200966 return NULL;
967
968 if (release_gil) {
969 Py_BEGIN_ALLOW_THREADS
970 faulthandler_raise_sigsegv();
971 Py_END_ALLOW_THREADS
972 } else {
973 faulthandler_raise_sigsegv();
974 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200975 Py_RETURN_NONE;
976}
977
Victor Stinner861d9ab2016-03-16 22:45:24 +0100978#ifdef WITH_THREAD
979static void
980faulthandler_fatal_error_thread(void *plock)
981{
Victor Stinner9a2329f2016-12-05 17:56:36 +0100982#ifndef __clang__
Victor Stinner861d9ab2016-03-16 22:45:24 +0100983 PyThread_type_lock *lock = (PyThread_type_lock *)plock;
Victor Stinner9a2329f2016-12-05 17:56:36 +0100984#endif
Victor Stinner861d9ab2016-03-16 22:45:24 +0100985
986 Py_FatalError("in new thread");
987
Victor Stinner9a2329f2016-12-05 17:56:36 +0100988#ifndef __clang__
989 /* Issue #28152: Py_FatalError() is declared with
990 __attribute__((__noreturn__)). GCC emits a warning without
991 "PyThread_release_lock()" (compiler bug?), but Clang is smarter and
992 emits a warning on the return. */
993
Victor Stinner861d9ab2016-03-16 22:45:24 +0100994 /* notify the caller that we are done */
995 PyThread_release_lock(lock);
Victor Stinner9a2329f2016-12-05 17:56:36 +0100996#endif
Victor Stinner861d9ab2016-03-16 22:45:24 +0100997}
998
999static PyObject *
1000faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
1001{
1002 long thread;
1003 PyThread_type_lock lock;
1004
1005 faulthandler_suppress_crash_report();
1006
1007 lock = PyThread_allocate_lock();
1008 if (lock == NULL)
1009 return PyErr_NoMemory();
1010
1011 PyThread_acquire_lock(lock, WAIT_LOCK);
1012
1013 thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
1014 if (thread == -1) {
1015 PyThread_free_lock(lock);
1016 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
1017 return NULL;
1018 }
1019
1020 /* wait until the thread completes: it will never occur, since Py_FatalError()
1021 exits the process immedialty. */
1022 PyThread_acquire_lock(lock, WAIT_LOCK);
1023 PyThread_release_lock(lock);
1024 PyThread_free_lock(lock);
1025
1026 Py_RETURN_NONE;
1027}
1028#endif
1029
Victor Stinner024e37a2011-03-31 01:31:06 +02001030static PyObject *
1031faulthandler_sigfpe(PyObject *self, PyObject *args)
1032{
1033 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
1034 PowerPC. Use volatile to disable compile-time optimizations. */
1035 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +02001036 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +02001037 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +02001038 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
1039 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001040 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +02001041 /* This line is never reached, but we pretend to make something with z
1042 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +02001043 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +02001044}
1045
Victor Stinnerd727e232011-04-01 12:13:55 +02001046static PyObject *
1047faulthandler_sigabrt(PyObject *self, PyObject *args)
1048{
Victor Stinner7a399122014-09-30 13:40:12 +02001049 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +02001050 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +02001051 Py_RETURN_NONE;
1052}
1053
Victor Stinner024e37a2011-03-31 01:31:06 +02001054static PyObject *
1055faulthandler_fatal_error_py(PyObject *self, PyObject *args)
1056{
1057 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +01001058 int release_gil = 0;
1059 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +02001060 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +02001061 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +01001062 if (release_gil) {
1063 Py_BEGIN_ALLOW_THREADS
1064 Py_FatalError(message);
1065 Py_END_ALLOW_THREADS
1066 }
1067 else {
1068 Py_FatalError(message);
1069 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001070 Py_RETURN_NONE;
1071}
1072
1073#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner404cdc52016-03-23 10:39:17 +01001074#define FAULTHANDLER_STACK_OVERFLOW
1075
Victor Stinner19276f12015-03-23 21:20:27 +01001076#ifdef __INTEL_COMPILER
1077 /* Issue #23654: Turn off ICC's tail call optimization for the
1078 * stack_overflow generator. ICC turns the recursive tail call into
1079 * a loop. */
1080# pragma intel optimization_level 0
1081#endif
1082static
Benjamin Petersonca470632016-09-06 13:47:26 -07001083uintptr_t
1084stack_overflow(uintptr_t min_sp, uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +02001085{
1086 /* allocate 4096 bytes on the stack at each call */
1087 unsigned char buffer[4096];
Benjamin Petersonca470632016-09-06 13:47:26 -07001088 uintptr_t sp = (uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +02001089 *depth += 1;
Victor Stinner928ad282016-03-23 15:19:12 +01001090 if (sp < min_sp || max_sp < sp)
Victor Stinnerf0480752011-03-31 11:34:08 +02001091 return sp;
Victor Stinner928ad282016-03-23 15:19:12 +01001092 buffer[0] = 1;
1093 buffer[4095] = 0;
1094 return stack_overflow(min_sp, max_sp, depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001095}
1096
1097static PyObject *
1098faulthandler_stack_overflow(PyObject *self)
1099{
1100 size_t depth, size;
Benjamin Petersonca470632016-09-06 13:47:26 -07001101 uintptr_t sp = (uintptr_t)&depth;
1102 uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +02001103
Victor Stinner7a399122014-09-30 13:40:12 +02001104 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +02001105 depth = 0;
Victor Stinner928ad282016-03-23 15:19:12 +01001106 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
1107 sp + STACK_OVERFLOW_MAX_SIZE,
1108 &depth);
Victor Stinnerf0480752011-03-31 11:34:08 +02001109 if (sp < stop)
1110 size = stop - sp;
1111 else
1112 size = sp - stop;
1113 PyErr_Format(PyExc_RuntimeError,
1114 "unable to raise a stack overflow (allocated %zu bytes "
1115 "on the stack, %zu recursive calls)",
1116 size, depth);
1117 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001118}
Victor Stinner928ad282016-03-23 15:19:12 +01001119#endif /* defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) */
Victor Stinner024e37a2011-03-31 01:31:06 +02001120
1121
1122static int
1123faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1124{
1125#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001126 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001127#endif
1128
1129#ifdef FAULTHANDLER_LATER
1130 Py_VISIT(thread.file);
1131#endif
1132#ifdef FAULTHANDLER_USER
1133 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001134 for (signum=0; signum < NSIG; signum++)
1135 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001136 }
1137#endif
1138 Py_VISIT(fatal_error.file);
1139 return 0;
1140}
1141
Victor Stinner404cdc52016-03-23 10:39:17 +01001142#ifdef MS_WINDOWS
1143static PyObject *
1144faulthandler_raise_exception(PyObject *self, PyObject *args)
1145{
1146 unsigned int code, flags = 0;
1147 if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
1148 return NULL;
1149 faulthandler_suppress_crash_report();
1150 RaiseException(code, flags, 0, NULL);
1151 Py_RETURN_NONE;
1152}
1153#endif
1154
Victor Stinner024e37a2011-03-31 01:31:06 +02001155PyDoc_STRVAR(module_doc,
1156"faulthandler module.");
1157
1158static PyMethodDef module_methods[] = {
1159 {"enable",
Victor Stinner404cdc52016-03-23 10:39:17 +01001160 (PyCFunction)faulthandler_py_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001161 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001162 "enable the fault handler")},
1163 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1164 PyDoc_STR("disable(): disable the fault handler")},
1165 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1166 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1167 {"dump_traceback",
1168 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001169 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001170 "dump the traceback of the current thread, or of all threads "
1171 "if all_threads is True, into file")},
1172#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001173 {"dump_traceback_later",
1174 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1175 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001176 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001177 "or each timeout seconds if repeat is True. If exit is True, "
1178 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001179 {"cancel_dump_traceback_later",
1180 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1181 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1182 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001183#endif
1184
1185#ifdef FAULTHANDLER_USER
1186 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001187 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1188 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001189 "register a handler for the signal 'signum': dump the "
Victor Stinner024e37a2011-03-31 01:31:06 +02001190 "traceback of the current thread, or of all threads if "
1191 "all_threads is True, into file")},
1192 {"unregister",
1193 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1194 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1195 "'signum' registered by register()")},
1196#endif
1197
Victor Stinner50838282014-09-30 13:54:14 +02001198 {"_read_null", faulthandler_read_null, METH_NOARGS,
1199 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001200 "a SIGSEGV or SIGBUS signal depending on the platform")},
1201 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001202 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner861d9ab2016-03-16 22:45:24 +01001203#ifdef WITH_THREAD
1204 {"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
1205 PyDoc_STR("fatal_error_c_thread(): "
1206 "call Py_FatalError() in a new C thread.")},
1207#endif
Victor Stinner9db521c2014-09-30 13:49:09 +02001208 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001209 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001210 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1211 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001212 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1213 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
Victor Stinner404cdc52016-03-23 10:39:17 +01001214#ifdef FAULTHANDLER_STACK_OVERFLOW
Victor Stinner024e37a2011-03-31 01:31:06 +02001215 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1216 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1217#endif
Victor Stinner404cdc52016-03-23 10:39:17 +01001218#ifdef MS_WINDOWS
1219 {"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
1220 PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
1221#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001222 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001223};
1224
1225static struct PyModuleDef module_def = {
1226 PyModuleDef_HEAD_INIT,
1227 "faulthandler",
1228 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001229 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001230 module_methods,
1231 NULL,
1232 faulthandler_traverse,
1233 NULL,
1234 NULL
1235};
1236
1237PyMODINIT_FUNC
1238PyInit_faulthandler(void)
1239{
Victor Stinner404cdc52016-03-23 10:39:17 +01001240 PyObject *m = PyModule_Create(&module_def);
1241 if (m == NULL)
1242 return NULL;
1243
1244 /* Add constants for unit tests */
1245#ifdef MS_WINDOWS
1246 /* RaiseException() codes (prefixed by an underscore) */
1247 if (PyModule_AddIntConstant(m, "_EXCEPTION_ACCESS_VIOLATION",
1248 EXCEPTION_ACCESS_VIOLATION))
1249 return NULL;
1250 if (PyModule_AddIntConstant(m, "_EXCEPTION_INT_DIVIDE_BY_ZERO",
1251 EXCEPTION_INT_DIVIDE_BY_ZERO))
1252 return NULL;
1253 if (PyModule_AddIntConstant(m, "_EXCEPTION_STACK_OVERFLOW",
1254 EXCEPTION_STACK_OVERFLOW))
1255 return NULL;
1256
1257 /* RaiseException() flags (prefixed by an underscore) */
1258 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
1259 EXCEPTION_NONCONTINUABLE))
1260 return NULL;
1261 if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
1262 EXCEPTION_NONCONTINUABLE_EXCEPTION))
1263 return NULL;
1264#endif
1265
1266 return m;
Victor Stinner024e37a2011-03-31 01:31:06 +02001267}
1268
Victor Stinner410dd7d2011-05-11 20:56:08 +02001269/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1270 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001271
1272static int
1273faulthandler_env_options(void)
1274{
1275 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001276 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001277
Victor Stinner88983502013-09-08 11:36:23 +02001278 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1279 /* PYTHONFAULTHANDLER environment variable is missing
1280 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001281 int has_key;
1282
Victor Stinner024e37a2011-03-31 01:31:06 +02001283 xoptions = PySys_GetXOptions();
1284 if (xoptions == NULL)
1285 return -1;
1286
1287 key = PyUnicode_FromString("faulthandler");
1288 if (key == NULL)
1289 return -1;
1290
Victor Stinner25095b22011-05-26 13:47:08 +02001291 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001292 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001293 if (has_key <= 0)
1294 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001295 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001296
1297 module = PyImport_ImportModule("faulthandler");
1298 if (module == NULL) {
1299 return -1;
1300 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001301 res = _PyObject_CallMethodId(module, &PyId_enable, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +02001302 Py_DECREF(module);
1303 if (res == NULL)
1304 return -1;
1305 Py_DECREF(res);
1306 return 0;
1307}
1308
1309int _PyFaulthandler_Init(void)
1310{
1311#ifdef HAVE_SIGALTSTACK
1312 int err;
1313
1314 /* Try to allocate an alternate stack for faulthandler() signal handler to
1315 * be able to allocate memory on the stack, even on a stack overflow. If it
1316 * fails, ignore the error. */
1317 stack.ss_flags = 0;
1318 stack.ss_size = SIGSTKSZ;
1319 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1320 if (stack.ss_sp != NULL) {
Christophe Zeitouny20fbf8a2017-03-23 10:14:29 -07001321 err = sigaltstack(&stack, &old_stack);
Victor Stinner024e37a2011-03-31 01:31:06 +02001322 if (err) {
1323 PyMem_Free(stack.ss_sp);
1324 stack.ss_sp = NULL;
1325 }
1326 }
1327#endif
1328#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001329 thread.file = NULL;
1330 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001331 thread.running = PyThread_allocate_lock();
1332 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001333 PyErr_SetString(PyExc_RuntimeError,
1334 "could not allocate locks for faulthandler");
1335 return -1;
1336 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001337 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001338#endif
1339
1340 return faulthandler_env_options();
1341}
1342
1343void _PyFaulthandler_Fini(void)
1344{
1345#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001346 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001347#endif
1348
1349#ifdef FAULTHANDLER_LATER
1350 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001351 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001352 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001353 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001354 PyThread_free_lock(thread.cancel_event);
1355 thread.cancel_event = NULL;
1356 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001357 if (thread.running) {
1358 PyThread_free_lock(thread.running);
1359 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001360 }
1361#endif
1362
1363#ifdef FAULTHANDLER_USER
1364 /* user */
1365 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001366 for (signum=0; signum < NSIG; signum++)
1367 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001368 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001369 user_signals = NULL;
1370 }
1371#endif
1372
1373 /* fatal */
1374 faulthandler_disable();
1375#ifdef HAVE_SIGALTSTACK
1376 if (stack.ss_sp != NULL) {
Christophe Zeitouny20fbf8a2017-03-23 10:14:29 -07001377 /* Fetch the current alt stack */
1378 stack_t current_stack;
1379 if (sigaltstack(NULL, &current_stack) == 0) {
1380 if (current_stack.ss_sp == stack.ss_sp) {
1381 /* The current alt stack is the one that we installed.
1382 It is safe to restore the old stack that we found when
1383 we installed ours */
1384 sigaltstack(&old_stack, NULL);
1385 } else {
1386 /* Someone switched to a different alt stack and didn't
1387 restore ours when they were done (if they're done).
1388 There's not much we can do in this unlikely case */
1389 }
1390 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001391 PyMem_Free(stack.ss_sp);
1392 stack.ss_sp = NULL;
1393 }
1394#endif
1395}