After catching a SIGSEGV through a signal handler, I am trying to use mmap to map the address. I can't figure out why mmap fails with Cannot allocate memory error.
Here is the C code. I am trying to run this on macOS.
#include <signal.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
void *addr;
static void catch_function(int signo, siginfo_t *si, void *unused) {
printf("Got SIGSEGV at address: 0x%lx\n", (long)si->si_addr);
void *ptr = mmap(addr, 100, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANON | MAP_FIXED, 0, 0);
if (ptr == MAP_FAILED) {
perror("mmap");
}
}
int main(void) {
int page_size = getpagesize();
if (signal(SIGSEGV, catch_function) == SIG_ERR) {
fputs("An error occurred while setting a signal handler.\n", stderr);
return 1;
}
addr = (void *)(page_size * 100);
// trigger segfault
*((int *)addr) = 1;
}
The cause of the segmentation fault(SIGSEGV) is the attempt to write to an invalid memory address.
In your case, I think the
addrvariable is set to a memory address that is not allocated.Here's the updated code:
(Didn't tested it yet)