blob: abedd5b0c256d906eea373b7d33ba0a3ec7e1f15 [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 Stinnerda9edae2011-04-04 11:05:21 +0200421#ifdef HAVE_PTHREAD_H
422 sigset_t set;
423
424 /* we don't want to receive any signal */
425 sigfillset(&set);
426#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
427 pthread_sigmask(SIG_SETMASK, &set, NULL);
428#else
429 sigprocmask(SIG_SETMASK, &set, NULL);
430#endif
431#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200432
433 do {
434 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200435 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200436 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200437 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200438 break;
439 }
440 /* Timeout => dump traceback */
441 assert(st == PY_LOCK_FAILURE);
442
443 /* get the thread holding the GIL, NULL if no thread hold the GIL */
444 current = _Py_atomic_load_relaxed(&_PyThreadState_Current);
445
Victor Stinnerc790a532011-04-08 13:39:59 +0200446 write(thread.fd, thread.header, thread.header_len);
447
Victor Stinner024e37a2011-03-31 01:31:06 +0200448 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
449 ok = (errmsg == NULL);
450
451 if (thread.exit)
452 _exit(1);
453 } while (ok && thread.repeat);
454
455 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200456 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200457}
458
459static void
Victor Stinnerde10f402011-04-08 12:57:06 +0200460cancel_dump_tracebacks_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200461{
Victor Stinnerde10f402011-04-08 12:57:06 +0200462 /* notify cancellation */
463 PyThread_release_lock(thread.cancel_event);
464
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200465 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200466 PyThread_acquire_lock(thread.running, 1);
467 PyThread_release_lock(thread.running);
468
469 /* The main thread should always hold the cancel_event lock */
470 PyThread_acquire_lock(thread.cancel_event, 1);
471
Victor Stinner024e37a2011-03-31 01:31:06 +0200472 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200473 if (thread.header) {
474 free(thread.header);
475 thread.header = NULL;
476 }
477}
478
479static char*
480format_timeout(double timeout)
481{
482 unsigned long us, sec, min, hour;
483 double intpart, fracpart;
484 char buffer[100];
485
486 fracpart = modf(timeout, &intpart);
487 sec = (unsigned long)intpart;
488 us = (unsigned long)(fracpart * 1e6);
489 min = sec / 60;
490 sec %= 60;
491 hour = min / 60;
492 min %= 60;
493
494 if (us != 0)
495 PyOS_snprintf(buffer, sizeof(buffer),
496 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
497 hour, min, sec, us);
498 else
499 PyOS_snprintf(buffer, sizeof(buffer),
500 "Timeout (%lu:%02lu:%02lu)!\n",
501 hour, min, sec);
502
503 return strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200504}
505
506static PyObject*
Victor Stinner96994402011-04-07 11:37:19 +0200507faulthandler_dump_tracebacks_later(PyObject *self,
508 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200509{
510 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
511 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200512 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200513 int repeat = 0;
514 PyObject *file = NULL;
515 int fd;
516 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200517 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200518 char *header;
519 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200520
521 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
522 "d|iOi:dump_tracebacks_later", kwlist,
523 &timeout, &repeat, &file, &exit))
524 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200525 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200526 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
527 return NULL;
528 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200529 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200530 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200531 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
532 return NULL;
533 }
534
Victor Stinnera4de6d82011-04-09 00:47:23 +0200535 tstate = get_thread_state();
536 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200537 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200538
Victor Stinner024e37a2011-03-31 01:31:06 +0200539 file = faulthandler_get_fileno(file, &fd);
540 if (file == NULL)
541 return NULL;
542
Victor Stinnerc790a532011-04-08 13:39:59 +0200543 /* format the timeout */
544 header = format_timeout(timeout);
545 if (header == NULL)
546 return PyErr_NoMemory();
547 header_len = strlen(header);
548
Victor Stinner024e37a2011-03-31 01:31:06 +0200549 /* Cancel previous thread, if running */
Victor Stinnerde10f402011-04-08 12:57:06 +0200550 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200551
552 Py_XDECREF(thread.file);
553 Py_INCREF(file);
554 thread.file = file;
555 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200556 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200557 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200558 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200559 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200560 thread.header = header;
561 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200562
563 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200564 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200565
Victor Stinner024e37a2011-03-31 01:31:06 +0200566 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200567 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200568 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200569 free(header);
570 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200571 PyErr_SetString(PyExc_RuntimeError,
572 "unable to start watchdog thread");
573 return NULL;
574 }
575
576 Py_RETURN_NONE;
577}
578
579static PyObject*
Victor Stinner702624e2011-03-31 03:42:34 +0200580faulthandler_cancel_dump_tracebacks_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200581{
Victor Stinnerde10f402011-04-08 12:57:06 +0200582 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200583 Py_RETURN_NONE;
584}
585#endif /* FAULTHANDLER_LATER */
586
587#ifdef FAULTHANDLER_USER
588/* Handler of user signals (e.g. SIGUSR1).
589
590 Dump the traceback of the current thread, or of all threads if
591 thread.all_threads is true.
592
593 This function is signal safe and should only call signal safe functions. */
594
595static void
596faulthandler_user(int signum)
597{
598 user_signal_t *user;
599 PyThreadState *tstate;
600
601 user = &user_signals[signum];
602 if (!user->enabled)
603 return;
604
Victor Stinnerff4cd882011-04-07 11:50:25 +0200605#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200606 /* PyThreadState_Get() doesn't give the state of the current thread if
607 the thread doesn't hold the GIL. Read the thread local storage (TLS)
608 instead: call PyGILState_GetThisThreadState(). */
609 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200610#else
611 tstate = PyThreadState_Get();
612#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200613
614 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200615 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
616 else {
617 if (tstate == NULL)
618 return;
Victor Stinner024e37a2011-03-31 01:31:06 +0200619 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200620 }
621}
622
623static int
624check_signum(int signum)
625{
626 unsigned int i;
627
628 for (i=0; i < faulthandler_nsignals; i++) {
629 if (faulthandler_handlers[i].signum == signum) {
630 PyErr_Format(PyExc_RuntimeError,
631 "signal %i cannot be registered, "
632 "use enable() instead",
633 signum);
634 return 0;
635 }
636 }
637 if (signum < 1 || NSIG <= signum) {
638 PyErr_SetString(PyExc_ValueError, "signal number out of range");
639 return 0;
640 }
641 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200642}
643
644static PyObject*
645faulthandler_register(PyObject *self,
646 PyObject *args, PyObject *kwargs)
647{
648 static char *kwlist[] = {"signum", "file", "all_threads", NULL};
649 int signum;
650 PyObject *file = NULL;
651 int all_threads = 0;
652 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200653 user_signal_t *user;
654 _Py_sighandler_t previous;
655#ifdef HAVE_SIGACTION
656 struct sigaction action;
657#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200658 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200659 int err;
660
661 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
662 "i|Oi:register", kwlist,
663 &signum, &file, &all_threads))
664 return NULL;
665
Victor Stinner44378d42011-04-01 15:37:12 +0200666 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200667 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200668
Victor Stinnera4de6d82011-04-09 00:47:23 +0200669 tstate = get_thread_state();
670 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200671 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200672
673 file = faulthandler_get_fileno(file, &fd);
674 if (file == NULL)
675 return NULL;
676
677 if (user_signals == NULL) {
678 user_signals = calloc(NSIG, sizeof(user_signal_t));
679 if (user_signals == NULL)
680 return PyErr_NoMemory();
681 }
682 user = &user_signals[signum];
683
684 if (!user->enabled) {
685#ifdef HAVE_SIGACTION
686 action.sa_handler = faulthandler_user;
687 sigemptyset(&action.sa_mask);
688 /* if the signal is received while the kernel is executing a system
689 call, try to restart the system call instead of interrupting it and
690 return EINTR */
691 action.sa_flags = SA_RESTART;
692#ifdef HAVE_SIGALTSTACK
693 if (stack.ss_sp != NULL) {
694 /* Call the signal handler on an alternate signal stack
695 provided by sigaltstack() */
696 action.sa_flags |= SA_ONSTACK;
697 }
698#endif
699 err = sigaction(signum, &action, &previous);
700#else
701 previous = signal(signum, faulthandler_user);
702 err = (previous == SIG_ERR);
703#endif
704 if (err) {
705 PyErr_SetFromErrno(PyExc_OSError);
706 return NULL;
707 }
708 }
709
710 Py_XDECREF(user->file);
711 Py_INCREF(file);
712 user->file = file;
713 user->fd = fd;
714 user->all_threads = all_threads;
715 user->previous = previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200716 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200717 user->enabled = 1;
718
719 Py_RETURN_NONE;
720}
721
722static int
723faulthandler_unregister(user_signal_t *user, int signum)
724{
Victor Stinnera01ca122011-04-01 12:56:17 +0200725 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200726 return 0;
727 user->enabled = 0;
728#ifdef HAVE_SIGACTION
729 (void)sigaction(signum, &user->previous, NULL);
730#else
731 (void)signal(signum, user->previous);
732#endif
733 Py_CLEAR(user->file);
734 user->fd = -1;
735 return 1;
736}
737
738static PyObject*
739faulthandler_unregister_py(PyObject *self, PyObject *args)
740{
741 int signum;
742 user_signal_t *user;
743 int change;
744
745 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
746 return NULL;
747
Victor Stinner44378d42011-04-01 15:37:12 +0200748 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200749 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200750
Victor Stinnercfa71232011-04-08 12:48:15 +0200751 if (user_signals == NULL)
752 Py_RETURN_FALSE;
753
Victor Stinner024e37a2011-03-31 01:31:06 +0200754 user = &user_signals[signum];
755 change = faulthandler_unregister(user, signum);
756 return PyBool_FromLong(change);
757}
758#endif /* FAULTHANDLER_USER */
759
760
761static PyObject *
762faulthandler_read_null(PyObject *self, PyObject *args)
763{
764 int *x = NULL, y;
765 int release_gil = 0;
766 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
767 return NULL;
768 if (release_gil) {
769 Py_BEGIN_ALLOW_THREADS
770 y = *x;
771 Py_END_ALLOW_THREADS
772 } else
773 y = *x;
774 return PyLong_FromLong(y);
775
776}
777
778static PyObject *
779faulthandler_sigsegv(PyObject *self, PyObject *args)
780{
781#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200782 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
783 handler and then gives back the execution flow to the program (without
784 calling explicitly the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200785 SIGSEGV was raised by the kernel because of a fault, and so if the
786 program retries to execute the same instruction, the fault will be
787 raised again.
788
789 Here the fault is simulated by a fake SIGSEGV signal raised by the
790 application. We have to raise SIGSEGV at lease twice: once for
791 faulthandler_fatal_error(), and one more time for the previous signal
792 handler. */
793 while(1)
794 raise(SIGSEGV);
795#else
796 raise(SIGSEGV);
797#endif
798 Py_RETURN_NONE;
799}
800
801static PyObject *
802faulthandler_sigfpe(PyObject *self, PyObject *args)
803{
804 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
805 PowerPC. Use volatile to disable compile-time optimizations. */
806 volatile int x = 1, y = 0, z;
807 z = x / y;
808 /* if the division by zero didn't raise a SIGFPE, raise it manually */
809 raise(SIGFPE);
810 Py_RETURN_NONE;
811}
812
Victor Stinnerd727e232011-04-01 12:13:55 +0200813static PyObject *
814faulthandler_sigabrt(PyObject *self, PyObject *args)
815{
816#if _MSC_VER
817 /* If Python is compiled in debug mode with Visual Studio, abort() opens
818 a popup asking the user how to handle the assertion. Use raise(SIGABRT)
819 instead. */
820 raise(SIGABRT);
821#else
822 abort();
823#endif
824 Py_RETURN_NONE;
825}
826
Victor Stinner024e37a2011-03-31 01:31:06 +0200827#ifdef SIGBUS
828static PyObject *
829faulthandler_sigbus(PyObject *self, PyObject *args)
830{
831 raise(SIGBUS);
832 Py_RETURN_NONE;
833}
834#endif
835
836#ifdef SIGILL
837static PyObject *
838faulthandler_sigill(PyObject *self, PyObject *args)
839{
Victor Stinner024e37a2011-03-31 01:31:06 +0200840 raise(SIGILL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200841 Py_RETURN_NONE;
842}
843#endif
844
845static PyObject *
846faulthandler_fatal_error_py(PyObject *self, PyObject *args)
847{
848 char *message;
849 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
850 return NULL;
851 Py_FatalError(message);
852 Py_RETURN_NONE;
853}
854
855#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinnerf0480752011-03-31 11:34:08 +0200856void*
857stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200858{
859 /* allocate 4096 bytes on the stack at each call */
860 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200861 void *sp = &buffer;
862 *depth += 1;
863 if (sp < min_sp || max_sp < sp)
864 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200865 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200866 buffer[4095] = 0;
867 return stack_overflow(min_sp, max_sp, depth);
868}
869
870static PyObject *
871faulthandler_stack_overflow(PyObject *self)
872{
873 size_t depth, size;
874 void *sp = &depth, *stop;
875
876 depth = 0;
877 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
878 sp + STACK_OVERFLOW_MAX_SIZE,
879 &depth);
880 if (sp < stop)
881 size = stop - sp;
882 else
883 size = sp - stop;
884 PyErr_Format(PyExc_RuntimeError,
885 "unable to raise a stack overflow (allocated %zu bytes "
886 "on the stack, %zu recursive calls)",
887 size, depth);
888 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200889}
890#endif
891
892
893static int
894faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
895{
896#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200897 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200898#endif
899
900#ifdef FAULTHANDLER_LATER
901 Py_VISIT(thread.file);
902#endif
903#ifdef FAULTHANDLER_USER
904 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200905 for (signum=0; signum < NSIG; signum++)
906 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200907 }
908#endif
909 Py_VISIT(fatal_error.file);
910 return 0;
911}
912
913PyDoc_STRVAR(module_doc,
914"faulthandler module.");
915
916static PyMethodDef module_methods[] = {
917 {"enable",
918 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
919 PyDoc_STR("enable(file=sys.stderr, all_threads=False): "
920 "enable the fault handler")},
921 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
922 PyDoc_STR("disable(): disable the fault handler")},
923 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
924 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
925 {"dump_traceback",
926 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
927 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=False): "
928 "dump the traceback of the current thread, or of all threads "
929 "if all_threads is True, into file")},
930#ifdef FAULTHANDLER_LATER
931 {"dump_tracebacks_later",
Victor Stinner96994402011-04-07 11:37:19 +0200932 (PyCFunction)faulthandler_dump_tracebacks_later, METH_VARARGS|METH_KEYWORDS,
933 PyDoc_STR("dump_tracebacks_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +0200934 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +0200935 "or each timeout seconds if repeat is True. If exit is True, "
936 "call _exit(1) which is not safe.")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200937 {"cancel_dump_tracebacks_later",
Victor Stinner702624e2011-03-31 03:42:34 +0200938 (PyCFunction)faulthandler_cancel_dump_tracebacks_later_py, METH_NOARGS,
Victor Stinner024e37a2011-03-31 01:31:06 +0200939 PyDoc_STR("cancel_dump_tracebacks_later():\ncancel the previous call "
940 "to dump_tracebacks_later().")},
941#endif
942
943#ifdef FAULTHANDLER_USER
944 {"register",
945 (PyCFunction)faulthandler_register, METH_VARARGS|METH_KEYWORDS,
946 PyDoc_STR("register(signum, file=sys.stderr, all_threads=False): "
947 "register an handler for the signal 'signum': dump the "
948 "traceback of the current thread, or of all threads if "
949 "all_threads is True, into file")},
950 {"unregister",
951 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
952 PyDoc_STR("unregister(signum): unregister the handler of the signal "
953 "'signum' registered by register()")},
954#endif
955
956 {"_read_null", faulthandler_read_null, METH_VARARGS,
957 PyDoc_STR("_read_null(release_gil=False): read from NULL, raise "
958 "a SIGSEGV or SIGBUS signal depending on the platform")},
959 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
960 PyDoc_STR("_sigsegv(): raise a SIGSEGV signal")},
Victor Stinnerd727e232011-04-01 12:13:55 +0200961 {"_sigabrt", faulthandler_sigabrt, METH_VARARGS,
962 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200963 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
964 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
965#ifdef SIGBUS
966 {"_sigbus", (PyCFunction)faulthandler_sigbus, METH_NOARGS,
967 PyDoc_STR("_sigbus(): raise a SIGBUS signal")},
968#endif
969#ifdef SIGILL
970 {"_sigill", (PyCFunction)faulthandler_sigill, METH_NOARGS,
971 PyDoc_STR("_sigill(): raise a SIGILL signal")},
972#endif
973 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
974 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
975#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
976 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
977 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
978#endif
979 {NULL, NULL} /* terminator */
980};
981
982static struct PyModuleDef module_def = {
983 PyModuleDef_HEAD_INIT,
984 "faulthandler",
985 module_doc,
986 0, /* non negative size to be able to unload the module */
987 module_methods,
988 NULL,
989 faulthandler_traverse,
990 NULL,
991 NULL
992};
993
994PyMODINIT_FUNC
995PyInit_faulthandler(void)
996{
997 return PyModule_Create(&module_def);
998}
999
1000/* Call faulthandler.enable() if PYTHONFAULTHANDLER environment variable is
1001 defined, or if sys._xoptions has a 'faulthandler' key. */
1002
1003static int
1004faulthandler_env_options(void)
1005{
1006 PyObject *xoptions, *key, *module, *res;
1007 int enable;
1008
1009 if (!Py_GETENV("PYTHONFAULTHANDLER")) {
1010 xoptions = PySys_GetXOptions();
1011 if (xoptions == NULL)
1012 return -1;
1013
1014 key = PyUnicode_FromString("faulthandler");
1015 if (key == NULL)
1016 return -1;
1017
1018 enable = PyDict_Contains(xoptions, key);
1019 Py_DECREF(key);
1020 if (!enable)
1021 return 0;
1022 }
1023 else
1024 enable = 1;
1025
1026 module = PyImport_ImportModule("faulthandler");
1027 if (module == NULL) {
1028 return -1;
1029 }
1030 res = PyObject_CallMethod(module, "enable", "");
1031 Py_DECREF(module);
1032 if (res == NULL)
1033 return -1;
1034 Py_DECREF(res);
1035 return 0;
1036}
1037
1038int _PyFaulthandler_Init(void)
1039{
1040#ifdef HAVE_SIGALTSTACK
1041 int err;
1042
1043 /* Try to allocate an alternate stack for faulthandler() signal handler to
1044 * be able to allocate memory on the stack, even on a stack overflow. If it
1045 * fails, ignore the error. */
1046 stack.ss_flags = 0;
1047 stack.ss_size = SIGSTKSZ;
1048 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1049 if (stack.ss_sp != NULL) {
1050 err = sigaltstack(&stack, NULL);
1051 if (err) {
1052 PyMem_Free(stack.ss_sp);
1053 stack.ss_sp = NULL;
1054 }
1055 }
1056#endif
1057#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001058 thread.file = NULL;
1059 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001060 thread.running = PyThread_allocate_lock();
1061 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001062 PyErr_SetString(PyExc_RuntimeError,
1063 "could not allocate locks for faulthandler");
1064 return -1;
1065 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001066 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001067#endif
1068
1069 return faulthandler_env_options();
1070}
1071
1072void _PyFaulthandler_Fini(void)
1073{
1074#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001075 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001076#endif
1077
1078#ifdef FAULTHANDLER_LATER
1079 /* later */
Victor Stinnerde10f402011-04-08 12:57:06 +02001080 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +02001081 if (thread.cancel_event) {
Victor Stinnerde10f402011-04-08 12:57:06 +02001082 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001083 PyThread_free_lock(thread.cancel_event);
1084 thread.cancel_event = NULL;
1085 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001086 if (thread.running) {
1087 PyThread_free_lock(thread.running);
1088 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001089 }
1090#endif
1091
1092#ifdef FAULTHANDLER_USER
1093 /* user */
1094 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001095 for (signum=0; signum < NSIG; signum++)
1096 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner024e37a2011-03-31 01:31:06 +02001097 free(user_signals);
1098 user_signals = NULL;
1099 }
1100#endif
1101
1102 /* fatal */
1103 faulthandler_disable();
1104#ifdef HAVE_SIGALTSTACK
1105 if (stack.ss_sp != NULL) {
1106 PyMem_Free(stack.ss_sp);
1107 stack.ss_sp = NULL;
1108 }
1109#endif
1110}