blob: 530ddc7efd670f937e5f3c9516188795b6ede67d [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 Stinner024e37a2011-03-31 01:31:06 +0200383 Py_XDECREF(fatal_error.file);
Victor Stinner95bb7142015-03-12 15:32:03 +0100384 Py_XINCREF(file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200385 fatal_error.file = file;
386 fatal_error.fd = fd;
387 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200388 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200389
390 if (!fatal_error.enabled) {
391 fatal_error.enabled = 1;
392
393 for (i=0; i < faulthandler_nsignals; i++) {
394 handler = &faulthandler_handlers[i];
395#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200396 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200397 sigemptyset(&action.sa_mask);
398 /* Do not prevent the signal from being received from within
399 its own signal handler */
400 action.sa_flags = SA_NODEFER;
401#ifdef HAVE_SIGALTSTACK
402 if (stack.ss_sp != NULL) {
403 /* Call the signal handler on an alternate signal stack
404 provided by sigaltstack() */
405 action.sa_flags |= SA_ONSTACK;
406 }
407#endif
408 err = sigaction(handler->signum, &action, &handler->previous);
409#else
410 handler->previous = signal(handler->signum,
411 faulthandler_fatal_error);
412 err = (handler->previous == SIG_ERR);
413#endif
414 if (err) {
415 PyErr_SetFromErrno(PyExc_RuntimeError);
416 return NULL;
417 }
418 handler->enabled = 1;
419 }
420 }
421 Py_RETURN_NONE;
422}
423
424static void
425faulthandler_disable(void)
426{
427 unsigned int i;
428 fault_handler_t *handler;
429
430 if (fatal_error.enabled) {
431 fatal_error.enabled = 0;
432 for (i=0; i < faulthandler_nsignals; i++) {
433 handler = &faulthandler_handlers[i];
434 if (!handler->enabled)
435 continue;
436#ifdef HAVE_SIGACTION
437 (void)sigaction(handler->signum, &handler->previous, NULL);
438#else
439 (void)signal(handler->signum, handler->previous);
440#endif
441 handler->enabled = 0;
442 }
443 }
444
445 Py_CLEAR(fatal_error.file);
446}
447
448static PyObject*
449faulthandler_disable_py(PyObject *self)
450{
451 if (!fatal_error.enabled) {
452 Py_INCREF(Py_False);
453 return Py_False;
454 }
455 faulthandler_disable();
456 Py_INCREF(Py_True);
457 return Py_True;
458}
459
460static PyObject*
461faulthandler_is_enabled(PyObject *self)
462{
463 return PyBool_FromLong(fatal_error.enabled);
464}
465
466#ifdef FAULTHANDLER_LATER
467
468static void
469faulthandler_thread(void *unused)
470{
471 PyLockStatus st;
472 const char* errmsg;
473 PyThreadState *current;
474 int ok;
Victor Stinnercf2a8072011-04-19 23:30:57 +0200475#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
Victor Stinnerda9edae2011-04-04 11:05:21 +0200476 sigset_t set;
477
478 /* we don't want to receive any signal */
479 sigfillset(&set);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200480 pthread_sigmask(SIG_SETMASK, &set, NULL);
Victor Stinnerda9edae2011-04-04 11:05:21 +0200481#endif
Victor Stinner024e37a2011-03-31 01:31:06 +0200482
483 do {
484 st = PyThread_acquire_lock_timed(thread.cancel_event,
Victor Stinner94189322011-04-08 13:00:31 +0200485 thread.timeout_us, 0);
Victor Stinner024e37a2011-03-31 01:31:06 +0200486 if (st == PY_LOCK_ACQUIRED) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200487 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +0200488 break;
489 }
490 /* Timeout => dump traceback */
491 assert(st == PY_LOCK_FAILURE);
492
493 /* get the thread holding the GIL, NULL if no thread hold the GIL */
Serhiy Storchaka53fa8b22015-02-16 09:40:12 +0200494 current = (PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current);
Victor Stinner024e37a2011-03-31 01:31:06 +0200495
Victor Stinnerc7489a52015-04-01 18:48:58 +0200496 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200497
Victor Stinner024e37a2011-03-31 01:31:06 +0200498 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, current);
499 ok = (errmsg == NULL);
500
501 if (thread.exit)
502 _exit(1);
503 } while (ok && thread.repeat);
504
505 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200506 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200507}
508
509static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200510cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200511{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200512 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200513 PyThread_release_lock(thread.cancel_event);
514
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200515 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200516 PyThread_acquire_lock(thread.running, 1);
517 PyThread_release_lock(thread.running);
518
519 /* The main thread should always hold the cancel_event lock */
520 PyThread_acquire_lock(thread.cancel_event, 1);
521
Victor Stinner024e37a2011-03-31 01:31:06 +0200522 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200523 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200524 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200525 thread.header = NULL;
526 }
527}
528
529static char*
530format_timeout(double timeout)
531{
532 unsigned long us, sec, min, hour;
533 double intpart, fracpart;
534 char buffer[100];
535
536 fracpart = modf(timeout, &intpart);
537 sec = (unsigned long)intpart;
538 us = (unsigned long)(fracpart * 1e6);
539 min = sec / 60;
540 sec %= 60;
541 hour = min / 60;
542 min %= 60;
543
544 if (us != 0)
545 PyOS_snprintf(buffer, sizeof(buffer),
546 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
547 hour, min, sec, us);
548 else
549 PyOS_snprintf(buffer, sizeof(buffer),
550 "Timeout (%lu:%02lu:%02lu)!\n",
551 hour, min, sec);
552
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200553 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200554}
555
556static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200557faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200558 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200559{
560 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
561 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200562 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200563 int repeat = 0;
564 PyObject *file = NULL;
565 int fd;
566 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200567 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200568 char *header;
569 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200570
571 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200572 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200573 &timeout, &repeat, &file, &exit))
574 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200575 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200576 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
577 return NULL;
578 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200579 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200580 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200581 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
582 return NULL;
583 }
584
Victor Stinnera4de6d82011-04-09 00:47:23 +0200585 tstate = get_thread_state();
586 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200587 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200588
Victor Stinner95bb7142015-03-12 15:32:03 +0100589 fd = faulthandler_get_fileno(&file);
590 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200591 return NULL;
592
Victor Stinnerc790a532011-04-08 13:39:59 +0200593 /* format the timeout */
594 header = format_timeout(timeout);
595 if (header == NULL)
596 return PyErr_NoMemory();
597 header_len = strlen(header);
598
Victor Stinner024e37a2011-03-31 01:31:06 +0200599 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200600 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200601
602 Py_XDECREF(thread.file);
Victor Stinner95bb7142015-03-12 15:32:03 +0100603 Py_XINCREF(file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200604 thread.file = file;
605 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200606 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200607 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200608 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200609 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200610 thread.header = header;
611 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200612
613 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200614 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200615
Victor Stinner024e37a2011-03-31 01:31:06 +0200616 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200617 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200618 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200619 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200620 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200621 PyErr_SetString(PyExc_RuntimeError,
622 "unable to start watchdog thread");
623 return NULL;
624 }
625
626 Py_RETURN_NONE;
627}
628
629static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200630faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200631{
Georg Brandldeb92b52012-09-22 08:58:55 +0200632 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200633 Py_RETURN_NONE;
634}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200635#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200636
637#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200638static int
639faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
640{
641#ifdef HAVE_SIGACTION
642 struct sigaction action;
643 action.sa_handler = faulthandler_user;
644 sigemptyset(&action.sa_mask);
645 /* if the signal is received while the kernel is executing a system
646 call, try to restart the system call instead of interrupting it and
647 return EINTR. */
648 action.sa_flags = SA_RESTART;
649 if (chain) {
650 /* do not prevent the signal from being received from within its
651 own signal handler */
652 action.sa_flags = SA_NODEFER;
653 }
654#ifdef HAVE_SIGALTSTACK
655 if (stack.ss_sp != NULL) {
656 /* Call the signal handler on an alternate signal stack
657 provided by sigaltstack() */
658 action.sa_flags |= SA_ONSTACK;
659 }
660#endif
661 return sigaction(signum, &action, p_previous);
662#else
663 _Py_sighandler_t previous;
664 previous = signal(signum, faulthandler_user);
665 if (p_previous != NULL)
666 *p_previous = previous;
667 return (previous == SIG_ERR);
668#endif
669}
670
Victor Stinner024e37a2011-03-31 01:31:06 +0200671/* Handler of user signals (e.g. SIGUSR1).
672
673 Dump the traceback of the current thread, or of all threads if
674 thread.all_threads is true.
675
676 This function is signal safe and should only call signal safe functions. */
677
678static void
679faulthandler_user(int signum)
680{
681 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200682 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200683
684 user = &user_signals[signum];
685 if (!user->enabled)
686 return;
687
Victor Stinnerc7489a52015-04-01 18:48:58 +0200688 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200689
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200690#ifdef HAVE_SIGACTION
691 if (user->chain) {
692 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200693 errno = save_errno;
694
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200695 /* call the previous signal handler */
696 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200697
698 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200699 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200700 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200701 }
702#else
703 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200704 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200705 /* call the previous signal handler */
706 user->previous(signum);
707 }
708#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200709}
710
711static int
712check_signum(int signum)
713{
714 unsigned int i;
715
716 for (i=0; i < faulthandler_nsignals; i++) {
717 if (faulthandler_handlers[i].signum == signum) {
718 PyErr_Format(PyExc_RuntimeError,
719 "signal %i cannot be registered, "
720 "use enable() instead",
721 signum);
722 return 0;
723 }
724 }
725 if (signum < 1 || NSIG <= signum) {
726 PyErr_SetString(PyExc_ValueError, "signal number out of range");
727 return 0;
728 }
729 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200730}
731
732static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200733faulthandler_register_py(PyObject *self,
734 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200735{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200736 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200737 int signum;
738 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200739 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200740 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200741 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200742 user_signal_t *user;
743 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200744 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200745 int err;
746
747 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200748 "i|Oii:register", kwlist,
749 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200750 return NULL;
751
Victor Stinner44378d42011-04-01 15:37:12 +0200752 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200753 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200754
Victor Stinnera4de6d82011-04-09 00:47:23 +0200755 tstate = get_thread_state();
756 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200757 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200758
Victor Stinner95bb7142015-03-12 15:32:03 +0100759 fd = faulthandler_get_fileno(&file);
760 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200761 return NULL;
762
763 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200764 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200765 if (user_signals == NULL)
766 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200767 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200768 }
769 user = &user_signals[signum];
770
771 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200772 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200773 if (err) {
774 PyErr_SetFromErrno(PyExc_OSError);
775 return NULL;
776 }
Victor Stinner8d379542013-07-02 00:14:56 +0200777
778 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200779 }
780
781 Py_XDECREF(user->file);
Victor Stinner95bb7142015-03-12 15:32:03 +0100782 Py_XINCREF(file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200783 user->file = file;
784 user->fd = fd;
785 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200786 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200787 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200788 user->enabled = 1;
789
790 Py_RETURN_NONE;
791}
792
793static int
794faulthandler_unregister(user_signal_t *user, int signum)
795{
Victor Stinnera01ca122011-04-01 12:56:17 +0200796 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200797 return 0;
798 user->enabled = 0;
799#ifdef HAVE_SIGACTION
800 (void)sigaction(signum, &user->previous, NULL);
801#else
802 (void)signal(signum, user->previous);
803#endif
804 Py_CLEAR(user->file);
805 user->fd = -1;
806 return 1;
807}
808
809static PyObject*
810faulthandler_unregister_py(PyObject *self, PyObject *args)
811{
812 int signum;
813 user_signal_t *user;
814 int change;
815
816 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
817 return NULL;
818
Victor Stinner44378d42011-04-01 15:37:12 +0200819 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200820 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200821
Victor Stinnercfa71232011-04-08 12:48:15 +0200822 if (user_signals == NULL)
823 Py_RETURN_FALSE;
824
Victor Stinner024e37a2011-03-31 01:31:06 +0200825 user = &user_signals[signum];
826 change = faulthandler_unregister(user, signum);
827 return PyBool_FromLong(change);
828}
829#endif /* FAULTHANDLER_USER */
830
831
Victor Stinner7a399122014-09-30 13:40:12 +0200832static void
833faulthandler_suppress_crash_report(void)
834{
835#ifdef MS_WINDOWS
836 UINT mode;
837
838 /* Configure Windows to not display the Windows Error Reporting dialog */
839 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
840 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
841#endif
842
843#ifdef HAVE_SYS_RESOURCE_H
844 struct rlimit rl;
845
846 /* Disable creation of core dump */
847 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
848 rl.rlim_cur = 0;
849 setrlimit(RLIMIT_CORE, &rl);
850 }
851#endif
852
853#ifdef _MSC_VER
854 /* Visual Studio: configure abort() to not display an error message nor
855 open a popup asking to report the fault. */
856 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
857#endif
858}
859
Victor Stinner024e37a2011-03-31 01:31:06 +0200860static PyObject *
861faulthandler_read_null(PyObject *self, PyObject *args)
862{
Victor Stinnera2477202012-01-30 00:07:43 +0100863 volatile int *x;
864 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100865
Victor Stinner7a399122014-09-30 13:40:12 +0200866 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100867 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200868 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200869 return PyLong_FromLong(y);
870
871}
872
Victor Stinner50838282014-09-30 13:54:14 +0200873static void
874faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200875{
Victor Stinner7a399122014-09-30 13:40:12 +0200876 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200877#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200878 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
879 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200880 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200881 SIGSEGV was raised by the kernel because of a fault, and so if the
882 program retries to execute the same instruction, the fault will be
883 raised again.
884
885 Here the fault is simulated by a fake SIGSEGV signal raised by the
886 application. We have to raise SIGSEGV at lease twice: once for
887 faulthandler_fatal_error(), and one more time for the previous signal
888 handler. */
889 while(1)
890 raise(SIGSEGV);
891#else
892 raise(SIGSEGV);
893#endif
Victor Stinner50838282014-09-30 13:54:14 +0200894}
895
896static PyObject *
897faulthandler_sigsegv(PyObject *self, PyObject *args)
898{
899 int release_gil = 0;
900 if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
901 return NULL;
902
903 if (release_gil) {
904 Py_BEGIN_ALLOW_THREADS
905 faulthandler_raise_sigsegv();
906 Py_END_ALLOW_THREADS
907 } else {
908 faulthandler_raise_sigsegv();
909 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200910 Py_RETURN_NONE;
911}
912
913static PyObject *
914faulthandler_sigfpe(PyObject *self, PyObject *args)
915{
916 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
917 PowerPC. Use volatile to disable compile-time optimizations. */
918 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +0200919 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200920 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200921 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
922 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200923 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200924 /* This line is never reached, but we pretend to make something with z
925 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200926 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200927}
928
Victor Stinnerd727e232011-04-01 12:13:55 +0200929static PyObject *
930faulthandler_sigabrt(PyObject *self, PyObject *args)
931{
Victor Stinner7a399122014-09-30 13:40:12 +0200932 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200933 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200934 Py_RETURN_NONE;
935}
936
Victor Stinner024e37a2011-03-31 01:31:06 +0200937static PyObject *
938faulthandler_fatal_error_py(PyObject *self, PyObject *args)
939{
940 char *message;
941 if (!PyArg_ParseTuple(args, "y:fatal_error", &message))
942 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +0200943 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200944 Py_FatalError(message);
945 Py_RETURN_NONE;
946}
947
948#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner19276f12015-03-23 21:20:27 +0100949#ifdef __INTEL_COMPILER
950 /* Issue #23654: Turn off ICC's tail call optimization for the
951 * stack_overflow generator. ICC turns the recursive tail call into
952 * a loop. */
953# pragma intel optimization_level 0
954#endif
955static
956Py_uintptr_t
Victor Stinner7a5567a2015-02-11 14:23:35 +0100957stack_overflow(Py_uintptr_t min_sp, Py_uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +0200958{
959 /* allocate 4096 bytes on the stack at each call */
960 unsigned char buffer[4096];
Victor Stinner7a5567a2015-02-11 14:23:35 +0100961 Py_uintptr_t sp = (Py_uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +0200962 *depth += 1;
963 if (sp < min_sp || max_sp < sp)
964 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200965 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +0200966 buffer[4095] = 0;
967 return stack_overflow(min_sp, max_sp, depth);
968}
969
970static PyObject *
971faulthandler_stack_overflow(PyObject *self)
972{
973 size_t depth, size;
Victor Stinner7a5567a2015-02-11 14:23:35 +0100974 Py_uintptr_t sp = (Py_uintptr_t)&depth;
975 Py_uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +0200976
Victor Stinner7a399122014-09-30 13:40:12 +0200977 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +0200978 depth = 0;
979 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
980 sp + STACK_OVERFLOW_MAX_SIZE,
981 &depth);
982 if (sp < stop)
983 size = stop - sp;
984 else
985 size = sp - stop;
986 PyErr_Format(PyExc_RuntimeError,
987 "unable to raise a stack overflow (allocated %zu bytes "
988 "on the stack, %zu recursive calls)",
989 size, depth);
990 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200991}
992#endif
993
994
995static int
996faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
997{
998#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +0200999 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001000#endif
1001
1002#ifdef FAULTHANDLER_LATER
1003 Py_VISIT(thread.file);
1004#endif
1005#ifdef FAULTHANDLER_USER
1006 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001007 for (signum=0; signum < NSIG; signum++)
1008 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001009 }
1010#endif
1011 Py_VISIT(fatal_error.file);
1012 return 0;
1013}
1014
1015PyDoc_STRVAR(module_doc,
1016"faulthandler module.");
1017
1018static PyMethodDef module_methods[] = {
1019 {"enable",
1020 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001021 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001022 "enable the fault handler")},
1023 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1024 PyDoc_STR("disable(): disable the fault handler")},
1025 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1026 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1027 {"dump_traceback",
1028 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001029 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001030 "dump the traceback of the current thread, or of all threads "
1031 "if all_threads is True, into file")},
1032#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001033 {"dump_traceback_later",
1034 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1035 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001036 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001037 "or each timeout seconds if repeat is True. If exit is True, "
1038 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001039 {"cancel_dump_traceback_later",
1040 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1041 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1042 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001043#endif
1044
1045#ifdef FAULTHANDLER_USER
1046 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001047 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1048 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001049 "register an handler for the signal 'signum': dump the "
1050 "traceback of the current thread, or of all threads if "
1051 "all_threads is True, into file")},
1052 {"unregister",
1053 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1054 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1055 "'signum' registered by register()")},
1056#endif
1057
Victor Stinner50838282014-09-30 13:54:14 +02001058 {"_read_null", faulthandler_read_null, METH_NOARGS,
1059 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001060 "a SIGSEGV or SIGBUS signal depending on the platform")},
1061 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001062 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner9db521c2014-09-30 13:49:09 +02001063 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001064 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001065 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1066 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001067 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1068 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1069#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1070 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1071 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1072#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001073 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001074};
1075
1076static struct PyModuleDef module_def = {
1077 PyModuleDef_HEAD_INIT,
1078 "faulthandler",
1079 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001080 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001081 module_methods,
1082 NULL,
1083 faulthandler_traverse,
1084 NULL,
1085 NULL
1086};
1087
1088PyMODINIT_FUNC
1089PyInit_faulthandler(void)
1090{
1091 return PyModule_Create(&module_def);
1092}
1093
Victor Stinner410dd7d2011-05-11 20:56:08 +02001094/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1095 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001096
1097static int
1098faulthandler_env_options(void)
1099{
1100 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001101 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001102
Victor Stinner88983502013-09-08 11:36:23 +02001103 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1104 /* PYTHONFAULTHANDLER environment variable is missing
1105 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001106 int has_key;
1107
Victor Stinner024e37a2011-03-31 01:31:06 +02001108 xoptions = PySys_GetXOptions();
1109 if (xoptions == NULL)
1110 return -1;
1111
1112 key = PyUnicode_FromString("faulthandler");
1113 if (key == NULL)
1114 return -1;
1115
Victor Stinner25095b22011-05-26 13:47:08 +02001116 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001117 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001118 if (has_key <= 0)
1119 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001120 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001121
1122 module = PyImport_ImportModule("faulthandler");
1123 if (module == NULL) {
1124 return -1;
1125 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001126 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001127 Py_DECREF(module);
1128 if (res == NULL)
1129 return -1;
1130 Py_DECREF(res);
1131 return 0;
1132}
1133
1134int _PyFaulthandler_Init(void)
1135{
1136#ifdef HAVE_SIGALTSTACK
1137 int err;
1138
1139 /* Try to allocate an alternate stack for faulthandler() signal handler to
1140 * be able to allocate memory on the stack, even on a stack overflow. If it
1141 * fails, ignore the error. */
1142 stack.ss_flags = 0;
1143 stack.ss_size = SIGSTKSZ;
1144 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1145 if (stack.ss_sp != NULL) {
1146 err = sigaltstack(&stack, NULL);
1147 if (err) {
1148 PyMem_Free(stack.ss_sp);
1149 stack.ss_sp = NULL;
1150 }
1151 }
1152#endif
1153#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001154 thread.file = NULL;
1155 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001156 thread.running = PyThread_allocate_lock();
1157 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001158 PyErr_SetString(PyExc_RuntimeError,
1159 "could not allocate locks for faulthandler");
1160 return -1;
1161 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001162 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001163#endif
1164
1165 return faulthandler_env_options();
1166}
1167
1168void _PyFaulthandler_Fini(void)
1169{
1170#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001171 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001172#endif
1173
1174#ifdef FAULTHANDLER_LATER
1175 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001176 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001177 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001178 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001179 PyThread_free_lock(thread.cancel_event);
1180 thread.cancel_event = NULL;
1181 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001182 if (thread.running) {
1183 PyThread_free_lock(thread.running);
1184 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001185 }
1186#endif
1187
1188#ifdef FAULTHANDLER_USER
1189 /* user */
1190 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001191 for (signum=0; signum < NSIG; signum++)
1192 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001193 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001194 user_signals = NULL;
1195 }
1196#endif
1197
1198 /* fatal */
1199 faulthandler_disable();
1200#ifdef HAVE_SIGALTSTACK
1201 if (stack.ss_sp != NULL) {
1202 PyMem_Free(stack.ss_sp);
1203 stack.ss_sp = NULL;
1204 }
1205#endif
1206}