cstack-pointercallcc

How to get the stack pointer and return address and restore them to a previous state


I'm trying to implement a poor man's call with current continuation for a program written in C. I can "easily" access and memcpy the relevant part of the C stack (obviously, that's not portable and is full of UB, but I already bit that bullet).

What I'm wondering is how to get the actual stack pointer and return address and how to restore them. I have the impression that I can probably get away with doing it only for the stack pointer (the return address itself will be hopefully stashed inside the stack chunk that I copied&restored).

I suspect this will require a bit of assembly, but I'm hoping that there's ideally some clever way to avoid it.


Solution

  • Per request, my comments in the form of an answer (tho, you are doing something so specific that I doubt that anybody with the same question will ever read it :D)

    This could probably be done (in a non-portable way, of course) with setjmp/longjmp. I mean, it is almost the same thing as call/cc, but (and that a big but) for the fact that you can only go down the stack. So, you can go back to the caller, or the caller of the caller, or... ; but not, contrarily to call/cc, go "back" to a previously called function, in a stack as non-linear as Marty McFly's timeline is. The stack with setjmp is still the same classical, linear, stack, just you can fast unstack it. It is not the implicit tree that "stack" is with call/cc

    But, still, setjmp stores everything you need (stack pointer, registers, etc.). It is UB if used with an obsolete stack, but may be combining that with the ugly stack copy you intend to do...