blob: c17ffd8aca5b26cd7c4963ce0914fe50c5b5adb4 [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 Stinnera2477202012-01-30 00:07:43 +0100812
813 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200814 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200815 return PyLong_FromLong(y);
816
817}
818
Victor Stinner50838282014-09-30 13:54:14 +0200819static void
820faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200821{
822#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200823 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
824 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200825 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200826 SIGSEGV was raised by the kernel because of a fault, and so if the
827 program retries to execute the same instruction, the fault will be
828 raised again.
829
830 Here the fault is simulated by a fake SIGSEGV signal raised by the
831 application. We have to raise SIGSEGV at lease twice: once for
832 faulthandler_fatal_error(), and one more time for the previous signal
833 handler. */
834 while(1)
835 raise(SIGSEGV);
836#else
837 raise(SIGSEGV);
838#endif
Victor Stinner50838282014-09-30 13:54:14 +0200839}
840
841static PyObject *
842faulthandler_sigsegv(PyObject *self, PyObject *args)
843{
844 int release_gil = 0;
845 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
846 return NULL;
847
848 if (release_gil) {
849 Py_BEGIN_ALLOW_THREADS
850 faulthandler_raise_sigsegv();
851 Py_END_ALLOW_THREADS
852 } else {
853 faulthandler_raise_sigsegv();
854 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200855 Py_RETURN_NONE;
856}
857
858static PyObject *
859faulthandler_sigfpe(PyObject *self, PyObject *args)
860{
861 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
862 PowerPC. Use volatile to disable compile-time optimizations. */
863 volatile int x = 1, y = 0, z;
864 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200865 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
866 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200867 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200868 /* This line is never reached, but we pretend to make something with z
869 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200870 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200871}
872
Victor Stinnerd727e232011-04-01 12:13:55 +0200873static PyObject *
874faulthandler_sigabrt(PyObject *self, PyObject *args)
875{
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200876#ifdef _MSC_VER
877 /* Visual Studio: configure abort() to not display an error message nor
878 open a popup asking to report the fault. */
879 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
Victor Stinnerd727e232011-04-01 12:13:55 +0200880#endif
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200881 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200882 Py_RETURN_NONE;
883}
884
Victor Stinner024e37a2011-03-31 01:31:06 +0200885#ifdef SIGBUS
886static PyObject *
887faulthandler_sigbus(PyObject *self, PyObject *args)
888{
889 raise(SIGBUS);
890 Py_RETURN_NONE;
891}
892#endif
893
894#ifdef SIGILL
895static PyObject *
896faulthandler_sigill(PyObject *self, PyObject *args)
897{
Victor Stinner024e37a2011-03-31 01:31:06 +0200898 raise(SIGILL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200899 Py_RETURN_NONE;
900}
901#endif
902
903static PyObject *
904faulthandler_fatal_error_py(PyObject *self, PyObject *args)
905{
906 char *message;
907 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
908 return NULL;
909 Py_FatalError(message);
910 Py_RETURN_NONE;
911}
912
913#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner9b493042011-05-23 12:29:10 +0200914static void*
Victor Stinnerf0480752011-03-31 11:34:08 +0200915stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200916{
917 /* allocate 4096 bytes on the stack at each call */
918 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200919 void *sp = &buffer;
920 *depth += 1;
921 if (sp < min_sp || max_sp < sp)
922 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200923 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200924 buffer[4095] = 0;
925 return stack_overflow(min_sp, max_sp, depth);
926}
927
928static PyObject *
929faulthandler_stack_overflow(PyObject *self)
930{
931 size_t depth, size;
Victor Stinner425fcd32011-09-07 16:18:56 +0200932 char *sp = (char *)&depth, *stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200933
934 depth = 0;
935 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
936 sp + STACK_OVERFLOW_MAX_SIZE,
937 &depth);
938 if (sp < stop)
939 size = stop - sp;
940 else
941 size = sp - stop;
942 PyErr_Format(PyExc_RuntimeError,
943 "unable to raise a stack overflow (allocated %zu bytes "
944 "on the stack, %zu recursive calls)",
945 size, depth);
946 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200947}
948#endif
949
950
951static int
952faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
953{
954#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200955 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200956#endif
957
958#ifdef FAULTHANDLER_LATER
959 Py_VISIT(thread.file);
960#endif
961#ifdef FAULTHANDLER_USER
962 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200963 for (signum=0; signum < NSIG; signum++)
964 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200965 }
966#endif
967 Py_VISIT(fatal_error.file);
968 return 0;
969}
970
971PyDoc_STRVAR(module_doc,
972"faulthandler module.");
973
974static PyMethodDef module_methods[] = {
975 {"enable",
976 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200977 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200978 "enable the fault handler")},
979 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
980 PyDoc_STR("disable(): disable the fault handler")},
981 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
982 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
983 {"dump_traceback",
984 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200985 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200986 "dump the traceback of the current thread, or of all threads "
987 "if all_threads is True, into file")},
988#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +0200989 {"dump_traceback_later",
990 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
991 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +0200992 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +0200993 "or each timeout seconds if repeat is True. If exit is True, "
994 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +0200995 {"cancel_dump_traceback_later",
996 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
997 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
998 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200999#endif
1000
1001#ifdef FAULTHANDLER_USER
1002 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001003 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1004 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001005 "register an handler for the signal 'signum': dump the "
1006 "traceback of the current thread, or of all threads if "
1007 "all_threads is True, into file")},
1008 {"unregister",
1009 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1010 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1011 "'signum' registered by register()")},
1012#endif
1013
Victor Stinner50838282014-09-30 13:54:14 +02001014 {"_read_null", faulthandler_read_null, METH_NOARGS,
1015 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001016 "a SIGSEGV or SIGBUS signal depending on the platform")},
Victor Stinner50838282014-09-30 13:54:14 +02001017 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
1018 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner9db521c2014-09-30 13:49:09 +02001019 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001020 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001021 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1022 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
1023#ifdef SIGBUS
1024 {"_sigbus", (PyCFunction)faulthandler_sigbus, METH_NOARGS,
1025 PyDoc_STR("_sigbus(): raise a SIGBUS signal")},
1026#endif
1027#ifdef SIGILL
1028 {"_sigill", (PyCFunction)faulthandler_sigill, METH_NOARGS,
1029 PyDoc_STR("_sigill(): raise a SIGILL signal")},
1030#endif
1031 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1032 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1033#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1034 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1035 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1036#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001037 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001038};
1039
1040static struct PyModuleDef module_def = {
1041 PyModuleDef_HEAD_INIT,
1042 "faulthandler",
1043 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001044 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001045 module_methods,
1046 NULL,
1047 faulthandler_traverse,
1048 NULL,
1049 NULL
1050};
1051
1052PyMODINIT_FUNC
1053PyInit_faulthandler(void)
1054{
1055 return PyModule_Create(&module_def);
1056}
1057
Victor Stinner410dd7d2011-05-11 20:56:08 +02001058/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1059 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001060
1061static int
1062faulthandler_env_options(void)
1063{
1064 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001065 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001066
Victor Stinner88983502013-09-08 11:36:23 +02001067 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1068 /* PYTHONFAULTHANDLER environment variable is missing
1069 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001070 int has_key;
1071
Victor Stinner024e37a2011-03-31 01:31:06 +02001072 xoptions = PySys_GetXOptions();
1073 if (xoptions == NULL)
1074 return -1;
1075
1076 key = PyUnicode_FromString("faulthandler");
1077 if (key == NULL)
1078 return -1;
1079
Victor Stinner25095b22011-05-26 13:47:08 +02001080 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001081 Py_DECREF(key);
Victor Stinner25095b22011-05-26 13:47:08 +02001082 if (!has_key)
Victor Stinner024e37a2011-03-31 01:31:06 +02001083 return 0;
1084 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001085
1086 module = PyImport_ImportModule("faulthandler");
1087 if (module == NULL) {
1088 return -1;
1089 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001090 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001091 Py_DECREF(module);
1092 if (res == NULL)
1093 return -1;
1094 Py_DECREF(res);
1095 return 0;
1096}
1097
1098int _PyFaulthandler_Init(void)
1099{
1100#ifdef HAVE_SIGALTSTACK
1101 int err;
1102
1103 /* Try to allocate an alternate stack for faulthandler() signal handler to
1104 * be able to allocate memory on the stack, even on a stack overflow. If it
1105 * fails, ignore the error. */
1106 stack.ss_flags = 0;
1107 stack.ss_size = SIGSTKSZ;
1108 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1109 if (stack.ss_sp != NULL) {
1110 err = sigaltstack(&stack, NULL);
1111 if (err) {
1112 PyMem_Free(stack.ss_sp);
1113 stack.ss_sp = NULL;
1114 }
1115 }
1116#endif
1117#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001118 thread.file = NULL;
1119 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001120 thread.running = PyThread_allocate_lock();
1121 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001122 PyErr_SetString(PyExc_RuntimeError,
1123 "could not allocate locks for faulthandler");
1124 return -1;
1125 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001126 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001127#endif
1128
1129 return faulthandler_env_options();
1130}
1131
1132void _PyFaulthandler_Fini(void)
1133{
1134#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001135 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001136#endif
1137
1138#ifdef FAULTHANDLER_LATER
1139 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001140 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001141 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001142 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001143 PyThread_free_lock(thread.cancel_event);
1144 thread.cancel_event = NULL;
1145 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001146 if (thread.running) {
1147 PyThread_free_lock(thread.running);
1148 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001149 }
1150#endif
1151
1152#ifdef FAULTHANDLER_USER
1153 /* user */
1154 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001155 for (signum=0; signum < NSIG; signum++)
1156 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001157 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001158 user_signals = NULL;
1159 }
1160#endif
1161
1162 /* fatal */
1163 faulthandler_disable();
1164#ifdef HAVE_SIGALTSTACK
1165 if (stack.ss_sp != NULL) {
1166 PyMem_Free(stack.ss_sp);
1167 stack.ss_sp = NULL;
1168 }
1169#endif
1170}