Recently, I have wonder how to execute machine code instruction from memory in C/C++. I am aware of data execution protection. Anyway, I have this piece of code:

int main()
{
	// allocate 2 bytes for storing machine code
	char* mc_add = (char*)malloc(sizeof(char)*2);
	int reg_eax; // for storing register EAX

	_asm mov eax, 0x10; // assign EAX = 16
	_asm mov ecx, 0x01; // assign ECX = 1

	// ADD EAX, ECX  == 0x01C1
	*mc_add = 0x01;
	*(mc_add+1) = 0xC1;

        // *  I want to execute machine code instructuion from mc_add here *

	_asm mov reg_eax, eax; // get register EAX

	printf("Register EAX is%d", reg_eax); // print EAX

	free(mc_add); // free machine code

	return 0;
}

Using: Microsoft Visual Studio 2008

Recommended Answers

All 2 Replies

I have finally found the solution to my problem, so I am going to share it to anyone who interest the same thing as what I am

int main()
{
	// allocate 8 bytes for storing machine code
	char *mc_mov = (char*)VirtualAlloc(0, 8, 0x1000, 0x40);
	int reg_eax; // for storing register EAX

	*mc_mov = 0xC7; // MOV (Immediate 32 bit to 32-bit register)
	*(mc_mov+1) = 0xC0; // MOV to register EAX
	*(mc_mov+2) = 0x00; // Immediate 32 bit data = 0x00000000
	*(mc_mov+3) = 0x00;
	*(mc_mov+4) = 0x00;
	*(mc_mov+5) = 0x00;
	*(mc_mov+6) = 0xC2; // Return 16
	*(mc_mov+7) = 0x10; 

	CallWindowProc((WNDPROC)mc_mov, 0, 0, 0, 0);

	_asm mov reg_eax, eax; // get register EAX

	printf("Register EAX is %d", reg_eax); // print EAX

	VirtualFree((LPVOID)mc_mov, 8, 0x4000); // free machine code

	return 0;
}

Actually I have a simple library I wrote for executing machine code off an executable page.

The basis of it all for single page without a pointer(to arguments pushed on the stack) is simply:

  • typedef int (*fp)();
  • fp *code = new fp [original.size()];
  • memmove((void*)code, original.data(), original.size());
  • In a wrapper function, return ((fp)code)();
  • delete [] code;

Argument support is mind-numbingly easy.

I was working on an experimental metamophic engine, and assembler for it around the begining of summer, but sort of gave up when a bug with literals had me grinding my teeth.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.