Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

problems about simulating fork using ZwCreateProcess

264 views
Skip to first unread message

JeffBJ

unread,
May 18, 2012, 2:03:24 PM5/18/12
to jeffre...@gmail.com
I try to simulate fork using ZwCreateProcess. It seems to work when I
use some simple test program. But when I try to create a new process
using CreateProcess API in the forked child process. The child process
paused for a while( and so did parent process) and then crashed.
Could you experts give me some hint?
The following are the test code and fork reference implementation code:
\

/*****************************************************/
Test program code fragment:

if ((pid = fork()) < 0) {
printf("fork error");
return -1;
}

if (pid == 0) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &pi, sizeof(pi) );
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
//Child process will pause here for a while and then
crash.
if(CreateProcess(_T("C:\\Windows\\notepad.exe"), NULL, NULL, NULL,
FALSE, 0, NULL, NULL, &si, &pi))
{
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}else{
// fputs("cann't create process", fp2);
}
}else{
//Parent code
}

/
*****************************************************************************************************/
And the following is what I used the reference fork implementation
code from internet:


int win32_fork()
{
HANDLE hProcess = 0;
HANDLE hThread = 0;
BOOL bReturn;
InheritAll();
OBJECT_ATTRIBUTES oa = {sizeof oa};


ZwCreateProcess(&hProcess, PROCESS_ALL_ACCESS, &oa,
0, 0, NULL, NULL, NULL);
CONTEXT context = {CONTEXT_FULL
| CONTEXT_DEBUG_REGISTERS
| CONTEXT_FLOATING_POINT};
ZwGetContextThread(NtCurrentThread(), &context);
context.Eip = ULONG(child);

MEMORY_BASIC_INFORMATION mbi;
ZeroMemory( &mbi, sizeof( mbi ) );
ZwQueryVirtualMemory(NtCurrentProcess(), PVOID(context.Esp),
MemoryBasicInformation, &mbi, sizeof mbi,
0);

USER_STACK stack = {0, 0, PCHAR(mbi.BaseAddress) + mbi.RegionSize,
mbi.BaseAddress, mbi.AllocationBase};
CLIENT_ID cid;
ZwCreateThread(&hThread, THREAD_ALL_ACCESS, &oa,
hProcess, &cid, &context, &stack, TRUE);
THREAD_BASIC_INFORMATION tbi;
ZeroMemory( &tbi, sizeof( tbi ) );
ZwQueryInformationThread(NtCurrentThread(),
ThreadBasicInformation,
&tbi, sizeof tbi, 0);
PNT_TIB tib = (PNT_TIB)tbi.TebBaseAddress;
ZwQueryInformationThread(hThread, ThreadBasicInformation,
&tbi, sizeof tbi, 0);
ZwWriteVirtualMemory(hProcess, tbi.TebBaseAddress,
&tib->ExceptionList, sizeof tib-
>ExceptionList,
0);
InformCsrss(hProcess, hThread,
ULONG(cid.UniqueProcess), ULONG(cid.UniqueThread));

ZwResumeThread(hThread, 0);
ZwClose(hThread);
ZwClose(hProcess);
return int(cid.UniqueProcess);
}
0 new messages