blob: 1c247b72a806c5ac27512793ad8830122a9a0e78 [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{
Victor Stinner861d9ab2016-03-16 22:45:24 +0100205 PyThreadState *tstate = _PyThreadState_UncheckedGet();
Victor Stinnera4de6d82011-04-09 00:47:23 +0200206 if (tstate == NULL) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100207 /* just in case but very unlikely... */
Victor Stinnera4de6d82011-04-09 00:47:23 +0200208 PyErr_SetString(PyExc_RuntimeError,
209 "unable to get the current thread state");
210 return NULL;
211 }
212 return tstate;
213}
214
Victor Stinnerc7489a52015-04-01 18:48:58 +0200215static void
216faulthandler_dump_traceback(int fd, int all_threads,
217 PyInterpreterState *interp)
218{
219 static volatile int reentrant = 0;
220 PyThreadState *tstate;
221
222 if (reentrant)
223 return;
224
225 reentrant = 1;
226
227#ifdef WITH_THREAD
228 /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
229 are thus delivered to the thread that caused the fault. Get the Python
230 thread state of the current thread.
231
232 PyThreadState_Get() doesn't give the state of the thread that caused the
233 fault if the thread released the GIL, and so this function cannot be
234 used. Read the thread local storage (TLS) instead: call
235 PyGILState_GetThisThreadState(). */
236 tstate = PyGILState_GetThisThreadState();
237#else
Victor Stinner861d9ab2016-03-16 22:45:24 +0100238 tstate = _PyThreadState_UncheckedGet();
Victor Stinnerc7489a52015-04-01 18:48:58 +0200239#endif
240
Victor Stinner861d9ab2016-03-16 22:45:24 +0100241 if (all_threads) {
242 (void)_Py_DumpTracebackThreads(fd, NULL, tstate);
243 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200244 else {
245 if (tstate != NULL)
246 _Py_DumpTraceback(fd, tstate);
247 }
248
249 reentrant = 0;
250}
251
Victor Stinner024e37a2011-03-31 01:31:06 +0200252static PyObject*
253faulthandler_dump_traceback_py(PyObject *self,
254 PyObject *args, PyObject *kwargs)
255{
256 static char *kwlist[] = {"file", "all_threads", NULL};
257 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200258 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200259 PyThreadState *tstate;
260 const char *errmsg;
261 int fd;
262
263 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
264 "|Oi:dump_traceback", kwlist,
265 &file, &all_threads))
266 return NULL;
267
Victor Stinner95bb7142015-03-12 15:32:03 +0100268 fd = faulthandler_get_fileno(&file);
269 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200270 return NULL;
271
Victor Stinnera4de6d82011-04-09 00:47:23 +0200272 tstate = get_thread_state();
273 if (tstate == NULL)
Victor Stinner024e37a2011-03-31 01:31:06 +0200274 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200275
276 if (all_threads) {
Victor Stinner861d9ab2016-03-16 22:45:24 +0100277 errmsg = _Py_DumpTracebackThreads(fd, NULL, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +0200278 if (errmsg != NULL) {
279 PyErr_SetString(PyExc_RuntimeError, errmsg);
280 return NULL;
281 }
282 }
283 else {
284 _Py_DumpTraceback(fd, tstate);
285 }
Victor Stinnerc7489a52015-04-01 18:48:58 +0200286
287 if (PyErr_CheckSignals())
288 return NULL;
289
Victor Stinner024e37a2011-03-31 01:31:06 +0200290 Py_RETURN_NONE;
291}
292
293
Victor Stinner410dd7d2011-05-11 20:56:08 +0200294/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Victor Stinner024e37a2011-03-31 01:31:06 +0200295
296 Display the current Python traceback, restore the previous handler and call
297 the previous handler.
298
Victor Stinner410dd7d2011-05-11 20:56:08 +0200299 On Windows, don't explicitly call the previous handler, because the Windows
Victor Stinner024e37a2011-03-31 01:31:06 +0200300 signal handler would not be called (for an unknown reason). The execution of
301 the program continues at faulthandler_fatal_error() exit, but the same
302 instruction will raise the same fault (signal), and so the previous handler
303 will be called.
304
Victor Stinner410dd7d2011-05-11 20:56:08 +0200305 This function is signal-safe and should only call signal-safe functions. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200306
307static void
Victor Stinner44e31ba2011-04-07 11:39:03 +0200308faulthandler_fatal_error(int signum)
Victor Stinner024e37a2011-03-31 01:31:06 +0200309{
310 const int fd = fatal_error.fd;
311 unsigned int i;
312 fault_handler_t *handler = NULL;
Victor Stinnerc9256172011-05-07 12:20:11 +0200313 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200314
315 if (!fatal_error.enabled)
316 return;
317
318 for (i=0; i < faulthandler_nsignals; i++) {
319 handler = &faulthandler_handlers[i];
320 if (handler->signum == signum)
321 break;
322 }
323 if (handler == NULL) {
324 /* faulthandler_nsignals == 0 (unlikely) */
325 return;
326 }
327
328 /* restore the previous handler */
329#ifdef HAVE_SIGACTION
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200330 (void)sigaction(signum, &handler->previous, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200331#else
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200332 (void)signal(signum, handler->previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200333#endif
334 handler->enabled = 0;
335
336 PUTS(fd, "Fatal Python error: ");
337 PUTS(fd, handler->name);
338 PUTS(fd, "\n\n");
339
Victor Stinnerc7489a52015-04-01 18:48:58 +0200340 faulthandler_dump_traceback(fd, fatal_error.all_threads,
341 fatal_error.interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200342
Victor Stinnerc9256172011-05-07 12:20:11 +0200343 errno = save_errno;
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200344#ifdef MS_WINDOWS
345 if (signum == SIGSEGV) {
Victor Stinner410dd7d2011-05-11 20:56:08 +0200346 /* don't explicitly call the previous handler for SIGSEGV in this signal
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200347 handler, because the Windows signal handler would not be called */
348 return;
349 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200350#endif
R David Murrayfc069992013-12-13 20:52:19 -0500351 /* call the previous signal handler: it is called immediately if we use
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200352 sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
353 raise(signum);
Victor Stinner024e37a2011-03-31 01:31:06 +0200354}
355
Victor Stinnerd727e232011-04-01 12:13:55 +0200356/* Install the handler for fatal signals, faulthandler_fatal_error(). */
Victor Stinner024e37a2011-03-31 01:31:06 +0200357
358static PyObject*
359faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
360{
361 static char *kwlist[] = {"file", "all_threads", NULL};
362 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200363 int all_threads = 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200364 unsigned int i;
365 fault_handler_t *handler;
366#ifdef HAVE_SIGACTION
367 struct sigaction action;
368#endif
369 int err;
370 int fd;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200371 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200372
373 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
374 "|Oi:enable", kwlist, &file, &all_threads))
375 return NULL;
376
Victor Stinner95bb7142015-03-12 15:32:03 +0100377 fd = faulthandler_get_fileno(&file);
378 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200379 return NULL;
380
Victor Stinnera4de6d82011-04-09 00:47:23 +0200381 tstate = get_thread_state();
382 if (tstate == NULL)
383 return NULL;
384
Victor Stinner95bb7142015-03-12 15:32:03 +0100385 Py_XINCREF(file);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200386 Py_SETREF(fatal_error.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200387 fatal_error.fd = fd;
388 fatal_error.all_threads = all_threads;
Victor Stinnera4de6d82011-04-09 00:47:23 +0200389 fatal_error.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200390
391 if (!fatal_error.enabled) {
392 fatal_error.enabled = 1;
393
394 for (i=0; i < faulthandler_nsignals; i++) {
395 handler = &faulthandler_handlers[i];
396#ifdef HAVE_SIGACTION
Victor Stinner44e31ba2011-04-07 11:39:03 +0200397 action.sa_handler = faulthandler_fatal_error;
Victor Stinner024e37a2011-03-31 01:31:06 +0200398 sigemptyset(&action.sa_mask);
399 /* Do not prevent the signal from being received from within
400 its own signal handler */
401 action.sa_flags = SA_NODEFER;
402#ifdef HAVE_SIGALTSTACK
403 if (stack.ss_sp != NULL) {
404 /* Call the signal handler on an alternate signal stack
405 provided by sigaltstack() */
406 action.sa_flags |= SA_ONSTACK;
407 }
408#endif
409 err = sigaction(handler->signum, &action, &handler->previous);
410#else
411 handler->previous = signal(handler->signum,
412 faulthandler_fatal_error);
413 err = (handler->previous == SIG_ERR);
414#endif
415 if (err) {
416 PyErr_SetFromErrno(PyExc_RuntimeError);
417 return NULL;
418 }
419 handler->enabled = 1;
420 }
421 }
422 Py_RETURN_NONE;
423}
424
425static void
426faulthandler_disable(void)
427{
428 unsigned int i;
429 fault_handler_t *handler;
430
431 if (fatal_error.enabled) {
432 fatal_error.enabled = 0;
433 for (i=0; i < faulthandler_nsignals; i++) {
434 handler = &faulthandler_handlers[i];
435 if (!handler->enabled)
436 continue;
437#ifdef HAVE_SIGACTION
438 (void)sigaction(handler->signum, &handler->previous, NULL);
439#else
440 (void)signal(handler->signum, handler->previous);
441#endif
442 handler->enabled = 0;
443 }
444 }
445
446 Py_CLEAR(fatal_error.file);
447}
448
449static PyObject*
450faulthandler_disable_py(PyObject *self)
451{
452 if (!fatal_error.enabled) {
453 Py_INCREF(Py_False);
454 return Py_False;
455 }
456 faulthandler_disable();
457 Py_INCREF(Py_True);
458 return Py_True;
459}
460
461static PyObject*
462faulthandler_is_enabled(PyObject *self)
463{
464 return PyBool_FromLong(fatal_error.enabled);
465}
466
467#ifdef FAULTHANDLER_LATER
468
469static void
470faulthandler_thread(void *unused)
471{
472 PyLockStatus st;
473 const char* errmsg;
Victor Stinner024e37a2011-03-31 01:31:06 +0200474 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
Victor Stinnerc7489a52015-04-01 18:48:58 +0200493 _Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
Victor Stinnerc790a532011-04-08 13:39:59 +0200494
Victor Stinner861d9ab2016-03-16 22:45:24 +0100495 errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
Victor Stinner024e37a2011-03-31 01:31:06 +0200496 ok = (errmsg == NULL);
497
498 if (thread.exit)
499 _exit(1);
500 } while (ok && thread.repeat);
501
502 /* The only way out */
Victor Stinnerde10f402011-04-08 12:57:06 +0200503 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200504}
505
506static void
Georg Brandldeb92b52012-09-22 08:58:55 +0200507cancel_dump_traceback_later(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200508{
Victor Stinner410dd7d2011-05-11 20:56:08 +0200509 /* Notify cancellation */
Victor Stinnerde10f402011-04-08 12:57:06 +0200510 PyThread_release_lock(thread.cancel_event);
511
Victor Stinnera4d4f1b2011-04-01 03:00:05 +0200512 /* Wait for thread to join */
Victor Stinnerde10f402011-04-08 12:57:06 +0200513 PyThread_acquire_lock(thread.running, 1);
514 PyThread_release_lock(thread.running);
515
516 /* The main thread should always hold the cancel_event lock */
517 PyThread_acquire_lock(thread.cancel_event, 1);
518
Victor Stinner024e37a2011-03-31 01:31:06 +0200519 Py_CLEAR(thread.file);
Victor Stinnerc790a532011-04-08 13:39:59 +0200520 if (thread.header) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200521 PyMem_Free(thread.header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200522 thread.header = NULL;
523 }
524}
525
526static char*
527format_timeout(double timeout)
528{
529 unsigned long us, sec, min, hour;
530 double intpart, fracpart;
531 char buffer[100];
532
533 fracpart = modf(timeout, &intpart);
534 sec = (unsigned long)intpart;
535 us = (unsigned long)(fracpart * 1e6);
536 min = sec / 60;
537 sec %= 60;
538 hour = min / 60;
539 min %= 60;
540
541 if (us != 0)
542 PyOS_snprintf(buffer, sizeof(buffer),
543 "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
544 hour, min, sec, us);
545 else
546 PyOS_snprintf(buffer, sizeof(buffer),
547 "Timeout (%lu:%02lu:%02lu)!\n",
548 hour, min, sec);
549
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200550 return _PyMem_Strdup(buffer);
Victor Stinner024e37a2011-03-31 01:31:06 +0200551}
552
553static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200554faulthandler_dump_traceback_later(PyObject *self,
Victor Stinner96994402011-04-07 11:37:19 +0200555 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200556{
557 static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
558 double timeout;
Victor Stinner94189322011-04-08 13:00:31 +0200559 PY_TIMEOUT_T timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200560 int repeat = 0;
561 PyObject *file = NULL;
562 int fd;
563 int exit = 0;
Victor Stinner96994402011-04-07 11:37:19 +0200564 PyThreadState *tstate;
Victor Stinnerc790a532011-04-08 13:39:59 +0200565 char *header;
566 size_t header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200567
568 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Georg Brandldeb92b52012-09-22 08:58:55 +0200569 "d|iOi:dump_traceback_later", kwlist,
Victor Stinner024e37a2011-03-31 01:31:06 +0200570 &timeout, &repeat, &file, &exit))
571 return NULL;
Victor Stinnerc790a532011-04-08 13:39:59 +0200572 if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200573 PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
574 return NULL;
575 }
Victor Stinnerc790a532011-04-08 13:39:59 +0200576 timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
Victor Stinner94189322011-04-08 13:00:31 +0200577 if (timeout_us <= 0) {
Victor Stinner024e37a2011-03-31 01:31:06 +0200578 PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
579 return NULL;
580 }
581
Victor Stinnera4de6d82011-04-09 00:47:23 +0200582 tstate = get_thread_state();
583 if (tstate == NULL)
Victor Stinner96994402011-04-07 11:37:19 +0200584 return NULL;
Victor Stinner96994402011-04-07 11:37:19 +0200585
Victor Stinner95bb7142015-03-12 15:32:03 +0100586 fd = faulthandler_get_fileno(&file);
587 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200588 return NULL;
589
Victor Stinnerc790a532011-04-08 13:39:59 +0200590 /* format the timeout */
591 header = format_timeout(timeout);
592 if (header == NULL)
593 return PyErr_NoMemory();
594 header_len = strlen(header);
595
Victor Stinner024e37a2011-03-31 01:31:06 +0200596 /* Cancel previous thread, if running */
Georg Brandldeb92b52012-09-22 08:58:55 +0200597 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200598
Victor Stinner95bb7142015-03-12 15:32:03 +0100599 Py_XINCREF(file);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200600 Py_SETREF(thread.file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200601 thread.fd = fd;
Victor Stinner94189322011-04-08 13:00:31 +0200602 thread.timeout_us = timeout_us;
Victor Stinner024e37a2011-03-31 01:31:06 +0200603 thread.repeat = repeat;
Victor Stinner96994402011-04-07 11:37:19 +0200604 thread.interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200605 thread.exit = exit;
Victor Stinnerc790a532011-04-08 13:39:59 +0200606 thread.header = header;
607 thread.header_len = header_len;
Victor Stinner024e37a2011-03-31 01:31:06 +0200608
609 /* Arm these locks to serve as events when released */
Victor Stinnerde10f402011-04-08 12:57:06 +0200610 PyThread_acquire_lock(thread.running, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +0200611
Victor Stinner024e37a2011-03-31 01:31:06 +0200612 if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
Victor Stinnerde10f402011-04-08 12:57:06 +0200613 PyThread_release_lock(thread.running);
Victor Stinner024e37a2011-03-31 01:31:06 +0200614 Py_CLEAR(thread.file);
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200615 PyMem_Free(header);
Victor Stinnerc790a532011-04-08 13:39:59 +0200616 thread.header = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200617 PyErr_SetString(PyExc_RuntimeError,
618 "unable to start watchdog thread");
619 return NULL;
620 }
621
622 Py_RETURN_NONE;
623}
624
625static PyObject*
Georg Brandldeb92b52012-09-22 08:58:55 +0200626faulthandler_cancel_dump_traceback_later_py(PyObject *self)
Victor Stinner024e37a2011-03-31 01:31:06 +0200627{
Georg Brandldeb92b52012-09-22 08:58:55 +0200628 cancel_dump_traceback_later();
Victor Stinner024e37a2011-03-31 01:31:06 +0200629 Py_RETURN_NONE;
630}
Victor Stinner410dd7d2011-05-11 20:56:08 +0200631#endif /* FAULTHANDLER_LATER */
Victor Stinner024e37a2011-03-31 01:31:06 +0200632
633#ifdef FAULTHANDLER_USER
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200634static int
635faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
636{
637#ifdef HAVE_SIGACTION
638 struct sigaction action;
639 action.sa_handler = faulthandler_user;
640 sigemptyset(&action.sa_mask);
641 /* if the signal is received while the kernel is executing a system
642 call, try to restart the system call instead of interrupting it and
643 return EINTR. */
644 action.sa_flags = SA_RESTART;
645 if (chain) {
646 /* do not prevent the signal from being received from within its
647 own signal handler */
648 action.sa_flags = SA_NODEFER;
649 }
650#ifdef HAVE_SIGALTSTACK
651 if (stack.ss_sp != NULL) {
652 /* Call the signal handler on an alternate signal stack
653 provided by sigaltstack() */
654 action.sa_flags |= SA_ONSTACK;
655 }
656#endif
657 return sigaction(signum, &action, p_previous);
658#else
659 _Py_sighandler_t previous;
660 previous = signal(signum, faulthandler_user);
661 if (p_previous != NULL)
662 *p_previous = previous;
663 return (previous == SIG_ERR);
664#endif
665}
666
Victor Stinner024e37a2011-03-31 01:31:06 +0200667/* Handler of user signals (e.g. SIGUSR1).
668
669 Dump the traceback of the current thread, or of all threads if
670 thread.all_threads is true.
671
672 This function is signal safe and should only call signal safe functions. */
673
674static void
675faulthandler_user(int signum)
676{
677 user_signal_t *user;
Victor Stinnerc9256172011-05-07 12:20:11 +0200678 int save_errno = errno;
Victor Stinner024e37a2011-03-31 01:31:06 +0200679
680 user = &user_signals[signum];
681 if (!user->enabled)
682 return;
683
Victor Stinnerc7489a52015-04-01 18:48:58 +0200684 faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
Victor Stinner024e37a2011-03-31 01:31:06 +0200685
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200686#ifdef HAVE_SIGACTION
687 if (user->chain) {
688 (void)sigaction(signum, &user->previous, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200689 errno = save_errno;
690
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200691 /* call the previous signal handler */
692 raise(signum);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200693
694 save_errno = errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200695 (void)faulthandler_register(signum, user->chain, NULL);
Victor Stinner3cc635d2012-08-09 02:43:41 +0200696 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200697 }
698#else
699 if (user->chain) {
Victor Stinner3cc635d2012-08-09 02:43:41 +0200700 errno = save_errno;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200701 /* call the previous signal handler */
702 user->previous(signum);
703 }
704#endif
Victor Stinner44378d42011-04-01 15:37:12 +0200705}
706
707static int
708check_signum(int signum)
709{
710 unsigned int i;
711
712 for (i=0; i < faulthandler_nsignals; i++) {
713 if (faulthandler_handlers[i].signum == signum) {
714 PyErr_Format(PyExc_RuntimeError,
715 "signal %i cannot be registered, "
716 "use enable() instead",
717 signum);
718 return 0;
719 }
720 }
721 if (signum < 1 || NSIG <= signum) {
722 PyErr_SetString(PyExc_ValueError, "signal number out of range");
723 return 0;
724 }
725 return 1;
Victor Stinner024e37a2011-03-31 01:31:06 +0200726}
727
728static PyObject*
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200729faulthandler_register_py(PyObject *self,
730 PyObject *args, PyObject *kwargs)
Victor Stinner024e37a2011-03-31 01:31:06 +0200731{
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200732 static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
Victor Stinner024e37a2011-03-31 01:31:06 +0200733 int signum;
734 PyObject *file = NULL;
Victor Stinner7bba62f2011-05-07 12:43:00 +0200735 int all_threads = 1;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200736 int chain = 0;
Victor Stinner024e37a2011-03-31 01:31:06 +0200737 int fd;
Victor Stinner024e37a2011-03-31 01:31:06 +0200738 user_signal_t *user;
739 _Py_sighandler_t previous;
Victor Stinner44378d42011-04-01 15:37:12 +0200740 PyThreadState *tstate;
Victor Stinner024e37a2011-03-31 01:31:06 +0200741 int err;
742
743 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200744 "i|Oii:register", kwlist,
745 &signum, &file, &all_threads, &chain))
Victor Stinner024e37a2011-03-31 01:31:06 +0200746 return NULL;
747
Victor Stinner44378d42011-04-01 15:37:12 +0200748 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200749 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200750
Victor Stinnera4de6d82011-04-09 00:47:23 +0200751 tstate = get_thread_state();
752 if (tstate == NULL)
Victor Stinner44378d42011-04-01 15:37:12 +0200753 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200754
Victor Stinner95bb7142015-03-12 15:32:03 +0100755 fd = faulthandler_get_fileno(&file);
756 if (fd < 0)
Victor Stinner024e37a2011-03-31 01:31:06 +0200757 return NULL;
758
759 if (user_signals == NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200760 user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200761 if (user_signals == NULL)
762 return PyErr_NoMemory();
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200763 memset(user_signals, 0, NSIG * sizeof(user_signal_t));
Victor Stinner024e37a2011-03-31 01:31:06 +0200764 }
765 user = &user_signals[signum];
766
767 if (!user->enabled) {
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200768 err = faulthandler_register(signum, chain, &previous);
Victor Stinner024e37a2011-03-31 01:31:06 +0200769 if (err) {
770 PyErr_SetFromErrno(PyExc_OSError);
771 return NULL;
772 }
Victor Stinner8d379542013-07-02 00:14:56 +0200773
774 user->previous = previous;
Victor Stinner024e37a2011-03-31 01:31:06 +0200775 }
776
Victor Stinner95bb7142015-03-12 15:32:03 +0100777 Py_XINCREF(file);
Serhiy Storchaka5a57ade2015-12-24 10:35:59 +0200778 Py_SETREF(user->file, file);
Victor Stinner024e37a2011-03-31 01:31:06 +0200779 user->fd = fd;
780 user->all_threads = all_threads;
Victor Stinnera9a9dab2011-07-13 23:39:53 +0200781 user->chain = chain;
Victor Stinner44378d42011-04-01 15:37:12 +0200782 user->interp = tstate->interp;
Victor Stinner024e37a2011-03-31 01:31:06 +0200783 user->enabled = 1;
784
785 Py_RETURN_NONE;
786}
787
788static int
789faulthandler_unregister(user_signal_t *user, int signum)
790{
Victor Stinnera01ca122011-04-01 12:56:17 +0200791 if (!user->enabled)
Victor Stinner024e37a2011-03-31 01:31:06 +0200792 return 0;
793 user->enabled = 0;
794#ifdef HAVE_SIGACTION
795 (void)sigaction(signum, &user->previous, NULL);
796#else
797 (void)signal(signum, user->previous);
798#endif
799 Py_CLEAR(user->file);
800 user->fd = -1;
801 return 1;
802}
803
804static PyObject*
805faulthandler_unregister_py(PyObject *self, PyObject *args)
806{
807 int signum;
808 user_signal_t *user;
809 int change;
810
811 if (!PyArg_ParseTuple(args, "i:unregister", &signum))
812 return NULL;
813
Victor Stinner44378d42011-04-01 15:37:12 +0200814 if (!check_signum(signum))
Victor Stinner024e37a2011-03-31 01:31:06 +0200815 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +0200816
Victor Stinnercfa71232011-04-08 12:48:15 +0200817 if (user_signals == NULL)
818 Py_RETURN_FALSE;
819
Victor Stinner024e37a2011-03-31 01:31:06 +0200820 user = &user_signals[signum];
821 change = faulthandler_unregister(user, signum);
822 return PyBool_FromLong(change);
823}
824#endif /* FAULTHANDLER_USER */
825
826
Victor Stinner7a399122014-09-30 13:40:12 +0200827static void
828faulthandler_suppress_crash_report(void)
829{
830#ifdef MS_WINDOWS
831 UINT mode;
832
833 /* Configure Windows to not display the Windows Error Reporting dialog */
834 mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
835 SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
836#endif
837
838#ifdef HAVE_SYS_RESOURCE_H
839 struct rlimit rl;
840
841 /* Disable creation of core dump */
842 if (getrlimit(RLIMIT_CORE, &rl) != 0) {
843 rl.rlim_cur = 0;
844 setrlimit(RLIMIT_CORE, &rl);
845 }
846#endif
847
848#ifdef _MSC_VER
849 /* Visual Studio: configure abort() to not display an error message nor
850 open a popup asking to report the fault. */
851 _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
852#endif
853}
854
Victor Stinner024e37a2011-03-31 01:31:06 +0200855static PyObject *
856faulthandler_read_null(PyObject *self, PyObject *args)
857{
Victor Stinnera2477202012-01-30 00:07:43 +0100858 volatile int *x;
859 volatile int y;
Victor Stinnera2477202012-01-30 00:07:43 +0100860
Victor Stinner7a399122014-09-30 13:40:12 +0200861 faulthandler_suppress_crash_report();
Victor Stinnera2477202012-01-30 00:07:43 +0100862 x = NULL;
Victor Stinner50838282014-09-30 13:54:14 +0200863 y = *x;
Victor Stinner024e37a2011-03-31 01:31:06 +0200864 return PyLong_FromLong(y);
865
866}
867
Victor Stinner50838282014-09-30 13:54:14 +0200868static void
869faulthandler_raise_sigsegv(void)
Victor Stinner024e37a2011-03-31 01:31:06 +0200870{
Victor Stinner7a399122014-09-30 13:40:12 +0200871 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200872#if defined(MS_WINDOWS)
Victor Stinnerbc6a4db2011-04-01 12:08:57 +0200873 /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
874 handler and then gives back the execution flow to the program (without
Victor Stinner410dd7d2011-05-11 20:56:08 +0200875 explicitly calling the previous error handler). In a normal case, the
Victor Stinner024e37a2011-03-31 01:31:06 +0200876 SIGSEGV was raised by the kernel because of a fault, and so if the
877 program retries to execute the same instruction, the fault will be
878 raised again.
879
880 Here the fault is simulated by a fake SIGSEGV signal raised by the
881 application. We have to raise SIGSEGV at lease twice: once for
882 faulthandler_fatal_error(), and one more time for the previous signal
883 handler. */
884 while(1)
885 raise(SIGSEGV);
886#else
887 raise(SIGSEGV);
888#endif
Victor Stinner50838282014-09-30 13:54:14 +0200889}
890
891static PyObject *
892faulthandler_sigsegv(PyObject *self, PyObject *args)
893{
894 int release_gil = 0;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100895 if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
Victor Stinner50838282014-09-30 13:54:14 +0200896 return NULL;
897
898 if (release_gil) {
899 Py_BEGIN_ALLOW_THREADS
900 faulthandler_raise_sigsegv();
901 Py_END_ALLOW_THREADS
902 } else {
903 faulthandler_raise_sigsegv();
904 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200905 Py_RETURN_NONE;
906}
907
Victor Stinner861d9ab2016-03-16 22:45:24 +0100908#ifdef WITH_THREAD
909static void
910faulthandler_fatal_error_thread(void *plock)
911{
912 PyThread_type_lock *lock = (PyThread_type_lock *)plock;
913
914 Py_FatalError("in new thread");
915
916 /* notify the caller that we are done */
917 PyThread_release_lock(lock);
918}
919
920static PyObject *
921faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
922{
923 long thread;
924 PyThread_type_lock lock;
925
926 faulthandler_suppress_crash_report();
927
928 lock = PyThread_allocate_lock();
929 if (lock == NULL)
930 return PyErr_NoMemory();
931
932 PyThread_acquire_lock(lock, WAIT_LOCK);
933
934 thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
935 if (thread == -1) {
936 PyThread_free_lock(lock);
937 PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
938 return NULL;
939 }
940
941 /* wait until the thread completes: it will never occur, since Py_FatalError()
942 exits the process immedialty. */
943 PyThread_acquire_lock(lock, WAIT_LOCK);
944 PyThread_release_lock(lock);
945 PyThread_free_lock(lock);
946
947 Py_RETURN_NONE;
948}
949#endif
950
Victor Stinner024e37a2011-03-31 01:31:06 +0200951static PyObject *
952faulthandler_sigfpe(PyObject *self, PyObject *args)
953{
954 /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
955 PowerPC. Use volatile to disable compile-time optimizations. */
956 volatile int x = 1, y = 0, z;
Victor Stinner7a399122014-09-30 13:40:12 +0200957 faulthandler_suppress_crash_report();
Victor Stinner024e37a2011-03-31 01:31:06 +0200958 z = x / y;
Victor Stinner410dd7d2011-05-11 20:56:08 +0200959 /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
960 raise it manually. */
Victor Stinner024e37a2011-03-31 01:31:06 +0200961 raise(SIGFPE);
Victor Stinner410dd7d2011-05-11 20:56:08 +0200962 /* This line is never reached, but we pretend to make something with z
963 to silence a compiler warning. */
Victor Stinnere0c9a752011-05-09 14:44:26 +0200964 return PyLong_FromLong(z);
Victor Stinner024e37a2011-03-31 01:31:06 +0200965}
966
Victor Stinnerd727e232011-04-01 12:13:55 +0200967static PyObject *
968faulthandler_sigabrt(PyObject *self, PyObject *args)
969{
Victor Stinner7a399122014-09-30 13:40:12 +0200970 faulthandler_suppress_crash_report();
Victor Stinner00bc6cc2011-05-10 01:30:03 +0200971 abort();
Victor Stinnerd727e232011-04-01 12:13:55 +0200972 Py_RETURN_NONE;
973}
974
Victor Stinner024e37a2011-03-31 01:31:06 +0200975static PyObject *
976faulthandler_fatal_error_py(PyObject *self, PyObject *args)
977{
978 char *message;
Victor Stinner57003f82016-03-15 17:23:35 +0100979 int release_gil = 0;
980 if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
Victor Stinner024e37a2011-03-31 01:31:06 +0200981 return NULL;
Victor Stinner7a399122014-09-30 13:40:12 +0200982 faulthandler_suppress_crash_report();
Victor Stinner57003f82016-03-15 17:23:35 +0100983 if (release_gil) {
984 Py_BEGIN_ALLOW_THREADS
985 Py_FatalError(message);
986 Py_END_ALLOW_THREADS
987 }
988 else {
989 Py_FatalError(message);
990 }
Victor Stinner024e37a2011-03-31 01:31:06 +0200991 Py_RETURN_NONE;
992}
993
994#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
Victor Stinner19276f12015-03-23 21:20:27 +0100995#ifdef __INTEL_COMPILER
996 /* Issue #23654: Turn off ICC's tail call optimization for the
997 * stack_overflow generator. ICC turns the recursive tail call into
998 * a loop. */
999# pragma intel optimization_level 0
1000#endif
1001static
1002Py_uintptr_t
Victor Stinner7a5567a2015-02-11 14:23:35 +01001003stack_overflow(Py_uintptr_t min_sp, Py_uintptr_t max_sp, size_t *depth)
Victor Stinner024e37a2011-03-31 01:31:06 +02001004{
1005 /* allocate 4096 bytes on the stack at each call */
1006 unsigned char buffer[4096];
Victor Stinner7a5567a2015-02-11 14:23:35 +01001007 Py_uintptr_t sp = (Py_uintptr_t)&buffer;
Victor Stinnerf0480752011-03-31 11:34:08 +02001008 *depth += 1;
1009 if (sp < min_sp || max_sp < sp)
1010 return sp;
Victor Stinner024e37a2011-03-31 01:31:06 +02001011 buffer[0] = 1;
Victor Stinnerf0480752011-03-31 11:34:08 +02001012 buffer[4095] = 0;
1013 return stack_overflow(min_sp, max_sp, depth);
1014}
1015
1016static PyObject *
1017faulthandler_stack_overflow(PyObject *self)
1018{
1019 size_t depth, size;
Victor Stinner7a5567a2015-02-11 14:23:35 +01001020 Py_uintptr_t sp = (Py_uintptr_t)&depth;
1021 Py_uintptr_t stop;
Victor Stinnerf0480752011-03-31 11:34:08 +02001022
Victor Stinner7a399122014-09-30 13:40:12 +02001023 faulthandler_suppress_crash_report();
Victor Stinnerf0480752011-03-31 11:34:08 +02001024 depth = 0;
1025 stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
1026 sp + STACK_OVERFLOW_MAX_SIZE,
1027 &depth);
1028 if (sp < stop)
1029 size = stop - sp;
1030 else
1031 size = sp - stop;
1032 PyErr_Format(PyExc_RuntimeError,
1033 "unable to raise a stack overflow (allocated %zu bytes "
1034 "on the stack, %zu recursive calls)",
1035 size, depth);
1036 return NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001037}
1038#endif
1039
1040
1041static int
1042faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
1043{
1044#ifdef FAULTHANDLER_USER
Victor Stinner96994402011-04-07 11:37:19 +02001045 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001046#endif
1047
1048#ifdef FAULTHANDLER_LATER
1049 Py_VISIT(thread.file);
1050#endif
1051#ifdef FAULTHANDLER_USER
1052 if (user_signals != NULL) {
Victor Stinner96994402011-04-07 11:37:19 +02001053 for (signum=0; signum < NSIG; signum++)
1054 Py_VISIT(user_signals[signum].file);
Victor Stinner024e37a2011-03-31 01:31:06 +02001055 }
1056#endif
1057 Py_VISIT(fatal_error.file);
1058 return 0;
1059}
1060
1061PyDoc_STRVAR(module_doc,
1062"faulthandler module.");
1063
1064static PyMethodDef module_methods[] = {
1065 {"enable",
1066 (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001067 PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001068 "enable the fault handler")},
1069 {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
1070 PyDoc_STR("disable(): disable the fault handler")},
1071 {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
1072 PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
1073 {"dump_traceback",
1074 (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
Victor Stinner7bba62f2011-05-07 12:43:00 +02001075 PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001076 "dump the traceback of the current thread, or of all threads "
1077 "if all_threads is True, into file")},
1078#ifdef FAULTHANDLER_LATER
Georg Brandldeb92b52012-09-22 08:58:55 +02001079 {"dump_traceback_later",
1080 (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
1081 PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
Victor Stinner024e37a2011-03-31 01:31:06 +02001082 "dump the traceback of all threads in timeout seconds,\n"
Victor Stinner96994402011-04-07 11:37:19 +02001083 "or each timeout seconds if repeat is True. If exit is True, "
1084 "call _exit(1) which is not safe.")},
Georg Brandldeb92b52012-09-22 08:58:55 +02001085 {"cancel_dump_traceback_later",
1086 (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
1087 PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
1088 "to dump_traceback_later().")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001089#endif
1090
1091#ifdef FAULTHANDLER_USER
1092 {"register",
Victor Stinnera9a9dab2011-07-13 23:39:53 +02001093 (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
1094 PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
Victor Stinner024e37a2011-03-31 01:31:06 +02001095 "register an handler for the signal 'signum': dump the "
1096 "traceback of the current thread, or of all threads if "
1097 "all_threads is True, into file")},
1098 {"unregister",
1099 faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
1100 PyDoc_STR("unregister(signum): unregister the handler of the signal "
1101 "'signum' registered by register()")},
1102#endif
1103
Victor Stinner50838282014-09-30 13:54:14 +02001104 {"_read_null", faulthandler_read_null, METH_NOARGS,
1105 PyDoc_STR("_read_null(): read from NULL, raise "
Victor Stinner024e37a2011-03-31 01:31:06 +02001106 "a SIGSEGV or SIGBUS signal depending on the platform")},
1107 {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
Victor Stinner50838282014-09-30 13:54:14 +02001108 PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
Victor Stinner861d9ab2016-03-16 22:45:24 +01001109#ifdef WITH_THREAD
1110 {"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
1111 PyDoc_STR("fatal_error_c_thread(): "
1112 "call Py_FatalError() in a new C thread.")},
1113#endif
Victor Stinner9db521c2014-09-30 13:49:09 +02001114 {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
Victor Stinnerd727e232011-04-01 12:13:55 +02001115 PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001116 {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
1117 PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
Victor Stinner024e37a2011-03-31 01:31:06 +02001118 {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
1119 PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
1120#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
1121 {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
1122 PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
1123#endif
Victor Stinner410dd7d2011-05-11 20:56:08 +02001124 {NULL, NULL} /* sentinel */
Victor Stinner024e37a2011-03-31 01:31:06 +02001125};
1126
1127static struct PyModuleDef module_def = {
1128 PyModuleDef_HEAD_INIT,
1129 "faulthandler",
1130 module_doc,
Victor Stinner410dd7d2011-05-11 20:56:08 +02001131 0, /* non-negative size to be able to unload the module */
Victor Stinner024e37a2011-03-31 01:31:06 +02001132 module_methods,
1133 NULL,
1134 faulthandler_traverse,
1135 NULL,
1136 NULL
1137};
1138
1139PyMODINIT_FUNC
1140PyInit_faulthandler(void)
1141{
1142 return PyModule_Create(&module_def);
1143}
1144
Victor Stinner410dd7d2011-05-11 20:56:08 +02001145/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
1146 is defined, or if sys._xoptions has a 'faulthandler' key. */
Victor Stinner024e37a2011-03-31 01:31:06 +02001147
1148static int
1149faulthandler_env_options(void)
1150{
1151 PyObject *xoptions, *key, *module, *res;
Victor Stinner88983502013-09-08 11:36:23 +02001152 char *p;
Victor Stinner024e37a2011-03-31 01:31:06 +02001153
Victor Stinner88983502013-09-08 11:36:23 +02001154 if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
1155 /* PYTHONFAULTHANDLER environment variable is missing
1156 or an empty string */
Victor Stinner25095b22011-05-26 13:47:08 +02001157 int has_key;
1158
Victor Stinner024e37a2011-03-31 01:31:06 +02001159 xoptions = PySys_GetXOptions();
1160 if (xoptions == NULL)
1161 return -1;
1162
1163 key = PyUnicode_FromString("faulthandler");
1164 if (key == NULL)
1165 return -1;
1166
Victor Stinner25095b22011-05-26 13:47:08 +02001167 has_key = PyDict_Contains(xoptions, key);
Victor Stinner024e37a2011-03-31 01:31:06 +02001168 Py_DECREF(key);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +03001169 if (has_key <= 0)
1170 return has_key;
Victor Stinner024e37a2011-03-31 01:31:06 +02001171 }
Victor Stinner024e37a2011-03-31 01:31:06 +02001172
1173 module = PyImport_ImportModule("faulthandler");
1174 if (module == NULL) {
1175 return -1;
1176 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001177 res = _PyObject_CallMethodId(module, &PyId_enable, "");
Victor Stinner024e37a2011-03-31 01:31:06 +02001178 Py_DECREF(module);
1179 if (res == NULL)
1180 return -1;
1181 Py_DECREF(res);
1182 return 0;
1183}
1184
1185int _PyFaulthandler_Init(void)
1186{
1187#ifdef HAVE_SIGALTSTACK
1188 int err;
1189
1190 /* Try to allocate an alternate stack for faulthandler() signal handler to
1191 * be able to allocate memory on the stack, even on a stack overflow. If it
1192 * fails, ignore the error. */
1193 stack.ss_flags = 0;
1194 stack.ss_size = SIGSTKSZ;
1195 stack.ss_sp = PyMem_Malloc(stack.ss_size);
1196 if (stack.ss_sp != NULL) {
1197 err = sigaltstack(&stack, NULL);
1198 if (err) {
1199 PyMem_Free(stack.ss_sp);
1200 stack.ss_sp = NULL;
1201 }
1202 }
1203#endif
1204#ifdef FAULTHANDLER_LATER
Victor Stinner024e37a2011-03-31 01:31:06 +02001205 thread.file = NULL;
1206 thread.cancel_event = PyThread_allocate_lock();
Victor Stinnerde10f402011-04-08 12:57:06 +02001207 thread.running = PyThread_allocate_lock();
1208 if (!thread.cancel_event || !thread.running) {
Victor Stinner024e37a2011-03-31 01:31:06 +02001209 PyErr_SetString(PyExc_RuntimeError,
1210 "could not allocate locks for faulthandler");
1211 return -1;
1212 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001213 PyThread_acquire_lock(thread.cancel_event, 1);
Victor Stinner024e37a2011-03-31 01:31:06 +02001214#endif
1215
1216 return faulthandler_env_options();
1217}
1218
1219void _PyFaulthandler_Fini(void)
1220{
1221#ifdef FAULTHANDLER_USER
Victor Stinnera01ca122011-04-01 12:56:17 +02001222 unsigned int signum;
Victor Stinner024e37a2011-03-31 01:31:06 +02001223#endif
1224
1225#ifdef FAULTHANDLER_LATER
1226 /* later */
Victor Stinner024e37a2011-03-31 01:31:06 +02001227 if (thread.cancel_event) {
Georg Brandldeb92b52012-09-22 08:58:55 +02001228 cancel_dump_traceback_later();
Victor Stinnerde10f402011-04-08 12:57:06 +02001229 PyThread_release_lock(thread.cancel_event);
Victor Stinner024e37a2011-03-31 01:31:06 +02001230 PyThread_free_lock(thread.cancel_event);
1231 thread.cancel_event = NULL;
1232 }
Victor Stinnerde10f402011-04-08 12:57:06 +02001233 if (thread.running) {
1234 PyThread_free_lock(thread.running);
1235 thread.running = NULL;
Victor Stinner024e37a2011-03-31 01:31:06 +02001236 }
1237#endif
1238
1239#ifdef FAULTHANDLER_USER
1240 /* user */
1241 if (user_signals != NULL) {
Victor Stinnera01ca122011-04-01 12:56:17 +02001242 for (signum=0; signum < NSIG; signum++)
1243 faulthandler_unregister(&user_signals[signum], signum);
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001244 PyMem_Free(user_signals);
Victor Stinner024e37a2011-03-31 01:31:06 +02001245 user_signals = NULL;
1246 }
1247#endif
1248
1249 /* fatal */
1250 faulthandler_disable();
1251#ifdef HAVE_SIGALTSTACK
1252 if (stack.ss_sp != NULL) {
1253 PyMem_Free(stack.ss_sp);
1254 stack.ss_sp = NULL;
1255 }
1256#endif
1257}