Direct assignment of code to function pointer: not working in gcc 4.x
Ian Lance Taylor
iant@google.com
Tue Feb 17 04:11:00 GMT 2009
Anibal Caceres Hernando <anibal.caceres@ericsson.com> writes:
> int main() {
> char *code = new char[5];
> int codeIndex = 0;
> printf("Start!!\n");
>
> code[codeIndex++]=0x55; //push %ebp
> code[codeIndex++]=0x89; //mov %esp,%ebp
> code[codeIndex++]=0xe5; //"
>
> code[codeIndex++]=0xc9; //LEAVE
> code[codeIndex++]=0xc3; //RET
>
> FunctionType invoke=(FunctionType)&code[0];
> invoke();
>
> printf("Finish!!\n");
> return 0;
> }
>
> If this is compiled with gcc 3.3.3 it executes without any problem:
> prints "Start!!", then executes invoke(), which does nothing, as you
> can see (the assembler is just a call to an empty function), and
> finally it prints "Finish!!".
> But the problem happens when I compile this using gcc 4.1.2 (and
> the same happens with 4.2.2): prints "Start!!", and it gives a
> Segmentation Violation when it starts executing invoke (I've seen
> using the gdb that the SIGSEGV happens just in the first instruction,
> in the "push %ebp").
This program requires an executable stack. You neglected to mention
which system you are running on. If it is GNU/Linux, see the
execstack(8) man page.
Ian
More information about the Gcc-help
mailing list