Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of executable stack in Linux (i386 architecture)

Tags:

c

linux

x86

gcc

elf

I found that when we use nested functions, GCC requires an executable stack for trampoline code. However, following code, when compiled using gcc doesn't show an executable stack. (I used execstack to verify if the stack is executable)

#include <stdio.h>
#include <unistd.h>

int main()
{
        int add( int a, int b)
        {
                return a + b;
        }
        return add(2, 3);
}

Why does this not result in a executable stack? And if it is not supposed to, then can someone give example of a code construct that does give an executable stack?

like image 739
gjain Avatar asked May 12 '12 13:05

gjain


1 Answers

If the nested function doesn't depend in its "parent"'s stack at all, then it's just a plain function - the nesting is syntactic (and scoping) sugar.

And if you don't take the address of the nested function, no trampoline code is necessary either. So you'll need something a bit more involved to trigger all that.

Here's a dummy example:

// file t.c
int doit(int (*fun)(int), int x)
{
    return fun(x);
}

int foo(int a)
{
        int add(int b)
        {
                return a + b;
        }
        return doit(&add, 2);
}

int main(void)
{
    return foo(1);
}
$ gcc -Wtrampolines t.c
t.c: In function 'foo':
t.c:8:13: warning: trampoline generated for nested function 'add'
$ ./a.out 
$ echo $?
3
$ execstack a.out 
X a.out
like image 171
Mat Avatar answered Oct 10 '22 01:10

Mat