I've read that setjmp "saves the program state" in the passed-in jmp_buf variable, but I haven't found any description of exactly what that entails. Does it make a copy of all the application's memory? Just the registers? The stack?
The following is from C in a Nutshell by Peter Prinz and Tony Crawford:
The
setjmp()
macro saves the current environment at the time of the call in a buffer specified by its argument. The environment includes the stack, and with it all variables that have automatic storage duration.
Here is what ISO/IEC 9899:TC2 has to say in section 7.13:
The environment of a call to the
setjmp
macro consists of information sufficient for a call to thelongjmp
function to return execution to the correct block and invocation of that block, were it called recursively. It does not include the state of the floating-point status flags, of open files, or of any other component of the abstract machine.
Here is an interesting reference by P.J. Plauger in his book, The Standard C Library:
One of the dangers [of implementing setjmp] lies in expression evaluation. A typical computer has some number of registers that it uses to hold intermediate results while evaluating an expression. Write a sufficiently complex expression, however, and you may exhaust the available registers...
setjmp
must guess how much "calling context" to store in thejmp_buf
data object. It is a safe bet that certain registers must be saved.
And finally, from Expert C Programming by Peter Van Der Linden.
Setjmp saves a copy of the program counter and the current pointer to the top of the stack.
Based on the above information, it looks to me like the "current environment" is left up to the implementation.
It's just the registers that need to be preserved across a function call according to the platforms ABI.
Source: disassembling setjmp on x86, x64, arm32, arm64 on various operating systems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With