blob: 6e8fbf78fde67325e46e4ff524b81c93adb6df96 [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)
8#include <pthread.h>
9#endif
10
Victor Stinner96994402011-04-07 11:37:19 +020011/* Allocate at maximum 100 MB of the stack to raise the stack overflow */
12#define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)
13
Victor Stinner024e37a2011-03-31 01:31:06 +020014#ifdef WITH_THREAD
15# define FAULTHANDLER_LATER
16#endif
17
18#ifndef MS_WINDOWS
Victor Stinnerd727e232011-04-01 12:13:55 +020019 /* register() is useless on Windows, because only SIGSEGV, SIGABRT and
20 SIGILL can be handled by the process, and these signals can only be used
21 with enable(), not using register() */
Victor Stinner024e37a2011-03-31 01:31:06 +020022# define FAULTHANDLER_USER
23#endif
24
25#define PUTS(fd, str) write(fd, str, strlen(str))
26
27#ifdef HAVE_SIGACTION
28typedef struct sigaction _Py_sighandler_t;
29#else
30typedef PyOS_sighandler_t _Py_sighandler_t;
31#endif
32
33typedef struct {
34 int signum;
35 int enabled;
36 const char* name;
37 _Py_sighandler_t previous;
38 int all_threads;
39} fault_handler_t;
40
41static struct {
42 int enabled;
43 PyObject *file;
44 int fd;
45 int all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +020046 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020047} fatal_error = {0, NULL, -1, 0};
48
49#ifdef FAULTHANDLER_LATER
50static struct {
51 PyObject *file;
52 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020053 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020054 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020055 PyInterpreterState *interp;
56 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020057 char *header;
58 size_t header_len;
Victor Stinner410dd7d2011-05-11 20:56:08 +020059 /* The main thread always holds this lock. It is only released when
60 faulthandler_thread() is interrupted before this thread exits, or at
Victor Stinnerde10f402011-04-08 12:57:06 +020061 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020062 PyThread_type_lock cancel_event;
63 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020064 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020065} thread;
66#endif
67
68#ifdef FAULTHANDLER_USER
69typedef struct {
70 int enabled;
71 PyObject *file;
72 int fd;
73 int all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +020074 int chain;
Victor Stinner024e37a2011-03-31 01:31:06 +020075 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020076 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020077} user_signal_t;
78
79static user_signal_t *user_signals;
80
81/* the following macros come from Python: Modules/signalmodule.c */
82#if defined(PYOS_OS2) && !defined(PYCC_GCC)
83#define NSIG 12
84#endif
85#ifndef NSIG
86# if defined(_NSIG)
87# define NSIG _NSIG /* For BSD/SysV */
88# elif defined(_SIGMAX)
89# define NSIG (_SIGMAX + 1) /* For QNX */
90# elif defined(SIGMAX)
91# define NSIG (SIGMAX + 1) /* For djgpp */
92# else
93# define NSIG 64 /* Use a reasonable default value */
94# endif
95#endif
96
Victor Stinnera9a9dab2011-07-13 23:39:53 +020097static void faulthandler_user(int signum);
Victor Stinner024e37a2011-03-31 01:31:06 +020098#endif /* FAULTHANDLER_USER */
99
100
101static fault_handler_t faulthandler_handlers[] = {
102#ifdef SIGBUS
103 {SIGBUS, 0, "Bus error", },
104#endif
105#ifdef SIGILL
106 {SIGILL, 0, "Illegal instruction", },
107#endif
108 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200109 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200110 /* define SIGSEGV at the end to make it the default choice if searching the
111 handler fails in faulthandler_fatal_error() */
112 {SIGSEGV, 0, "Segmentation fault", }
113};
114static const unsigned char faulthandler_nsignals = \
Victor Stinner63941882011-09-29 00:42:28 +0200115 Py_ARRAY_LENGTH(faulthandler_handlers);
Victor Stinner024e37a2011-03-31 01:31:06 +0200116
117#ifdef HAVE_SIGALTSTACK
118static stack_t stack;
119#endif
120
121
122/* Get the file descriptor of a file by calling its fileno() method and then
123 call its flush() method.
124
125 If file is NULL or Py_None, use sys.stderr as the new file.
126
127 On success, return the new file and write the file descriptor into *p_fd.
128 On error, return NULL. */
129
130static PyObject*
131faulthandler_get_fileno(PyObject *file, int *p_fd)
132{
133 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200134 _Py_IDENTIFIER(fileno);
135 _Py_IDENTIFIER(flush);
Victor Stinner024e37a2011-03-31 01:31:06 +0200136 long fd_long;
137 int fd;
138
139 if (file == NULL || file == Py_None) {
140 file = PySys_GetObject("stderr");
141 if (file == NULL) {
142 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
143 return NULL;
144 }
145 }
146
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200147 result = _PyObject_CallMethodId(file, &PyId_fileno, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200148 if (result == NULL)
149 return NULL;
150
151 fd = -1;
152 if (PyLong_Check(result)) {
153 fd_long = PyLong_AsLong(result);
154 if (0 <= fd_long && fd_long < INT_MAX)
155 fd = (int)fd_long;
156 }
157 Py_DECREF(result);
158
159 if (fd == -1) {
160 PyErr_SetString(PyExc_RuntimeError,
161 "file.fileno() is not a valid file descriptor");
162 return NULL;
163 }
164
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200165 result = _PyObject_CallMethodId(file, &PyId_flush, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200166 if (result != NULL)
167 Py_DECREF(result);
168 else {
169 /* ignore flush() error */
170 PyErr_Clear();
171 }
172 *p_fd = fd;
173 return file;
174}
175
Victor Stinnera4de6d82011-04-09 00:47:23 +0200176/* Get the state of the current thread: only call this function if the current
177 thread holds the GIL. Raise an exception on error. */
178static PyThreadState*
179get_thread_state(void)
180{
181 PyThreadState *tstate = PyThreadState_Get();
182 if (tstate == NULL) {
183 PyErr_SetString(PyExc_RuntimeError,
184 "unable to get the current thread state");
185 return NULL;
186 }
187 return tstate;
188}
189
Victor Stinner024e37a2011-03-31 01:31:06 +0200190static PyObject*
191faulthandler_dump_traceback_py(PyObject *self,
192 PyObject *args, PyObject *kwargs)
193{
194 static char *kwlist[] = {"file", "all_threads", NULL};
195 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200196 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200197 PyThreadState *tstate;
198 const char *errmsg;
199 int fd;
200
201 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
202 "|Oi:dump_traceback", kwlist,
203 &file, &all_threads))
204 return NULL;
205
206 file = faulthandler_get_fileno(file, &fd);
207 if (file == NULL)
208 return NULL;
209
Victor Stinnera4de6d82011-04-09 00:47:23 +0200210 tstate = get_thread_state();
211 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200212 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200213
214 if (all_threads) {
215 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
216 if (errmsg != NULL) {
217 PyErr_SetString(PyExc_RuntimeError, errmsg);
218 return NULL;
219 }
220 }
221 else {
222 _Py_DumpTraceback(fd, tstate);
223 }
224 Py_RETURN_NONE;
225}
226
227
Victor Stinner410dd7d2011-05-11 20:56:08 +0200228/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200229
230 Display the current Python traceback, restore the previous handler and call
231 the previous handler.
232
Victor Stinner410dd7d2011-05-11 20:56:08 +0200233 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200234 signal handler would not be called (for an unknown reason). The execution of
235 the program continues at faulthandler_fatal_error() exit, but the same
236 instruction will raise the same fault (signal), and so the previous handler
237 will be called.
238
Victor Stinner410dd7d2011-05-11 20:56:08 +0200239 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200240
241static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200242faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200243{
244 const int fd = fatal_error.fd;
245 unsigned int i;
246 fault_handler_t *handler = NULL;
247 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200248 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200249
250 if (!fatal_error.enabled)
251 return;
252
253 for (i=0; i < faulthandler_nsignals; i++) {
254 handler = &faulthandler_handlers[i];
255 if (handler->signum == signum)
256 break;
257 }
258 if (handler == NULL) {
259 /* faulthandler_nsignals == 0 (unlikely) */
260 return;
261 }
262
263 /* restore the previous handler */
264#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200265 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200266#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200267 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200268#endif
269 handler->enabled = 0;
270
271 PUTS(fd, "Fatal Python error: ");
272 PUTS(fd, handler->name);
273 PUTS(fd, "\n\n");
274
Victor Stinnerff4cd882011-04-07 11:50:25 +0200275#ifdef WITH_THREAD
Victor Stinnerd727e232011-04-01 12:13:55 +0200276 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
Victor Stinner410dd7d2011-05-11 20:56:08 +0200277 are thus delivered to the thread that caused the fault. Get the Python
Victor Stinnerd727e232011-04-01 12:13:55 +0200278 thread state of the current thread.
Victor Stinner024e37a2011-03-31 01:31:06 +0200279
280 PyThreadState_Get() doesn't give the state of the thread that caused the
281 fault if the thread released the GIL, and so this function cannot be
282 used. Read the thread local storage (TLS) instead: call
283 PyGILState_GetThisThreadState(). */
284 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200285#else
286 tstate = PyThreadState_Get();
287#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200288
289 if (fatal_error.all_threads)
Victor Stinnera4de6d82011-04-09 00:47:23 +0200290 _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
291 else {
292 if (tstate != NULL)
293 _Py_DumpTraceback(fd, tstate);
294 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200295
Victor Stinnerc9256172011-05-07 12:20:11 +0200296 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200297#ifdef MS_WINDOWS
298 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200299 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200300 handler, because the Windows signal handler would not be called */
301 return;
302 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200303#endif
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200304 /* call the previous signal handler: it is called immediatly if we use
305 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
306 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200307}
308
Victor Stinnerd727e232011-04-01 12:13:55 +0200309/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200310
311static PyObject*
312faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
313{
314 static char *kwlist[] = {"file", "all_threads", NULL};
315 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200316 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200317 unsigned int i;
318 fault_handler_t *handler;
319#ifdef HAVE_SIGACTION
320 struct sigaction action;
321#endif
322 int err;
323 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200324 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200325
326 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
327 "|Oi:enable", kwlist, &file, &all_threads))
328 return NULL;
329
330 file = faulthandler_get_fileno(file, &fd);
331 if (file == NULL)
332 return NULL;
333
Victor Stinnera4de6d82011-04-09 00:47:23 +0200334 tstate = get_thread_state();
335 if (tstate == NULL)
336 return NULL;
337
Victor Stinner024e37a2011-03-31 01:31:06 +0200338 Py_XDECREF(fatal_error.file);
339 Py_INCREF(file);
340 fatal_error.file = file;
341 fatal_error.fd = fd;
342 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200343 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200344
345 if (!fatal_error.enabled) {
346 fatal_error.enabled = 1;
347
348 for (i=0; i < faulthandler_nsignals; i++) {
349 handler = &faulthandler_handlers[i];
350#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200351 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200352 sigemptyset(&action.sa_mask);
353 /* Do not prevent the signal from being received from within
354 its own signal handler */
355 action.sa_flags = SA_NODEFER;
356#ifdef HAVE_SIGALTSTACK
357 if (stack.ss_sp != NULL) {
358 /* Call the signal handler on an alternate signal stack
359 provided by sigaltstack() */
360 action.sa_flags |= SA_ONSTACK;
361 }
362#endif
363 err = sigaction(handler->signum, &action, &handler->previous);
364#else
365 handler->previous = signal(handler->signum,
366 faulthandler_fatal_error);
367 err = (handler->previous == SIG_ERR);
368#endif
369 if (err) {
370 PyErr_SetFromErrno(PyExc_RuntimeError);
371 return NULL;
372 }
373 handler->enabled = 1;
374 }
375 }
376 Py_RETURN_NONE;
377}
378
379static void
380faulthandler_disable(void)
381{
382 unsigned int i;
383 fault_handler_t *handler;
384
385 if (fatal_error.enabled) {
386 fatal_error.enabled = 0;
387 for (i=0; i < faulthandler_nsignals; i++) {
388 handler = &faulthandler_handlers[i];
389 if (!handler->enabled)
390 continue;
391#ifdef HAVE_SIGACTION
392 (void)sigaction(handler->signum, &handler->previous, NULL);
393#else
394 (void)signal(handler->signum, handler->previous);
395#endif
396 handler->enabled = 0;
397 }
398 }
399
400 Py_CLEAR(fatal_error.file);
401}
402
403static PyObject*
404faulthandler_disable_py(PyObject *self)
405{
406 if (!fatal_error.enabled) {
407 Py_INCREF(Py_False);
408 return Py_False;
409 }
410 faulthandler_disable();
411 Py_INCREF(Py_True);
412 return Py_True;
413}
414
415static PyObject*
416faulthandler_is_enabled(PyObject *self)
417{
418 return PyBool_FromLong(fatal_error.enabled);
419}
420
421#ifdef FAULTHANDLER_LATER
422
423static void
424faulthandler_thread(void *unused)
425{
426 PyLockStatus st;
427 const char* errmsg;
428 PyThreadState *current;
429 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200430#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200431 sigset_t set;
432
433 /* we don't want to receive any signal */
434 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200435 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200436#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200437
438 do {
439 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200440 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200441 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200442 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200443 break;
444 }
445 /* Timeout => dump traceback */
446 assert(st == PY_LOCK_FAILURE);
447
448 /* get the thread holding the GIL, NULL if no thread hold the GIL */
449 current = _Py_atomic_load_relaxed(&_PyThreadState_Current);
450
Victor Stinnerc790a532011-04-08 13:39:59 +0200451 write(thread.fd, thread.header, thread.header_len);
452
Victor Stinner024e37a2011-03-31 01:31:06 +0200453 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
454 ok = (errmsg == NULL);
455
456 if (thread.exit)
457 _exit(1);
458 } while (ok && thread.repeat);
459
460 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200461 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200462}
463
464static void
Victor Stinnerde10f402011-04-08 12:57:06 +0200465cancel_dump_tracebacks_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200466{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200467 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200468 PyThread_release_lock(thread.cancel_event);
469
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200470 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200471 PyThread_acquire_lock(thread.running, 1);
472 PyThread_release_lock(thread.running);
473
474 /* The main thread should always hold the cancel_event lock */
475 PyThread_acquire_lock(thread.cancel_event, 1);
476
Victor Stinner024e37a2011-03-31 01:31:06 +0200477 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200478 if (thread.header) {
479 free(thread.header);
480 thread.header = NULL;
481 }
482}
483
484static char*
485format_timeout(double timeout)
486{
487 unsigned long us, sec, min, hour;
488 double intpart, fracpart;
489 char buffer[100];
490
491 fracpart = modf(timeout, &intpart);
492 sec = (unsigned long)intpart;
493 us = (unsigned long)(fracpart * 1e6);
494 min = sec / 60;
495 sec %= 60;
496 hour = min / 60;
497 min %= 60;
498
499 if (us != 0)
500 PyOS_snprintf(buffer, sizeof(buffer),
501 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
502 hour, min, sec, us);
503 else
504 PyOS_snprintf(buffer, sizeof(buffer),
505 "Timeout (%lu:%02lu:%02lu)!\n",
506 hour, min, sec);
507
508 return strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200509}
510
511static PyObject*
Victor Stinner96994402011-04-07 11:37:19 +0200512faulthandler_dump_tracebacks_later(PyObject *self,
513 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200514{
515 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
516 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200517 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200518 int repeat = 0;
519 PyObject *file = NULL;
520 int fd;
521 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200522 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200523 char *header;
524 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200525
526 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
527 "d|iOi:dump_tracebacks_later", kwlist,
528 &timeout, &repeat, &file, &exit))
529 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200530 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200531 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
532 return NULL;
533 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200534 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200535 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200536 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
537 return NULL;
538 }
539
Victor Stinnera4de6d82011-04-09 00:47:23 +0200540 tstate = get_thread_state();
541 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200542 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200543
Victor Stinner024e37a2011-03-31 01:31:06 +0200544 file = faulthandler_get_fileno(file, &fd);
545 if (file == NULL)
546 return NULL;
547
Victor Stinnerc790a532011-04-08 13:39:59 +0200548 /* format the timeout */
549 header = format_timeout(timeout);
550 if (header == NULL)
551 return PyErr_NoMemory();
552 header_len = strlen(header);
553
Victor Stinner024e37a2011-03-31 01:31:06 +0200554 /* Cancel previous thread, if running */
Victor Stinnerde10f402011-04-08 12:57:06 +0200555 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200556
557 Py_XDECREF(thread.file);
558 Py_INCREF(file);
559 thread.file = file;
560 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200561 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200562 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200563 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200564 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200565 thread.header = header;
566 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200567
568 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200569 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200570
Victor Stinner024e37a2011-03-31 01:31:06 +0200571 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200572 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200573 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200574 free(header);
575 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200576 PyErr_SetString(PyExc_RuntimeError,
577 "unable to start watchdog thread");
578 return NULL;
579 }
580
581 Py_RETURN_NONE;
582}
583
584static PyObject*
Victor Stinner702624e2011-03-31 03:42:34 +0200585faulthandler_cancel_dump_tracebacks_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200586{
Victor Stinnerde10f402011-04-08 12:57:06 +0200587 cancel_dump_tracebacks_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200588 Py_RETURN_NONE;
589}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200590#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200591
592#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200593static int
594faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
595{
596#ifdef HAVE_SIGACTION
597 struct sigaction action;
598 action.sa_handler = faulthandler_user;
599 sigemptyset(&action.sa_mask);
600 /* if the signal is received while the kernel is executing a system
601 call, try to restart the system call instead of interrupting it and
602 return EINTR. */
603 action.sa_flags = SA_RESTART;
604 if (chain) {
605 /* do not prevent the signal from being received from within its
606 own signal handler */
607 action.sa_flags = SA_NODEFER;
608 }
609#ifdef HAVE_SIGALTSTACK
610 if (stack.ss_sp != NULL) {
611 /* Call the signal handler on an alternate signal stack
612 provided by sigaltstack() */
613 action.sa_flags |= SA_ONSTACK;
614 }
615#endif
616 return sigaction(signum, &action, p_previous);
617#else
618 _Py_sighandler_t previous;
619 previous = signal(signum, faulthandler_user);
620 if (p_previous != NULL)
621 *p_previous = previous;
622 return (previous == SIG_ERR);
623#endif
624}
625
Victor Stinner024e37a2011-03-31 01:31:06 +0200626/* Handler of user signals (e.g. SIGUSR1).
627
628 Dump the traceback of the current thread, or of all threads if
629 thread.all_threads is true.
630
631 This function is signal safe and should only call signal safe functions. */
632
633static void
634faulthandler_user(int signum)
635{
636 user_signal_t *user;
637 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200638 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200639
640 user = &user_signals[signum];
641 if (!user->enabled)
642 return;
643
Victor Stinnerff4cd882011-04-07 11:50:25 +0200644#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200645 /* PyThreadState_Get() doesn't give the state of the current thread if
646 the thread doesn't hold the GIL. Read the thread local storage (TLS)
647 instead: call PyGILState_GetThisThreadState(). */
648 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200649#else
650 tstate = PyThreadState_Get();
651#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200652
653 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200654 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
655 else {
656 if (tstate == NULL)
657 return;
Victor Stinner024e37a2011-03-31 01:31:06 +0200658 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200659 }
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200660#ifdef HAVE_SIGACTION
661 if (user->chain) {
662 (void)sigaction(signum, &user->previous, NULL);
663 /* call the previous signal handler */
664 raise(signum);
665 (void)faulthandler_register(signum, user->chain, NULL);
666 }
667#else
668 if (user->chain) {
669 /* call the previous signal handler */
670 user->previous(signum);
671 }
672#endif
Victor Stinnerc9256172011-05-07 12:20:11 +0200673 errno = save_errno;
Victor Stinner44378d42011-04-01 15:37:12 +0200674}
675
676static int
677check_signum(int signum)
678{
679 unsigned int i;
680
681 for (i=0; i < faulthandler_nsignals; i++) {
682 if (faulthandler_handlers[i].signum == signum) {
683 PyErr_Format(PyExc_RuntimeError,
684 "signal %i cannot be registered, "
685 "use enable() instead",
686 signum);
687 return 0;
688 }
689 }
690 if (signum < 1 || NSIG <= signum) {
691 PyErr_SetString(PyExc_ValueError, "signal number out of range");
692 return 0;
693 }
694 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200695}
696
697static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200698faulthandler_register_py(PyObject *self,
699 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200700{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200701 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200702 int signum;
703 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200704 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200705 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200706 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200707 user_signal_t *user;
708 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200709 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200710 int err;
711
712 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200713 "i|Oii:register", kwlist,
714 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200715 return NULL;
716
Victor Stinner44378d42011-04-01 15:37:12 +0200717 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200718 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200719
Victor Stinnera4de6d82011-04-09 00:47:23 +0200720 tstate = get_thread_state();
721 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200722 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200723
724 file = faulthandler_get_fileno(file, &fd);
725 if (file == NULL)
726 return NULL;
727
728 if (user_signals == NULL) {
729 user_signals = calloc(NSIG, sizeof(user_signal_t));
730 if (user_signals == NULL)
731 return PyErr_NoMemory();
732 }
733 user = &user_signals[signum];
734
735 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200736 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200737 if (err) {
738 PyErr_SetFromErrno(PyExc_OSError);
739 return NULL;
740 }
741 }
742
743 Py_XDECREF(user->file);
744 Py_INCREF(file);
745 user->file = file;
746 user->fd = fd;
747 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200748 user->chain = chain;
Victor Stinner024e37a2011-03-31 01:31:06 +0200749 user->previous = previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200750 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200751 user->enabled = 1;
752
753 Py_RETURN_NONE;
754}
755
756static int
757faulthandler_unregister(user_signal_t *user, int signum)
758{
Victor Stinnera01ca122011-04-01 12:56:17 +0200759 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200760 return 0;
761 user->enabled = 0;
762#ifdef HAVE_SIGACTION
763 (void)sigaction(signum, &user->previous, NULL);
764#else
765 (void)signal(signum, user->previous);
766#endif
767 Py_CLEAR(user->file);
768 user->fd = -1;
769 return 1;
770}
771
772static PyObject*
773faulthandler_unregister_py(PyObject *self, PyObject *args)
774{
775 int signum;
776 user_signal_t *user;
777 int change;
778
779 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
780 return NULL;
781
Victor Stinner44378d42011-04-01 15:37:12 +0200782 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200783 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200784
Victor Stinnercfa71232011-04-08 12:48:15 +0200785 if (user_signals == NULL)
786 Py_RETURN_FALSE;
787
Victor Stinner024e37a2011-03-31 01:31:06 +0200788 user = &user_signals[signum];
789 change = faulthandler_unregister(user, signum);
790 return PyBool_FromLong(change);
791}
792#endif /* FAULTHANDLER_USER */
793
794
795static PyObject *
796faulthandler_read_null(PyObject *self, PyObject *args)
797{
Victor Stinnera2477202012-01-30 00:07:43 +0100798 volatile int *x;
799 volatile int y;
Victor Stinner024e37a2011-03-31 01:31:06 +0200800 int release_gil = 0;
801 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
802 return NULL;
Victor Stinnera2477202012-01-30 00:07:43 +0100803
804 x = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200805 if (release_gil) {
806 Py_BEGIN_ALLOW_THREADS
807 y = *x;
808 Py_END_ALLOW_THREADS
809 } else
810 y = *x;
811 return PyLong_FromLong(y);
812
813}
814
815static PyObject *
816faulthandler_sigsegv(PyObject *self, PyObject *args)
817{
818#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200819 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
820 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200821 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200822 SIGSEGV was raised by the kernel because of a fault, and so if the
823 program retries to execute the same instruction, the fault will be
824 raised again.
825
826 Here the fault is simulated by a fake SIGSEGV signal raised by the
827 application. We have to raise SIGSEGV at lease twice: once for
828 faulthandler_fatal_error(), and one more time for the previous signal
829 handler. */
830 while(1)
831 raise(SIGSEGV);
832#else
833 raise(SIGSEGV);
834#endif
835 Py_RETURN_NONE;
836}
837
838static PyObject *
839faulthandler_sigfpe(PyObject *self, PyObject *args)
840{
841 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
842 PowerPC. Use volatile to disable compile-time optimizations. */
843 volatile int x = 1, y = 0, z;
844 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200845 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
846 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200847 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200848 /* This line is never reached, but we pretend to make something with z
849 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200850 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200851}
852
Victor Stinnerd727e232011-04-01 12:13:55 +0200853static PyObject *
854faulthandler_sigabrt(PyObject *self, PyObject *args)
855{
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200856#ifdef _MSC_VER
857 /* Visual Studio: configure abort() to not display an error message nor
858 open a popup asking to report the fault. */
859 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
Victor Stinnerd727e232011-04-01 12:13:55 +0200860#endif
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200861 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200862 Py_RETURN_NONE;
863}
864
Victor Stinner024e37a2011-03-31 01:31:06 +0200865#ifdef SIGBUS
866static PyObject *
867faulthandler_sigbus(PyObject *self, PyObject *args)
868{
869 raise(SIGBUS);
870 Py_RETURN_NONE;
871}
872#endif
873
874#ifdef SIGILL
875static PyObject *
876faulthandler_sigill(PyObject *self, PyObject *args)
877{
Victor Stinner024e37a2011-03-31 01:31:06 +0200878 raise(SIGILL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200879 Py_RETURN_NONE;
880}
881#endif
882
883static PyObject *
884faulthandler_fatal_error_py(PyObject *self, PyObject *args)
885{
886 char *message;
887 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
888 return NULL;
889 Py_FatalError(message);
890 Py_RETURN_NONE;
891}
892
893#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner9b493042011-05-23 12:29:10 +0200894static void*
Victor Stinnerf0480752011-03-31 11:34:08 +0200895stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200896{
897 /* allocate 4096 bytes on the stack at each call */
898 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200899 void *sp = &buffer;
900 *depth += 1;
901 if (sp < min_sp || max_sp < sp)
902 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200903 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200904 buffer[4095] = 0;
905 return stack_overflow(min_sp, max_sp, depth);
906}
907
908static PyObject *
909faulthandler_stack_overflow(PyObject *self)
910{
911 size_t depth, size;
Victor Stinner425fcd32011-09-07 16:18:56 +0200912 char *sp = (char *)&depth, *stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200913
914 depth = 0;
915 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
916 sp + STACK_OVERFLOW_MAX_SIZE,
917 &depth);
918 if (sp < stop)
919 size = stop - sp;
920 else
921 size = sp - stop;
922 PyErr_Format(PyExc_RuntimeError,
923 "unable to raise a stack overflow (allocated %zu bytes "
924 "on the stack, %zu recursive calls)",
925 size, depth);
926 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200927}
928#endif
929
930
931static int
932faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
933{
934#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200935 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200936#endif
937
938#ifdef FAULTHANDLER_LATER
939 Py_VISIT(thread.file);
940#endif
941#ifdef FAULTHANDLER_USER
942 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200943 for (signum=0; signum < NSIG; signum++)
944 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200945 }
946#endif
947 Py_VISIT(fatal_error.file);
948 return 0;
949}
950
951PyDoc_STRVAR(module_doc,
952"faulthandler module.");
953
954static PyMethodDef module_methods[] = {
955 {"enable",
956 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200957 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200958 "enable the fault handler")},
959 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
960 PyDoc_STR("disable(): disable the fault handler")},
961 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
962 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
963 {"dump_traceback",
964 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200965 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200966 "dump the traceback of the current thread, or of all threads "
967 "if all_threads is True, into file")},
968#ifdef FAULTHANDLER_LATER
969 {"dump_tracebacks_later",
Victor Stinner96994402011-04-07 11:37:19 +0200970 (PyCFunction)faulthandler_dump_tracebacks_later, METH_VARARGS|METH_KEYWORDS,
971 PyDoc_STR("dump_tracebacks_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +0200972 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +0200973 "or each timeout seconds if repeat is True. If exit is True, "
974 "call _exit(1) which is not safe.")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200975 {"cancel_dump_tracebacks_later",
Victor Stinner702624e2011-03-31 03:42:34 +0200976 (PyCFunction)faulthandler_cancel_dump_tracebacks_later_py, METH_NOARGS,
Victor Stinner024e37a2011-03-31 01:31:06 +0200977 PyDoc_STR("cancel_dump_tracebacks_later():\ncancel the previous call "
978 "to dump_tracebacks_later().")},
979#endif
980
981#ifdef FAULTHANDLER_USER
982 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200983 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
984 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200985 "register an handler for the signal 'signum': dump the "
986 "traceback of the current thread, or of all threads if "
987 "all_threads is True, into file")},
988 {"unregister",
989 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
990 PyDoc_STR("unregister(signum): unregister the handler of the signal "
991 "'signum' registered by register()")},
992#endif
993
994 {"_read_null", faulthandler_read_null, METH_VARARGS,
995 PyDoc_STR("_read_null(release_gil=False): read from NULL, raise "
996 "a SIGSEGV or SIGBUS signal depending on the platform")},
997 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
998 PyDoc_STR("_sigsegv(): raise a SIGSEGV signal")},
Victor Stinnerd727e232011-04-01 12:13:55 +0200999 {"_sigabrt", faulthandler_sigabrt, METH_VARARGS,
1000 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001001 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1002 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
1003#ifdef SIGBUS
1004 {"_sigbus", (PyCFunction)faulthandler_sigbus, METH_NOARGS,
1005 PyDoc_STR("_sigbus(): raise a SIGBUS signal")},
1006#endif
1007#ifdef SIGILL
1008 {"_sigill", (PyCFunction)faulthandler_sigill, METH_NOARGS,
1009 PyDoc_STR("_sigill(): raise a SIGILL signal")},
1010#endif
1011 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1012 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1013#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1014 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1015 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1016#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001017 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001018};
1019
1020static struct PyModuleDef module_def = {
1021 PyModuleDef_HEAD_INIT,
1022 "faulthandler",
1023 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001024 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001025 module_methods,
1026 NULL,
1027 faulthandler_traverse,
1028 NULL,
1029 NULL
1030};
1031
1032PyMODINIT_FUNC
1033PyInit_faulthandler(void)
1034{
1035 return PyModule_Create(&module_def);
1036}
1037
Victor Stinner410dd7d2011-05-11 20:56:08 +02001038/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1039 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001040
1041static int
1042faulthandler_env_options(void)
1043{
1044 PyObject *xoptions, *key, *module, *res;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001045 _Py_IDENTIFIER(enable);
Victor Stinner024e37a2011-03-31 01:31:06 +02001046
1047 if (!Py_GETENV("PYTHONFAULTHANDLER")) {
Victor Stinner25095b22011-05-26 13:47:08 +02001048 int has_key;
1049
Victor Stinner024e37a2011-03-31 01:31:06 +02001050 xoptions = PySys_GetXOptions();
1051 if (xoptions == NULL)
1052 return -1;
1053
1054 key = PyUnicode_FromString("faulthandler");
1055 if (key == NULL)
1056 return -1;
1057
Victor Stinner25095b22011-05-26 13:47:08 +02001058 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001059 Py_DECREF(key);
Victor Stinner25095b22011-05-26 13:47:08 +02001060 if (!has_key)
Victor Stinner024e37a2011-03-31 01:31:06 +02001061 return 0;
1062 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001063
1064 module = PyImport_ImportModule("faulthandler");
1065 if (module == NULL) {
1066 return -1;
1067 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001068 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001069 Py_DECREF(module);
1070 if (res == NULL)
1071 return -1;
1072 Py_DECREF(res);
1073 return 0;
1074}
1075
1076int _PyFaulthandler_Init(void)
1077{
1078#ifdef HAVE_SIGALTSTACK
1079 int err;
1080
1081 /* Try to allocate an alternate stack for faulthandler() signal handler to
1082 * be able to allocate memory on the stack, even on a stack overflow. If it
1083 * fails, ignore the error. */
1084 stack.ss_flags = 0;
1085 stack.ss_size = SIGSTKSZ;
1086 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1087 if (stack.ss_sp != NULL) {
1088 err = sigaltstack(&stack, NULL);
1089 if (err) {
1090 PyMem_Free(stack.ss_sp);
1091 stack.ss_sp = NULL;
1092 }
1093 }
1094#endif
1095#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001096 thread.file = NULL;
1097 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001098 thread.running = PyThread_allocate_lock();
1099 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001100 PyErr_SetString(PyExc_RuntimeError,
1101 "could not allocate locks for faulthandler");
1102 return -1;
1103 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001104 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001105#endif
1106
1107 return faulthandler_env_options();
1108}
1109
1110void _PyFaulthandler_Fini(void)
1111{
1112#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001113 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001114#endif
1115
1116#ifdef FAULTHANDLER_LATER
1117 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001118 if (thread.cancel_event) {
Victor Stinner1134b0d2012-01-10 22:44:11 +01001119 cancel_dump_tracebacks_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001120 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001121 PyThread_free_lock(thread.cancel_event);
1122 thread.cancel_event = NULL;
1123 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001124 if (thread.running) {
1125 PyThread_free_lock(thread.running);
1126 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001127 }
1128#endif
1129
1130#ifdef FAULTHANDLER_USER
1131 /* user */
1132 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001133 for (signum=0; signum < NSIG; signum++)
1134 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner024e37a2011-03-31 01:31:06 +02001135 free(user_signals);
1136 user_signals = NULL;
1137 }
1138#endif
1139
1140 /* fatal */
1141 faulthandler_disable();
1142#ifdef HAVE_SIGALTSTACK
1143 if (stack.ss_sp != NULL) {
1144 PyMem_Free(stack.ss_sp);
1145 stack.ss_sp = NULL;
1146 }
1147#endif
1148}