I am currently developing a code emulator more for fun than for anything else, using libemu as the core for this emulator.
The only thing that I really want achieve is to load an entire PE into memory and let it rip.
So I've build a little TODO list with the following items:
- Read the headers ◦Check if the PE is Valid (x86 Platform)
- Extract the required data to setup the memory segments
- Hook all the imported functions to my custom API.
- Set the EIP to work correctly
- Build the stack segment (set esp and ebp)
- Set the Eflags
I've managed to get most of this done within a day. Although I seem to have issues with setting the stack segment correctly. Currently I set my registers with the following code segment:
/* Set Registers */
entry_point = pe->nt_header->AddressOfEntryPoint;
emu_cpu_eip_set(cpu, entry_point);
emu_cpu_reg32_set(cpu, eax, 0x00
emu_cpu_reg32_set(cpu, ecx, 0x00);
emu_cpu_reg32_set(cpu, edx, entry_point);
emu_cpu_reg32_set(cpu, ebx, 0x00);
emu_cpu_reg32_set(cpu, ebp, (0x0095f000 - 0x1000 / 2));
emu_cpu_reg32_set(cpu, esp, emu_cpu_reg32_get(cpu, ebp));
emu_cpu_reg32_set(cpu, esi, 0x00);
emu_cpu_reg32_set(cpu, edi, 0x00);
emu_cpu_eflags_set(cpu, 0x0000246);
I am thinking the issue lays within the ebp register. The values seem odd, but PyEmu seems to use them aswell. The reason I think the issue lays within the use of the stack is well it's hardcoded to start with and second the code that crashes is 83 65 f8 00 that translates to 00692D67, and dword ptr [ebp-8], 0 in Assembler.
I think that the stack is set with the use of the NTLoader for the PE files. But I can't seem to find it or the documentation about this.
Any pointers on how to continue would be really really appreciated.
- Robin
ps. I've cross posted this on a couple of boards etc to increase the chance for an answer. I've read a lot of old Windows documentation about loading PE files but they all just point at the SP segment in the headers. But as thats not the ESP I doubt it's the base (EBP) of the stack.
One cross-post can be found on OpenRCE: http://www.openrce.org/forums/posts/2171 The other cross-post can be found at SysInternals: http://forum.sysinternals.com/topic28898_post138041.html#138041