I am new to basics of gcc compilation. As far as I know the stack is inexecutable for security reasons. Then how can we have code on stack and execute. I observed this in case of a function returning pointer to a function. it does not return pointer to code but rather to a location on stack which has the code to be executed. How is that allowed in linux?
It is already done by gcc. I want to know how is it even possible?
Here is the c code:
#include<stdio.h>
typedef int (* funcptr) ();
funcptr f ()
{
int g ()
{
}
return (&g);
}
main ()
{
funcptr fp;
fp = f();
fp ();
}
And here is the portion of the assembly code geerating code on the stack:
#Starting trampoline code. The trampoline code is a small
#piece of code set up inside the stack!!!. This code, when
#executed, loads ecx with the static link and calls the
#function g
movb $-71, (%eax) # This is B9, the opcode for
"movl address_in_next_loc ecx"
this, when executed, will
load the static link in ecx
movl %edx, 1(%eax) # address_in_next_loc=ebp-16
the static link effectively
movb $-23, 5(%eax) # This is E9. the opcode for
jmp addr_nxt_ins + offset_
in_nxt_loc
Since the offset_in_nxt_loc
is &g - addr_nxt_ins, this
results in a jump to &g
movl $g.1831, %ecx # Stores &g - addr_nxt_ins
leal 10(%eax), %edx #
subl %edx, %ecx #
movl %ecx, %edx #
movl %edx, 6(%eax) #
#End of trampoline code