Below is my attempt to read the machine code pointed to by a function pointer and print it. Currently, the data being printed is not the same as the code that is generated… I’ve checked the values of the pointers created in the produced executable and listed by the disassembler (there is a difference between code/debugger) but don’t see anything too troubling, or understand how I might fix the problem.
void dummy();
int _tmain(int argc, _TCHAR* argv[])
{
int i;
printf("\nReading dummy...\n");
for(i = 0; i < 25; i++)
printf("%.2X ", ((char *)((void *)dummy))[i]);
puts("");
dummy();
getchar();
return 0;
}
void __declspec(naked) dummy()
{
__asm
{
nop;
nop;
nop;
nop;
ret;
}
}
Two common mistakes to make here. First off, cast to
unsigned char*instead of char*. Next, and the important one, Project + Properties, Linker, General and turn off Incremental Linking.With incremental linking enabled, a function address actually points to a little stub that contains nothing but a JMP to the real function. Which allows the linker to replace old code with new code without having to rebuild the entire executable image. Your code is reading that stub instead of the real function when incremental linking is enabled. Proper output: