blob: 48c43912cecc8bf9a5cdc2d215df0075249844e8 [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>
7
Victor Stinner96994402011-04-07 11:37:19 +02008/* Allocate at maximum 100 MB of the stack to raise the stack overflow */
9#define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)
10
Victor Stinner024e37a2011-03-31 01:31:06 +020011#ifdef WITH_THREAD
12# define FAULTHANDLER_LATER
13#endif
14
15#ifndef MS_WINDOWS
Victor Stinnerd727e232011-04-01 12:13:55 +020016 /* register() is useless on Windows, because only SIGSEGV, SIGABRT and
17 SIGILL can be handled by the process, and these signals can only be used
18 with enable(), not using register() */
Victor Stinner024e37a2011-03-31 01:31:06 +020019# define FAULTHANDLER_USER
20#endif
21
22#define PUTS(fd, str) write(fd, str, strlen(str))
23
24#ifdef HAVE_SIGACTION
25typedef struct sigaction _Py_sighandler_t;
26#else
27typedef PyOS_sighandler_t _Py_sighandler_t;
28#endif
29
30typedef struct {
31 int signum;
32 int enabled;
33 const char* name;
34 _Py_sighandler_t previous;
35 int all_threads;
36} fault_handler_t;
37
38static struct {
39 int enabled;
40 PyObject *file;
41 int fd;
42 int all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +020043 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020044} fatal_error = {0, NULL, -1, 0};
45
46#ifdef FAULTHANDLER_LATER
47static struct {
48 PyObject *file;
49 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020050 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020051 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020052 PyInterpreterState *interp;
53 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020054 char *header;
55 size_t header_len;
Victor Stinnerde10f402011-04-08 12:57:06 +020056 /* The main thread always hold this lock. It is only released when
57 faulthandler_thread() is interrupted until this thread exits, or at
58 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020059 PyThread_type_lock cancel_event;
60 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020061 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020062} thread;
63#endif
64
65#ifdef FAULTHANDLER_USER
66typedef struct {
67 int enabled;
68 PyObject *file;
69 int fd;
70 int all_threads;
71 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020072 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020073} user_signal_t;
74
75static user_signal_t *user_signals;
76
77/* the following macros come from Python: Modules/signalmodule.c */
78#if defined(PYOS_OS2) && !defined(PYCC_GCC)
79#define NSIG 12
80#endif
81#ifndef NSIG
82# if defined(_NSIG)
83# define NSIG _NSIG /* For BSD/SysV */
84# elif defined(_SIGMAX)
85# define NSIG (_SIGMAX + 1) /* For QNX */
86# elif defined(SIGMAX)
87# define NSIG (SIGMAX + 1) /* For djgpp */
88# else
89# define NSIG 64 /* Use a reasonable default value */
90# endif
91#endif
92
93#endif /* FAULTHANDLER_USER */
94
95
96static fault_handler_t faulthandler_handlers[] = {
97#ifdef SIGBUS
98 {SIGBUS, 0, "Bus error", },
99#endif
100#ifdef SIGILL
101 {SIGILL, 0, "Illegal instruction", },
102#endif
103 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200104 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200105 /* define SIGSEGV at the end to make it the default choice if searching the
106 handler fails in faulthandler_fatal_error() */
107 {SIGSEGV, 0, "Segmentation fault", }
108};
109static const unsigned char faulthandler_nsignals = \
110 sizeof(faulthandler_handlers) / sizeof(faulthandler_handlers[0]);
111
112#ifdef HAVE_SIGALTSTACK
113static stack_t stack;
114#endif
115
116
117/* Get the file descriptor of a file by calling its fileno() method and then
118 call its flush() method.
119
120 If file is NULL or Py_None, use sys.stderr as the new file.
121
122 On success, return the new file and write the file descriptor into *p_fd.
123 On error, return NULL. */
124
125static PyObject*
126faulthandler_get_fileno(PyObject *file, int *p_fd)
127{
128 PyObject *result;
129 long fd_long;
130 int fd;
131
132 if (file == NULL || file == Py_None) {
133 file = PySys_GetObject("stderr");
134 if (file == NULL) {
135 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
136 return NULL;
137 }
138 }
139
140 result = PyObject_CallMethod(file, "fileno", "");
141 if (result == NULL)
142 return NULL;
143
144 fd = -1;
145 if (PyLong_Check(result)) {
146 fd_long = PyLong_AsLong(result);
147 if (0 <= fd_long && fd_long < INT_MAX)
148 fd = (int)fd_long;
149 }
150 Py_DECREF(result);
151
152 if (fd == -1) {
153 PyErr_SetString(PyExc_RuntimeError,
154 "file.fileno() is not a valid file descriptor");
155 return NULL;
156 }
157
158 result = PyObject_CallMethod(file, "flush", "");
159 if (result != NULL)
160 Py_DECREF(result);
161 else {
162 /* ignore flush() error */
163 PyErr_Clear();
164 }
165 *p_fd = fd;
166 return file;
167}
168
Victor Stinnera4de6d82011-04-09 00:47:23 +0200169/* Get the state of the current thread: only call this function if the current
170 thread holds the GIL. Raise an exception on error. */
171static PyThreadState*
172get_thread_state(void)
173{
174 PyThreadState *tstate = PyThreadState_Get();
175 if (tstate == NULL) {
176 PyErr_SetString(PyExc_RuntimeError,
177 "unable to get the current thread state");
178 return NULL;
179 }
180 return tstate;
181}
182
Victor Stinner024e37a2011-03-31 01:31:06 +0200183static PyObject*
184faulthandler_dump_traceback_py(PyObject *self,
185 PyObject *args, PyObject *kwargs)
186{
187 static char *kwlist[] = {"file", "all_threads", NULL};
188 PyObject *file = NULL;
189 int all_threads = 0;
190 PyThreadState *tstate;
191 const char *errmsg;
192 int fd;
193
194 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
195 "|Oi:dump_traceback", kwlist,
196 &file, &all_threads))
197 return NULL;
198
199 file = faulthandler_get_fileno(file, &fd);
200 if (file == NULL)
201 return NULL;
202
Victor Stinnera4de6d82011-04-09 00:47:23 +0200203 tstate = get_thread_state();
204 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200205 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200206
207 if (all_threads) {
208 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
209 if (errmsg != NULL) {
210 PyErr_SetString(PyExc_RuntimeError, errmsg);
211 return NULL;
212 }
213 }
214 else {
215 _Py_DumpTraceback(fd, tstate);
216 }
217 Py_RETURN_NONE;
218}
219
220
Victor Stinnerd727e232011-04-01 12:13:55 +0200221/* Handler of SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200222
223 Display the current Python traceback, restore the previous handler and call
224 the previous handler.
225
226 On Windows, don't call explictly the previous handler, because Windows
227 signal handler would not be called (for an unknown reason). The execution of
228 the program continues at faulthandler_fatal_error() exit, but the same
229 instruction will raise the same fault (signal), and so the previous handler
230 will be called.
231
232 This function is signal safe and should only call signal safe functions. */
233
234static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200235faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200236{
237 const int fd = fatal_error.fd;
238 unsigned int i;
239 fault_handler_t *handler = NULL;
240 PyThreadState *tstate;
241
242 if (!fatal_error.enabled)
243 return;
244
245 for (i=0; i < faulthandler_nsignals; i++) {
246 handler = &faulthandler_handlers[i];
247 if (handler->signum == signum)
248 break;
249 }
250 if (handler == NULL) {
251 /* faulthandler_nsignals == 0 (unlikely) */
252 return;
253 }
254
255 /* restore the previous handler */
256#ifdef HAVE_SIGACTION
257 (void)sigaction(handler->signum, &handler->previous, NULL);
258#else
259 (void)signal(handler->signum, handler->previous);
260#endif
261 handler->enabled = 0;
262
263 PUTS(fd, "Fatal Python error: ");
264 PUTS(fd, handler->name);
265 PUTS(fd, "\n\n");
266
Victor Stinnerff4cd882011-04-07 11:50:25 +0200267#ifdef WITH_THREAD
Victor Stinnerd727e232011-04-01 12:13:55 +0200268 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
269 so are delivered to the thread that caused the fault. Get the Python
270 thread state of the current thread.
Victor Stinner024e37a2011-03-31 01:31:06 +0200271
272 PyThreadState_Get() doesn't give the state of the thread that caused the
273 fault if the thread released the GIL, and so this function cannot be
274 used. Read the thread local storage (TLS) instead: call
275 PyGILState_GetThisThreadState(). */
276 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200277#else
278 tstate = PyThreadState_Get();
279#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200280
281 if (fatal_error.all_threads)
Victor Stinnera4de6d82011-04-09 00:47:23 +0200282 _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
283 else {
284 if (tstate != NULL)
285 _Py_DumpTraceback(fd, tstate);
286 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200287
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200288#ifdef MS_WINDOWS
289 if (signum == SIGSEGV) {
290 /* don't call explictly the previous handler for SIGSEGV in this signal
291 handler, because the Windows signal handler would not be called */
292 return;
293 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200294#endif
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200295 /* call the previous signal handler: it is called immediatly if we use
296 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
297 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200298}
299
Victor Stinnerd727e232011-04-01 12:13:55 +0200300/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200301
302static PyObject*
303faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
304{
305 static char *kwlist[] = {"file", "all_threads", NULL};
306 PyObject *file = NULL;
307 int all_threads = 0;
308 unsigned int i;
309 fault_handler_t *handler;
310#ifdef HAVE_SIGACTION
311 struct sigaction action;
312#endif
313 int err;
314 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200315 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200316
317 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
318 "|Oi:enable", kwlist, &file, &all_threads))
319 return NULL;
320
321 file = faulthandler_get_fileno(file, &fd);
322 if (file == NULL)
323 return NULL;
324
Victor Stinnera4de6d82011-04-09 00:47:23 +0200325 tstate = get_thread_state();
326 if (tstate == NULL)
327 return NULL;
328
Victor Stinner024e37a2011-03-31 01:31:06 +0200329 Py_XDECREF(fatal_error.file);
330 Py_INCREF(file);
331 fatal_error.file = file;
332 fatal_error.fd = fd;
333 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200334 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200335
336 if (!fatal_error.enabled) {
337 fatal_error.enabled = 1;
338
339 for (i=0; i < faulthandler_nsignals; i++) {
340 handler = &faulthandler_handlers[i];
341#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200342 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200343 sigemptyset(&action.sa_mask);
344 /* Do not prevent the signal from being received from within
345 its own signal handler */
346 action.sa_flags = SA_NODEFER;
347#ifdef HAVE_SIGALTSTACK
348 if (stack.ss_sp != NULL) {
349 /* Call the signal handler on an alternate signal stack
350 provided by sigaltstack() */
351 action.sa_flags |= SA_ONSTACK;
352 }
353#endif
354 err = sigaction(handler->signum, &action, &handler->previous);
355#else
356 handler->previous = signal(handler->signum,
357 faulthandler_fatal_error);
358 err = (handler->previous == SIG_ERR);
359#endif
360 if (err) {
361 PyErr_SetFromErrno(PyExc_RuntimeError);
362 return NULL;
363 }
364 handler->enabled = 1;
365 }
366 }
367 Py_RETURN_NONE;
368}
369
370static void
371faulthandler_disable(void)
372{
373 unsigned int i;
374 fault_handler_t *handler;
375
376 if (fatal_error.enabled) {
377 fatal_error.enabled = 0;
378 for (i=0; i < faulthandler_nsignals; i++) {
379 handler = &faulthandler_handlers[i];
380 if (!handler->enabled)
381 continue;
382#ifdef HAVE_SIGACTION
383 (void)sigaction(handler->signum, &handler->previous, NULL);
384#else
385 (void)signal(handler->signum, handler->previous);
386#endif
387 handler->enabled = 0;
388 }
389 }
390
391 Py_CLEAR(fatal_error.file);
392}
393
394static PyObject*
395faulthandler_disable_py(PyObject *self)
396{
397 if (!fatal_error.enabled) {
398 Py_INCREF(Py_False);
399 return Py_False;
400 }
401 faulthandler_disable();
402 Py_INCREF(Py_True);
403 return Py_True;
404}
405
406static PyObject*
407faulthandler_is_enabled(PyObject *self)
408{
409 return PyBool_FromLong(fatal_error.enabled);
410}
411
412#ifdef FAULTHANDLER_LATER
413
414static void
415faulthandler_thread(void *unused)
416{
417 PyLockStatus st;
418 const char* errmsg;
419 PyThreadState *current;
420 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200421#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200422 sigset_t set;
423
424 /* we don't want to receive any signal */
425 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200426 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200427#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200428
429 do {
430 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200431 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200432 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200433 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200434 break;
435 }
436 /* Timeout => dump traceback */
437 assert(st == PY_LOCK_FAILURE);
438
439 /* get the thread holding the GIL, NULL if no thread hold the GIL */
440 current = _Py_atomic_load_relaxed(&_PyThreadState_Current);
441
Victor Stinnerc790a532011-04-08 13:39:59 +0200442 write(thread.fd, thread.header, thread.header_len);
443
Victor Stinner024e37a2011-03-31 01:31:06 +0200444 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
445 ok = (errmsg == NULL);
446
447 if (thread.exit)
448 _exit(1);
449 } while (ok && thread.repeat);
450
451 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200452 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200453}
454
455static void
Victor Stinnerde10f402011-04-08 12:57:06 +0200456cancel_dump_tracebacks_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200457{
Victor Stinnerde10f402011-04-08 12:57:06 +0200458 /* notify cancellation */
459 PyThread_release_lock(thread.cancel_event);
460
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200461 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200462 PyThread_acquire_lock(thread.running, 1);
463 PyThread_release_lock(thread.running);
464
465 /* The main thread should always hold the cancel_event lock */
466 PyThread_acquire_lock(thread.cancel_event, 1);
467
Victor Stinner024e37a2011-03-31 01:31:06 +0200468 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200469 if (thread.header) {
470 free(thread.header);
471 thread.header = NULL;
472 }
473}
474
475static char*
476format_timeout(double timeout)
477{
478 unsigned long us, sec, min, hour;
479 double intpart, fracpart;
480 char buffer[100];
481
482 fracpart = modf(timeout, &intpart);
483 sec = (unsigned long)intpart;
484 us = (unsigned long)(fracpart * 1e6);
485 min = sec / 60;
486 sec %= 60;
487 hour = min / 60;
488 min %= 60;
489
490 if (us != 0)
491 PyOS_snprintf(buffer, sizeof(buffer),
492 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
493 hour, min, sec, us);
494 else
495 PyOS_snprintf(buffer, sizeof(buffer),
496 "Timeout (%lu:%02lu:%02lu)!\n",
497 hour, min, sec);
498
499 return strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200500}
501
502static PyObject*
Victor Stinner96994402011-04-07 11:37:19 +0200503faulthandler_dump_tracebacks_later(PyObject *self,
504 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200505{
506 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
507 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200508 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200509 int repeat = 0;
510 PyObject *file = NULL;
511 int fd;
512 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200513 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200514 char *header;
515 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200516
517 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
518 "d|iOi:dump_tracebacks_later", kwlist,
519 &timeout, &repeat, &file, &exit))
520 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200521 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200522 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
523 return NULL;
524 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200525 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200526 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200527 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
528 return NULL;
529 }
530
Victor Stinnera4de6d82011-04-09 00:47:23 +0200531 tstate = get_thread_state();
532 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200533 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200534
Victor Stinner024e37a2011-03-31 01:31:06 +0200535 file = faulthandler_get_fileno(file, &fd);
536 if (file == NULL)
537 return NULL;
538
Victor Stinnerc790a532011-04-08 13:39:59 +0200539 /* format the timeout */
540 header = format_timeout(timeout);
541 if (header == NULL)
542 return PyErr_NoMemory();
543 header_len = strlen(header);
544
Victor Stinner024e37a2011-03-31 01:31:06 +0200545 /* Cancel previous thread, if running */
Victor Stinnerde10f402011-04-08 12:57:06 +0200546 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200547
548 Py_XDECREF(thread.file);
549 Py_INCREF(file);
550 thread.file = file;
551 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200552 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200553 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200554 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200555 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200556 thread.header = header;
557 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200558
559 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200560 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200561
Victor Stinner024e37a2011-03-31 01:31:06 +0200562 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200563 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200564 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200565 free(header);
566 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200567 PyErr_SetString(PyExc_RuntimeError,
568 "unable to start watchdog thread");
569 return NULL;
570 }
571
572 Py_RETURN_NONE;
573}
574
575static PyObject*
Victor Stinner702624e2011-03-31 03:42:34 +0200576faulthandler_cancel_dump_tracebacks_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200577{
Victor Stinnerde10f402011-04-08 12:57:06 +0200578 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200579 Py_RETURN_NONE;
580}
581#endif /* FAULTHANDLER_LATER */
582
583#ifdef FAULTHANDLER_USER
584/* Handler of user signals (e.g. SIGUSR1).
585
586 Dump the traceback of the current thread, or of all threads if
587 thread.all_threads is true.
588
589 This function is signal safe and should only call signal safe functions. */
590
591static void
592faulthandler_user(int signum)
593{
594 user_signal_t *user;
595 PyThreadState *tstate;
596
597 user = &user_signals[signum];
598 if (!user->enabled)
599 return;
600
Victor Stinnerff4cd882011-04-07 11:50:25 +0200601#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200602 /* PyThreadState_Get() doesn't give the state of the current thread if
603 the thread doesn't hold the GIL. Read the thread local storage (TLS)
604 instead: call PyGILState_GetThisThreadState(). */
605 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200606#else
607 tstate = PyThreadState_Get();
608#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200609
610 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200611 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
612 else {
613 if (tstate == NULL)
614 return;
Victor Stinner024e37a2011-03-31 01:31:06 +0200615 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200616 }
617}
618
619static int
620check_signum(int signum)
621{
622 unsigned int i;
623
624 for (i=0; i < faulthandler_nsignals; i++) {
625 if (faulthandler_handlers[i].signum == signum) {
626 PyErr_Format(PyExc_RuntimeError,
627 "signal %i cannot be registered, "
628 "use enable() instead",
629 signum);
630 return 0;
631 }
632 }
633 if (signum < 1 || NSIG <= signum) {
634 PyErr_SetString(PyExc_ValueError, "signal number out of range");
635 return 0;
636 }
637 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200638}
639
640static PyObject*
641faulthandler_register(PyObject *self,
642 PyObject *args, PyObject *kwargs)
643{
644 static char *kwlist[] = {"signum", "file", "all_threads", NULL};
645 int signum;
646 PyObject *file = NULL;
647 int all_threads = 0;
648 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200649 user_signal_t *user;
650 _Py_sighandler_t previous;
651#ifdef HAVE_SIGACTION
652 struct sigaction action;
653#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200654 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200655 int err;
656
657 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
658 "i|Oi:register", kwlist,
659 &signum, &file, &all_threads))
660 return NULL;
661
Victor Stinner44378d42011-04-01 15:37:12 +0200662 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200663 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200664
Victor Stinnera4de6d82011-04-09 00:47:23 +0200665 tstate = get_thread_state();
666 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200667 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200668
669 file = faulthandler_get_fileno(file, &fd);
670 if (file == NULL)
671 return NULL;
672
673 if (user_signals == NULL) {
674 user_signals = calloc(NSIG, sizeof(user_signal_t));
675 if (user_signals == NULL)
676 return PyErr_NoMemory();
677 }
678 user = &user_signals[signum];
679
680 if (!user->enabled) {
681#ifdef HAVE_SIGACTION
682 action.sa_handler = faulthandler_user;
683 sigemptyset(&action.sa_mask);
684 /* if the signal is received while the kernel is executing a system
685 call, try to restart the system call instead of interrupting it and
686 return EINTR */
687 action.sa_flags = SA_RESTART;
688#ifdef HAVE_SIGALTSTACK
689 if (stack.ss_sp != NULL) {
690 /* Call the signal handler on an alternate signal stack
691 provided by sigaltstack() */
692 action.sa_flags |= SA_ONSTACK;
693 }
694#endif
695 err = sigaction(signum, &action, &previous);
696#else
697 previous = signal(signum, faulthandler_user);
698 err = (previous == SIG_ERR);
699#endif
700 if (err) {
701 PyErr_SetFromErrno(PyExc_OSError);
702 return NULL;
703 }
704 }
705
706 Py_XDECREF(user->file);
707 Py_INCREF(file);
708 user->file = file;
709 user->fd = fd;
710 user->all_threads = all_threads;
711 user->previous = previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200712 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200713 user->enabled = 1;
714
715 Py_RETURN_NONE;
716}
717
718static int
719faulthandler_unregister(user_signal_t *user, int signum)
720{
Victor Stinnera01ca122011-04-01 12:56:17 +0200721 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200722 return 0;
723 user->enabled = 0;
724#ifdef HAVE_SIGACTION
725 (void)sigaction(signum, &user->previous, NULL);
726#else
727 (void)signal(signum, user->previous);
728#endif
729 Py_CLEAR(user->file);
730 user->fd = -1;
731 return 1;
732}
733
734static PyObject*
735faulthandler_unregister_py(PyObject *self, PyObject *args)
736{
737 int signum;
738 user_signal_t *user;
739 int change;
740
741 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
742 return NULL;
743
Victor Stinner44378d42011-04-01 15:37:12 +0200744 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200745 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200746
Victor Stinnercfa71232011-04-08 12:48:15 +0200747 if (user_signals == NULL)
748 Py_RETURN_FALSE;
749
Victor Stinner024e37a2011-03-31 01:31:06 +0200750 user = &user_signals[signum];
751 change = faulthandler_unregister(user, signum);
752 return PyBool_FromLong(change);
753}
754#endif /* FAULTHANDLER_USER */
755
756
757static PyObject *
758faulthandler_read_null(PyObject *self, PyObject *args)
759{
760 int *x = NULL, y;
761 int release_gil = 0;
762 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
763 return NULL;
764 if (release_gil) {
765 Py_BEGIN_ALLOW_THREADS
766 y = *x;
767 Py_END_ALLOW_THREADS
768 } else
769 y = *x;
770 return PyLong_FromLong(y);
771
772}
773
774static PyObject *
775faulthandler_sigsegv(PyObject *self, PyObject *args)
776{
777#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200778 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
779 handler and then gives back the execution flow to the program (without
780 calling explicitly the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200781 SIGSEGV was raised by the kernel because of a fault, and so if the
782 program retries to execute the same instruction, the fault will be
783 raised again.
784
785 Here the fault is simulated by a fake SIGSEGV signal raised by the
786 application. We have to raise SIGSEGV at lease twice: once for
787 faulthandler_fatal_error(), and one more time for the previous signal
788 handler. */
789 while(1)
790 raise(SIGSEGV);
791#else
792 raise(SIGSEGV);
793#endif
794 Py_RETURN_NONE;
795}
796
797static PyObject *
798faulthandler_sigfpe(PyObject *self, PyObject *args)
799{
800 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
801 PowerPC. Use volatile to disable compile-time optimizations. */
802 volatile int x = 1, y = 0, z;
803 z = x / y;
804 /* if the division by zero didn't raise a SIGFPE, raise it manually */
805 raise(SIGFPE);
806 Py_RETURN_NONE;
807}
808
Victor Stinnerd727e232011-04-01 12:13:55 +0200809static PyObject *
810faulthandler_sigabrt(PyObject *self, PyObject *args)
811{
812#if _MSC_VER
813 /* If Python is compiled in debug mode with Visual Studio, abort() opens
814 a popup asking the user how to handle the assertion. Use raise(SIGABRT)
815 instead. */
816 raise(SIGABRT);
817#else
818 abort();
819#endif
820 Py_RETURN_NONE;
821}
822
Victor Stinner024e37a2011-03-31 01:31:06 +0200823#ifdef SIGBUS
824static PyObject *
825faulthandler_sigbus(PyObject *self, PyObject *args)
826{
827 raise(SIGBUS);
828 Py_RETURN_NONE;
829}
830#endif
831
832#ifdef SIGILL
833static PyObject *
834faulthandler_sigill(PyObject *self, PyObject *args)
835{
Victor Stinner024e37a2011-03-31 01:31:06 +0200836 raise(SIGILL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200837 Py_RETURN_NONE;
838}
839#endif
840
841static PyObject *
842faulthandler_fatal_error_py(PyObject *self, PyObject *args)
843{
844 char *message;
845 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
846 return NULL;
847 Py_FatalError(message);
848 Py_RETURN_NONE;
849}
850
851#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinnerf0480752011-03-31 11:34:08 +0200852void*
853stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200854{
855 /* allocate 4096 bytes on the stack at each call */
856 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200857 void *sp = &buffer;
858 *depth += 1;
859 if (sp < min_sp || max_sp < sp)
860 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200861 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200862 buffer[4095] = 0;
863 return stack_overflow(min_sp, max_sp, depth);
864}
865
866static PyObject *
867faulthandler_stack_overflow(PyObject *self)
868{
869 size_t depth, size;
870 void *sp = &depth, *stop;
871
872 depth = 0;
873 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
874 sp + STACK_OVERFLOW_MAX_SIZE,
875 &depth);
876 if (sp < stop)
877 size = stop - sp;
878 else
879 size = sp - stop;
880 PyErr_Format(PyExc_RuntimeError,
881 "unable to raise a stack overflow (allocated %zu bytes "
882 "on the stack, %zu recursive calls)",
883 size, depth);
884 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200885}
886#endif
887
888
889static int
890faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
891{
892#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200893 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200894#endif
895
896#ifdef FAULTHANDLER_LATER
897 Py_VISIT(thread.file);
898#endif
899#ifdef FAULTHANDLER_USER
900 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200901 for (signum=0; signum < NSIG; signum++)
902 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200903 }
904#endif
905 Py_VISIT(fatal_error.file);
906 return 0;
907}
908
909PyDoc_STRVAR(module_doc,
910"faulthandler module.");
911
912static PyMethodDef module_methods[] = {
913 {"enable",
914 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
915 PyDoc_STR("enable(file=sys.stderr, all_threads=False): "
916 "enable the fault handler")},
917 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
918 PyDoc_STR("disable(): disable the fault handler")},
919 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
920 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
921 {"dump_traceback",
922 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
923 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=False): "
924 "dump the traceback of the current thread, or of all threads "
925 "if all_threads is True, into file")},
926#ifdef FAULTHANDLER_LATER
927 {"dump_tracebacks_later",
Victor Stinner96994402011-04-07 11:37:19 +0200928 (PyCFunction)faulthandler_dump_tracebacks_later, METH_VARARGS|METH_KEYWORDS,
929 PyDoc_STR("dump_tracebacks_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +0200930 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +0200931 "or each timeout seconds if repeat is True. If exit is True, "
932 "call _exit(1) which is not safe.")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200933 {"cancel_dump_tracebacks_later",
Victor Stinner702624e2011-03-31 03:42:34 +0200934 (PyCFunction)faulthandler_cancel_dump_tracebacks_later_py, METH_NOARGS,
Victor Stinner024e37a2011-03-31 01:31:06 +0200935 PyDoc_STR("cancel_dump_tracebacks_later():\ncancel the previous call "
936 "to dump_tracebacks_later().")},
937#endif
938
939#ifdef FAULTHANDLER_USER
940 {"register",
941 (PyCFunction)faulthandler_register, METH_VARARGS|METH_KEYWORDS,
942 PyDoc_STR("register(signum, file=sys.stderr, all_threads=False): "
943 "register an handler for the signal 'signum': dump the "
944 "traceback of the current thread, or of all threads if "
945 "all_threads is True, into file")},
946 {"unregister",
947 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
948 PyDoc_STR("unregister(signum): unregister the handler of the signal "
949 "'signum' registered by register()")},
950#endif
951
952 {"_read_null", faulthandler_read_null, METH_VARARGS,
953 PyDoc_STR("_read_null(release_gil=False): read from NULL, raise "
954 "a SIGSEGV or SIGBUS signal depending on the platform")},
955 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
956 PyDoc_STR("_sigsegv(): raise a SIGSEGV signal")},
Victor Stinnerd727e232011-04-01 12:13:55 +0200957 {"_sigabrt", faulthandler_sigabrt, METH_VARARGS,
958 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200959 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
960 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
961#ifdef SIGBUS
962 {"_sigbus", (PyCFunction)faulthandler_sigbus, METH_NOARGS,
963 PyDoc_STR("_sigbus(): raise a SIGBUS signal")},
964#endif
965#ifdef SIGILL
966 {"_sigill", (PyCFunction)faulthandler_sigill, METH_NOARGS,
967 PyDoc_STR("_sigill(): raise a SIGILL signal")},
968#endif
969 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
970 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
971#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
972 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
973 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
974#endif
975 {NULL, NULL} /* terminator */
976};
977
978static struct PyModuleDef module_def = {
979 PyModuleDef_HEAD_INIT,
980 "faulthandler",
981 module_doc,
982 0, /* non negative size to be able to unload the module */
983 module_methods,
984 NULL,
985 faulthandler_traverse,
986 NULL,
987 NULL
988};
989
990PyMODINIT_FUNC
991PyInit_faulthandler(void)
992{
993 return PyModule_Create(&module_def);
994}
995
996/* Call faulthandler.enable() if PYTHONFAULTHANDLER environment variable is
997 defined, or if sys._xoptions has a 'faulthandler' key. */
998
999static int
1000faulthandler_env_options(void)
1001{
1002 PyObject *xoptions, *key, *module, *res;
1003 int enable;
1004
1005 if (!Py_GETENV("PYTHONFAULTHANDLER")) {
1006 xoptions = PySys_GetXOptions();
1007 if (xoptions == NULL)
1008 return -1;
1009
1010 key = PyUnicode_FromString("faulthandler");
1011 if (key == NULL)
1012 return -1;
1013
1014 enable = PyDict_Contains(xoptions, key);
1015 Py_DECREF(key);
1016 if (!enable)
1017 return 0;
1018 }
1019 else
1020 enable = 1;
1021
1022 module = PyImport_ImportModule("faulthandler");
1023 if (module == NULL) {
1024 return -1;
1025 }
1026 res = PyObject_CallMethod(module, "enable", "");
1027 Py_DECREF(module);
1028 if (res == NULL)
1029 return -1;
1030 Py_DECREF(res);
1031 return 0;
1032}
1033
1034int _PyFaulthandler_Init(void)
1035{
1036#ifdef HAVE_SIGALTSTACK
1037 int err;
1038
1039 /* Try to allocate an alternate stack for faulthandler() signal handler to
1040 * be able to allocate memory on the stack, even on a stack overflow. If it
1041 * fails, ignore the error. */
1042 stack.ss_flags = 0;
1043 stack.ss_size = SIGSTKSZ;
1044 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1045 if (stack.ss_sp != NULL) {
1046 err = sigaltstack(&stack, NULL);
1047 if (err) {
1048 PyMem_Free(stack.ss_sp);
1049 stack.ss_sp = NULL;
1050 }
1051 }
1052#endif
1053#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001054 thread.file = NULL;
1055 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001056 thread.running = PyThread_allocate_lock();
1057 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001058 PyErr_SetString(PyExc_RuntimeError,
1059 "could not allocate locks for faulthandler");
1060 return -1;
1061 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001062 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001063#endif
1064
1065 return faulthandler_env_options();
1066}
1067
1068void _PyFaulthandler_Fini(void)
1069{
1070#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001071 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001072#endif
1073
1074#ifdef FAULTHANDLER_LATER
1075 /* later */
Victor Stinnerde10f402011-04-08 12:57:06 +02001076 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +02001077 if (thread.cancel_event) {
Victor Stinnerde10f402011-04-08 12:57:06 +02001078 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001079 PyThread_free_lock(thread.cancel_event);
1080 thread.cancel_event = NULL;
1081 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001082 if (thread.running) {
1083 PyThread_free_lock(thread.running);
1084 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001085 }
1086#endif
1087
1088#ifdef FAULTHANDLER_USER
1089 /* user */
1090 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001091 for (signum=0; signum < NSIG; signum++)
1092 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner024e37a2011-03-31 01:31:06 +02001093 free(user_signals);
1094 user_signals = NULL;
1095 }
1096#endif
1097
1098 /* fatal */
1099 faulthandler_disable();
1100#ifdef HAVE_SIGALTSTACK
1101 if (stack.ss_sp != NULL) {
1102 PyMem_Free(stack.ss_sp);
1103 stack.ss_sp = NULL;
1104 }
1105#endif
1106}