blob: def7b29d6d3a05780ac0444b0a946eaf9b037e99 [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.
Victor Stinner95bb7142015-03-12 15:32:03 +0100136 If file is an integer, it will be treated as file descriptor.
Victor Stinner024e37a2011-03-31 01:31:06 +0200137
Victor Stinner95bb7142015-03-12 15:32:03 +0100138 On success, return the file descriptor and write the new file into *file_ptr.
139 On error, return -1. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200140
Victor Stinner95bb7142015-03-12 15:32:03 +0100141static int
142faulthandler_get_fileno(PyObject **file_ptr)
Victor Stinner024e37a2011-03-31 01:31:06 +0200143{
144 PyObject *result;
145 long fd_long;
146 int fd;
Victor Stinner95bb7142015-03-12 15:32:03 +0100147 PyObject *file = *file_ptr;
Victor Stinner024e37a2011-03-31 01:31:06 +0200148
149 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100150 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200151 if (file == NULL) {
152 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
Victor Stinner95bb7142015-03-12 15:32:03 +0100153 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200154 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200155 if (file == Py_None) {
156 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
Victor Stinner95bb7142015-03-12 15:32:03 +0100157 return -1;
Victor Stinnere2d66902014-05-14 17:15:50 +0200158 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200159 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100160 else if (PyLong_Check(file)) {
161 fd = _PyLong_AsInt(file);
162 if (fd == -1 && PyErr_Occurred())
163 return -1;
164 if (fd < 0 || !_PyVerify_fd(fd)) {
165 PyErr_SetString(PyExc_ValueError,
166 "file is not a valid file descripter");
167 return -1;
168 }
169 *file_ptr = NULL;
170 return fd;
171 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200172
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200173 result = _PyObject_CallMethodId(file, &PyId_fileno, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200174 if (result == NULL)
Victor Stinner95bb7142015-03-12 15:32:03 +0100175 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200176
177 fd = -1;
178 if (PyLong_Check(result)) {
179 fd_long = PyLong_AsLong(result);
180 if (0 <= fd_long && fd_long < INT_MAX)
181 fd = (int)fd_long;
182 }
183 Py_DECREF(result);
184
185 if (fd == -1) {
186 PyErr_SetString(PyExc_RuntimeError,
187 "file.fileno() is not a valid file descriptor");
Victor Stinner95bb7142015-03-12 15:32:03 +0100188 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200189 }
190
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200191 result = _PyObject_CallMethodId(file, &PyId_flush, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200192 if (result != NULL)
193 Py_DECREF(result);
194 else {
195 /* ignore flush() error */
196 PyErr_Clear();
197 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100198 *file_ptr = file;
199 return fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200200}
201
Victor Stinnera4de6d82011-04-09 00:47:23 +0200202/* Get the state of the current thread: only call this function if the current
203 thread holds the GIL. Raise an exception on error. */
204static PyThreadState*
205get_thread_state(void)
206{
207 PyThreadState *tstate = PyThreadState_Get();
208 if (tstate == NULL) {
209 PyErr_SetString(PyExc_RuntimeError,
210 "unable to get the current thread state");
211 return NULL;
212 }
213 return tstate;
214}
215
Victor Stinner024e37a2011-03-31 01:31:06 +0200216static PyObject*
217faulthandler_dump_traceback_py(PyObject *self,
218 PyObject *args, PyObject *kwargs)
219{
220 static char *kwlist[] = {"file", "all_threads", NULL};
221 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200222 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200223 PyThreadState *tstate;
224 const char *errmsg;
225 int fd;
226
227 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
228 "|Oi:dump_traceback", kwlist,
229 &file, &all_threads))
230 return NULL;
231
Victor Stinner95bb7142015-03-12 15:32:03 +0100232 fd = faulthandler_get_fileno(&file);
233 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200234 return NULL;
235
Victor Stinnera4de6d82011-04-09 00:47:23 +0200236 tstate = get_thread_state();
237 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200238 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200239
240 if (all_threads) {
241 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
242 if (errmsg != NULL) {
243 PyErr_SetString(PyExc_RuntimeError, errmsg);
244 return NULL;
245 }
246 }
247 else {
248 _Py_DumpTraceback(fd, tstate);
249 }
250 Py_RETURN_NONE;
251}
252
253
Victor Stinner410dd7d2011-05-11 20:56:08 +0200254/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200255
256 Display the current Python traceback, restore the previous handler and call
257 the previous handler.
258
Victor Stinner410dd7d2011-05-11 20:56:08 +0200259 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200260 signal handler would not be called (for an unknown reason). The execution of
261 the program continues at faulthandler_fatal_error() exit, but the same
262 instruction will raise the same fault (signal), and so the previous handler
263 will be called.
264
Victor Stinner410dd7d2011-05-11 20:56:08 +0200265 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200266
267static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200268faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200269{
270 const int fd = fatal_error.fd;
271 unsigned int i;
272 fault_handler_t *handler = NULL;
273 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200274 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200275
276 if (!fatal_error.enabled)
277 return;
278
279 for (i=0; i < faulthandler_nsignals; i++) {
280 handler = &faulthandler_handlers[i];
281 if (handler->signum == signum)
282 break;
283 }
284 if (handler == NULL) {
285 /* faulthandler_nsignals == 0 (unlikely) */
286 return;
287 }
288
289 /* restore the previous handler */
290#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200291 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200292#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200293 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200294#endif
295 handler->enabled = 0;
296
297 PUTS(fd, "Fatal Python error: ");
298 PUTS(fd, handler->name);
299 PUTS(fd, "\n\n");
300
Victor Stinnerff4cd882011-04-07 11:50:25 +0200301#ifdef WITH_THREAD
Victor Stinnerd727e232011-04-01 12:13:55 +0200302 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
Victor Stinner410dd7d2011-05-11 20:56:08 +0200303 are thus delivered to the thread that caused the fault. Get the Python
Victor Stinnerd727e232011-04-01 12:13:55 +0200304 thread state of the current thread.
Victor Stinner024e37a2011-03-31 01:31:06 +0200305
306 PyThreadState_Get() doesn't give the state of the thread that caused the
307 fault if the thread released the GIL, and so this function cannot be
308 used. Read the thread local storage (TLS) instead: call
309 PyGILState_GetThisThreadState(). */
310 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200311#else
312 tstate = PyThreadState_Get();
313#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200314
315 if (fatal_error.all_threads)
Victor Stinnera4de6d82011-04-09 00:47:23 +0200316 _Py_DumpTracebackThreads(fd, fatal_error.interp, tstate);
317 else {
318 if (tstate != NULL)
319 _Py_DumpTraceback(fd, tstate);
320 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200321
Victor Stinnerc9256172011-05-07 12:20:11 +0200322 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200323#ifdef MS_WINDOWS
324 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200325 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200326 handler, because the Windows signal handler would not be called */
327 return;
328 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200329#endif
R David Murrayfc069992013-12-13 20:52:19 -0500330 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200331 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
332 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200333}
334
Victor Stinnerd727e232011-04-01 12:13:55 +0200335/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200336
337static PyObject*
338faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
339{
340 static char *kwlist[] = {"file", "all_threads", NULL};
341 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200342 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200343 unsigned int i;
344 fault_handler_t *handler;
345#ifdef HAVE_SIGACTION
346 struct sigaction action;
347#endif
348 int err;
349 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200350 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200351
352 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
353 "|Oi:enable", kwlist, &file, &all_threads))
354 return NULL;
355
Victor Stinner95bb7142015-03-12 15:32:03 +0100356 fd = faulthandler_get_fileno(&file);
357 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200358 return NULL;
359
Victor Stinnera4de6d82011-04-09 00:47:23 +0200360 tstate = get_thread_state();
361 if (tstate == NULL)
362 return NULL;
363
Victor Stinner024e37a2011-03-31 01:31:06 +0200364 Py_XDECREF(fatal_error.file);
Victor Stinner95bb7142015-03-12 15:32:03 +0100365 Py_XINCREF(file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200366 fatal_error.file = file;
367 fatal_error.fd = fd;
368 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200369 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200370
371 if (!fatal_error.enabled) {
372 fatal_error.enabled = 1;
373
374 for (i=0; i < faulthandler_nsignals; i++) {
375 handler = &faulthandler_handlers[i];
376#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200377 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200378 sigemptyset(&action.sa_mask);
379 /* Do not prevent the signal from being received from within
380 its own signal handler */
381 action.sa_flags = SA_NODEFER;
382#ifdef HAVE_SIGALTSTACK
383 if (stack.ss_sp != NULL) {
384 /* Call the signal handler on an alternate signal stack
385 provided by sigaltstack() */
386 action.sa_flags |= SA_ONSTACK;
387 }
388#endif
389 err = sigaction(handler->signum, &action, &handler->previous);
390#else
391 handler->previous = signal(handler->signum,
392 faulthandler_fatal_error);
393 err = (handler->previous == SIG_ERR);
394#endif
395 if (err) {
396 PyErr_SetFromErrno(PyExc_RuntimeError);
397 return NULL;
398 }
399 handler->enabled = 1;
400 }
401 }
402 Py_RETURN_NONE;
403}
404
405static void
406faulthandler_disable(void)
407{
408 unsigned int i;
409 fault_handler_t *handler;
410
411 if (fatal_error.enabled) {
412 fatal_error.enabled = 0;
413 for (i=0; i < faulthandler_nsignals; i++) {
414 handler = &faulthandler_handlers[i];
415 if (!handler->enabled)
416 continue;
417#ifdef HAVE_SIGACTION
418 (void)sigaction(handler->signum, &handler->previous, NULL);
419#else
420 (void)signal(handler->signum, handler->previous);
421#endif
422 handler->enabled = 0;
423 }
424 }
425
426 Py_CLEAR(fatal_error.file);
427}
428
429static PyObject*
430faulthandler_disable_py(PyObject *self)
431{
432 if (!fatal_error.enabled) {
433 Py_INCREF(Py_False);
434 return Py_False;
435 }
436 faulthandler_disable();
437 Py_INCREF(Py_True);
438 return Py_True;
439}
440
441static PyObject*
442faulthandler_is_enabled(PyObject *self)
443{
444 return PyBool_FromLong(fatal_error.enabled);
445}
446
447#ifdef FAULTHANDLER_LATER
448
449static void
450faulthandler_thread(void *unused)
451{
452 PyLockStatus st;
453 const char* errmsg;
454 PyThreadState *current;
455 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200456#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200457 sigset_t set;
458
459 /* we don't want to receive any signal */
460 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200461 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200462#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200463
464 do {
465 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200466 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200467 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200468 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200469 break;
470 }
471 /* Timeout => dump traceback */
472 assert(st == PY_LOCK_FAILURE);
473
474 /* get the thread holding the GIL, NULL if no thread hold the GIL */
Serhiy Storchaka53fa8b22015-02-16 09:40:12 +0200475 current = (PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current);
Victor Stinner024e37a2011-03-31 01:31:06 +0200476
Victor Stinner56cb1252012-10-31 00:33:57 +0100477 write(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200478
Victor Stinner024e37a2011-03-31 01:31:06 +0200479 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
480 ok = (errmsg == NULL);
481
482 if (thread.exit)
483 _exit(1);
484 } while (ok && thread.repeat);
485
486 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200487 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200488}
489
490static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200491cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200492{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200493 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200494 PyThread_release_lock(thread.cancel_event);
495
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200496 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200497 PyThread_acquire_lock(thread.running, 1);
498 PyThread_release_lock(thread.running);
499
500 /* The main thread should always hold the cancel_event lock */
501 PyThread_acquire_lock(thread.cancel_event, 1);
502
Victor Stinner024e37a2011-03-31 01:31:06 +0200503 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200504 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200505 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200506 thread.header = NULL;
507 }
508}
509
510static char*
511format_timeout(double timeout)
512{
513 unsigned long us, sec, min, hour;
514 double intpart, fracpart;
515 char buffer[100];
516
517 fracpart = modf(timeout, &intpart);
518 sec = (unsigned long)intpart;
519 us = (unsigned long)(fracpart * 1e6);
520 min = sec / 60;
521 sec %= 60;
522 hour = min / 60;
523 min %= 60;
524
525 if (us != 0)
526 PyOS_snprintf(buffer, sizeof(buffer),
527 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
528 hour, min, sec, us);
529 else
530 PyOS_snprintf(buffer, sizeof(buffer),
531 "Timeout (%lu:%02lu:%02lu)!\n",
532 hour, min, sec);
533
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200534 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200535}
536
537static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200538faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200539 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200540{
541 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
542 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200543 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200544 int repeat = 0;
545 PyObject *file = NULL;
546 int fd;
547 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200548 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200549 char *header;
550 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200551
552 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200553 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200554 &timeout, &repeat, &file, &exit))
555 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200556 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200557 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
558 return NULL;
559 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200560 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200561 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200562 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
563 return NULL;
564 }
565
Victor Stinnera4de6d82011-04-09 00:47:23 +0200566 tstate = get_thread_state();
567 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200568 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200569
Victor Stinner95bb7142015-03-12 15:32:03 +0100570 fd = faulthandler_get_fileno(&file);
571 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200572 return NULL;
573
Victor Stinnerc790a532011-04-08 13:39:59 +0200574 /* format the timeout */
575 header = format_timeout(timeout);
576 if (header == NULL)
577 return PyErr_NoMemory();
578 header_len = strlen(header);
579
Victor Stinner024e37a2011-03-31 01:31:06 +0200580 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200581 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200582
583 Py_XDECREF(thread.file);
Victor Stinner95bb7142015-03-12 15:32:03 +0100584 Py_XINCREF(file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200585 thread.file = file;
586 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200587 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200588 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200589 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200590 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200591 thread.header = header;
592 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200593
594 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200595 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200596
Victor Stinner024e37a2011-03-31 01:31:06 +0200597 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200598 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200599 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200600 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200601 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200602 PyErr_SetString(PyExc_RuntimeError,
603 "unable to start watchdog thread");
604 return NULL;
605 }
606
607 Py_RETURN_NONE;
608}
609
610static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200611faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200612{
Georg Brandldeb92b52012-09-22 08:58:55 +0200613 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200614 Py_RETURN_NONE;
615}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200616#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200617
618#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200619static int
620faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
621{
622#ifdef HAVE_SIGACTION
623 struct sigaction action;
624 action.sa_handler = faulthandler_user;
625 sigemptyset(&action.sa_mask);
626 /* if the signal is received while the kernel is executing a system
627 call, try to restart the system call instead of interrupting it and
628 return EINTR. */
629 action.sa_flags = SA_RESTART;
630 if (chain) {
631 /* do not prevent the signal from being received from within its
632 own signal handler */
633 action.sa_flags = SA_NODEFER;
634 }
635#ifdef HAVE_SIGALTSTACK
636 if (stack.ss_sp != NULL) {
637 /* Call the signal handler on an alternate signal stack
638 provided by sigaltstack() */
639 action.sa_flags |= SA_ONSTACK;
640 }
641#endif
642 return sigaction(signum, &action, p_previous);
643#else
644 _Py_sighandler_t previous;
645 previous = signal(signum, faulthandler_user);
646 if (p_previous != NULL)
647 *p_previous = previous;
648 return (previous == SIG_ERR);
649#endif
650}
651
Victor Stinner024e37a2011-03-31 01:31:06 +0200652/* Handler of user signals (e.g. SIGUSR1).
653
654 Dump the traceback of the current thread, or of all threads if
655 thread.all_threads is true.
656
657 This function is signal safe and should only call signal safe functions. */
658
659static void
660faulthandler_user(int signum)
661{
662 user_signal_t *user;
663 PyThreadState *tstate;
Victor Stinnerc9256172011-05-07 12:20:11 +0200664 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200665
666 user = &user_signals[signum];
667 if (!user->enabled)
668 return;
669
Victor Stinnerff4cd882011-04-07 11:50:25 +0200670#ifdef WITH_THREAD
Victor Stinner024e37a2011-03-31 01:31:06 +0200671 /* PyThreadState_Get() doesn't give the state of the current thread if
672 the thread doesn't hold the GIL. Read the thread local storage (TLS)
673 instead: call PyGILState_GetThisThreadState(). */
674 tstate = PyGILState_GetThisThreadState();
Victor Stinnerff4cd882011-04-07 11:50:25 +0200675#else
676 tstate = PyThreadState_Get();
677#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200678
679 if (user->all_threads)
Victor Stinner44378d42011-04-01 15:37:12 +0200680 _Py_DumpTracebackThreads(user->fd, user->interp, tstate);
681 else {
Victor Stinner98a387b2012-08-01 19:36:36 +0200682 if (tstate != NULL)
683 _Py_DumpTraceback(user->fd, tstate);
Victor Stinner44378d42011-04-01 15:37:12 +0200684 }
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200685#ifdef HAVE_SIGACTION
686 if (user->chain) {
687 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200688 errno = save_errno;
689
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200690 /* call the previous signal handler */
691 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200692
693 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200694 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200695 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200696 }
697#else
698 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200699 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200700 /* call the previous signal handler */
701 user->previous(signum);
702 }
703#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200704}
705
706static int
707check_signum(int signum)
708{
709 unsigned int i;
710
711 for (i=0; i < faulthandler_nsignals; i++) {
712 if (faulthandler_handlers[i].signum == signum) {
713 PyErr_Format(PyExc_RuntimeError,
714 "signal %i cannot be registered, "
715 "use enable() instead",
716 signum);
717 return 0;
718 }
719 }
720 if (signum < 1 || NSIG <= signum) {
721 PyErr_SetString(PyExc_ValueError, "signal number out of range");
722 return 0;
723 }
724 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200725}
726
727static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200728faulthandler_register_py(PyObject *self,
729 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200730{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200731 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200732 int signum;
733 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200734 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200735 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200736 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200737 user_signal_t *user;
738 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200739 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200740 int err;
741
742 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200743 "i|Oii:register", kwlist,
744 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200745 return NULL;
746
Victor Stinner44378d42011-04-01 15:37:12 +0200747 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200748 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200749
Victor Stinnera4de6d82011-04-09 00:47:23 +0200750 tstate = get_thread_state();
751 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200752 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200753
Victor Stinner95bb7142015-03-12 15:32:03 +0100754 fd = faulthandler_get_fileno(&file);
755 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200756 return NULL;
757
758 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200759 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200760 if (user_signals == NULL)
761 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200762 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200763 }
764 user = &user_signals[signum];
765
766 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200767 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200768 if (err) {
769 PyErr_SetFromErrno(PyExc_OSError);
770 return NULL;
771 }
Victor Stinner8d379542013-07-02 00:14:56 +0200772
773 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200774 }
775
776 Py_XDECREF(user->file);
Victor Stinner95bb7142015-03-12 15:32:03 +0100777 Py_XINCREF(file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200778 user->file = file;
779 user->fd = fd;
780 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200781 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200782 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200783 user->enabled = 1;
784
785 Py_RETURN_NONE;
786}
787
788static int
789faulthandler_unregister(user_signal_t *user, int signum)
790{
Victor Stinnera01ca122011-04-01 12:56:17 +0200791 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200792 return 0;
793 user->enabled = 0;
794#ifdef HAVE_SIGACTION
795 (void)sigaction(signum, &user->previous, NULL);
796#else
797 (void)signal(signum, user->previous);
798#endif
799 Py_CLEAR(user->file);
800 user->fd = -1;
801 return 1;
802}
803
804static PyObject*
805faulthandler_unregister_py(PyObject *self, PyObject *args)
806{
807 int signum;
808 user_signal_t *user;
809 int change;
810
811 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
812 return NULL;
813
Victor Stinner44378d42011-04-01 15:37:12 +0200814 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200815 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200816
Victor Stinnercfa71232011-04-08 12:48:15 +0200817 if (user_signals == NULL)
818 Py_RETURN_FALSE;
819
Victor Stinner024e37a2011-03-31 01:31:06 +0200820 user = &user_signals[signum];
821 change = faulthandler_unregister(user, signum);
822 return PyBool_FromLong(change);
823}
824#endif /* FAULTHANDLER_USER */
825
826
Victor Stinner7a399122014-09-30 13:40:12 +0200827static void
828faulthandler_suppress_crash_report(void)
829{
830#ifdef MS_WINDOWS
831 UINT mode;
832
833 /* Configure Windows to not display the Windows Error Reporting dialog */
834 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
835 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
836#endif
837
838#ifdef HAVE_SYS_RESOURCE_H
839 struct rlimit rl;
840
841 /* Disable creation of core dump */
842 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
843 rl.rlim_cur = 0;
844 setrlimit(RLIMIT_CORE, &rl);
845 }
846#endif
847
848#ifdef _MSC_VER
849 /* Visual Studio: configure abort() to not display an error message nor
850 open a popup asking to report the fault. */
851 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
852#endif
853}
854
Victor Stinner024e37a2011-03-31 01:31:06 +0200855static PyObject *
856faulthandler_read_null(PyObject *self, PyObject *args)
857{
Victor Stinnera2477202012-01-30 00:07:43 +0100858 volatile int *x;
859 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100860
Victor Stinner7a399122014-09-30 13:40:12 +0200861 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100862 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200863 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200864 return PyLong_FromLong(y);
865
866}
867
Victor Stinner50838282014-09-30 13:54:14 +0200868static void
869faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200870{
Victor Stinner7a399122014-09-30 13:40:12 +0200871 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200872#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200873 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
874 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200875 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200876 SIGSEGV was raised by the kernel because of a fault, and so if the
877 program retries to execute the same instruction, the fault will be
878 raised again.
879
880 Here the fault is simulated by a fake SIGSEGV signal raised by the
881 application. We have to raise SIGSEGV at lease twice: once for
882 faulthandler_fatal_error(), and one more time for the previous signal
883 handler. */
884 while(1)
885 raise(SIGSEGV);
886#else
887 raise(SIGSEGV);
888#endif
Victor Stinner50838282014-09-30 13:54:14 +0200889}
890
891static PyObject *
892faulthandler_sigsegv(PyObject *self, PyObject *args)
893{
894 int release_gil = 0;
895 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
896 return NULL;
897
898 if (release_gil) {
899 Py_BEGIN_ALLOW_THREADS
900 faulthandler_raise_sigsegv();
901 Py_END_ALLOW_THREADS
902 } else {
903 faulthandler_raise_sigsegv();
904 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200905 Py_RETURN_NONE;
906}
907
908static PyObject *
909faulthandler_sigfpe(PyObject *self, PyObject *args)
910{
911 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
912 PowerPC. Use volatile to disable compile-time optimizations. */
913 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +0200914 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200915 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200916 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
917 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200918 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200919 /* This line is never reached, but we pretend to make something with z
920 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200921 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200922}
923
Victor Stinnerd727e232011-04-01 12:13:55 +0200924static PyObject *
925faulthandler_sigabrt(PyObject *self, PyObject *args)
926{
Victor Stinner7a399122014-09-30 13:40:12 +0200927 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200928 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200929 Py_RETURN_NONE;
930}
931
Victor Stinner024e37a2011-03-31 01:31:06 +0200932static PyObject *
933faulthandler_fatal_error_py(PyObject *self, PyObject *args)
934{
935 char *message;
936 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
937 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +0200938 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200939 Py_FatalError(message);
940 Py_RETURN_NONE;
941}
942
943#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner7a5567a2015-02-11 14:23:35 +0100944static Py_uintptr_t
945stack_overflow(Py_uintptr_t min_sp, Py_uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200946{
947 /* allocate 4096 bytes on the stack at each call */
948 unsigned char buffer[4096];
Victor Stinner7a5567a2015-02-11 14:23:35 +0100949 Py_uintptr_t sp = (Py_uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +0200950 *depth += 1;
951 if (sp < min_sp || max_sp < sp)
952 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200953 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200954 buffer[4095] = 0;
955 return stack_overflow(min_sp, max_sp, depth);
956}
957
958static PyObject *
959faulthandler_stack_overflow(PyObject *self)
960{
961 size_t depth, size;
Victor Stinner7a5567a2015-02-11 14:23:35 +0100962 Py_uintptr_t sp = (Py_uintptr_t)&depth;
963 Py_uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200964
Victor Stinner7a399122014-09-30 13:40:12 +0200965 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +0200966 depth = 0;
967 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
968 sp + STACK_OVERFLOW_MAX_SIZE,
969 &depth);
970 if (sp < stop)
971 size = stop - sp;
972 else
973 size = sp - stop;
974 PyErr_Format(PyExc_RuntimeError,
975 "unable to raise a stack overflow (allocated %zu bytes "
976 "on the stack, %zu recursive calls)",
977 size, depth);
978 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200979}
980#endif
981
982
983static int
984faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
985{
986#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200987 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +0200988#endif
989
990#ifdef FAULTHANDLER_LATER
991 Py_VISIT(thread.file);
992#endif
993#ifdef FAULTHANDLER_USER
994 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +0200995 for (signum=0; signum < NSIG; signum++)
996 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200997 }
998#endif
999 Py_VISIT(fatal_error.file);
1000 return 0;
1001}
1002
1003PyDoc_STRVAR(module_doc,
1004"faulthandler module.");
1005
1006static PyMethodDef module_methods[] = {
1007 {"enable",
1008 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001009 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001010 "enable the fault handler")},
1011 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1012 PyDoc_STR("disable(): disable the fault handler")},
1013 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1014 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1015 {"dump_traceback",
1016 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001017 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001018 "dump the traceback of the current thread, or of all threads "
1019 "if all_threads is True, into file")},
1020#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001021 {"dump_traceback_later",
1022 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1023 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001024 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001025 "or each timeout seconds if repeat is True. If exit is True, "
1026 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001027 {"cancel_dump_traceback_later",
1028 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1029 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1030 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001031#endif
1032
1033#ifdef FAULTHANDLER_USER
1034 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001035 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1036 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001037 "register an handler for the signal 'signum': dump the "
1038 "traceback of the current thread, or of all threads if "
1039 "all_threads is True, into file")},
1040 {"unregister",
1041 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1042 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1043 "'signum' registered by register()")},
1044#endif
1045
Victor Stinner50838282014-09-30 13:54:14 +02001046 {"_read_null", faulthandler_read_null, METH_NOARGS,
1047 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001048 "a SIGSEGV or SIGBUS signal depending on the platform")},
1049 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001050 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner9db521c2014-09-30 13:49:09 +02001051 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001052 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001053 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1054 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001055 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1056 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1057#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1058 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1059 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1060#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001061 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001062};
1063
1064static struct PyModuleDef module_def = {
1065 PyModuleDef_HEAD_INIT,
1066 "faulthandler",
1067 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001068 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001069 module_methods,
1070 NULL,
1071 faulthandler_traverse,
1072 NULL,
1073 NULL
1074};
1075
1076PyMODINIT_FUNC
1077PyInit_faulthandler(void)
1078{
1079 return PyModule_Create(&module_def);
1080}
1081
Victor Stinner410dd7d2011-05-11 20:56:08 +02001082/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1083 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001084
1085static int
1086faulthandler_env_options(void)
1087{
1088 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001089 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001090
Victor Stinner88983502013-09-08 11:36:23 +02001091 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1092 /* PYTHONFAULTHANDLER environment variable is missing
1093 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001094 int has_key;
1095
Victor Stinner024e37a2011-03-31 01:31:06 +02001096 xoptions = PySys_GetXOptions();
1097 if (xoptions == NULL)
1098 return -1;
1099
1100 key = PyUnicode_FromString("faulthandler");
1101 if (key == NULL)
1102 return -1;
1103
Victor Stinner25095b22011-05-26 13:47:08 +02001104 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001105 Py_DECREF(key);
Victor Stinner25095b22011-05-26 13:47:08 +02001106 if (!has_key)
Victor Stinner024e37a2011-03-31 01:31:06 +02001107 return 0;
1108 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001109
1110 module = PyImport_ImportModule("faulthandler");
1111 if (module == NULL) {
1112 return -1;
1113 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001114 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001115 Py_DECREF(module);
1116 if (res == NULL)
1117 return -1;
1118 Py_DECREF(res);
1119 return 0;
1120}
1121
1122int _PyFaulthandler_Init(void)
1123{
1124#ifdef HAVE_SIGALTSTACK
1125 int err;
1126
1127 /* Try to allocate an alternate stack for faulthandler() signal handler to
1128 * be able to allocate memory on the stack, even on a stack overflow. If it
1129 * fails, ignore the error. */
1130 stack.ss_flags = 0;
1131 stack.ss_size = SIGSTKSZ;
1132 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1133 if (stack.ss_sp != NULL) {
1134 err = sigaltstack(&stack, NULL);
1135 if (err) {
1136 PyMem_Free(stack.ss_sp);
1137 stack.ss_sp = NULL;
1138 }
1139 }
1140#endif
1141#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001142 thread.file = NULL;
1143 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001144 thread.running = PyThread_allocate_lock();
1145 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001146 PyErr_SetString(PyExc_RuntimeError,
1147 "could not allocate locks for faulthandler");
1148 return -1;
1149 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001150 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001151#endif
1152
1153 return faulthandler_env_options();
1154}
1155
1156void _PyFaulthandler_Fini(void)
1157{
1158#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001159 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001160#endif
1161
1162#ifdef FAULTHANDLER_LATER
1163 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001164 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001165 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001166 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001167 PyThread_free_lock(thread.cancel_event);
1168 thread.cancel_event = NULL;
1169 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001170 if (thread.running) {
1171 PyThread_free_lock(thread.running);
1172 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001173 }
1174#endif
1175
1176#ifdef FAULTHANDLER_USER
1177 /* user */
1178 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001179 for (signum=0; signum < NSIG; signum++)
1180 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001181 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001182 user_signals = NULL;
1183 }
1184#endif
1185
1186 /* fatal */
1187 faulthandler_disable();
1188#ifdef HAVE_SIGALTSTACK
1189 if (stack.ss_sp != NULL) {
1190 PyMem_Free(stack.ss_sp);
1191 stack.ss_sp = NULL;
1192 }
1193#endif
1194}