Hi,
The following code was working properly in gcc 3.3.3, but is not
working if I compile it with gcc 4.1.2., it gives a Segmentation
Violation when it's run.
What the code does do is to generate assembler opcodes and then execute
them directly as if they were a function, using a function pointer.
Following is a simplified version of the code:
#include <stdio.h>
typedef void (*FunctionType)();
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").
I guess something related with this should have been changed from
gcc 3.x to gcc 4.x, and I would like to know what is it, and if there's
a problem to have this kind of code working in gcc 4.x
Thank you very much.
Kind regards,
Anibal Caceres.