How to write a signal handler to catch SIGSEGV?

前端 未结 5 1377
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 15:26

I want to write a signal handler to catch SIGSEGV. I protect a block of memory for read or write using

char *buffer;
char *p;
char a;
int pagesize = 4096;

         


        
5条回答
  •  逝去的感伤
    2020-11-22 15:54

    You should not return from the signal handler, as then behavior is undefined. Rather, jump out of it with longjmp.

    This is only okay if the signal is generated in an async-signal-safe function. Otherwise, behavior is undefined if the program ever calls another async-signal-unsafe function. Hence, the signal handler should only be established immediately before it is necessary, and disestablished as soon as possible.

    In fact, I know of very few uses of a SIGSEGV handler:

    • use an async-signal-safe backtrace library to log a backtrace, then die.
    • in a VM such as the JVM or CLR: check if the SIGSEGV occurred in JIT-compiled code. If not, die; if so, then throw a language-specific exception (not a C++ exception), which works because the JIT compiler knew that the trap could happen and generated appropriate frame unwind data.
    • clone() and exec() a debugger (do not use fork() – that calls callbacks registered by pthread_atfork()).

    Finally, note that any action that triggers SIGSEGV is probably UB, as this is accessing invalid memory. However, this would not be the case if the signal was, say, SIGFPE.

提交回复
热议问题