Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exactly what "program state" does setjmp save?

Tags:

c

setjmp

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?

like image 750
Norg74 Avatar asked Aug 12 '14 14:08

Norg74


2 Answers

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 the longjmp 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 the jmp_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.

like image 180
embedded_guy Avatar answered Oct 22 '22 13:10

embedded_guy


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.

like image 43
jtlim Avatar answered Oct 22 '22 15:10

jtlim