3.26 Other weird stack hacks
It just restores (almost) all registers, takesRAfrom structure and jumps there. This effectively works as if
setjmp() returned to caller. Also,RAXis set to be equal to the second argument of longjmp(). This works
as if setjmp() returned non-zero value at first place.
As a side effect ofSPrestoration, all values in stack which has been set and used between setjmp()
and longjmp() calls are just dropped. They will not be used anymore. Hence, longjmp() usually jumps
backwards^53.
This implies that, unlike in throw/catch mechanism in C++, no memory will be freed, no destructors will
be called, etc. Hence, this technique sometimes can be dangerous. Nevertheless, it’s still quite popular.
It’s still used in Oracle RDBMS.
It also has unexpected side-effect: if some buffer has been overflown inside of a function (maybe due to
remote attack), and a function wants to report error, and it calls longjmp(), overwritten stack part just
gets unused.
As an exercise, you can try to understand, why not all registers are saved. Why XMM0-XMM5 and other
registers are skipped?
3.26 Other weird stack hacks
3.26.1 Accessing arguments/local variables of caller
From C/C++ basics we know that this is impossible for a function to access arguments of caller function
or its local variables.
Nevertheless, it’s possible using dirty hacks. For example:
#include <stdio.h>
void f(char text)
{
// print stack
int tmp=&text;
for (int i=0; i<20; i++)
{
printf ("0x%x\n", *tmp);
tmp++;
};
};
void draw_text(int X, int Y, char* text)
{
f(text);
printf ("We are going to draw [%s] at %d:%d\n", text, X, Y);
};
int main()
{
printf ("address of main()=0x%x\n", &main);
printf ("address of draw_text()=0x%x\n", &draw_text);
draw_text(100, 200, "Hello!");
};
On 32-bit Ubuntu 16.04 and GCC 5.4.0, I got this:
address of main()=0x80484f8
address of draw_text()=0x80484cb
0x8048645 first argument to f()
0x8048628
0xbfd8ab98
(^53) However, there are some people who can use it for much more complicated things, imitating coroutines, etc:https://www.
embeddedrelated.com/showarticle/455.php,http://fanf.livejournal.com/105413.html