blob: 568724b6f1710c2d565015bd706521569c7c98fd [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)
Victor Stinner7a399122014-09-30 13:40:12 +02008# include <pthread.h>
9#endif
10#ifdef MS_WINDOWS
11# include <windows.h>
12#endif
13#ifdef HAVE_SYS_RESOURCE_H
14# include <sys/resource.h>
Victor Stinner0aafa4f2011-06-29 23:28:02 +020015#endif
16
Victor Stinner96994402011-04-07 11:37:19 +020017/* Allocate at maximum 100 MB of the stack to raise the stack overflow */
18#define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)
19
Victor Stinner024e37a2011-03-31 01:31:06 +020020#ifdef WITH_THREAD
21# define FAULTHANDLER_LATER
22#endif
23
24#ifndef MS_WINDOWS
Victor Stinnerd727e232011-04-01 12:13:55 +020025 /* register() is useless on Windows, because only SIGSEGV, SIGABRT and
26 SIGILL can be handled by the process, and these signals can only be used
27 with enable(), not using register() */
Victor Stinner024e37a2011-03-31 01:31:06 +020028# define FAULTHANDLER_USER
29#endif
30
Victor Stinner56cb1252012-10-31 00:33:57 +010031/* cast size_t to int because write() takes an int on Windows
32 (anyway, the length is smaller than 30 characters) */
33#define PUTS(fd, str) write(fd, str, (int)strlen(str))
Victor Stinner024e37a2011-03-31 01:31:06 +020034
Victor Stinnerbd303c12013-11-07 23:07:29 +010035_Py_IDENTIFIER(enable);
36_Py_IDENTIFIER(fileno);
37_Py_IDENTIFIER(flush);
38_Py_IDENTIFIER(stderr);
39
Victor Stinner024e37a2011-03-31 01:31:06 +020040#ifdef HAVE_SIGACTION
41typedef struct sigaction _Py_sighandler_t;
42#else
43typedef PyOS_sighandler_t _Py_sighandler_t;
44#endif
45
46typedef struct {
47 int signum;
48 int enabled;
49 const char* name;
50 _Py_sighandler_t previous;
51 int all_threads;
52} fault_handler_t;
53
54static struct {
55 int enabled;
56 PyObject *file;
57 int fd;
58 int all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +020059 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020060} fatal_error = {0, NULL, -1, 0};
61
62#ifdef FAULTHANDLER_LATER
63static struct {
64 PyObject *file;
65 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020066 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020067 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020068 PyInterpreterState *interp;
69 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020070 char *header;
71 size_t header_len;
Victor Stinner410dd7d2011-05-11 20:56:08 +020072 /* The main thread always holds this lock. It is only released when
73 faulthandler_thread() is interrupted before this thread exits, or at
Victor Stinnerde10f402011-04-08 12:57:06 +020074 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020075 PyThread_type_lock cancel_event;
76 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020077 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020078} thread;
79#endif
80
81#ifdef FAULTHANDLER_USER
82typedef struct {
83 int enabled;
84 PyObject *file;
85 int fd;
86 int all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +020087 int chain;
Victor Stinner024e37a2011-03-31 01:31:06 +020088 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020089 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020090} user_signal_t;
91
92static user_signal_t *user_signals;
93
94/* the following macros come from Python: Modules/signalmodule.c */
Victor Stinner024e37a2011-03-31 01:31:06 +020095#ifndef NSIG
96# if defined(_NSIG)
97# define NSIG _NSIG /* For BSD/SysV */
98# elif defined(_SIGMAX)
99# define NSIG (_SIGMAX + 1) /* For QNX */
100# elif defined(SIGMAX)
101# define NSIG (SIGMAX + 1) /* For djgpp */
102# else
103# define NSIG 64 /* Use a reasonable default value */
104# endif
105#endif
106
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200107static void faulthandler_user(int signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200108#endif /* FAULTHANDLER_USER */
109
110
111static fault_handler_t faulthandler_handlers[] = {
112#ifdef SIGBUS
113 {SIGBUS, 0, "Bus error", },
114#endif
115#ifdef SIGILL
116 {SIGILL, 0, "Illegal instruction", },
117#endif
118 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200119 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200120 /* define SIGSEGV at the end to make it the default choice if searching the
121 handler fails in faulthandler_fatal_error() */
122 {SIGSEGV, 0, "Segmentation fault", }
123};
124static const unsigned char faulthandler_nsignals = \
Victor Stinner63941882011-09-29 00:42:28 +0200125 Py_ARRAY_LENGTH(faulthandler_handlers);
Victor Stinner024e37a2011-03-31 01:31:06 +0200126
127#ifdef HAVE_SIGALTSTACK
128static stack_t stack;
129#endif
130
131
132/* Get the file descriptor of a file by calling its fileno() method and then
133 call its flush() method.
134
135 If file is NULL or Py_None, use sys.stderr as the new file.
136
137 On success, return the new file and write the file descriptor into *p_fd.
138 On error, return NULL. */
139
140static PyObject*
141faulthandler_get_fileno(PyObject *file, int *p_fd)
142{
143 PyObject *result;
144 long fd_long;
145 int fd;
146
147 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100148 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200149 if (file == NULL) {
150 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
151 return NULL;
152 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200153 if (file == Py_None) {
154 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
155 return NULL;
156 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200157 }
158
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200159 result = _PyObject_CallMethodId(file, &PyId_fileno, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200160 if (result == NULL)
161 return NULL;
162
163 fd = -1;
164 if (PyLong_Check(result)) {
165 fd_long = PyLong_AsLong(result);
166 if (0 <= fd_long && fd_long < INT_MAX)
167 fd = (int)fd_long;
168 }
169 Py_DECREF(result);
170
171 if (fd == -1) {
172 PyErr_SetString(PyExc_RuntimeError,
173 "file.fileno() is not a valid file descriptor");
174 return NULL;
175 }
176
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200177 result = _PyObject_CallMethodId(file, &PyId_flush, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200178 if (result != NULL)
179 Py_DECREF(result);
180 else {
181 /* ignore flush() error */
182 PyErr_Clear();
183 }
184 *p_fd = fd;
185 return file;
186}
187
Victor Stinnera4de6d82011-04-09 00:47:23 +0200188/* Get the state of the current thread: only call this function if the current
189 thread holds the GIL. Raise an exception on error. */
190static PyThreadState*
191get_thread_state(void)
192{
193 PyThreadState *tstate = PyThreadState_Get();
194 if (tstate == NULL) {
195 PyErr_SetString(PyExc_RuntimeError,
196 "unable to get the current thread state");
197 return NULL;
198 }
199 return tstate;
200}
201
Victor Stinner024e37a2011-03-31 01:31:06 +0200202static PyObject*
203faulthandler_dump_traceback_py(PyObject *self,
204 PyObject *args, PyObject *kwargs)
205{
206 static char *kwlist[] = {"file", "all_threads", NULL};
207 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200208 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200209 PyThreadState *tstate;
210 const char *errmsg;
211 int fd;
212
213 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
214 "|Oi:dump_traceback", kwlist,
215 &file, &all_threads))
216 return NULL;
217
218 file = faulthandler_get_fileno(file, &fd);
219 if (file == NULL)
220 return NULL;
221
Victor Stinnera4de6d82011-04-09 00:47:23 +0200222 tstate = get_thread_state();
223 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200224 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200225
226 if (all_threads) {
227 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
228 if (errmsg != NULL) {
229 PyErr_SetString(PyExc_RuntimeError, errmsg);
230 return NULL;
231 }
232 }
233 else {
234 _Py_DumpTraceback(fd, tstate);
235 }
236 Py_RETURN_NONE;
237}
238
239
Victor Stinner410dd7d2011-05-11 20:56:08 +0200240/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200241
242 Display the current Python traceback, restore the previous handler and call
243 the previous handler.
244
Victor Stinner410dd7d2011-05-11 20:56:08 +0200245 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200246 signal handler would not be called (for an unknown reason). The execution of
247 the program continues at faulthandler_fatal_error() exit, but the same
248 instruction will raise the same fault (signal), and so the previous handler
249 will be called.
250
Victor Stinner410dd7d2011-05-11 20:56:08 +0200251 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200252
253static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200254faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200255{
256 const int fd = fatal_error.fd;
257 unsigned int i;
258 fault_handler_t *handler = NULL;
259 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200260 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200261
262 if (!fatal_error.enabled)
263 return;
264
265 for (i=0; i < faulthandler_nsignals; i++) {
266 handler = &faulthandler_handlers[i];
267 if (handler->signum == signum)
268 break;
269 }
270 if (handler == NULL) {
271 /* faulthandler_nsignals == 0 (unlikely) */
272 return;
273 }
274
275 /* restore the previous handler */
276#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200277 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200278#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200279 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200280#endif
281 handler->enabled = 0;
282
283 PUTS(fd, "Fatal Python error: ");
284 PUTS(fd, handler->name);
285 PUTS(fd, "\n\n");
286
Victor Stinnerff4cd882011-04-07 11:50:25 +0200287#ifdef WITH_THREAD
Victor Stinnerd727e232011-04-01 12:13:55 +0200288 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
Victor Stinner410dd7d2011-05-11 20:56:08 +0200289 are thus delivered to the thread that caused the fault. Get the Python
Victor Stinnerd727e232011-04-01 12:13:55 +0200290 thread state of the current thread.
Victor Stinner024e37a2011-03-31 01:31:06 +0200291
292 PyThreadState_Get() doesn't give the state of the thread that caused the
293 fault if the thread released the GIL, and so this function cannot be
294 used. Read the thread local storage (TLS) instead: call
295 PyGILState_GetThisThreadState(). */
296 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200297#else
298 tstate = PyThreadState_Get();
299#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200300
301 if (fatal_error.all_threads)
Victor Stinnera4de6d82011-04-09 00:47:23 +0200302 _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
303 else {
304 if (tstate != NULL)
305 _Py_DumpTraceback(fd, tstate);
306 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200307
Victor Stinnerc9256172011-05-07 12:20:11 +0200308 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200309#ifdef MS_WINDOWS
310 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200311 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200312 handler, because the Windows signal handler would not be called */
313 return;
314 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200315#endif
R David Murrayfc069992013-12-13 20:52:19 -0500316 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200317 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
318 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200319}
320
Victor Stinnerd727e232011-04-01 12:13:55 +0200321/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200322
323static PyObject*
324faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
325{
326 static char *kwlist[] = {"file", "all_threads", NULL};
327 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200328 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200329 unsigned int i;
330 fault_handler_t *handler;
331#ifdef HAVE_SIGACTION
332 struct sigaction action;
333#endif
334 int err;
335 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200336 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200337
338 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
339 "|Oi:enable", kwlist, &file, &all_threads))
340 return NULL;
341
342 file = faulthandler_get_fileno(file, &fd);
343 if (file == NULL)
344 return NULL;
345
Victor Stinnera4de6d82011-04-09 00:47:23 +0200346 tstate = get_thread_state();
347 if (tstate == NULL)
348 return NULL;
349
Victor Stinner024e37a2011-03-31 01:31:06 +0200350 Py_XDECREF(fatal_error.file);
351 Py_INCREF(file);
352 fatal_error.file = file;
353 fatal_error.fd = fd;
354 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200355 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200356
357 if (!fatal_error.enabled) {
358 fatal_error.enabled = 1;
359
360 for (i=0; i < faulthandler_nsignals; i++) {
361 handler = &faulthandler_handlers[i];
362#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200363 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200364 sigemptyset(&action.sa_mask);
365 /* Do not prevent the signal from being received from within
366 its own signal handler */
367 action.sa_flags = SA_NODEFER;
368#ifdef HAVE_SIGALTSTACK
369 if (stack.ss_sp != NULL) {
370 /* Call the signal handler on an alternate signal stack
371 provided by sigaltstack() */
372 action.sa_flags |= SA_ONSTACK;
373 }
374#endif
375 err = sigaction(handler->signum, &action, &handler->previous);
376#else
377 handler->previous = signal(handler->signum,
378 faulthandler_fatal_error);
379 err = (handler->previous == SIG_ERR);
380#endif
381 if (err) {
382 PyErr_SetFromErrno(PyExc_RuntimeError);
383 return NULL;
384 }
385 handler->enabled = 1;
386 }
387 }
388 Py_RETURN_NONE;
389}
390
391static void
392faulthandler_disable(void)
393{
394 unsigned int i;
395 fault_handler_t *handler;
396
397 if (fatal_error.enabled) {
398 fatal_error.enabled = 0;
399 for (i=0; i < faulthandler_nsignals; i++) {
400 handler = &faulthandler_handlers[i];
401 if (!handler->enabled)
402 continue;
403#ifdef HAVE_SIGACTION
404 (void)sigaction(handler->signum, &handler->previous, NULL);
405#else
406 (void)signal(handler->signum, handler->previous);
407#endif
408 handler->enabled = 0;
409 }
410 }
411
412 Py_CLEAR(fatal_error.file);
413}
414
415static PyObject*
416faulthandler_disable_py(PyObject *self)
417{
418 if (!fatal_error.enabled) {
419 Py_INCREF(Py_False);
420 return Py_False;
421 }
422 faulthandler_disable();
423 Py_INCREF(Py_True);
424 return Py_True;
425}
426
427static PyObject*
428faulthandler_is_enabled(PyObject *self)
429{
430 return PyBool_FromLong(fatal_error.enabled);
431}
432
433#ifdef FAULTHANDLER_LATER
434
435static void
436faulthandler_thread(void *unused)
437{
438 PyLockStatus st;
439 const char* errmsg;
440 PyThreadState *current;
441 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200442#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200443 sigset_t set;
444
445 /* we don't want to receive any signal */
446 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200447 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200448#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200449
450 do {
451 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200452 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200453 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200454 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200455 break;
456 }
457 /* Timeout => dump traceback */
458 assert(st == PY_LOCK_FAILURE);
459
460 /* get the thread holding the GIL, NULL if no thread hold the GIL */
461 current = _Py_atomic_load_relaxed(&_PyThreadState_Current);
462
Victor Stinner56cb1252012-10-31 00:33:57 +0100463 write(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200464
Victor Stinner024e37a2011-03-31 01:31:06 +0200465 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
466 ok = (errmsg == NULL);
467
468 if (thread.exit)
469 _exit(1);
470 } while (ok && thread.repeat);
471
472 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200473 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200474}
475
476static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200477cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200478{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200479 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200480 PyThread_release_lock(thread.cancel_event);
481
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200482 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200483 PyThread_acquire_lock(thread.running, 1);
484 PyThread_release_lock(thread.running);
485
486 /* The main thread should always hold the cancel_event lock */
487 PyThread_acquire_lock(thread.cancel_event, 1);
488
Victor Stinner024e37a2011-03-31 01:31:06 +0200489 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200490 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200491 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200492 thread.header = NULL;
493 }
494}
495
496static char*
497format_timeout(double timeout)
498{
499 unsigned long us, sec, min, hour;
500 double intpart, fracpart;
501 char buffer[100];
502
503 fracpart = modf(timeout, &intpart);
504 sec = (unsigned long)intpart;
505 us = (unsigned long)(fracpart * 1e6);
506 min = sec / 60;
507 sec %= 60;
508 hour = min / 60;
509 min %= 60;
510
511 if (us != 0)
512 PyOS_snprintf(buffer, sizeof(buffer),
513 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
514 hour, min, sec, us);
515 else
516 PyOS_snprintf(buffer, sizeof(buffer),
517 "Timeout (%lu:%02lu:%02lu)!\n",
518 hour, min, sec);
519
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200520 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200521}
522
523static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200524faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200525 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200526{
527 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
528 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200529 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200530 int repeat = 0;
531 PyObject *file = NULL;
532 int fd;
533 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200534 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200535 char *header;
536 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200537
538 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200539 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200540 &timeout, &repeat, &file, &exit))
541 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200542 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200543 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
544 return NULL;
545 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200546 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200547 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200548 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
549 return NULL;
550 }
551
Victor Stinnera4de6d82011-04-09 00:47:23 +0200552 tstate = get_thread_state();
553 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200554 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200555
Victor Stinner024e37a2011-03-31 01:31:06 +0200556 file = faulthandler_get_fileno(file, &fd);
557 if (file == NULL)
558 return NULL;
559
Victor Stinnerc790a532011-04-08 13:39:59 +0200560 /* format the timeout */
561 header = format_timeout(timeout);
562 if (header == NULL)
563 return PyErr_NoMemory();
564 header_len = strlen(header);
565
Victor Stinner024e37a2011-03-31 01:31:06 +0200566 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200567 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200568
569 Py_XDECREF(thread.file);
570 Py_INCREF(file);
571 thread.file = file;
572 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200573 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200574 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200575 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200576 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200577 thread.header = header;
578 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200579
580 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200581 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200582
Victor Stinner024e37a2011-03-31 01:31:06 +0200583 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200584 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200585 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200586 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200587 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200588 PyErr_SetString(PyExc_RuntimeError,
589 "unable to start watchdog thread");
590 return NULL;
591 }
592
593 Py_RETURN_NONE;
594}
595
596static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200597faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200598{
Georg Brandldeb92b52012-09-22 08:58:55 +0200599 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200600 Py_RETURN_NONE;
601}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200602#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200603
604#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200605static int
606faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
607{
608#ifdef HAVE_SIGACTION
609 struct sigaction action;
610 action.sa_handler = faulthandler_user;
611 sigemptyset(&action.sa_mask);
612 /* if the signal is received while the kernel is executing a system
613 call, try to restart the system call instead of interrupting it and
614 return EINTR. */
615 action.sa_flags = SA_RESTART;
616 if (chain) {
617 /* do not prevent the signal from being received from within its
618 own signal handler */
619 action.sa_flags = SA_NODEFER;
620 }
621#ifdef HAVE_SIGALTSTACK
622 if (stack.ss_sp != NULL) {
623 /* Call the signal handler on an alternate signal stack
624 provided by sigaltstack() */
625 action.sa_flags |= SA_ONSTACK;
626 }
627#endif
628 return sigaction(signum, &action, p_previous);
629#else
630 _Py_sighandler_t previous;
631 previous = signal(signum, faulthandler_user);
632 if (p_previous != NULL)
633 *p_previous = previous;
634 return (previous == SIG_ERR);
635#endif
636}
637
Victor Stinner024e37a2011-03-31 01:31:06 +0200638/* Handler of user signals (e.g. SIGUSR1).
639
640 Dump the traceback of the current thread, or of all threads if
641 thread.all_threads is true.
642
643 This function is signal safe and should only call signal safe functions. */
644
645static void
646faulthandler_user(int signum)
647{
648 user_signal_t *user;
649 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200650 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200651
652 user = &user_signals[signum];
653 if (!user->enabled)
654 return;
655
Victor Stinnerff4cd882011-04-07 11:50:25 +0200656#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200657 /* PyThreadState_Get() doesn't give the state of the current thread if
658 the thread doesn't hold the GIL. Read the thread local storage (TLS)
659 instead: call PyGILState_GetThisThreadState(). */
660 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200661#else
662 tstate = PyThreadState_Get();
663#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200664
665 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200666 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
667 else {
Victor Stinner98a387b2012-08-01 19:36:36 +0200668 if (tstate != NULL)
669 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200670 }
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200671#ifdef HAVE_SIGACTION
672 if (user->chain) {
673 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200674 errno = save_errno;
675
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200676 /* call the previous signal handler */
677 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200678
679 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200680 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200681 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200682 }
683#else
684 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200685 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200686 /* call the previous signal handler */
687 user->previous(signum);
688 }
689#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200690}
691
692static int
693check_signum(int signum)
694{
695 unsigned int i;
696
697 for (i=0; i < faulthandler_nsignals; i++) {
698 if (faulthandler_handlers[i].signum == signum) {
699 PyErr_Format(PyExc_RuntimeError,
700 "signal %i cannot be registered, "
701 "use enable() instead",
702 signum);
703 return 0;
704 }
705 }
706 if (signum < 1 || NSIG <= signum) {
707 PyErr_SetString(PyExc_ValueError, "signal number out of range");
708 return 0;
709 }
710 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200711}
712
713static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200714faulthandler_register_py(PyObject *self,
715 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200716{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200717 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200718 int signum;
719 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200720 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200721 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200722 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200723 user_signal_t *user;
724 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200725 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200726 int err;
727
728 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200729 "i|Oii:register", kwlist,
730 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200731 return NULL;
732
Victor Stinner44378d42011-04-01 15:37:12 +0200733 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200734 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200735
Victor Stinnera4de6d82011-04-09 00:47:23 +0200736 tstate = get_thread_state();
737 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200738 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200739
740 file = faulthandler_get_fileno(file, &fd);
741 if (file == NULL)
742 return NULL;
743
744 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200745 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200746 if (user_signals == NULL)
747 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200748 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200749 }
750 user = &user_signals[signum];
751
752 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200753 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200754 if (err) {
755 PyErr_SetFromErrno(PyExc_OSError);
756 return NULL;
757 }
Victor Stinner8d379542013-07-02 00:14:56 +0200758
759 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200760 }
761
762 Py_XDECREF(user->file);
763 Py_INCREF(file);
764 user->file = file;
765 user->fd = fd;
766 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200767 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200768 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200769 user->enabled = 1;
770
771 Py_RETURN_NONE;
772}
773
774static int
775faulthandler_unregister(user_signal_t *user, int signum)
776{
Victor Stinnera01ca122011-04-01 12:56:17 +0200777 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200778 return 0;
779 user->enabled = 0;
780#ifdef HAVE_SIGACTION
781 (void)sigaction(signum, &user->previous, NULL);
782#else
783 (void)signal(signum, user->previous);
784#endif
785 Py_CLEAR(user->file);
786 user->fd = -1;
787 return 1;
788}
789
790static PyObject*
791faulthandler_unregister_py(PyObject *self, PyObject *args)
792{
793 int signum;
794 user_signal_t *user;
795 int change;
796
797 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
798 return NULL;
799
Victor Stinner44378d42011-04-01 15:37:12 +0200800 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200801 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200802
Victor Stinnercfa71232011-04-08 12:48:15 +0200803 if (user_signals == NULL)
804 Py_RETURN_FALSE;
805
Victor Stinner024e37a2011-03-31 01:31:06 +0200806 user = &user_signals[signum];
807 change = faulthandler_unregister(user, signum);
808 return PyBool_FromLong(change);
809}
810#endif /* FAULTHANDLER_USER */
811
812
Victor Stinner7a399122014-09-30 13:40:12 +0200813static void
814faulthandler_suppress_crash_report(void)
815{
816#ifdef MS_WINDOWS
817 UINT mode;
818
819 /* Configure Windows to not display the Windows Error Reporting dialog */
820 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
821 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
822#endif
823
824#ifdef HAVE_SYS_RESOURCE_H
825 struct rlimit rl;
826
827 /* Disable creation of core dump */
828 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
829 rl.rlim_cur = 0;
830 setrlimit(RLIMIT_CORE, &rl);
831 }
832#endif
833
834#ifdef _MSC_VER
835 /* Visual Studio: configure abort() to not display an error message nor
836 open a popup asking to report the fault. */
837 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
838#endif
839}
840
Victor Stinner024e37a2011-03-31 01:31:06 +0200841static PyObject *
842faulthandler_read_null(PyObject *self, PyObject *args)
843{
Victor Stinnera2477202012-01-30 00:07:43 +0100844 volatile int *x;
845 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100846
Victor Stinner7a399122014-09-30 13:40:12 +0200847 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100848 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200849 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200850 return PyLong_FromLong(y);
851
852}
853
Victor Stinner50838282014-09-30 13:54:14 +0200854static void
855faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200856{
Victor Stinner7a399122014-09-30 13:40:12 +0200857 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200858#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200859 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
860 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200861 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200862 SIGSEGV was raised by the kernel because of a fault, and so if the
863 program retries to execute the same instruction, the fault will be
864 raised again.
865
866 Here the fault is simulated by a fake SIGSEGV signal raised by the
867 application. We have to raise SIGSEGV at lease twice: once for
868 faulthandler_fatal_error(), and one more time for the previous signal
869 handler. */
870 while(1)
871 raise(SIGSEGV);
872#else
873 raise(SIGSEGV);
874#endif
Victor Stinner50838282014-09-30 13:54:14 +0200875}
876
877static PyObject *
878faulthandler_sigsegv(PyObject *self, PyObject *args)
879{
880 int release_gil = 0;
881 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
882 return NULL;
883
884 if (release_gil) {
885 Py_BEGIN_ALLOW_THREADS
886 faulthandler_raise_sigsegv();
887 Py_END_ALLOW_THREADS
888 } else {
889 faulthandler_raise_sigsegv();
890 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200891 Py_RETURN_NONE;
892}
893
894static PyObject *
895faulthandler_sigfpe(PyObject *self, PyObject *args)
896{
897 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
898 PowerPC. Use volatile to disable compile-time optimizations. */
899 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +0200900 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200901 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200902 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
903 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200904 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200905 /* This line is never reached, but we pretend to make something with z
906 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200907 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200908}
909
Victor Stinnerd727e232011-04-01 12:13:55 +0200910static PyObject *
911faulthandler_sigabrt(PyObject *self, PyObject *args)
912{
Victor Stinner7a399122014-09-30 13:40:12 +0200913 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200914 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200915 Py_RETURN_NONE;
916}
917
Victor Stinner024e37a2011-03-31 01:31:06 +0200918static PyObject *
919faulthandler_fatal_error_py(PyObject *self, PyObject *args)
920{
921 char *message;
922 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
923 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +0200924 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200925 Py_FatalError(message);
926 Py_RETURN_NONE;
927}
928
929#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner9b493042011-05-23 12:29:10 +0200930static void*
Victor Stinnerf0480752011-03-31 11:34:08 +0200931stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200932{
933 /* allocate 4096 bytes on the stack at each call */
934 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200935 void *sp = &buffer;
936 *depth += 1;
937 if (sp < min_sp || max_sp < sp)
938 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200939 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200940 buffer[4095] = 0;
941 return stack_overflow(min_sp, max_sp, depth);
942}
943
944static PyObject *
945faulthandler_stack_overflow(PyObject *self)
946{
947 size_t depth, size;
Victor Stinner425fcd32011-09-07 16:18:56 +0200948 char *sp = (char *)&depth, *stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200949
Victor Stinner7a399122014-09-30 13:40:12 +0200950 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +0200951 depth = 0;
952 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
953 sp + STACK_OVERFLOW_MAX_SIZE,
954 &depth);
955 if (sp < stop)
956 size = stop - sp;
957 else
958 size = sp - stop;
959 PyErr_Format(PyExc_RuntimeError,
960 "unable to raise a stack overflow (allocated %zu bytes "
961 "on the stack, %zu recursive calls)",
962 size, depth);
963 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200964}
965#endif
966
967
968static int
969faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
970{
971#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200972 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200973#endif
974
975#ifdef FAULTHANDLER_LATER
976 Py_VISIT(thread.file);
977#endif
978#ifdef FAULTHANDLER_USER
979 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200980 for (signum=0; signum < NSIG; signum++)
981 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200982 }
983#endif
984 Py_VISIT(fatal_error.file);
985 return 0;
986}
987
988PyDoc_STRVAR(module_doc,
989"faulthandler module.");
990
991static PyMethodDef module_methods[] = {
992 {"enable",
993 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200994 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200995 "enable the fault handler")},
996 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
997 PyDoc_STR("disable(): disable the fault handler")},
998 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
999 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1000 {"dump_traceback",
1001 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001002 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001003 "dump the traceback of the current thread, or of all threads "
1004 "if all_threads is True, into file")},
1005#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001006 {"dump_traceback_later",
1007 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1008 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001009 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001010 "or each timeout seconds if repeat is True. If exit is True, "
1011 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001012 {"cancel_dump_traceback_later",
1013 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1014 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1015 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001016#endif
1017
1018#ifdef FAULTHANDLER_USER
1019 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001020 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1021 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001022 "register an handler for the signal 'signum': dump the "
1023 "traceback of the current thread, or of all threads if "
1024 "all_threads is True, into file")},
1025 {"unregister",
1026 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1027 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1028 "'signum' registered by register()")},
1029#endif
1030
Victor Stinner50838282014-09-30 13:54:14 +02001031 {"_read_null", faulthandler_read_null, METH_NOARGS,
1032 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001033 "a SIGSEGV or SIGBUS signal depending on the platform")},
1034 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001035 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner9db521c2014-09-30 13:49:09 +02001036 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001037 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001038 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1039 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001040 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1041 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1042#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1043 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1044 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1045#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001046 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001047};
1048
1049static struct PyModuleDef module_def = {
1050 PyModuleDef_HEAD_INIT,
1051 "faulthandler",
1052 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001053 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001054 module_methods,
1055 NULL,
1056 faulthandler_traverse,
1057 NULL,
1058 NULL
1059};
1060
1061PyMODINIT_FUNC
1062PyInit_faulthandler(void)
1063{
1064 return PyModule_Create(&module_def);
1065}
1066
Victor Stinner410dd7d2011-05-11 20:56:08 +02001067/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1068 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001069
1070static int
1071faulthandler_env_options(void)
1072{
1073 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001074 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001075
Victor Stinner88983502013-09-08 11:36:23 +02001076 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1077 /* PYTHONFAULTHANDLER environment variable is missing
1078 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001079 int has_key;
1080
Victor Stinner024e37a2011-03-31 01:31:06 +02001081 xoptions = PySys_GetXOptions();
1082 if (xoptions == NULL)
1083 return -1;
1084
1085 key = PyUnicode_FromString("faulthandler");
1086 if (key == NULL)
1087 return -1;
1088
Victor Stinner25095b22011-05-26 13:47:08 +02001089 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001090 Py_DECREF(key);
Victor Stinner25095b22011-05-26 13:47:08 +02001091 if (!has_key)
Victor Stinner024e37a2011-03-31 01:31:06 +02001092 return 0;
1093 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001094
1095 module = PyImport_ImportModule("faulthandler");
1096 if (module == NULL) {
1097 return -1;
1098 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001099 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001100 Py_DECREF(module);
1101 if (res == NULL)
1102 return -1;
1103 Py_DECREF(res);
1104 return 0;
1105}
1106
1107int _PyFaulthandler_Init(void)
1108{
1109#ifdef HAVE_SIGALTSTACK
1110 int err;
1111
1112 /* Try to allocate an alternate stack for faulthandler() signal handler to
1113 * be able to allocate memory on the stack, even on a stack overflow. If it
1114 * fails, ignore the error. */
1115 stack.ss_flags = 0;
1116 stack.ss_size = SIGSTKSZ;
1117 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1118 if (stack.ss_sp != NULL) {
1119 err = sigaltstack(&stack, NULL);
1120 if (err) {
1121 PyMem_Free(stack.ss_sp);
1122 stack.ss_sp = NULL;
1123 }
1124 }
1125#endif
1126#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001127 thread.file = NULL;
1128 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001129 thread.running = PyThread_allocate_lock();
1130 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001131 PyErr_SetString(PyExc_RuntimeError,
1132 "could not allocate locks for faulthandler");
1133 return -1;
1134 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001135 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001136#endif
1137
1138 return faulthandler_env_options();
1139}
1140
1141void _PyFaulthandler_Fini(void)
1142{
1143#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001144 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001145#endif
1146
1147#ifdef FAULTHANDLER_LATER
1148 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001149 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001150 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001151 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001152 PyThread_free_lock(thread.cancel_event);
1153 thread.cancel_event = NULL;
1154 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001155 if (thread.running) {
1156 PyThread_free_lock(thread.running);
1157 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001158 }
1159#endif
1160
1161#ifdef FAULTHANDLER_USER
1162 /* user */
1163 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001164 for (signum=0; signum < NSIG; signum++)
1165 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001166 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001167 user_signals = NULL;
1168 }
1169#endif
1170
1171 /* fatal */
1172 faulthandler_disable();
1173#ifdef HAVE_SIGALTSTACK
1174 if (stack.ss_sp != NULL) {
1175 PyMem_Free(stack.ss_sp);
1176 stack.ss_sp = NULL;
1177 }
1178#endif
1179}