blob: 45c9fcb2af5e946d1b7396a0f3a321a55ec354da [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 Stinnerc7489a52015-04-01 18:48:58 +020031#define PUTS(fd, str) _Py_write_noraise(fd, str, strlen(str))
Victor Stinner024e37a2011-03-31 01:31:06 +020032
Victor Stinnerbd303c12013-11-07 23:07:29 +010033_Py_IDENTIFIER(enable);
34_Py_IDENTIFIER(fileno);
35_Py_IDENTIFIER(flush);
36_Py_IDENTIFIER(stderr);
37
Victor Stinner024e37a2011-03-31 01:31:06 +020038#ifdef HAVE_SIGACTION
39typedef struct sigaction _Py_sighandler_t;
40#else
41typedef PyOS_sighandler_t _Py_sighandler_t;
42#endif
43
44typedef struct {
45 int signum;
46 int enabled;
47 const char* name;
48 _Py_sighandler_t previous;
49 int all_threads;
50} fault_handler_t;
51
52static struct {
53 int enabled;
54 PyObject *file;
55 int fd;
56 int all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +020057 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020058} fatal_error = {0, NULL, -1, 0};
59
60#ifdef FAULTHANDLER_LATER
61static struct {
62 PyObject *file;
63 int fd;
Victor Stinner94189322011-04-08 13:00:31 +020064 PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
Victor Stinner024e37a2011-03-31 01:31:06 +020065 int repeat;
Victor Stinner024e37a2011-03-31 01:31:06 +020066 PyInterpreterState *interp;
67 int exit;
Victor Stinnerc790a532011-04-08 13:39:59 +020068 char *header;
69 size_t header_len;
Victor Stinner410dd7d2011-05-11 20:56:08 +020070 /* The main thread always holds this lock. It is only released when
71 faulthandler_thread() is interrupted before this thread exits, or at
Victor Stinnerde10f402011-04-08 12:57:06 +020072 Python exit. */
Victor Stinner024e37a2011-03-31 01:31:06 +020073 PyThread_type_lock cancel_event;
74 /* released by child thread when joined */
Victor Stinnerde10f402011-04-08 12:57:06 +020075 PyThread_type_lock running;
Victor Stinner024e37a2011-03-31 01:31:06 +020076} thread;
77#endif
78
79#ifdef FAULTHANDLER_USER
80typedef struct {
81 int enabled;
82 PyObject *file;
83 int fd;
84 int all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +020085 int chain;
Victor Stinner024e37a2011-03-31 01:31:06 +020086 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +020087 PyInterpreterState *interp;
Victor Stinner024e37a2011-03-31 01:31:06 +020088} user_signal_t;
89
90static user_signal_t *user_signals;
91
92/* the following macros come from Python: Modules/signalmodule.c */
Victor Stinner024e37a2011-03-31 01:31:06 +020093#ifndef NSIG
94# if defined(_NSIG)
95# define NSIG _NSIG /* For BSD/SysV */
96# elif defined(_SIGMAX)
97# define NSIG (_SIGMAX + 1) /* For QNX */
98# elif defined(SIGMAX)
99# define NSIG (SIGMAX + 1) /* For djgpp */
100# else
101# define NSIG 64 /* Use a reasonable default value */
102# endif
103#endif
104
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200105static void faulthandler_user(int signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200106#endif /* FAULTHANDLER_USER */
107
108
109static fault_handler_t faulthandler_handlers[] = {
110#ifdef SIGBUS
111 {SIGBUS, 0, "Bus error", },
112#endif
113#ifdef SIGILL
114 {SIGILL, 0, "Illegal instruction", },
115#endif
116 {SIGFPE, 0, "Floating point exception", },
Victor Stinnerd727e232011-04-01 12:13:55 +0200117 {SIGABRT, 0, "Aborted", },
Victor Stinner024e37a2011-03-31 01:31:06 +0200118 /* define SIGSEGV at the end to make it the default choice if searching the
119 handler fails in faulthandler_fatal_error() */
120 {SIGSEGV, 0, "Segmentation fault", }
121};
122static const unsigned char faulthandler_nsignals = \
Victor Stinner63941882011-09-29 00:42:28 +0200123 Py_ARRAY_LENGTH(faulthandler_handlers);
Victor Stinner024e37a2011-03-31 01:31:06 +0200124
125#ifdef HAVE_SIGALTSTACK
126static stack_t stack;
127#endif
128
129
130/* Get the file descriptor of a file by calling its fileno() method and then
131 call its flush() method.
132
133 If file is NULL or Py_None, use sys.stderr as the new file.
Victor Stinner95bb7142015-03-12 15:32:03 +0100134 If file is an integer, it will be treated as file descriptor.
Victor Stinner024e37a2011-03-31 01:31:06 +0200135
Victor Stinner95bb7142015-03-12 15:32:03 +0100136 On success, return the file descriptor and write the new file into *file_ptr.
137 On error, return -1. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200138
Victor Stinner95bb7142015-03-12 15:32:03 +0100139static int
140faulthandler_get_fileno(PyObject **file_ptr)
Victor Stinner024e37a2011-03-31 01:31:06 +0200141{
142 PyObject *result;
143 long fd_long;
144 int fd;
Victor Stinner95bb7142015-03-12 15:32:03 +0100145 PyObject *file = *file_ptr;
Victor Stinner024e37a2011-03-31 01:31:06 +0200146
147 if (file == NULL || file == Py_None) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100148 file = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner024e37a2011-03-31 01:31:06 +0200149 if (file == NULL) {
150 PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
Victor Stinner95bb7142015-03-12 15:32:03 +0100151 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200152 }
Victor Stinnere2d66902014-05-14 17:15:50 +0200153 if (file == Py_None) {
154 PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
Victor Stinner95bb7142015-03-12 15:32:03 +0100155 return -1;
Victor Stinnere2d66902014-05-14 17:15:50 +0200156 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200157 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100158 else if (PyLong_Check(file)) {
159 fd = _PyLong_AsInt(file);
160 if (fd == -1 && PyErr_Occurred())
161 return -1;
162 if (fd < 0 || !_PyVerify_fd(fd)) {
163 PyErr_SetString(PyExc_ValueError,
164 "file is not a valid file descripter");
165 return -1;
166 }
167 *file_ptr = NULL;
168 return fd;
169 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200170
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200171 result = _PyObject_CallMethodId(file, &PyId_fileno, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200172 if (result == NULL)
Victor Stinner95bb7142015-03-12 15:32:03 +0100173 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200174
175 fd = -1;
176 if (PyLong_Check(result)) {
177 fd_long = PyLong_AsLong(result);
178 if (0 <= fd_long && fd_long < INT_MAX)
179 fd = (int)fd_long;
180 }
181 Py_DECREF(result);
182
183 if (fd == -1) {
184 PyErr_SetString(PyExc_RuntimeError,
185 "file.fileno() is not a valid file descriptor");
Victor Stinner95bb7142015-03-12 15:32:03 +0100186 return -1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200187 }
188
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200189 result = _PyObject_CallMethodId(file, &PyId_flush, "");
Victor Stinner024e37a2011-03-31 01:31:06 +0200190 if (result != NULL)
191 Py_DECREF(result);
192 else {
193 /* ignore flush() error */
194 PyErr_Clear();
195 }
Victor Stinner95bb7142015-03-12 15:32:03 +0100196 *file_ptr = file;
197 return fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200198}
199
Victor Stinnera4de6d82011-04-09 00:47:23 +0200200/* Get the state of the current thread: only call this function if the current
201 thread holds the GIL. Raise an exception on error. */
202static PyThreadState*
203get_thread_state(void)
204{
205 PyThreadState *tstate = PyThreadState_Get();
206 if (tstate == NULL) {
207 PyErr_SetString(PyExc_RuntimeError,
208 "unable to get the current thread state");
209 return NULL;
210 }
211 return tstate;
212}
213
Victor Stinnerc7489a52015-04-01 18:48:58 +0200214static void
215faulthandler_dump_traceback(int fd, int all_threads,
216 PyInterpreterState *interp)
217{
218 static volatile int reentrant = 0;
219 PyThreadState *tstate;
220
221 if (reentrant)
222 return;
223
224 reentrant = 1;
225
226#ifdef WITH_THREAD
227 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
228 are thus delivered to the thread that caused the fault. Get the Python
229 thread state of the current thread.
230
231 PyThreadState_Get() doesn't give the state of the thread that caused the
232 fault if the thread released the GIL, and so this function cannot be
233 used. Read the thread local storage (TLS) instead: call
234 PyGILState_GetThisThreadState(). */
235 tstate = PyGILState_GetThisThreadState();
236#else
237 tstate = PyThreadState_Get();
238#endif
239
240 if (all_threads)
241 _Py_DumpTracebackThreads(fd, interp, tstate);
242 else {
243 if (tstate != NULL)
244 _Py_DumpTraceback(fd, tstate);
245 }
246
247 reentrant = 0;
248}
249
Victor Stinner024e37a2011-03-31 01:31:06 +0200250static PyObject*
251faulthandler_dump_traceback_py(PyObject *self,
252 PyObject *args, PyObject *kwargs)
253{
254 static char *kwlist[] = {"file", "all_threads", NULL};
255 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200256 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200257 PyThreadState *tstate;
258 const char *errmsg;
259 int fd;
260
261 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
262 "|Oi:dump_traceback", kwlist,
263 &file, &all_threads))
264 return NULL;
265
Victor Stinner95bb7142015-03-12 15:32:03 +0100266 fd = faulthandler_get_fileno(&file);
267 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200268 return NULL;
269
Victor Stinnera4de6d82011-04-09 00:47:23 +0200270 tstate = get_thread_state();
271 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200272 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200273
274 if (all_threads) {
275 errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
276 if (errmsg != NULL) {
277 PyErr_SetString(PyExc_RuntimeError, errmsg);
278 return NULL;
279 }
280 }
281 else {
282 _Py_DumpTraceback(fd, tstate);
283 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200284
285 if (PyErr_CheckSignals())
286 return NULL;
287
Victor Stinner024e37a2011-03-31 01:31:06 +0200288 Py_RETURN_NONE;
289}
290
291
Victor Stinner410dd7d2011-05-11 20:56:08 +0200292/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200293
294 Display the current Python traceback, restore the previous handler and call
295 the previous handler.
296
Victor Stinner410dd7d2011-05-11 20:56:08 +0200297 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200298 signal handler would not be called (for an unknown reason). The execution of
299 the program continues at faulthandler_fatal_error() exit, but the same
300 instruction will raise the same fault (signal), and so the previous handler
301 will be called.
302
Victor Stinner410dd7d2011-05-11 20:56:08 +0200303 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200304
305static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200306faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200307{
308 const int fd = fatal_error.fd;
309 unsigned int i;
310 fault_handler_t *handler = NULL;
Victor Stinnerc9256172011-05-07 12:20:11 +0200311 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200312
313 if (!fatal_error.enabled)
314 return;
315
316 for (i=0; i < faulthandler_nsignals; i++) {
317 handler = &faulthandler_handlers[i];
318 if (handler->signum == signum)
319 break;
320 }
321 if (handler == NULL) {
322 /* faulthandler_nsignals == 0 (unlikely) */
323 return;
324 }
325
326 /* restore the previous handler */
327#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200328 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200329#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200330 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200331#endif
332 handler->enabled = 0;
333
334 PUTS(fd, "Fatal Python error: ");
335 PUTS(fd, handler->name);
336 PUTS(fd, "\n\n");
337
Victor Stinnerc7489a52015-04-01 18:48:58 +0200338 faulthandler_dump_traceback(fd, fatal_error.all_threads,
339 fatal_error.interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200340
Victor Stinnerc9256172011-05-07 12:20:11 +0200341 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200342#ifdef MS_WINDOWS
343 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200344 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200345 handler, because the Windows signal handler would not be called */
346 return;
347 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200348#endif
R David Murrayfc069992013-12-13 20:52:19 -0500349 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200350 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
351 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200352}
353
Victor Stinnerd727e232011-04-01 12:13:55 +0200354/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200355
356static PyObject*
357faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
358{
359 static char *kwlist[] = {"file", "all_threads", NULL};
360 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200361 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200362 unsigned int i;
363 fault_handler_t *handler;
364#ifdef HAVE_SIGACTION
365 struct sigaction action;
366#endif
367 int err;
368 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200369 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200370
371 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
372 "|Oi:enable", kwlist, &file, &all_threads))
373 return NULL;
374
Victor Stinner95bb7142015-03-12 15:32:03 +0100375 fd = faulthandler_get_fileno(&file);
376 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200377 return NULL;
378
Victor Stinnera4de6d82011-04-09 00:47:23 +0200379 tstate = get_thread_state();
380 if (tstate == NULL)
381 return NULL;
382
Victor Stinner95bb7142015-03-12 15:32:03 +0100383 Py_XINCREF(file);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200384 Py_SETREF(fatal_error.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200385 fatal_error.fd = fd;
386 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200387 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200388
389 if (!fatal_error.enabled) {
390 fatal_error.enabled = 1;
391
392 for (i=0; i < faulthandler_nsignals; i++) {
393 handler = &faulthandler_handlers[i];
394#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200395 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200396 sigemptyset(&action.sa_mask);
397 /* Do not prevent the signal from being received from within
398 its own signal handler */
399 action.sa_flags = SA_NODEFER;
400#ifdef HAVE_SIGALTSTACK
401 if (stack.ss_sp != NULL) {
402 /* Call the signal handler on an alternate signal stack
403 provided by sigaltstack() */
404 action.sa_flags |= SA_ONSTACK;
405 }
406#endif
407 err = sigaction(handler->signum, &action, &handler->previous);
408#else
409 handler->previous = signal(handler->signum,
410 faulthandler_fatal_error);
411 err = (handler->previous == SIG_ERR);
412#endif
413 if (err) {
414 PyErr_SetFromErrno(PyExc_RuntimeError);
415 return NULL;
416 }
417 handler->enabled = 1;
418 }
419 }
420 Py_RETURN_NONE;
421}
422
423static void
424faulthandler_disable(void)
425{
426 unsigned int i;
427 fault_handler_t *handler;
428
429 if (fatal_error.enabled) {
430 fatal_error.enabled = 0;
431 for (i=0; i < faulthandler_nsignals; i++) {
432 handler = &faulthandler_handlers[i];
433 if (!handler->enabled)
434 continue;
435#ifdef HAVE_SIGACTION
436 (void)sigaction(handler->signum, &handler->previous, NULL);
437#else
438 (void)signal(handler->signum, handler->previous);
439#endif
440 handler->enabled = 0;
441 }
442 }
443
444 Py_CLEAR(fatal_error.file);
445}
446
447static PyObject*
448faulthandler_disable_py(PyObject *self)
449{
450 if (!fatal_error.enabled) {
451 Py_INCREF(Py_False);
452 return Py_False;
453 }
454 faulthandler_disable();
455 Py_INCREF(Py_True);
456 return Py_True;
457}
458
459static PyObject*
460faulthandler_is_enabled(PyObject *self)
461{
462 return PyBool_FromLong(fatal_error.enabled);
463}
464
465#ifdef FAULTHANDLER_LATER
466
467static void
468faulthandler_thread(void *unused)
469{
470 PyLockStatus st;
471 const char* errmsg;
472 PyThreadState *current;
473 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200474#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200475 sigset_t set;
476
477 /* we don't want to receive any signal */
478 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200479 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200480#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200481
482 do {
483 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200484 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200485 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200486 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200487 break;
488 }
489 /* Timeout => dump traceback */
490 assert(st == PY_LOCK_FAILURE);
491
492 /* get the thread holding the GIL, NULL if no thread hold the GIL */
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100493 current = _PyThreadState_UncheckedGet();
Victor Stinner024e37a2011-03-31 01:31:06 +0200494
Victor Stinnerc7489a52015-04-01 18:48:58 +0200495 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200496
Victor Stinner024e37a2011-03-31 01:31:06 +0200497 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
498 ok = (errmsg == NULL);
499
500 if (thread.exit)
501 _exit(1);
502 } while (ok && thread.repeat);
503
504 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200505 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200506}
507
508static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200509cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200510{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200511 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200512 PyThread_release_lock(thread.cancel_event);
513
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200514 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200515 PyThread_acquire_lock(thread.running, 1);
516 PyThread_release_lock(thread.running);
517
518 /* The main thread should always hold the cancel_event lock */
519 PyThread_acquire_lock(thread.cancel_event, 1);
520
Victor Stinner024e37a2011-03-31 01:31:06 +0200521 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200522 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200523 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200524 thread.header = NULL;
525 }
526}
527
528static char*
529format_timeout(double timeout)
530{
531 unsigned long us, sec, min, hour;
532 double intpart, fracpart;
533 char buffer[100];
534
535 fracpart = modf(timeout, &intpart);
536 sec = (unsigned long)intpart;
537 us = (unsigned long)(fracpart * 1e6);
538 min = sec / 60;
539 sec %= 60;
540 hour = min / 60;
541 min %= 60;
542
543 if (us != 0)
544 PyOS_snprintf(buffer, sizeof(buffer),
545 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
546 hour, min, sec, us);
547 else
548 PyOS_snprintf(buffer, sizeof(buffer),
549 "Timeout (%lu:%02lu:%02lu)!\n",
550 hour, min, sec);
551
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200552 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200553}
554
555static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200556faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200557 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200558{
559 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
560 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200561 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200562 int repeat = 0;
563 PyObject *file = NULL;
564 int fd;
565 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200566 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200567 char *header;
568 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200569
570 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200571 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200572 &timeout, &repeat, &file, &exit))
573 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200574 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200575 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
576 return NULL;
577 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200578 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200579 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200580 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
581 return NULL;
582 }
583
Victor Stinnera4de6d82011-04-09 00:47:23 +0200584 tstate = get_thread_state();
585 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200586 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200587
Victor Stinner95bb7142015-03-12 15:32:03 +0100588 fd = faulthandler_get_fileno(&file);
589 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200590 return NULL;
591
Victor Stinnerc790a532011-04-08 13:39:59 +0200592 /* format the timeout */
593 header = format_timeout(timeout);
594 if (header == NULL)
595 return PyErr_NoMemory();
596 header_len = strlen(header);
597
Victor Stinner024e37a2011-03-31 01:31:06 +0200598 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200599 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200600
Victor Stinner95bb7142015-03-12 15:32:03 +0100601 Py_XINCREF(file);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200602 Py_SETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200603 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200604 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200605 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200606 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200607 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200608 thread.header = header;
609 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200610
611 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200612 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200613
Victor Stinner024e37a2011-03-31 01:31:06 +0200614 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200615 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200616 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200617 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200618 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200619 PyErr_SetString(PyExc_RuntimeError,
620 "unable to start watchdog thread");
621 return NULL;
622 }
623
624 Py_RETURN_NONE;
625}
626
627static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200628faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200629{
Georg Brandldeb92b52012-09-22 08:58:55 +0200630 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200631 Py_RETURN_NONE;
632}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200633#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200634
635#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200636static int
637faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
638{
639#ifdef HAVE_SIGACTION
640 struct sigaction action;
641 action.sa_handler = faulthandler_user;
642 sigemptyset(&action.sa_mask);
643 /* if the signal is received while the kernel is executing a system
644 call, try to restart the system call instead of interrupting it and
645 return EINTR. */
646 action.sa_flags = SA_RESTART;
647 if (chain) {
648 /* do not prevent the signal from being received from within its
649 own signal handler */
650 action.sa_flags = SA_NODEFER;
651 }
652#ifdef HAVE_SIGALTSTACK
653 if (stack.ss_sp != NULL) {
654 /* Call the signal handler on an alternate signal stack
655 provided by sigaltstack() */
656 action.sa_flags |= SA_ONSTACK;
657 }
658#endif
659 return sigaction(signum, &action, p_previous);
660#else
661 _Py_sighandler_t previous;
662 previous = signal(signum, faulthandler_user);
663 if (p_previous != NULL)
664 *p_previous = previous;
665 return (previous == SIG_ERR);
666#endif
667}
668
Victor Stinner024e37a2011-03-31 01:31:06 +0200669/* Handler of user signals (e.g. SIGUSR1).
670
671 Dump the traceback of the current thread, or of all threads if
672 thread.all_threads is true.
673
674 This function is signal safe and should only call signal safe functions. */
675
676static void
677faulthandler_user(int signum)
678{
679 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200680 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200681
682 user = &user_signals[signum];
683 if (!user->enabled)
684 return;
685
Victor Stinnerc7489a52015-04-01 18:48:58 +0200686 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200687
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200688#ifdef HAVE_SIGACTION
689 if (user->chain) {
690 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200691 errno = save_errno;
692
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200693 /* call the previous signal handler */
694 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200695
696 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200697 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200698 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200699 }
700#else
701 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200702 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200703 /* call the previous signal handler */
704 user->previous(signum);
705 }
706#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200707}
708
709static int
710check_signum(int signum)
711{
712 unsigned int i;
713
714 for (i=0; i < faulthandler_nsignals; i++) {
715 if (faulthandler_handlers[i].signum == signum) {
716 PyErr_Format(PyExc_RuntimeError,
717 "signal %i cannot be registered, "
718 "use enable() instead",
719 signum);
720 return 0;
721 }
722 }
723 if (signum < 1 || NSIG <= signum) {
724 PyErr_SetString(PyExc_ValueError, "signal number out of range");
725 return 0;
726 }
727 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200728}
729
730static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200731faulthandler_register_py(PyObject *self,
732 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200733{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200734 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200735 int signum;
736 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200737 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200738 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200739 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200740 user_signal_t *user;
741 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200742 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200743 int err;
744
745 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200746 "i|Oii:register", kwlist,
747 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200748 return NULL;
749
Victor Stinner44378d42011-04-01 15:37:12 +0200750 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200751 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200752
Victor Stinnera4de6d82011-04-09 00:47:23 +0200753 tstate = get_thread_state();
754 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200755 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200756
Victor Stinner95bb7142015-03-12 15:32:03 +0100757 fd = faulthandler_get_fileno(&file);
758 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200759 return NULL;
760
761 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200762 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200763 if (user_signals == NULL)
764 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200765 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200766 }
767 user = &user_signals[signum];
768
769 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200770 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200771 if (err) {
772 PyErr_SetFromErrno(PyExc_OSError);
773 return NULL;
774 }
Victor Stinner8d379542013-07-02 00:14:56 +0200775
776 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200777 }
778
Victor Stinner95bb7142015-03-12 15:32:03 +0100779 Py_XINCREF(file);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200780 Py_SETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200781 user->fd = fd;
782 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200783 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200784 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200785 user->enabled = 1;
786
787 Py_RETURN_NONE;
788}
789
790static int
791faulthandler_unregister(user_signal_t *user, int signum)
792{
Victor Stinnera01ca122011-04-01 12:56:17 +0200793 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200794 return 0;
795 user->enabled = 0;
796#ifdef HAVE_SIGACTION
797 (void)sigaction(signum, &user->previous, NULL);
798#else
799 (void)signal(signum, user->previous);
800#endif
801 Py_CLEAR(user->file);
802 user->fd = -1;
803 return 1;
804}
805
806static PyObject*
807faulthandler_unregister_py(PyObject *self, PyObject *args)
808{
809 int signum;
810 user_signal_t *user;
811 int change;
812
813 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
814 return NULL;
815
Victor Stinner44378d42011-04-01 15:37:12 +0200816 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200817 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200818
Victor Stinnercfa71232011-04-08 12:48:15 +0200819 if (user_signals == NULL)
820 Py_RETURN_FALSE;
821
Victor Stinner024e37a2011-03-31 01:31:06 +0200822 user = &user_signals[signum];
823 change = faulthandler_unregister(user, signum);
824 return PyBool_FromLong(change);
825}
826#endif /* FAULTHANDLER_USER */
827
828
Victor Stinner7a399122014-09-30 13:40:12 +0200829static void
830faulthandler_suppress_crash_report(void)
831{
832#ifdef MS_WINDOWS
833 UINT mode;
834
835 /* Configure Windows to not display the Windows Error Reporting dialog */
836 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
837 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
838#endif
839
840#ifdef HAVE_SYS_RESOURCE_H
841 struct rlimit rl;
842
843 /* Disable creation of core dump */
844 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
845 rl.rlim_cur = 0;
846 setrlimit(RLIMIT_CORE, &rl);
847 }
848#endif
849
850#ifdef _MSC_VER
851 /* Visual Studio: configure abort() to not display an error message nor
852 open a popup asking to report the fault. */
853 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
854#endif
855}
856
Victor Stinner024e37a2011-03-31 01:31:06 +0200857static PyObject *
858faulthandler_read_null(PyObject *self, PyObject *args)
859{
Victor Stinnera2477202012-01-30 00:07:43 +0100860 volatile int *x;
861 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100862
Victor Stinner7a399122014-09-30 13:40:12 +0200863 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100864 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200865 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200866 return PyLong_FromLong(y);
867
868}
869
Victor Stinner50838282014-09-30 13:54:14 +0200870static void
871faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200872{
Victor Stinner7a399122014-09-30 13:40:12 +0200873 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200874#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200875 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
876 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200877 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200878 SIGSEGV was raised by the kernel because of a fault, and so if the
879 program retries to execute the same instruction, the fault will be
880 raised again.
881
882 Here the fault is simulated by a fake SIGSEGV signal raised by the
883 application. We have to raise SIGSEGV at lease twice: once for
884 faulthandler_fatal_error(), and one more time for the previous signal
885 handler. */
886 while(1)
887 raise(SIGSEGV);
888#else
889 raise(SIGSEGV);
890#endif
Victor Stinner50838282014-09-30 13:54:14 +0200891}
892
893static PyObject *
894faulthandler_sigsegv(PyObject *self, PyObject *args)
895{
896 int release_gil = 0;
897 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
898 return NULL;
899
900 if (release_gil) {
901 Py_BEGIN_ALLOW_THREADS
902 faulthandler_raise_sigsegv();
903 Py_END_ALLOW_THREADS
904 } else {
905 faulthandler_raise_sigsegv();
906 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200907 Py_RETURN_NONE;
908}
909
910static PyObject *
911faulthandler_sigfpe(PyObject *self, PyObject *args)
912{
913 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
914 PowerPC. Use volatile to disable compile-time optimizations. */
915 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +0200916 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200917 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200918 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
919 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200920 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200921 /* This line is never reached, but we pretend to make something with z
922 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200923 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200924}
925
Victor Stinnerd727e232011-04-01 12:13:55 +0200926static PyObject *
927faulthandler_sigabrt(PyObject *self, PyObject *args)
928{
Victor Stinner7a399122014-09-30 13:40:12 +0200929 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200930 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200931 Py_RETURN_NONE;
932}
933
Victor Stinner024e37a2011-03-31 01:31:06 +0200934static PyObject *
935faulthandler_fatal_error_py(PyObject *self, PyObject *args)
936{
937 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +0100938 int release_gil = 0;
939 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +0200940 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +0200941 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +0100942 if (release_gil) {
943 Py_BEGIN_ALLOW_THREADS
944 Py_FatalError(message);
945 Py_END_ALLOW_THREADS
946 }
947 else {
948 Py_FatalError(message);
949 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200950 Py_RETURN_NONE;
951}
952
953#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner19276f12015-03-23 21:20:27 +0100954#ifdef __INTEL_COMPILER
955 /* Issue #23654: Turn off ICC's tail call optimization for the
956 * stack_overflow generator. ICC turns the recursive tail call into
957 * a loop. */
958# pragma intel optimization_level 0
959#endif
960static
961Py_uintptr_t
Victor Stinner7a5567a2015-02-11 14:23:35 +0100962stack_overflow(Py_uintptr_t min_sp, Py_uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200963{
964 /* allocate 4096 bytes on the stack at each call */
965 unsigned char buffer[4096];
Victor Stinner7a5567a2015-02-11 14:23:35 +0100966 Py_uintptr_t sp = (Py_uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +0200967 *depth += 1;
968 if (sp < min_sp || max_sp < sp)
969 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200970 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200971 buffer[4095] = 0;
972 return stack_overflow(min_sp, max_sp, depth);
973}
974
975static PyObject *
976faulthandler_stack_overflow(PyObject *self)
977{
978 size_t depth, size;
Victor Stinner7a5567a2015-02-11 14:23:35 +0100979 Py_uintptr_t sp = (Py_uintptr_t)&depth;
980 Py_uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200981
Victor Stinner7a399122014-09-30 13:40:12 +0200982 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +0200983 depth = 0;
984 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
985 sp + STACK_OVERFLOW_MAX_SIZE,
986 &depth);
987 if (sp < stop)
988 size = stop - sp;
989 else
990 size = sp - stop;
991 PyErr_Format(PyExc_RuntimeError,
992 "unable to raise a stack overflow (allocated %zu bytes "
993 "on the stack, %zu recursive calls)",
994 size, depth);
995 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200996}
997#endif
998
999
1000static int
1001faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1002{
1003#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001004 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001005#endif
1006
1007#ifdef FAULTHANDLER_LATER
1008 Py_VISIT(thread.file);
1009#endif
1010#ifdef FAULTHANDLER_USER
1011 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001012 for (signum=0; signum < NSIG; signum++)
1013 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001014 }
1015#endif
1016 Py_VISIT(fatal_error.file);
1017 return 0;
1018}
1019
1020PyDoc_STRVAR(module_doc,
1021"faulthandler module.");
1022
1023static PyMethodDef module_methods[] = {
1024 {"enable",
1025 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001026 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001027 "enable the fault handler")},
1028 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1029 PyDoc_STR("disable(): disable the fault handler")},
1030 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1031 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1032 {"dump_traceback",
1033 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001034 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001035 "dump the traceback of the current thread, or of all threads "
1036 "if all_threads is True, into file")},
1037#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001038 {"dump_traceback_later",
1039 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1040 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001041 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001042 "or each timeout seconds if repeat is True. If exit is True, "
1043 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001044 {"cancel_dump_traceback_later",
1045 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1046 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1047 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001048#endif
1049
1050#ifdef FAULTHANDLER_USER
1051 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001052 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1053 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001054 "register an handler for the signal 'signum': dump the "
1055 "traceback of the current thread, or of all threads if "
1056 "all_threads is True, into file")},
1057 {"unregister",
1058 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1059 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1060 "'signum' registered by register()")},
1061#endif
1062
Victor Stinner50838282014-09-30 13:54:14 +02001063 {"_read_null", faulthandler_read_null, METH_NOARGS,
1064 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001065 "a SIGSEGV or SIGBUS signal depending on the platform")},
1066 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001067 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner9db521c2014-09-30 13:49:09 +02001068 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001069 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001070 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1071 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001072 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1073 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1074#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1075 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1076 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1077#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001078 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001079};
1080
1081static struct PyModuleDef module_def = {
1082 PyModuleDef_HEAD_INIT,
1083 "faulthandler",
1084 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001085 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001086 module_methods,
1087 NULL,
1088 faulthandler_traverse,
1089 NULL,
1090 NULL
1091};
1092
1093PyMODINIT_FUNC
1094PyInit_faulthandler(void)
1095{
1096 return PyModule_Create(&module_def);
1097}
1098
Victor Stinner410dd7d2011-05-11 20:56:08 +02001099/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1100 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001101
1102static int
1103faulthandler_env_options(void)
1104{
1105 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001106 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001107
Victor Stinner88983502013-09-08 11:36:23 +02001108 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1109 /* PYTHONFAULTHANDLER environment variable is missing
1110 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001111 int has_key;
1112
Victor Stinner024e37a2011-03-31 01:31:06 +02001113 xoptions = PySys_GetXOptions();
1114 if (xoptions == NULL)
1115 return -1;
1116
1117 key = PyUnicode_FromString("faulthandler");
1118 if (key == NULL)
1119 return -1;
1120
Victor Stinner25095b22011-05-26 13:47:08 +02001121 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001122 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001123 if (has_key <= 0)
1124 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001125 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001126
1127 module = PyImport_ImportModule("faulthandler");
1128 if (module == NULL) {
1129 return -1;
1130 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001131 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001132 Py_DECREF(module);
1133 if (res == NULL)
1134 return -1;
1135 Py_DECREF(res);
1136 return 0;
1137}
1138
1139int _PyFaulthandler_Init(void)
1140{
1141#ifdef HAVE_SIGALTSTACK
1142 int err;
1143
1144 /* Try to allocate an alternate stack for faulthandler() signal handler to
1145 * be able to allocate memory on the stack, even on a stack overflow. If it
1146 * fails, ignore the error. */
1147 stack.ss_flags = 0;
1148 stack.ss_size = SIGSTKSZ;
1149 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1150 if (stack.ss_sp != NULL) {
1151 err = sigaltstack(&stack, NULL);
1152 if (err) {
1153 PyMem_Free(stack.ss_sp);
1154 stack.ss_sp = NULL;
1155 }
1156 }
1157#endif
1158#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001159 thread.file = NULL;
1160 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001161 thread.running = PyThread_allocate_lock();
1162 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001163 PyErr_SetString(PyExc_RuntimeError,
1164 "could not allocate locks for faulthandler");
1165 return -1;
1166 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001167 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001168#endif
1169
1170 return faulthandler_env_options();
1171}
1172
1173void _PyFaulthandler_Fini(void)
1174{
1175#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001176 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001177#endif
1178
1179#ifdef FAULTHANDLER_LATER
1180 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001181 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001182 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001183 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001184 PyThread_free_lock(thread.cancel_event);
1185 thread.cancel_event = NULL;
1186 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001187 if (thread.running) {
1188 PyThread_free_lock(thread.running);
1189 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001190 }
1191#endif
1192
1193#ifdef FAULTHANDLER_USER
1194 /* user */
1195 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001196 for (signum=0; signum < NSIG; signum++)
1197 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001198 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001199 user_signals = NULL;
1200 }
1201#endif
1202
1203 /* fatal */
1204 faulthandler_disable();
1205#ifdef HAVE_SIGALTSTACK
1206 if (stack.ss_sp != NULL) {
1207 PyMem_Free(stack.ss_sp);
1208 stack.ss_sp = NULL;
1209 }
1210#endif
1211}