#include <windows.h>
#include <stdio.h>
void f1(void) {
MessageBox(0, "f1", "", 0);
}
void f2(void) {
MessageBox(0, "f2", "", 0);
}
int main(void)
{
char *mem;
int len;
int i;
len = (int)(&f2 - &f1);
printf("len : %d\n", len);
mem = (char*)malloc(len * sizeof(char));
////// BLOCK 1
// Put these lines in comment and uncomment the last call to func() just after the system("PAUSE"); => All is ok
CopyMemory(mem, (void*)&f1, len);
// for (i = 0; i < len; i++) {
// printf("%X ", (unsigned char)mem);
// }
//********************************************
printf("\n");
free(mem);
//////////////////////////////////
char *seh;
seh = (char*)VirtualAlloc(0, 0x10000, MEM_COMMIT, PAGE_READWRITE);
*seh = 0xC3; // RET instruction (opcode)
PDWORD OLDProtect;
VirtualProtect(seh, 0x00000010, PAGE_EXECUTE_READ | PAGE_GUARD, OLDProtect);
FARPROC func;
func = (FARPROC)f1;
func();
func = (FARPROC)seh;
system("PAUSE");
////// BLOCK 2
func(); // put this line in comment and uncomment the block above => all is ok
//////////////////////////////////
system("PAUSE");
return 0;
}
CopyMemory(mem, (void*)&f1, len);
CopyMemory(mem, (void*)&f1, len);
printf("%X ", (unsigned char)mem)
Code&f1 is an address that points to executable code. Doing any such thing as using CopyMemory on such an address alone gives me the creeps.CopyMemory(mem, (void*)&f1, len);
CodeLooking a bit closer at it, you cast char* to unsigned char (note the pointer) which you print out len times. Not only do you print out the address instead of the memory (which I suspect was what you intended), but printf with %X expects int, too...printf("%X ", (unsigned char)mem)
All in all, the code is just scary, sorry. :)
Copying around executable memory and fiddling with pointers and differently-sized variables in such a manner is the devil's code. If you don't shoot your foot that way today, you sure will tomorrow.
In fact, the forum interpretes [ i ] characters like italic.
In fact, I would like to access my function at runtime in order to detect if a breakpoint (INT 3) has been placed.In my opinion, there is absolutely no excuse for reading from or writing to executable data, except if someone is writing a debugger or an executable packer (both of these obviously don't work otherwise).
I need to detect any 0xCC opcode in the function that's why I have written this piece of code.
What is the best way ?