Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep stack unwinding

First of all, this is definitely about C, no C++ solutions are requested.

Target: Return to the caller function (A) beyond multiple stack frames.

I have some solutions, but none of them feels like the best option.

The easiest one in the sense of implementation is longjmp/setjmp, but I am not sure if it destroys auto variables, because as wiki refers, no normal stack unwinding taking part if longjmp is performed.

Here is a short description of the program flow: the A function calls file processing function, which results in many internal and recursive invocations. At some point, file reader meets EOF, so the job of file processing is done and control should be given to A function.

Comparing each read character against EOF or '\0'? No, thanks. UPD: I can avoid dynamic allocations in the call chain between setjmp and longjmp.

Not being sure about auto variables, I do not know what will happen in sequential calls to file processing (there is more than 1 file).

So:

1) Whats about 'no stack unwinding' by longjmp? How danger is that if I got all the data holders available (pointers).

2) Other neat and effective ways to go back to the A frame?

like image 326
Iskander Sharipov Avatar asked Oct 17 '25 23:10

Iskander Sharipov


1 Answers

I don't know what you read somewhere, but setjmp/longjmp is exactly the tool foreseen for the task.

longjmp re-establishes the "stack" exactly (well sort of) as it has been at the call to setjmp, all modifications to the "stack" that had been done between the two are lost, including all auto variables that have been defined. This re-establishment of the stack is brute forward, in C there is no concept of destructors, and this is perhaps meant by "no stack unwinding".

I put "stack" in quotes since this is not a term that the C standard applies, it only talks about state and allows that this is organized how it pleases to the implementation.

Now the only information that you are able to keep from the time between setjmp and longjmp are:

  • the value that you pass to longjmp
  • the value of modified volatile objects that you defined before setjmp

So in the branch where you come back from longjmp you have to use this (and only this) information to cleanup your mess: close files, free objects that you malloced etc.

like image 83
Jens Gustedt Avatar answered Oct 19 '25 12:10

Jens Gustedt