Handling memory allocation failure using a signal handler

John Scott jscott at posteo.net
Thu Apr 28 01:30:10 CEST 2022


Hi GMPers,

I'm familiar with the previous discussions and arguments around the
matter, and I'm aware that handling out-of-memory errors with GMP is
difficult. The manual says that calling longjmp() from a memory
allocation function is undefined. If this is not true anymore, please
let me know and disregard the following.

I wonder if using a signal handler on SIGABRT is supported or if this
too is undefined? And if it's not undefined, what about calling
longjmp() from the signal handler? An example of how one might do this
is the following:

#define _POSIX_C_SOURCE 200809L
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void oom(int signo, siginfo_t *info, void *context) {
	if(info->si_code == SI_USER && info->si_pid == getpid()) {
		/* Handle being out of memory, including possibly
		 * by doing a longjmp(). It is safe to call
		 * non-async-signal-safe functions here since the
		 * signal was syncronously raised. */
		_Exit(EXIT_FAILURE);
	} else {
		abort();
	}
}

int main(void) {
	struct sigaction act = {
		.sa_sigaction = oom,
		.sa_flags = SA_NODEFER|SA_RESETHAND|SA_SIGINFO
	};
	if(sigemptyset(&act.sa_mask) == -1) {
		perror("Failed to empty signal set");
		exit(EXIT_FAILURE);
	}
	if(sigaction(SIGABRT, &act, NULL) == -1) {
		perror("Failed to set up signal handler");
		exit(EXIT_FAILURE);
	}

	/* do some GMP stuff */
}

bearing in mind that a valid signal handler for SIGABRT must not return.

Thanks
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 252 bytes
Desc: This is a digitally signed message part
URL: <https://gmplib.org/list-archives/gmp-discuss/attachments/20220427/bb014d5a/attachment.bin>


More information about the gmp-discuss mailing list