blob: 6a145dc5f04a79656ef013427bfbaa3ad986abfe [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
Victor Stinner56cb1252012-10-31 00:33:57 +010025/* cast size_t to int because write() takes an int on Windows
26 (anyway, the length is smaller than 30 characters) */
27#define PUTS(fd, str) write(fd, str, (int)strlen(str))
Victor Stinner024e37a2011-03-31 01:31:06 +020028
Victor Stinnerbd303c12013-11-07 23:07:29 +010029_Py_IDENTIFIER(enable);
30_Py_IDENTIFIER(fileno);
31_Py_IDENTIFIER(flush);
32_Py_IDENTIFIER(stderr);
33
Victor Stinner024e37a2011-03-31 01:31:06 +020034#ifdef HAVE_SIGACTION
35typedef struct sigaction _Py_sighandler_t;
36#else
37typedef PyOS_sighandler_t _Py_sighandler_t;
38#endif
39
40typedef struct {
41 int signum;
42 int enabled;
43 const char* name;
44 _Py_sighandler_t previous;
45 int all_threads;
46} fault_handler_t;
47
48static struct {
49 int enabled;
50 PyObject *file;
51 int fd;
52 int all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +020053 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020054} fatal_error = {0, NULL, -1, 0};
55
56#ifdef FAULTHANDLER_LATER
57static struct {
58 PyObject *file;
59 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020060 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020061 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020062 PyInterpreterState *interp;
63 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020064 char *header;
65 size_t header_len;
Victor Stinner410dd7d2011-05-11 20:56:08 +020066 /* The main thread always holds this lock. It is only released when
67 faulthandler_thread() is interrupted before this thread exits, or at
Victor Stinnerde10f402011-04-08 12:57:06 +020068 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020069 PyThread_type_lock cancel_event;
70 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020071 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020072} thread;
73#endif
74
75#ifdef FAULTHANDLER_USER
76typedef struct {
77 int enabled;
78 PyObject *file;
79 int fd;
80 int all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +020081 int chain;
Victor Stinner024e37a2011-03-31 01:31:06 +020082 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020083 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020084} user_signal_t;
85
86static user_signal_t *user_signals;
87
88/* the following macros come from Python: Modules/signalmodule.c */
Victor Stinner024e37a2011-03-31 01:31:06 +020089#ifndef NSIG
90# if defined(_NSIG)
91# define NSIG _NSIG /* For BSD/SysV */
92# elif defined(_SIGMAX)
93# define NSIG (_SIGMAX + 1) /* For QNX */
94# elif defined(SIGMAX)
95# define NSIG (SIGMAX + 1) /* For djgpp */
96# else
97# define NSIG 64 /* Use a reasonable default value */
98# endif
99#endif
100
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200101static void faulthandler_user(int signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200102#endif /* FAULTHANDLER_USER */
103
104
105static fault_handler_t faulthandler_handlers[] = {
106#ifdef SIGBUS
107 {SIGBUS, 0, "Bus error", },
108#endif
109#ifdef SIGILL
110 {SIGILL, 0, "Illegal instruction", },
111#endif
112 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200113 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200114 /* define SIGSEGV at the end to make it the default choice if searching the
115 handler fails in faulthandler_fatal_error() */
116 {SIGSEGV, 0, "Segmentation fault", }
117};
118static const unsigned char faulthandler_nsignals = \
Victor Stinner63941882011-09-29 00:42:28 +0200119 Py_ARRAY_LENGTH(faulthandler_handlers);
Victor Stinner024e37a2011-03-31 01:31:06 +0200120
121#ifdef HAVE_SIGALTSTACK
122static stack_t stack;
123#endif
124
125
126/* Get the file descriptor of a file by calling its fileno() method and then
127 call its flush() method.
128
129 If file is NULL or Py_None, use sys.stderr as the new file.
130
131 On success, return the new file and write the file descriptor into *p_fd.
132 On error, return NULL. */
133
134static PyObject*
135faulthandler_get_fileno(PyObject *file, int *p_fd)
136{
137 PyObject *result;
138 long fd_long;
139 int fd;
140
141 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100142 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200143 if (file == NULL) {
144 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
145 return NULL;
146 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200147 if (file == Py_None) {
148 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
149 return NULL;
150 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200151 }
152
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200153 result = _PyObject_CallMethodId(file, &PyId_fileno, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200154 if (result == NULL)
155 return NULL;
156
157 fd = -1;
158 if (PyLong_Check(result)) {
159 fd_long = PyLong_AsLong(result);
160 if (0 <= fd_long && fd_long < INT_MAX)
161 fd = (int)fd_long;
162 }
163 Py_DECREF(result);
164
165 if (fd == -1) {
166 PyErr_SetString(PyExc_RuntimeError,
167 "file.fileno() is not a valid file descriptor");
168 return NULL;
169 }
170
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200171 result = _PyObject_CallMethodId(file, &PyId_flush, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200172 if (result != NULL)
173 Py_DECREF(result);
174 else {
175 /* ignore flush() error */
176 PyErr_Clear();
177 }
178 *p_fd = fd;
179 return file;
180}
181
Victor Stinnera4de6d82011-04-09 00:47:23 +0200182/* Get the state of the current thread: only call this function if the current
183 thread holds the GIL. Raise an exception on error. */
184static PyThreadState*
185get_thread_state(void)
186{
187 PyThreadState *tstate = PyThreadState_Get();
188 if (tstate == NULL) {
189 PyErr_SetString(PyExc_RuntimeError,
190 "unable to get the current thread state");
191 return NULL;
192 }
193 return tstate;
194}
195
Victor Stinner024e37a2011-03-31 01:31:06 +0200196static PyObject*
197faulthandler_dump_traceback_py(PyObject *self,
198 PyObject *args, PyObject *kwargs)
199{
200 static char *kwlist[] = {"file", "all_threads", NULL};
201 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200202 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200203 PyThreadState *tstate;
204 const char *errmsg;
205 int fd;
206
207 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
208 "|Oi:dump_traceback", kwlist,
209 &file, &all_threads))
210 return NULL;
211
212 file = faulthandler_get_fileno(file, &fd);
213 if (file == NULL)
214 return NULL;
215
Victor Stinnera4de6d82011-04-09 00:47:23 +0200216 tstate = get_thread_state();
217 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200218 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200219
220 if (all_threads) {
221 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
222 if (errmsg != NULL) {
223 PyErr_SetString(PyExc_RuntimeError, errmsg);
224 return NULL;
225 }
226 }
227 else {
228 _Py_DumpTraceback(fd, tstate);
229 }
230 Py_RETURN_NONE;
231}
232
233
Victor Stinner410dd7d2011-05-11 20:56:08 +0200234/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200235
236 Display the current Python traceback, restore the previous handler and call
237 the previous handler.
238
Victor Stinner410dd7d2011-05-11 20:56:08 +0200239 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200240 signal handler would not be called (for an unknown reason). The execution of
241 the program continues at faulthandler_fatal_error() exit, but the same
242 instruction will raise the same fault (signal), and so the previous handler
243 will be called.
244
Victor Stinner410dd7d2011-05-11 20:56:08 +0200245 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200246
247static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200248faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200249{
250 const int fd = fatal_error.fd;
251 unsigned int i;
252 fault_handler_t *handler = NULL;
253 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200254 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200255
256 if (!fatal_error.enabled)
257 return;
258
259 for (i=0; i < faulthandler_nsignals; i++) {
260 handler = &faulthandler_handlers[i];
261 if (handler->signum == signum)
262 break;
263 }
264 if (handler == NULL) {
265 /* faulthandler_nsignals == 0 (unlikely) */
266 return;
267 }
268
269 /* restore the previous handler */
270#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200271 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200272#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200273 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200274#endif
275 handler->enabled = 0;
276
277 PUTS(fd, "Fatal Python error: ");
278 PUTS(fd, handler->name);
279 PUTS(fd, "\n\n");
280
Victor Stinnerff4cd882011-04-07 11:50:25 +0200281#ifdef WITH_THREAD
Victor Stinnerd727e232011-04-01 12:13:55 +0200282 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
Victor Stinner410dd7d2011-05-11 20:56:08 +0200283 are thus delivered to the thread that caused the fault. Get the Python
Victor Stinnerd727e232011-04-01 12:13:55 +0200284 thread state of the current thread.
Victor Stinner024e37a2011-03-31 01:31:06 +0200285
286 PyThreadState_Get() doesn't give the state of the thread that caused the
287 fault if the thread released the GIL, and so this function cannot be
288 used. Read the thread local storage (TLS) instead: call
289 PyGILState_GetThisThreadState(). */
290 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200291#else
292 tstate = PyThreadState_Get();
293#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200294
295 if (fatal_error.all_threads)
Victor Stinnera4de6d82011-04-09 00:47:23 +0200296 _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
297 else {
298 if (tstate != NULL)
299 _Py_DumpTraceback(fd, tstate);
300 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200301
Victor Stinnerc9256172011-05-07 12:20:11 +0200302 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200303#ifdef MS_WINDOWS
304 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200305 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200306 handler, because the Windows signal handler would not be called */
307 return;
308 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200309#endif
R David Murrayfc069992013-12-13 20:52:19 -0500310 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200311 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
312 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200313}
314
Victor Stinnerd727e232011-04-01 12:13:55 +0200315/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200316
317static PyObject*
318faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
319{
320 static char *kwlist[] = {"file", "all_threads", NULL};
321 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200322 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200323 unsigned int i;
324 fault_handler_t *handler;
325#ifdef HAVE_SIGACTION
326 struct sigaction action;
327#endif
328 int err;
329 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200330 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200331
332 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
333 "|Oi:enable", kwlist, &file, &all_threads))
334 return NULL;
335
336 file = faulthandler_get_fileno(file, &fd);
337 if (file == NULL)
338 return NULL;
339
Victor Stinnera4de6d82011-04-09 00:47:23 +0200340 tstate = get_thread_state();
341 if (tstate == NULL)
342 return NULL;
343
Victor Stinner024e37a2011-03-31 01:31:06 +0200344 Py_XDECREF(fatal_error.file);
345 Py_INCREF(file);
346 fatal_error.file = file;
347 fatal_error.fd = fd;
348 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200349 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200350
351 if (!fatal_error.enabled) {
352 fatal_error.enabled = 1;
353
354 for (i=0; i < faulthandler_nsignals; i++) {
355 handler = &faulthandler_handlers[i];
356#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200357 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200358 sigemptyset(&action.sa_mask);
359 /* Do not prevent the signal from being received from within
360 its own signal handler */
361 action.sa_flags = SA_NODEFER;
362#ifdef HAVE_SIGALTSTACK
363 if (stack.ss_sp != NULL) {
364 /* Call the signal handler on an alternate signal stack
365 provided by sigaltstack() */
366 action.sa_flags |= SA_ONSTACK;
367 }
368#endif
369 err = sigaction(handler->signum, &action, &handler->previous);
370#else
371 handler->previous = signal(handler->signum,
372 faulthandler_fatal_error);
373 err = (handler->previous == SIG_ERR);
374#endif
375 if (err) {
376 PyErr_SetFromErrno(PyExc_RuntimeError);
377 return NULL;
378 }
379 handler->enabled = 1;
380 }
381 }
382 Py_RETURN_NONE;
383}
384
385static void
386faulthandler_disable(void)
387{
388 unsigned int i;
389 fault_handler_t *handler;
390
391 if (fatal_error.enabled) {
392 fatal_error.enabled = 0;
393 for (i=0; i < faulthandler_nsignals; i++) {
394 handler = &faulthandler_handlers[i];
395 if (!handler->enabled)
396 continue;
397#ifdef HAVE_SIGACTION
398 (void)sigaction(handler->signum, &handler->previous, NULL);
399#else
400 (void)signal(handler->signum, handler->previous);
401#endif
402 handler->enabled = 0;
403 }
404 }
405
406 Py_CLEAR(fatal_error.file);
407}
408
409static PyObject*
410faulthandler_disable_py(PyObject *self)
411{
412 if (!fatal_error.enabled) {
413 Py_INCREF(Py_False);
414 return Py_False;
415 }
416 faulthandler_disable();
417 Py_INCREF(Py_True);
418 return Py_True;
419}
420
421static PyObject*
422faulthandler_is_enabled(PyObject *self)
423{
424 return PyBool_FromLong(fatal_error.enabled);
425}
426
427#ifdef FAULTHANDLER_LATER
428
429static void
430faulthandler_thread(void *unused)
431{
432 PyLockStatus st;
433 const char* errmsg;
434 PyThreadState *current;
435 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200436#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200437 sigset_t set;
438
439 /* we don't want to receive any signal */
440 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200441 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200442#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200443
444 do {
445 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200446 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200447 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200448 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200449 break;
450 }
451 /* Timeout => dump traceback */
452 assert(st == PY_LOCK_FAILURE);
453
454 /* get the thread holding the GIL, NULL if no thread hold the GIL */
455 current = _Py_atomic_load_relaxed(&_PyThreadState_Current);
456
Victor Stinner56cb1252012-10-31 00:33:57 +0100457 write(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200458
Victor Stinner024e37a2011-03-31 01:31:06 +0200459 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
460 ok = (errmsg == NULL);
461
462 if (thread.exit)
463 _exit(1);
464 } while (ok && thread.repeat);
465
466 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200467 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200468}
469
470static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200471cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200472{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200473 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200474 PyThread_release_lock(thread.cancel_event);
475
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200476 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200477 PyThread_acquire_lock(thread.running, 1);
478 PyThread_release_lock(thread.running);
479
480 /* The main thread should always hold the cancel_event lock */
481 PyThread_acquire_lock(thread.cancel_event, 1);
482
Victor Stinner024e37a2011-03-31 01:31:06 +0200483 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200484 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200485 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200486 thread.header = NULL;
487 }
488}
489
490static char*
491format_timeout(double timeout)
492{
493 unsigned long us, sec, min, hour;
494 double intpart, fracpart;
495 char buffer[100];
496
497 fracpart = modf(timeout, &intpart);
498 sec = (unsigned long)intpart;
499 us = (unsigned long)(fracpart * 1e6);
500 min = sec / 60;
501 sec %= 60;
502 hour = min / 60;
503 min %= 60;
504
505 if (us != 0)
506 PyOS_snprintf(buffer, sizeof(buffer),
507 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
508 hour, min, sec, us);
509 else
510 PyOS_snprintf(buffer, sizeof(buffer),
511 "Timeout (%lu:%02lu:%02lu)!\n",
512 hour, min, sec);
513
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200514 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200515}
516
517static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200518faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200519 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200520{
521 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
522 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200523 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200524 int repeat = 0;
525 PyObject *file = NULL;
526 int fd;
527 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200528 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200529 char *header;
530 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200531
532 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200533 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200534 &timeout, &repeat, &file, &exit))
535 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200536 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200537 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
538 return NULL;
539 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200540 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200541 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200542 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
543 return NULL;
544 }
545
Victor Stinnera4de6d82011-04-09 00:47:23 +0200546 tstate = get_thread_state();
547 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200548 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200549
Victor Stinner024e37a2011-03-31 01:31:06 +0200550 file = faulthandler_get_fileno(file, &fd);
551 if (file == NULL)
552 return NULL;
553
Victor Stinnerc790a532011-04-08 13:39:59 +0200554 /* format the timeout */
555 header = format_timeout(timeout);
556 if (header == NULL)
557 return PyErr_NoMemory();
558 header_len = strlen(header);
559
Victor Stinner024e37a2011-03-31 01:31:06 +0200560 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200561 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200562
563 Py_XDECREF(thread.file);
564 Py_INCREF(file);
565 thread.file = file;
566 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200567 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200568 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200569 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200570 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200571 thread.header = header;
572 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200573
574 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200575 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200576
Victor Stinner024e37a2011-03-31 01:31:06 +0200577 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200578 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200579 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200580 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200581 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200582 PyErr_SetString(PyExc_RuntimeError,
583 "unable to start watchdog thread");
584 return NULL;
585 }
586
587 Py_RETURN_NONE;
588}
589
590static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200591faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200592{
Georg Brandldeb92b52012-09-22 08:58:55 +0200593 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200594 Py_RETURN_NONE;
595}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200596#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200597
598#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200599static int
600faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
601{
602#ifdef HAVE_SIGACTION
603 struct sigaction action;
604 action.sa_handler = faulthandler_user;
605 sigemptyset(&action.sa_mask);
606 /* if the signal is received while the kernel is executing a system
607 call, try to restart the system call instead of interrupting it and
608 return EINTR. */
609 action.sa_flags = SA_RESTART;
610 if (chain) {
611 /* do not prevent the signal from being received from within its
612 own signal handler */
613 action.sa_flags = SA_NODEFER;
614 }
615#ifdef HAVE_SIGALTSTACK
616 if (stack.ss_sp != NULL) {
617 /* Call the signal handler on an alternate signal stack
618 provided by sigaltstack() */
619 action.sa_flags |= SA_ONSTACK;
620 }
621#endif
622 return sigaction(signum, &action, p_previous);
623#else
624 _Py_sighandler_t previous;
625 previous = signal(signum, faulthandler_user);
626 if (p_previous != NULL)
627 *p_previous = previous;
628 return (previous == SIG_ERR);
629#endif
630}
631
Victor Stinner024e37a2011-03-31 01:31:06 +0200632/* Handler of user signals (e.g. SIGUSR1).
633
634 Dump the traceback of the current thread, or of all threads if
635 thread.all_threads is true.
636
637 This function is signal safe and should only call signal safe functions. */
638
639static void
640faulthandler_user(int signum)
641{
642 user_signal_t *user;
643 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200644 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200645
646 user = &user_signals[signum];
647 if (!user->enabled)
648 return;
649
Victor Stinnerff4cd882011-04-07 11:50:25 +0200650#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200651 /* PyThreadState_Get() doesn't give the state of the current thread if
652 the thread doesn't hold the GIL. Read the thread local storage (TLS)
653 instead: call PyGILState_GetThisThreadState(). */
654 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200655#else
656 tstate = PyThreadState_Get();
657#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200658
659 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200660 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
661 else {
Victor Stinner98a387b2012-08-01 19:36:36 +0200662 if (tstate != NULL)
663 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200664 }
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200665#ifdef HAVE_SIGACTION
666 if (user->chain) {
667 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200668 errno = save_errno;
669
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200670 /* call the previous signal handler */
671 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200672
673 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200674 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200675 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200676 }
677#else
678 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200679 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200680 /* call the previous signal handler */
681 user->previous(signum);
682 }
683#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200684}
685
686static int
687check_signum(int signum)
688{
689 unsigned int i;
690
691 for (i=0; i < faulthandler_nsignals; i++) {
692 if (faulthandler_handlers[i].signum == signum) {
693 PyErr_Format(PyExc_RuntimeError,
694 "signal %i cannot be registered, "
695 "use enable() instead",
696 signum);
697 return 0;
698 }
699 }
700 if (signum < 1 || NSIG <= signum) {
701 PyErr_SetString(PyExc_ValueError, "signal number out of range");
702 return 0;
703 }
704 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200705}
706
707static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200708faulthandler_register_py(PyObject *self,
709 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200710{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200711 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200712 int signum;
713 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200714 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200715 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200716 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200717 user_signal_t *user;
718 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200719 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200720 int err;
721
722 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200723 "i|Oii:register", kwlist,
724 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200725 return NULL;
726
Victor Stinner44378d42011-04-01 15:37:12 +0200727 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200728 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200729
Victor Stinnera4de6d82011-04-09 00:47:23 +0200730 tstate = get_thread_state();
731 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200732 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200733
734 file = faulthandler_get_fileno(file, &fd);
735 if (file == NULL)
736 return NULL;
737
738 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200739 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200740 if (user_signals == NULL)
741 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200742 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200743 }
744 user = &user_signals[signum];
745
746 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200747 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200748 if (err) {
749 PyErr_SetFromErrno(PyExc_OSError);
750 return NULL;
751 }
Victor Stinner8d379542013-07-02 00:14:56 +0200752
753 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200754 }
755
756 Py_XDECREF(user->file);
757 Py_INCREF(file);
758 user->file = file;
759 user->fd = fd;
760 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200761 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200762 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200763 user->enabled = 1;
764
765 Py_RETURN_NONE;
766}
767
768static int
769faulthandler_unregister(user_signal_t *user, int signum)
770{
Victor Stinnera01ca122011-04-01 12:56:17 +0200771 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200772 return 0;
773 user->enabled = 0;
774#ifdef HAVE_SIGACTION
775 (void)sigaction(signum, &user->previous, NULL);
776#else
777 (void)signal(signum, user->previous);
778#endif
779 Py_CLEAR(user->file);
780 user->fd = -1;
781 return 1;
782}
783
784static PyObject*
785faulthandler_unregister_py(PyObject *self, PyObject *args)
786{
787 int signum;
788 user_signal_t *user;
789 int change;
790
791 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
792 return NULL;
793
Victor Stinner44378d42011-04-01 15:37:12 +0200794 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200795 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200796
Victor Stinnercfa71232011-04-08 12:48:15 +0200797 if (user_signals == NULL)
798 Py_RETURN_FALSE;
799
Victor Stinner024e37a2011-03-31 01:31:06 +0200800 user = &user_signals[signum];
801 change = faulthandler_unregister(user, signum);
802 return PyBool_FromLong(change);
803}
804#endif /* FAULTHANDLER_USER */
805
806
807static PyObject *
808faulthandler_read_null(PyObject *self, PyObject *args)
809{
Victor Stinnera2477202012-01-30 00:07:43 +0100810 volatile int *x;
811 volatile int y;
Victor Stinner024e37a2011-03-31 01:31:06 +0200812 int release_gil = 0;
813 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
814 return NULL;
Victor Stinnera2477202012-01-30 00:07:43 +0100815
816 x = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200817 if (release_gil) {
818 Py_BEGIN_ALLOW_THREADS
819 y = *x;
820 Py_END_ALLOW_THREADS
821 } else
822 y = *x;
823 return PyLong_FromLong(y);
824
825}
826
827static PyObject *
828faulthandler_sigsegv(PyObject *self, PyObject *args)
829{
830#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200831 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
832 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200833 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200834 SIGSEGV was raised by the kernel because of a fault, and so if the
835 program retries to execute the same instruction, the fault will be
836 raised again.
837
838 Here the fault is simulated by a fake SIGSEGV signal raised by the
839 application. We have to raise SIGSEGV at lease twice: once for
840 faulthandler_fatal_error(), and one more time for the previous signal
841 handler. */
842 while(1)
843 raise(SIGSEGV);
844#else
845 raise(SIGSEGV);
846#endif
847 Py_RETURN_NONE;
848}
849
850static PyObject *
851faulthandler_sigfpe(PyObject *self, PyObject *args)
852{
853 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
854 PowerPC. Use volatile to disable compile-time optimizations. */
855 volatile int x = 1, y = 0, z;
856 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200857 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
858 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200859 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200860 /* This line is never reached, but we pretend to make something with z
861 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200862 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200863}
864
Victor Stinnerd727e232011-04-01 12:13:55 +0200865static PyObject *
866faulthandler_sigabrt(PyObject *self, PyObject *args)
867{
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200868#ifdef _MSC_VER
869 /* Visual Studio: configure abort() to not display an error message nor
870 open a popup asking to report the fault. */
871 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
Victor Stinnerd727e232011-04-01 12:13:55 +0200872#endif
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200873 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200874 Py_RETURN_NONE;
875}
876
Victor Stinner024e37a2011-03-31 01:31:06 +0200877#ifdef SIGBUS
878static PyObject *
879faulthandler_sigbus(PyObject *self, PyObject *args)
880{
881 raise(SIGBUS);
882 Py_RETURN_NONE;
883}
884#endif
885
886#ifdef SIGILL
887static PyObject *
888faulthandler_sigill(PyObject *self, PyObject *args)
889{
Victor Stinner024e37a2011-03-31 01:31:06 +0200890 raise(SIGILL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200891 Py_RETURN_NONE;
892}
893#endif
894
895static PyObject *
896faulthandler_fatal_error_py(PyObject *self, PyObject *args)
897{
898 char *message;
899 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
900 return NULL;
901 Py_FatalError(message);
902 Py_RETURN_NONE;
903}
904
905#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner9b493042011-05-23 12:29:10 +0200906static void*
Victor Stinnerf0480752011-03-31 11:34:08 +0200907stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200908{
909 /* allocate 4096 bytes on the stack at each call */
910 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200911 void *sp = &buffer;
912 *depth += 1;
913 if (sp < min_sp || max_sp < sp)
914 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200915 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200916 buffer[4095] = 0;
917 return stack_overflow(min_sp, max_sp, depth);
918}
919
920static PyObject *
921faulthandler_stack_overflow(PyObject *self)
922{
923 size_t depth, size;
Victor Stinner425fcd32011-09-07 16:18:56 +0200924 char *sp = (char *)&depth, *stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200925
926 depth = 0;
927 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
928 sp + STACK_OVERFLOW_MAX_SIZE,
929 &depth);
930 if (sp < stop)
931 size = stop - sp;
932 else
933 size = sp - stop;
934 PyErr_Format(PyExc_RuntimeError,
935 "unable to raise a stack overflow (allocated %zu bytes "
936 "on the stack, %zu recursive calls)",
937 size, depth);
938 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200939}
940#endif
941
942
943static int
944faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
945{
946#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200947 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200948#endif
949
950#ifdef FAULTHANDLER_LATER
951 Py_VISIT(thread.file);
952#endif
953#ifdef FAULTHANDLER_USER
954 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200955 for (signum=0; signum < NSIG; signum++)
956 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200957 }
958#endif
959 Py_VISIT(fatal_error.file);
960 return 0;
961}
962
963PyDoc_STRVAR(module_doc,
964"faulthandler module.");
965
966static PyMethodDef module_methods[] = {
967 {"enable",
968 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200969 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200970 "enable the fault handler")},
971 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
972 PyDoc_STR("disable(): disable the fault handler")},
973 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
974 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
975 {"dump_traceback",
976 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200977 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200978 "dump the traceback of the current thread, or of all threads "
979 "if all_threads is True, into file")},
980#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +0200981 {"dump_traceback_later",
982 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
983 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +0200984 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +0200985 "or each timeout seconds if repeat is True. If exit is True, "
986 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +0200987 {"cancel_dump_traceback_later",
988 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
989 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
990 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200991#endif
992
993#ifdef FAULTHANDLER_USER
994 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200995 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
996 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200997 "register an handler for the signal 'signum': dump the "
998 "traceback of the current thread, or of all threads if "
999 "all_threads is True, into file")},
1000 {"unregister",
1001 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1002 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1003 "'signum' registered by register()")},
1004#endif
1005
1006 {"_read_null", faulthandler_read_null, METH_VARARGS,
1007 PyDoc_STR("_read_null(release_gil=False): read from NULL, raise "
1008 "a SIGSEGV or SIGBUS signal depending on the platform")},
1009 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
1010 PyDoc_STR("_sigsegv(): raise a SIGSEGV signal")},
Victor Stinnerd727e232011-04-01 12:13:55 +02001011 {"_sigabrt", faulthandler_sigabrt, METH_VARARGS,
1012 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001013 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1014 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
1015#ifdef SIGBUS
1016 {"_sigbus", (PyCFunction)faulthandler_sigbus, METH_NOARGS,
1017 PyDoc_STR("_sigbus(): raise a SIGBUS signal")},
1018#endif
1019#ifdef SIGILL
1020 {"_sigill", (PyCFunction)faulthandler_sigill, METH_NOARGS,
1021 PyDoc_STR("_sigill(): raise a SIGILL signal")},
1022#endif
1023 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1024 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1025#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1026 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1027 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1028#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001029 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001030};
1031
1032static struct PyModuleDef module_def = {
1033 PyModuleDef_HEAD_INIT,
1034 "faulthandler",
1035 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001036 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001037 module_methods,
1038 NULL,
1039 faulthandler_traverse,
1040 NULL,
1041 NULL
1042};
1043
1044PyMODINIT_FUNC
1045PyInit_faulthandler(void)
1046{
1047 return PyModule_Create(&module_def);
1048}
1049
Victor Stinner410dd7d2011-05-11 20:56:08 +02001050/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1051 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001052
1053static int
1054faulthandler_env_options(void)
1055{
1056 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001057 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001058
Victor Stinner88983502013-09-08 11:36:23 +02001059 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1060 /* PYTHONFAULTHANDLER environment variable is missing
1061 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001062 int has_key;
1063
Victor Stinner024e37a2011-03-31 01:31:06 +02001064 xoptions = PySys_GetXOptions();
1065 if (xoptions == NULL)
1066 return -1;
1067
1068 key = PyUnicode_FromString("faulthandler");
1069 if (key == NULL)
1070 return -1;
1071
Victor Stinner25095b22011-05-26 13:47:08 +02001072 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001073 Py_DECREF(key);
Victor Stinner25095b22011-05-26 13:47:08 +02001074 if (!has_key)
Victor Stinner024e37a2011-03-31 01:31:06 +02001075 return 0;
1076 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001077
1078 module = PyImport_ImportModule("faulthandler");
1079 if (module == NULL) {
1080 return -1;
1081 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001082 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001083 Py_DECREF(module);
1084 if (res == NULL)
1085 return -1;
1086 Py_DECREF(res);
1087 return 0;
1088}
1089
1090int _PyFaulthandler_Init(void)
1091{
1092#ifdef HAVE_SIGALTSTACK
1093 int err;
1094
1095 /* Try to allocate an alternate stack for faulthandler() signal handler to
1096 * be able to allocate memory on the stack, even on a stack overflow. If it
1097 * fails, ignore the error. */
1098 stack.ss_flags = 0;
1099 stack.ss_size = SIGSTKSZ;
1100 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1101 if (stack.ss_sp != NULL) {
1102 err = sigaltstack(&stack, NULL);
1103 if (err) {
1104 PyMem_Free(stack.ss_sp);
1105 stack.ss_sp = NULL;
1106 }
1107 }
1108#endif
1109#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001110 thread.file = NULL;
1111 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001112 thread.running = PyThread_allocate_lock();
1113 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001114 PyErr_SetString(PyExc_RuntimeError,
1115 "could not allocate locks for faulthandler");
1116 return -1;
1117 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001118 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001119#endif
1120
1121 return faulthandler_env_options();
1122}
1123
1124void _PyFaulthandler_Fini(void)
1125{
1126#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001127 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001128#endif
1129
1130#ifdef FAULTHANDLER_LATER
1131 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001132 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001133 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001134 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001135 PyThread_free_lock(thread.cancel_event);
1136 thread.cancel_event = NULL;
1137 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001138 if (thread.running) {
1139 PyThread_free_lock(thread.running);
1140 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001141 }
1142#endif
1143
1144#ifdef FAULTHANDLER_USER
1145 /* user */
1146 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001147 for (signum=0; signum < NSIG; signum++)
1148 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001149 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001150 user_signals = NULL;
1151 }
1152#endif
1153
1154 /* fatal */
1155 faulthandler_disable();
1156#ifdef HAVE_SIGALTSTACK
1157 if (stack.ss_sp != NULL) {
1158 PyMem_Free(stack.ss_sp);
1159 stack.ss_sp = NULL;
1160 }
1161#endif
1162}