blob: 27b1d54c60ccbb02395c9a498bd3f9812abdec14 [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 }
147 }
148
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200149 result = _PyObject_CallMethodId(file, &PyId_fileno, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200150 if (result == NULL)
151 return NULL;
152
153 fd = -1;
154 if (PyLong_Check(result)) {
155 fd_long = PyLong_AsLong(result);
156 if (0 <= fd_long && fd_long < INT_MAX)
157 fd = (int)fd_long;
158 }
159 Py_DECREF(result);
160
161 if (fd == -1) {
162 PyErr_SetString(PyExc_RuntimeError,
163 "file.fileno() is not a valid file descriptor");
164 return NULL;
165 }
166
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200167 result = _PyObject_CallMethodId(file, &PyId_flush, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200168 if (result != NULL)
169 Py_DECREF(result);
170 else {
171 /* ignore flush() error */
172 PyErr_Clear();
173 }
174 *p_fd = fd;
175 return file;
176}
177
Victor Stinnera4de6d82011-04-09 00:47:23 +0200178/* Get the state of the current thread: only call this function if the current
179 thread holds the GIL. Raise an exception on error. */
180static PyThreadState*
181get_thread_state(void)
182{
183 PyThreadState *tstate = PyThreadState_Get();
184 if (tstate == NULL) {
185 PyErr_SetString(PyExc_RuntimeError,
186 "unable to get the current thread state");
187 return NULL;
188 }
189 return tstate;
190}
191
Victor Stinner024e37a2011-03-31 01:31:06 +0200192static PyObject*
193faulthandler_dump_traceback_py(PyObject *self,
194 PyObject *args, PyObject *kwargs)
195{
196 static char *kwlist[] = {"file", "all_threads", NULL};
197 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200198 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200199 PyThreadState *tstate;
200 const char *errmsg;
201 int fd;
202
203 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
204 "|Oi:dump_traceback", kwlist,
205 &file, &all_threads))
206 return NULL;
207
208 file = faulthandler_get_fileno(file, &fd);
209 if (file == NULL)
210 return NULL;
211
Victor Stinnera4de6d82011-04-09 00:47:23 +0200212 tstate = get_thread_state();
213 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200214 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200215
216 if (all_threads) {
217 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
218 if (errmsg != NULL) {
219 PyErr_SetString(PyExc_RuntimeError, errmsg);
220 return NULL;
221 }
222 }
223 else {
224 _Py_DumpTraceback(fd, tstate);
225 }
226 Py_RETURN_NONE;
227}
228
229
Victor Stinner410dd7d2011-05-11 20:56:08 +0200230/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200231
232 Display the current Python traceback, restore the previous handler and call
233 the previous handler.
234
Victor Stinner410dd7d2011-05-11 20:56:08 +0200235 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200236 signal handler would not be called (for an unknown reason). The execution of
237 the program continues at faulthandler_fatal_error() exit, but the same
238 instruction will raise the same fault (signal), and so the previous handler
239 will be called.
240
Victor Stinner410dd7d2011-05-11 20:56:08 +0200241 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200242
243static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200244faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200245{
246 const int fd = fatal_error.fd;
247 unsigned int i;
248 fault_handler_t *handler = NULL;
249 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200250 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200251
252 if (!fatal_error.enabled)
253 return;
254
255 for (i=0; i < faulthandler_nsignals; i++) {
256 handler = &faulthandler_handlers[i];
257 if (handler->signum == signum)
258 break;
259 }
260 if (handler == NULL) {
261 /* faulthandler_nsignals == 0 (unlikely) */
262 return;
263 }
264
265 /* restore the previous handler */
266#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200267 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200268#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200269 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200270#endif
271 handler->enabled = 0;
272
273 PUTS(fd, "Fatal Python error: ");
274 PUTS(fd, handler->name);
275 PUTS(fd, "\n\n");
276
Victor Stinnerff4cd882011-04-07 11:50:25 +0200277#ifdef WITH_THREAD
Victor Stinnerd727e232011-04-01 12:13:55 +0200278 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
Victor Stinner410dd7d2011-05-11 20:56:08 +0200279 are thus delivered to the thread that caused the fault. Get the Python
Victor Stinnerd727e232011-04-01 12:13:55 +0200280 thread state of the current thread.
Victor Stinner024e37a2011-03-31 01:31:06 +0200281
282 PyThreadState_Get() doesn't give the state of the thread that caused the
283 fault if the thread released the GIL, and so this function cannot be
284 used. Read the thread local storage (TLS) instead: call
285 PyGILState_GetThisThreadState(). */
286 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200287#else
288 tstate = PyThreadState_Get();
289#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200290
291 if (fatal_error.all_threads)
Victor Stinnera4de6d82011-04-09 00:47:23 +0200292 _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
293 else {
294 if (tstate != NULL)
295 _Py_DumpTraceback(fd, tstate);
296 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200297
Victor Stinnerc9256172011-05-07 12:20:11 +0200298 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200299#ifdef MS_WINDOWS
300 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200301 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200302 handler, because the Windows signal handler would not be called */
303 return;
304 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200305#endif
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200306 /* call the previous signal handler: it is called immediatly if we use
307 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
308 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200309}
310
Victor Stinnerd727e232011-04-01 12:13:55 +0200311/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200312
313static PyObject*
314faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
315{
316 static char *kwlist[] = {"file", "all_threads", NULL};
317 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200318 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200319 unsigned int i;
320 fault_handler_t *handler;
321#ifdef HAVE_SIGACTION
322 struct sigaction action;
323#endif
324 int err;
325 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200326 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200327
328 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
329 "|Oi:enable", kwlist, &file, &all_threads))
330 return NULL;
331
332 file = faulthandler_get_fileno(file, &fd);
333 if (file == NULL)
334 return NULL;
335
Victor Stinnera4de6d82011-04-09 00:47:23 +0200336 tstate = get_thread_state();
337 if (tstate == NULL)
338 return NULL;
339
Victor Stinner024e37a2011-03-31 01:31:06 +0200340 Py_XDECREF(fatal_error.file);
341 Py_INCREF(file);
342 fatal_error.file = file;
343 fatal_error.fd = fd;
344 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200345 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200346
347 if (!fatal_error.enabled) {
348 fatal_error.enabled = 1;
349
350 for (i=0; i < faulthandler_nsignals; i++) {
351 handler = &faulthandler_handlers[i];
352#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200353 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200354 sigemptyset(&action.sa_mask);
355 /* Do not prevent the signal from being received from within
356 its own signal handler */
357 action.sa_flags = SA_NODEFER;
358#ifdef HAVE_SIGALTSTACK
359 if (stack.ss_sp != NULL) {
360 /* Call the signal handler on an alternate signal stack
361 provided by sigaltstack() */
362 action.sa_flags |= SA_ONSTACK;
363 }
364#endif
365 err = sigaction(handler->signum, &action, &handler->previous);
366#else
367 handler->previous = signal(handler->signum,
368 faulthandler_fatal_error);
369 err = (handler->previous == SIG_ERR);
370#endif
371 if (err) {
372 PyErr_SetFromErrno(PyExc_RuntimeError);
373 return NULL;
374 }
375 handler->enabled = 1;
376 }
377 }
378 Py_RETURN_NONE;
379}
380
381static void
382faulthandler_disable(void)
383{
384 unsigned int i;
385 fault_handler_t *handler;
386
387 if (fatal_error.enabled) {
388 fatal_error.enabled = 0;
389 for (i=0; i < faulthandler_nsignals; i++) {
390 handler = &faulthandler_handlers[i];
391 if (!handler->enabled)
392 continue;
393#ifdef HAVE_SIGACTION
394 (void)sigaction(handler->signum, &handler->previous, NULL);
395#else
396 (void)signal(handler->signum, handler->previous);
397#endif
398 handler->enabled = 0;
399 }
400 }
401
402 Py_CLEAR(fatal_error.file);
403}
404
405static PyObject*
406faulthandler_disable_py(PyObject *self)
407{
408 if (!fatal_error.enabled) {
409 Py_INCREF(Py_False);
410 return Py_False;
411 }
412 faulthandler_disable();
413 Py_INCREF(Py_True);
414 return Py_True;
415}
416
417static PyObject*
418faulthandler_is_enabled(PyObject *self)
419{
420 return PyBool_FromLong(fatal_error.enabled);
421}
422
423#ifdef FAULTHANDLER_LATER
424
425static void
426faulthandler_thread(void *unused)
427{
428 PyLockStatus st;
429 const char* errmsg;
430 PyThreadState *current;
431 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200432#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200433 sigset_t set;
434
435 /* we don't want to receive any signal */
436 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200437 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200438#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200439
440 do {
441 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200442 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200443 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200444 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200445 break;
446 }
447 /* Timeout => dump traceback */
448 assert(st == PY_LOCK_FAILURE);
449
450 /* get the thread holding the GIL, NULL if no thread hold the GIL */
451 current = _Py_atomic_load_relaxed(&_PyThreadState_Current);
452
Victor Stinner56cb1252012-10-31 00:33:57 +0100453 write(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200454
Victor Stinner024e37a2011-03-31 01:31:06 +0200455 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
456 ok = (errmsg == NULL);
457
458 if (thread.exit)
459 _exit(1);
460 } while (ok && thread.repeat);
461
462 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200463 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200464}
465
466static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200467cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200468{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200469 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200470 PyThread_release_lock(thread.cancel_event);
471
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200472 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200473 PyThread_acquire_lock(thread.running, 1);
474 PyThread_release_lock(thread.running);
475
476 /* The main thread should always hold the cancel_event lock */
477 PyThread_acquire_lock(thread.cancel_event, 1);
478
Victor Stinner024e37a2011-03-31 01:31:06 +0200479 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200480 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200481 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200482 thread.header = NULL;
483 }
484}
485
486static char*
487format_timeout(double timeout)
488{
489 unsigned long us, sec, min, hour;
490 double intpart, fracpart;
491 char buffer[100];
492
493 fracpart = modf(timeout, &intpart);
494 sec = (unsigned long)intpart;
495 us = (unsigned long)(fracpart * 1e6);
496 min = sec / 60;
497 sec %= 60;
498 hour = min / 60;
499 min %= 60;
500
501 if (us != 0)
502 PyOS_snprintf(buffer, sizeof(buffer),
503 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
504 hour, min, sec, us);
505 else
506 PyOS_snprintf(buffer, sizeof(buffer),
507 "Timeout (%lu:%02lu:%02lu)!\n",
508 hour, min, sec);
509
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200510 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200511}
512
513static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200514faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200515 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200516{
517 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
518 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200519 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200520 int repeat = 0;
521 PyObject *file = NULL;
522 int fd;
523 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200524 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200525 char *header;
526 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200527
528 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200529 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200530 &timeout, &repeat, &file, &exit))
531 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200532 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200533 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
534 return NULL;
535 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200536 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200537 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200538 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
539 return NULL;
540 }
541
Victor Stinnera4de6d82011-04-09 00:47:23 +0200542 tstate = get_thread_state();
543 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200544 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200545
Victor Stinner024e37a2011-03-31 01:31:06 +0200546 file = faulthandler_get_fileno(file, &fd);
547 if (file == NULL)
548 return NULL;
549
Victor Stinnerc790a532011-04-08 13:39:59 +0200550 /* format the timeout */
551 header = format_timeout(timeout);
552 if (header == NULL)
553 return PyErr_NoMemory();
554 header_len = strlen(header);
555
Victor Stinner024e37a2011-03-31 01:31:06 +0200556 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200557 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200558
559 Py_XDECREF(thread.file);
560 Py_INCREF(file);
561 thread.file = file;
562 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200563 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200564 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200565 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200566 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200567 thread.header = header;
568 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200569
570 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200571 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200572
Victor Stinner024e37a2011-03-31 01:31:06 +0200573 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200574 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200575 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200576 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200577 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200578 PyErr_SetString(PyExc_RuntimeError,
579 "unable to start watchdog thread");
580 return NULL;
581 }
582
583 Py_RETURN_NONE;
584}
585
586static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200587faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200588{
Georg Brandldeb92b52012-09-22 08:58:55 +0200589 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200590 Py_RETURN_NONE;
591}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200592#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200593
594#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200595static int
596faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
597{
598#ifdef HAVE_SIGACTION
599 struct sigaction action;
600 action.sa_handler = faulthandler_user;
601 sigemptyset(&action.sa_mask);
602 /* if the signal is received while the kernel is executing a system
603 call, try to restart the system call instead of interrupting it and
604 return EINTR. */
605 action.sa_flags = SA_RESTART;
606 if (chain) {
607 /* do not prevent the signal from being received from within its
608 own signal handler */
609 action.sa_flags = SA_NODEFER;
610 }
611#ifdef HAVE_SIGALTSTACK
612 if (stack.ss_sp != NULL) {
613 /* Call the signal handler on an alternate signal stack
614 provided by sigaltstack() */
615 action.sa_flags |= SA_ONSTACK;
616 }
617#endif
618 return sigaction(signum, &action, p_previous);
619#else
620 _Py_sighandler_t previous;
621 previous = signal(signum, faulthandler_user);
622 if (p_previous != NULL)
623 *p_previous = previous;
624 return (previous == SIG_ERR);
625#endif
626}
627
Victor Stinner024e37a2011-03-31 01:31:06 +0200628/* Handler of user signals (e.g. SIGUSR1).
629
630 Dump the traceback of the current thread, or of all threads if
631 thread.all_threads is true.
632
633 This function is signal safe and should only call signal safe functions. */
634
635static void
636faulthandler_user(int signum)
637{
638 user_signal_t *user;
639 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200640 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200641
642 user = &user_signals[signum];
643 if (!user->enabled)
644 return;
645
Victor Stinnerff4cd882011-04-07 11:50:25 +0200646#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200647 /* PyThreadState_Get() doesn't give the state of the current thread if
648 the thread doesn't hold the GIL. Read the thread local storage (TLS)
649 instead: call PyGILState_GetThisThreadState(). */
650 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200651#else
652 tstate = PyThreadState_Get();
653#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200654
655 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200656 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
657 else {
Victor Stinner98a387b2012-08-01 19:36:36 +0200658 if (tstate != NULL)
659 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200660 }
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200661#ifdef HAVE_SIGACTION
662 if (user->chain) {
663 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200664 errno = save_errno;
665
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200666 /* call the previous signal handler */
667 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200668
669 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200670 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200671 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200672 }
673#else
674 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200675 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200676 /* call the previous signal handler */
677 user->previous(signum);
678 }
679#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200680}
681
682static int
683check_signum(int signum)
684{
685 unsigned int i;
686
687 for (i=0; i < faulthandler_nsignals; i++) {
688 if (faulthandler_handlers[i].signum == signum) {
689 PyErr_Format(PyExc_RuntimeError,
690 "signal %i cannot be registered, "
691 "use enable() instead",
692 signum);
693 return 0;
694 }
695 }
696 if (signum < 1 || NSIG <= signum) {
697 PyErr_SetString(PyExc_ValueError, "signal number out of range");
698 return 0;
699 }
700 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200701}
702
703static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200704faulthandler_register_py(PyObject *self,
705 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200706{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200707 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200708 int signum;
709 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200710 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200711 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200712 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200713 user_signal_t *user;
714 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200715 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200716 int err;
717
718 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200719 "i|Oii:register", kwlist,
720 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200721 return NULL;
722
Victor Stinner44378d42011-04-01 15:37:12 +0200723 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200724 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200725
Victor Stinnera4de6d82011-04-09 00:47:23 +0200726 tstate = get_thread_state();
727 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200728 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200729
730 file = faulthandler_get_fileno(file, &fd);
731 if (file == NULL)
732 return NULL;
733
734 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200735 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200736 if (user_signals == NULL)
737 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200738 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200739 }
740 user = &user_signals[signum];
741
742 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200743 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200744 if (err) {
745 PyErr_SetFromErrno(PyExc_OSError);
746 return NULL;
747 }
Victor Stinner8d379542013-07-02 00:14:56 +0200748
749 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200750 }
751
752 Py_XDECREF(user->file);
753 Py_INCREF(file);
754 user->file = file;
755 user->fd = fd;
756 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200757 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200758 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200759 user->enabled = 1;
760
761 Py_RETURN_NONE;
762}
763
764static int
765faulthandler_unregister(user_signal_t *user, int signum)
766{
Victor Stinnera01ca122011-04-01 12:56:17 +0200767 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200768 return 0;
769 user->enabled = 0;
770#ifdef HAVE_SIGACTION
771 (void)sigaction(signum, &user->previous, NULL);
772#else
773 (void)signal(signum, user->previous);
774#endif
775 Py_CLEAR(user->file);
776 user->fd = -1;
777 return 1;
778}
779
780static PyObject*
781faulthandler_unregister_py(PyObject *self, PyObject *args)
782{
783 int signum;
784 user_signal_t *user;
785 int change;
786
787 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
788 return NULL;
789
Victor Stinner44378d42011-04-01 15:37:12 +0200790 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200791 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200792
Victor Stinnercfa71232011-04-08 12:48:15 +0200793 if (user_signals == NULL)
794 Py_RETURN_FALSE;
795
Victor Stinner024e37a2011-03-31 01:31:06 +0200796 user = &user_signals[signum];
797 change = faulthandler_unregister(user, signum);
798 return PyBool_FromLong(change);
799}
800#endif /* FAULTHANDLER_USER */
801
802
803static PyObject *
804faulthandler_read_null(PyObject *self, PyObject *args)
805{
Victor Stinnera2477202012-01-30 00:07:43 +0100806 volatile int *x;
807 volatile int y;
Victor Stinner024e37a2011-03-31 01:31:06 +0200808 int release_gil = 0;
809 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
810 return NULL;
Victor Stinnera2477202012-01-30 00:07:43 +0100811
812 x = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200813 if (release_gil) {
814 Py_BEGIN_ALLOW_THREADS
815 y = *x;
816 Py_END_ALLOW_THREADS
817 } else
818 y = *x;
819 return PyLong_FromLong(y);
820
821}
822
823static PyObject *
824faulthandler_sigsegv(PyObject *self, PyObject *args)
825{
826#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200827 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
828 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200829 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200830 SIGSEGV was raised by the kernel because of a fault, and so if the
831 program retries to execute the same instruction, the fault will be
832 raised again.
833
834 Here the fault is simulated by a fake SIGSEGV signal raised by the
835 application. We have to raise SIGSEGV at lease twice: once for
836 faulthandler_fatal_error(), and one more time for the previous signal
837 handler. */
838 while(1)
839 raise(SIGSEGV);
840#else
841 raise(SIGSEGV);
842#endif
843 Py_RETURN_NONE;
844}
845
846static PyObject *
847faulthandler_sigfpe(PyObject *self, PyObject *args)
848{
849 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
850 PowerPC. Use volatile to disable compile-time optimizations. */
851 volatile int x = 1, y = 0, z;
852 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200853 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
854 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200855 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200856 /* This line is never reached, but we pretend to make something with z
857 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200858 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200859}
860
Victor Stinnerd727e232011-04-01 12:13:55 +0200861static PyObject *
862faulthandler_sigabrt(PyObject *self, PyObject *args)
863{
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200864#ifdef _MSC_VER
865 /* Visual Studio: configure abort() to not display an error message nor
866 open a popup asking to report the fault. */
867 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
Victor Stinnerd727e232011-04-01 12:13:55 +0200868#endif
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200869 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200870 Py_RETURN_NONE;
871}
872
Victor Stinner024e37a2011-03-31 01:31:06 +0200873#ifdef SIGBUS
874static PyObject *
875faulthandler_sigbus(PyObject *self, PyObject *args)
876{
877 raise(SIGBUS);
878 Py_RETURN_NONE;
879}
880#endif
881
882#ifdef SIGILL
883static PyObject *
884faulthandler_sigill(PyObject *self, PyObject *args)
885{
Victor Stinner024e37a2011-03-31 01:31:06 +0200886 raise(SIGILL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200887 Py_RETURN_NONE;
888}
889#endif
890
891static PyObject *
892faulthandler_fatal_error_py(PyObject *self, PyObject *args)
893{
894 char *message;
895 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
896 return NULL;
897 Py_FatalError(message);
898 Py_RETURN_NONE;
899}
900
901#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner9b493042011-05-23 12:29:10 +0200902static void*
Victor Stinnerf0480752011-03-31 11:34:08 +0200903stack_overflow(void *min_sp, void *max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200904{
905 /* allocate 4096 bytes on the stack at each call */
906 unsigned char buffer[4096];
Victor Stinnerf0480752011-03-31 11:34:08 +0200907 void *sp = &buffer;
908 *depth += 1;
909 if (sp < min_sp || max_sp < sp)
910 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200911 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200912 buffer[4095] = 0;
913 return stack_overflow(min_sp, max_sp, depth);
914}
915
916static PyObject *
917faulthandler_stack_overflow(PyObject *self)
918{
919 size_t depth, size;
Victor Stinner425fcd32011-09-07 16:18:56 +0200920 char *sp = (char *)&depth, *stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200921
922 depth = 0;
923 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
924 sp + STACK_OVERFLOW_MAX_SIZE,
925 &depth);
926 if (sp < stop)
927 size = stop - sp;
928 else
929 size = sp - stop;
930 PyErr_Format(PyExc_RuntimeError,
931 "unable to raise a stack overflow (allocated %zu bytes "
932 "on the stack, %zu recursive calls)",
933 size, depth);
934 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200935}
936#endif
937
938
939static int
940faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
941{
942#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200943 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200944#endif
945
946#ifdef FAULTHANDLER_LATER
947 Py_VISIT(thread.file);
948#endif
949#ifdef FAULTHANDLER_USER
950 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200951 for (signum=0; signum < NSIG; signum++)
952 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200953 }
954#endif
955 Py_VISIT(fatal_error.file);
956 return 0;
957}
958
959PyDoc_STRVAR(module_doc,
960"faulthandler module.");
961
962static PyMethodDef module_methods[] = {
963 {"enable",
964 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200965 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200966 "enable the fault handler")},
967 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
968 PyDoc_STR("disable(): disable the fault handler")},
969 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
970 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
971 {"dump_traceback",
972 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +0200973 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200974 "dump the traceback of the current thread, or of all threads "
975 "if all_threads is True, into file")},
976#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +0200977 {"dump_traceback_later",
978 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
979 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +0200980 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +0200981 "or each timeout seconds if repeat is True. If exit is True, "
982 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +0200983 {"cancel_dump_traceback_later",
984 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
985 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
986 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +0200987#endif
988
989#ifdef FAULTHANDLER_USER
990 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200991 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
992 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +0200993 "register an handler for the signal 'signum': dump the "
994 "traceback of the current thread, or of all threads if "
995 "all_threads is True, into file")},
996 {"unregister",
997 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
998 PyDoc_STR("unregister(signum): unregister the handler of the signal "
999 "'signum' registered by register()")},
1000#endif
1001
1002 {"_read_null", faulthandler_read_null, METH_VARARGS,
1003 PyDoc_STR("_read_null(release_gil=False): read from NULL, raise "
1004 "a SIGSEGV or SIGBUS signal depending on the platform")},
1005 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
1006 PyDoc_STR("_sigsegv(): raise a SIGSEGV signal")},
Victor Stinnerd727e232011-04-01 12:13:55 +02001007 {"_sigabrt", faulthandler_sigabrt, METH_VARARGS,
1008 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001009 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1010 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
1011#ifdef SIGBUS
1012 {"_sigbus", (PyCFunction)faulthandler_sigbus, METH_NOARGS,
1013 PyDoc_STR("_sigbus(): raise a SIGBUS signal")},
1014#endif
1015#ifdef SIGILL
1016 {"_sigill", (PyCFunction)faulthandler_sigill, METH_NOARGS,
1017 PyDoc_STR("_sigill(): raise a SIGILL signal")},
1018#endif
1019 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1020 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1021#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1022 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1023 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1024#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001025 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001026};
1027
1028static struct PyModuleDef module_def = {
1029 PyModuleDef_HEAD_INIT,
1030 "faulthandler",
1031 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001032 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001033 module_methods,
1034 NULL,
1035 faulthandler_traverse,
1036 NULL,
1037 NULL
1038};
1039
1040PyMODINIT_FUNC
1041PyInit_faulthandler(void)
1042{
1043 return PyModule_Create(&module_def);
1044}
1045
Victor Stinner410dd7d2011-05-11 20:56:08 +02001046/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1047 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001048
1049static int
1050faulthandler_env_options(void)
1051{
1052 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001053 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001054
Victor Stinner88983502013-09-08 11:36:23 +02001055 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1056 /* PYTHONFAULTHANDLER environment variable is missing
1057 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001058 int has_key;
1059
Victor Stinner024e37a2011-03-31 01:31:06 +02001060 xoptions = PySys_GetXOptions();
1061 if (xoptions == NULL)
1062 return -1;
1063
1064 key = PyUnicode_FromString("faulthandler");
1065 if (key == NULL)
1066 return -1;
1067
Victor Stinner25095b22011-05-26 13:47:08 +02001068 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001069 Py_DECREF(key);
Victor Stinner25095b22011-05-26 13:47:08 +02001070 if (!has_key)
Victor Stinner024e37a2011-03-31 01:31:06 +02001071 return 0;
1072 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001073
1074 module = PyImport_ImportModule("faulthandler");
1075 if (module == NULL) {
1076 return -1;
1077 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001078 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001079 Py_DECREF(module);
1080 if (res == NULL)
1081 return -1;
1082 Py_DECREF(res);
1083 return 0;
1084}
1085
1086int _PyFaulthandler_Init(void)
1087{
1088#ifdef HAVE_SIGALTSTACK
1089 int err;
1090
1091 /* Try to allocate an alternate stack for faulthandler() signal handler to
1092 * be able to allocate memory on the stack, even on a stack overflow. If it
1093 * fails, ignore the error. */
1094 stack.ss_flags = 0;
1095 stack.ss_size = SIGSTKSZ;
1096 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1097 if (stack.ss_sp != NULL) {
1098 err = sigaltstack(&stack, NULL);
1099 if (err) {
1100 PyMem_Free(stack.ss_sp);
1101 stack.ss_sp = NULL;
1102 }
1103 }
1104#endif
1105#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001106 thread.file = NULL;
1107 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001108 thread.running = PyThread_allocate_lock();
1109 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001110 PyErr_SetString(PyExc_RuntimeError,
1111 "could not allocate locks for faulthandler");
1112 return -1;
1113 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001114 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001115#endif
1116
1117 return faulthandler_env_options();
1118}
1119
1120void _PyFaulthandler_Fini(void)
1121{
1122#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001123 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001124#endif
1125
1126#ifdef FAULTHANDLER_LATER
1127 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001128 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001129 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001130 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001131 PyThread_free_lock(thread.cancel_event);
1132 thread.cancel_event = NULL;
1133 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001134 if (thread.running) {
1135 PyThread_free_lock(thread.running);
1136 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001137 }
1138#endif
1139
1140#ifdef FAULTHANDLER_USER
1141 /* user */
1142 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001143 for (signum=0; signum < NSIG; signum++)
1144 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001145 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001146 user_signals = NULL;
1147 }
1148#endif
1149
1150 /* fatal */
1151 faulthandler_disable();
1152#ifdef HAVE_SIGALTSTACK
1153 if (stack.ss_sp != NULL) {
1154 PyMem_Free(stack.ss_sp);
1155 stack.ss_sp = NULL;
1156 }
1157#endif
1158}