Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Longjmp out of signal handler?

From the question:

Is it good programming practice to use setjmp and longjmp in C?

Two of the comments left said:

"You can't throw an exception in a signal handler, but you can do a longjmp safely -- as long as you know what you are doing. – Dietrich Epp Aug 31 at 19:57 @Dietrich: +1 to your comment. This is a little-known and completely-under-appreciated fact. There are a number of problems that cannot be solved (nasty race conditions) without using longjmp out of signal handlers. Asynchronous interruption of blocking syscalls is the classic example."

I was under the impression that signal handlers were called by the kernel when it encountered an exceptional condition (e.g. divide by 0). Also, that they're only called if you specifically register them.

This would seem to imply (to me) that they aren't called through your normal code.

Moving on with that thought... setjmp and longjmp as I understand them are for collapsing up the stack to a previous point and state. I don't understand how you can collapse up a stack when a signal handler is called since its called from the Kernel as a one-off circumstance rather than from your own code. What's the next thing up the stack from a signal handler!?

like image 763
John Humphreys Avatar asked Sep 07 '11 13:09

John Humphreys


People also ask

Can a signal handler be interrupted?

Signal handlers can be interrupted by signals, including their own. If a signal is not reset before its handler is called, the handler can interrupt its own execution. A handler that always successfully executes its code despite interrupting itself or being interrupted is async-signal-safe.

What is the purpose of a signal handler?

A signal handler is a function which is called by the target environment when the corresponding signal occurs. The target environment suspends execution of the program until the signal handler returns or calls longjmp() . Signal handlers can be set with signal() or sigaction() .

What happens when a signal handler returns?

If a signal handler returns in such a situation, the program is abnormally terminated. The call to signal establishes signal handling for only one occurrence of a signal. Before the signal-handling function is called, the library resets the signal so that the default action is performed if the same signal occurs again.


4 Answers

The way the kernel "calls" a signal handler is by interrupting the thread, saving the signal mask and processor state in a ucontext_t structure on the stack just beyond (below, on grows-down implementations) the interrupted code's stack pointer, and restarting execution at the address of the signal handler. The kernel does not need to keep track of any "this process is in a signal handler" state; that's entirely a consequence of the new call frame that was created.

If the interrupted thread was in the middle of a system call, the kernel will back out of the kernelspace code and adjust the return address to repeat the system call (if SA_RESTART is set for the signal and the system call is a restartable one) or put EINTR in the return code (if not restartable).

It should be noted that longjmp is async-signal-unsafe. This means it invokes undefined behavior if you call it from a signal handler if the signal interrupted another async-signal-unsafe function. But as long as the interrupted code is not using library functions, or only using library functions that are marked async-signal-safe, it's legal to call longjmp from a signal handler.

Finally, my answer is based on POSIX since the question is tagged unix. If the question were just about pure C, I suspect the answer is somewhat different, but signals are rather useless without POSIX anyway...

like image 161
R.. GitHub STOP HELPING ICE Avatar answered Oct 05 '22 04:10

R.. GitHub STOP HELPING ICE


longjmp does not perform normal stack unwinding. Instead, the stack pointer is simply restored from the context saved by setjmp.

Here is an illustration on how this can bite you with non-async-safe critical parts in your code. It is advisable to e.g. mask the offending signal during critical code.

like image 37
makes Avatar answered Oct 05 '22 03:10

makes


worth reading this: http://man7.org/linux/man-pages/man2/sigreturn.2.html in regard to how Linux handles signal handler invocation, and in this case how it manages signal handler exit, my reading of this suggests that executing a longjmp() from a signal handler (resulting in no call of sigreturn()) might be at best "undefined"... also have to take into account on which thread (and thus user stack) the setjmp() was called, and on which thread (and thus user stack) longjmp() in subsequently called also!

like image 21
Larry Cable Avatar answered Oct 05 '22 04:10

Larry Cable


This doesn't answer the question of whether or not it is "good" to do this, but this is how to do it. In my application, I have a complicated interaction between custom hardware, huge page, shared memory, NUMA lock memory, etc, and it is possible to have memory that seems to be decently allocated but when you touch it (write in this case), it throws a BUS error or SEGV fault in the middle of the application. I wanted to come up with a way of testing memory addresses to make sure that the shared memory wasn't node locked to a node that didn't have enough memory, so that the program would fail early with graceful error messages. So these signal handlers are ONLY used for this one piece of code (a small memcpy of 5 bytes) and not used to rescue the app while it is in use. I think it is safe here.

Apologies if this is not "correct". Please comment and I'll fix it up. I cobbled it together based on hints and some sample code that didn't work.

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

sigjmp_buf  JumpBuffer;

void handler(int);

int count = 0;

int main(void)
{
    struct sigaction sa;
    sa.sa_handler = handler;
    sigemptyset(&(sa.sa_mask));
    sigaddset(&(sa.sa_mask), SIGSEGV);
    sigaction(SIGSEGV, &sa, NULL);

    while (1) {
        int r = sigsetjmp(JumpBuffer,1);
        if (r == 0) {
            printf("Ready for memcpy, count=%d\n",count);
            usleep(1000000);
            char buffer[10];
#if 1
            char* dst = buffer; // this won't do bad
#else
            char* dst = nullptr; // this will cause a segfault
#endif
            memcpy(dst,"12345",5); // trigger seg fault here
            longjmp(JumpBuffer,2);
        }
        else if (r == 1)
        {
            printf("SEGV. count %d\n",count);
        }
        else if (r == 2)
        {
            printf("No segv. count %d\n",count);
        }
    }
    return 0;
}

void handler(int  sig)
{
    count++;
    siglongjmp(JumpBuffer, 1);
}

References

  • https://linux.die.net/man/3/sigsetjmp
  • https://pubs.opengroup.org/onlinepubs/9699919799/functions/longjmp.html
  • http://www.csl.mtu.edu/cs4411.ck/www/NOTES/non-local-goto/sig-1.html
  • https://www.gnu.org/software/libc/manual/html_node/Longjmp-in-Handler.html
like image 22
Mark Lakata Avatar answered Oct 05 '22 03:10

Mark Lakata