How can a program signal itself when it does a write access to a configurable memory region?
This would be something similar to the data-breakpoint feature found in some debuggers. POSIX compliance is desired but not required as long as it works on Linux.
Here there is an illustrative code of what I would like:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void configure_trap(void *FROM, void *TO){
/*
Set a trap on write access to any memory location from
address FROM to address TO.
When the trap is triggered, send SIGTRAP to the process.
There is no need for an answer to have the full code, just
an indication on how to proceed.
*/
}
char *ptr;
void trap_signal_handler(int signum){
if(ptr[123] == 'x'){
printf("Invalid value in ptr[123] !!!\n");
/*
Print a backtrace using libunwind. (Not part of this question.)
*/
}
}
void some_function(){
ptr[123] = 'x';
/*
This write access could be performed directly in this function or
another function called directly or indirectly by this one and it
could reside in this program or in an external library or could even
be performed in a system call.
trap_signal_handler should be called at this point.
After the signal handler has been executed, program should resume
normal operation.
*/
}
int main(){
struct sigaction sa = { .sa_handler = trap_signal_handler };
sigaction(SIGTRAP, &sa, NULL);
ptr = malloc(1024);
configure_trap(&ptr[123], &ptr[123]);
some_function();
return(0);
}
Thanks!