If I override the signal handler in the user code segment using the Linux system call "signal," then when the process receives a signal, the signal handler runs in user mode. After the signal handler completes its execution, how can we return to kernel mode? When the return statement of the signal handler is executed, and the current cs:rip points to the top of the user stack, how do we jump back to the kernel?
I am currently studying lessons about Linux exception control flow, and I am facing challenges in the section related to signal handlers.
Generally, the signal handler is installed through library code (e.g. signal()
, sigaction()
), and therefore the action of returning from the signal handler is transparently handled by the library.
To return from a signal the sigreturn
and rt_signreturn
syscalls are used, so when your signal handler function returns, it returns to a special stub set up by the library called "signal trampoline" used to perform one of these two syscalls.
The manual page describes this pretty well:
If the Linux kernel determines that an unblocked signal is pending for a process, then, at the next transition back to user mode in that process (e.g., upon return from a system call or when the process is rescheduled onto the CPU), it creates a new frame on the user-space stack where it saves various pieces of process context (processor status word, registers, signal mask, and signal stack settings).
The kernel also arranges that, during the transition back to user mode, the signal handler is called, and that, upon return from the handler, control passes to a piece of user-space code commonly called the "signal trampoline". The signal trampoline code in turn calls
sigreturn()
.This
sigreturn()
call undoes everything that was done—changing the process's signal mask, switching signal stacks (seesigaltstack(2)
)—in order to invoke the signal handler. Using the information that was earlier saved on the user-space stacksigreturn()
restores the process's signal mask, switches stacks, and restores the process's context (processor flags and registers, including the stack pointer and instruction pointer), so that the process resumes execution at the point where it was interrupted by the signal.