From dfaae947da7371d955b071095e4e6f42978a417f Mon Sep 17 00:00:00 2001 From: Sergey B Kirpichev Date: Fri, 13 Sep 2024 09:50:16 +0300 Subject: [PATCH] Add signal handler to catch SIGFPE on the GMP 6.3+ Since 6.3.0 some memory errors in mpz/realloc.c trigger SIGFPE exception. I think it's an upstream bug: helpful message should be emitted instead. This patch install SIGFPE handler, that does this. Closes #497 --- src/gmpy2.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/gmpy2.c b/src/gmpy2.c index 89ae1cd2..0629e0ba 100644 --- a/src/gmpy2.c +++ b/src/gmpy2.c @@ -96,6 +96,7 @@ #include #include #include +#include /* * we do have a dependence on Python's internals, specifically: @@ -567,6 +568,23 @@ static struct PyModuleDef moduledef = { NULL }; +void +gmp_abort_handler(int i) +{ + if (__GNU_MP_VERSION == 6 && __GNU_MP_VERSION_MINOR >= 3) { + if (gmp_errno & GMP_ERROR_DIVISION_BY_ZERO) { + printf("gmp: divide by zero\n"); + } + else if (gmp_errno & GMP_ERROR_SQRT_OF_NEGATIVE) { + printf("gmp: root of negative\n"); + } + else { + printf("gmp: out of memory\n"); + } + } + abort(); +} + PyMODINIT_FUNC PyInit_gmpy2(void) { PyObject *result = NULL; @@ -947,5 +965,7 @@ PyMODINIT_FUNC PyInit_gmpy2(void) /* LCOV_EXCL_STOP */ } + PyOS_setsig(SIGFPE, gmp_abort_handler); + return gmpy_module; }